from __future__ import annotations

import json
import os
import sys
from datetime import datetime
from pathlib import Path

from playwright.sync_api import sync_playwright

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

from e2e.conftest import settings as settings_fixture
from e2e.pages.wanzhanggui_order_page import WanyoujiFulfillmentPage
from e2e.pages.wanzhanggui_push_page import WANZHANGGUI_CONSOLE_URL
from e2e.utils.bug_reporter import BugReporter


def snapshot_page(page) -> dict:
    return {
        "page_url": page.url,
        "frames": [frame.url for frame in page.frames],
        "body_text": page.locator("body").inner_text(timeout=5000),
        "nodes": page.evaluate(
            """() => Array.from(document.querySelectorAll('taro-view-core, div, span, a'))
              .map(el => ({ text: (el.innerText || el.textContent || '').trim(), r: el.getBoundingClientRect(), cls: String(el.className || '') }))
              .filter(item => item.text && item.r.width > 0 && item.r.height > 0 && item.r.x >= 0 && item.r.x < 280)
              .map(item => ({ text: item.text, x: Math.round(item.r.x), y: Math.round(item.r.y), w: Math.round(item.r.width), h: Math.round(item.r.height), cls: item.cls }))
            """
        ),
        "frame_texts": [
            {
                "url": frame.url,
                "text": safe_frame_text(frame),
            }
            for frame in page.frames
            if frame != page.main_frame
        ],
    }


def safe_frame_text(frame) -> str:
    try:
        return frame.locator("body").inner_text(timeout=2000)[:2000]
    except Exception as exc:
        return f"<unreadable: {exc}>"


def main() -> None:
    sys.stdout.reconfigure(encoding="utf-8")
    cfg = settings_fixture.__wrapped__()
    phone = os.getenv("E2E_WANZHANGGUI_TENANT_PHONE", cfg.wanzhanggui_tenant_phone)
    password = os.getenv("E2E_WANZHANGGUI_TENANT_PASSWORD", cfg.wanzhanggui_tenant_password)
    out = Path("runtime/probes/wanzhanggui_settlement_menus") / datetime.now().strftime("%Y%m%d-%H%M%S")
    out.mkdir(parents=True, exist_ok=True)

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=120)
        context = browser.new_context(viewport={"width": cfg.viewport_width, "height": cfg.viewport_height})
        page = context.new_page()
        menu_page = WanyoujiFulfillmentPage(page, cfg.tenant_home_url, BugReporter(page, case_id="WZG-MENU-PROBE"))
        menu_page.login_main_account(phone, password)
        page.goto(WANZHANGGUI_CONSOLE_URL, wait_until="domcontentloaded")
        menu_page.wait_for_enterprise_console_shell()

        snapshots: list[dict] = []
        snapshots.append({"step": "console", **snapshot_page(page)})
        for parent in ["结算中心", "支付中心"]:
            clicked_parent = menu_page.click_sidebar_text_scrolled(parent, right_edge=True)
            page.wait_for_timeout(2500)
            snapshots.append({"step": f"parent:{parent}", "clicked": clicked_parent, **snapshot_page(page)})
            body_text = page.locator("body").inner_text(timeout=5000)
            leaf_candidates = [
                line.strip()
                for line in body_text.splitlines()
                if line.strip()
                and any(key in line for key in ["结算", "账单", "打款", "支付", "账户", "账号", "明细"])
                and len(line.strip()) <= 30
            ]
            for leaf in list(dict.fromkeys(leaf_candidates))[:12]:
                leaf_clicked = menu_page.click_sidebar_text_scrolled(leaf)
                page.wait_for_timeout(2500)
                snapshots.append({"step": f"leaf:{parent}>{leaf}", "clicked": leaf_clicked, **snapshot_page(page)})
                menu_page.click_sidebar_text_scrolled(parent, right_edge=True)
                page.wait_for_timeout(800)

        (out / "snapshot.json").write_text(json.dumps(snapshots, ensure_ascii=False, indent=2), encoding="utf-8")
        page.screenshot(path=str(out / "page.png"), full_page=True)
        context.close()
        browser.close()
    print(out)


if __name__ == "__main__":
    main()
