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

sys.path.insert(0, os.getcwd())

from e2e.conftest import settings as settings_fixture
from e2e.pages.wanzhanggui_order_page import WANYOUJI_CONSOLE_URL, WanyoujiFulfillmentPage
from e2e.utils.bug_reporter import BugReporter


def main() -> None:
    sys.stdout.reconfigure(encoding="utf-8")
    settings = settings_fixture.__wrapped__()
    owner_phone = os.getenv("E2E_TASK_WANYOUJI_PHONE", "19844527868").strip()
    owner_password = os.getenv("E2E_TASK_WANYOUJI_PASSWORD", "test123456").strip()
    run_dir = Path("runtime/probes/wanyouji_settlement_menus") / datetime.now().strftime("%Y%m%d-%H%M%S")
    run_dir.mkdir(parents=True, exist_ok=True)

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        context = browser.new_context(viewport={"width": settings.viewport_width, "height": settings.viewport_height})
        page = context.new_page()
        owner_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, BugReporter(page, case_id="MENU-PROBE"))
        owner_page.login_main_account(owner_phone, owner_password)
        owner_page.goto(WANYOUJI_CONSOLE_URL)
        owner_page.wait_for_enterprise_console_shell()
        clicked = owner_page.click_sidebar_text_scrolled("结算中心", right_edge=True)
        page.wait_for_timeout(2500)
        leaf_results = []
        for leaf in ["结算账单-丸友集", "结算明细-丸友集"]:
            leaf_clicked = owner_page.click_sidebar_text_scrolled(leaf)
            page.wait_for_timeout(4000)
            leaf_results.append(
                {
                    "leaf": leaf,
                    "clicked": leaf_clicked,
                    "page_url": page.url,
                    "frames": [frame.url for frame in page.frames],
                    "body_text": page.locator("body").inner_text(timeout=5000),
                }
            )
            owner_page.click_sidebar_text_scrolled("结算中心", right_edge=True)
            page.wait_for_timeout(1000)
        nodes = page.evaluate(
            """() => Array.from(document.querySelectorAll('taro-view-core, div, span'))
              .map(el => ({ text: (el.innerText || el.textContent || '').trim(), r: el.getBoundingClientRect(), cls: String(el.className || '') }))
              .filter(item => item.r.x >= 0 && item.r.x < 260 && item.r.width > 20 && item.r.height > 10)
              .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 }))
            """
        )
        snapshot = {
            "clicked": clicked,
            "page_url": page.url,
            "frames": [frame.url for frame in page.frames],
            "body_text": page.locator("body").inner_text(timeout=5000),
            "leaf_results": leaf_results,
            "nodes": nodes,
        }
        (run_dir / "snapshot.json").write_text(json.dumps(snapshot, ensure_ascii=False, indent=2), encoding="utf-8")
        page.screenshot(path=str(run_dir / "page.png"), full_page=True)
        print(f"丸友集结算菜单探测完成：{run_dir}")
        context.close()
        browser.close()


if __name__ == "__main__":
    main()
