from __future__ import annotations

import json
import sys
from pathlib import Path

from playwright.sync_api import sync_playwright


ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from e2e.conftest import settings as load_settings
from e2e.pages.wanzhanggui_order_page import WanzhangguiOrderPage


OUT = ROOT / "runtime" / "probes" / "wanzhanggui_main_appeal_page"
WANZHANGGUI_CONSOLE_URL = "https://test-merchant-lianlianyun.lianlianwz.com/productConsole?productCode=P20251204180120231330"


def main() -> None:
    OUT.mkdir(parents=True, exist_ok=True)
    settings = load_settings.__wrapped__()
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=False, slow_mo=100)
        context = browser.new_context(viewport={"width": 1920, "height": 1080})
        page = context.new_page()
        order_page = WanzhangguiOrderPage(page, settings.tenant_home_url, None)
        order_page.login_main_account(settings.wanzhanggui_tenant_phone, settings.wanzhanggui_tenant_password)
        order_page.goto(WANZHANGGUI_CONSOLE_URL)
        order_page.wait_for_enterprise_console_shell()
        page.wait_for_timeout(1200)
        order_page.click_sidebar_text("商家管理", right_edge=True)
        page.wait_for_timeout(800)
        order_page.click_sidebar_text("主单申诉单")
        page.wait_for_timeout(5000)

        frames = []
        for frame in page.frames:
            if not frame.url:
                continue
            try:
                text = frame.locator("body").inner_text(timeout=3000)
            except Exception:
                text = ""
            frames.append({"url": frame.url, "text": text[:3000]})

        snapshot = {
            "page_url": page.url,
            "page_text": page.locator("body").inner_text(timeout=5000),
            "frames": frames,
        }
        (OUT / "snapshot.json").write_text(json.dumps(snapshot, ensure_ascii=False, indent=2), encoding="utf-8")
        page.screenshot(path=str(OUT / "page.png"), full_page=True)
        browser.close()
        print(json.dumps({"out": str(OUT), "frames": [item["url"] for item in frames]}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
