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 WanyoujiFulfillmentPage
from e2e.tests.结算.test_e2e_settle_wanyouji_pay_001_payout import resolve_wanyouji_payout_account
from e2e.utils.bug_reporter import BugReporter


def main() -> None:
    sys.stdout.reconfigure(encoding="utf-8")
    settings = settings_fixture.__wrapped__()
    account, _ = resolve_wanyouji_payout_account()
    run_dir = Path("runtime/probes/wanyouji_workbench_state") / datetime.now().strftime("%Y%m%d-%H%M%S")
    run_dir.mkdir(parents=True, exist_ok=True)

    with sync_playwright() as playwright:
        browser = playwright.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="WYJ-WORKBENCH-STATE"))
        owner_page.login_main_account(account.phone, account.password)
        frame = owner_page.open_workshop_finance_settlement_shell()
        page.wait_for_timeout(5000)

        frames = []
        for item in page.frames:
            frame_info = {"url": item.url}
            try:
                frame_info["text"] = item.locator("body").inner_text(timeout=2000)
            except Exception as exc:
                frame_info["text_error"] = str(exc)
            if "test-wshop" in item.url:
                try:
                    frame_info["storage"] = item.evaluate(
                        """() => {
                            const dump = storage => {
                                const result = {};
                                for (let index = 0; index < storage.length; index += 1) {
                                    const key = storage.key(index);
                                    result[key] = storage.getItem(key);
                                }
                                return result;
                            };
                            return {
                                localStorage: dump(window.localStorage),
                                sessionStorage: dump(window.sessionStorage),
                                location: window.location.href,
                            };
                        }"""
                    )
                except Exception as exc:
                    frame_info["storage_error"] = str(exc)
            frames.append(frame_info)

        nodes = page.evaluate(
            """() => Array.from(document.querySelectorAll('taro-view-core, div, span, a, button, li'))
              .map(el => ({ text: (el.innerText || el.textContent || '').trim(), r: el.getBoundingClientRect(), cls: String(el.className || ''), tag: el.tagName }))
              .filter(item => item.text && item.r.width > 0 && item.r.height > 0)
              .filter(item => item.text.includes('财务') || item.text.includes('结算') || item.text.includes('工作室'))
              .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), tag: item.tag, cls: item.cls }))
            """
        )
        data = {
            "account": account.phone,
            "page_url": page.url,
            "frame_returned": frame.url if frame else "",
            "frames": frames,
            "cookies": context.cookies("https://test-wshop.lianlianwz.com"),
            "nodes": nodes,
        }
        (run_dir / "state.json").write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
        page.screenshot(path=str(run_dir / "page.png"), full_page=True)
        print(f"State probe done: {run_dir}")
        print("frames:", [item["url"] for item in frames])
        print("nodes:", json.dumps(nodes[:30], ensure_ascii=False, indent=2))
        context.close()
        browser.close()


if __name__ == "__main__":
    main()
