from __future__ import annotations

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

from dotenv import load_dotenv
from playwright.sync_api import sync_playwright

ROOT_DIR = Path(__file__).resolve().parents[1]
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))
load_dotenv(ROOT_DIR / ".env")

from e2e.conftest import settings as settings_fixture
from e2e.pages.wanzhanggui_order_page import WanyoujiFulfillmentPage
from e2e.tests.结算.test_e2e_settle_player_account_001_payment_account import resolve_player_account_for_payment
from e2e.tests.订单流转.test_e2e_task_001_external_order_dispatch_to_player import login_player_sub_account_by_sms
from e2e.utils.bug_reporter import BugReporter


def main() -> None:
    settings = settings_fixture.__wrapped__()
    player = resolve_player_account_for_payment()
    out_dir = Path("runtime/probes/player_payment_account") / (
        datetime.now().strftime("%Y%m%d-%H%M%S") + f"-{player.phone}"
    )
    out_dir.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": settings.viewport_width, "height": settings.viewport_height})
        page = context.new_page()
        bug_reporter = BugReporter(page, case_id="B-SETTLE-PLAYER-ACCOUNT-001-PROBE")
        player_browser_page = login_player_sub_account_by_sms(page, settings, bug_reporter, player)
        player_page = WanyoujiFulfillmentPage(player_browser_page, settings.tenant_home_url, bug_reporter)
        frame = player_page.open_player_income()
        before_text = frame.locator("body").inner_text(timeout=5000)
        clicked = player_page.open_player_payment_account_editor(frame)
        page.wait_for_timeout(2500)
        snapshot = {
            "player": player.phone,
            "clicked": clicked,
            "page_url": page.url,
            "before_text": before_text,
            "frames": [],
        }
        for index, candidate in enumerate(page.frames):
            item = {"index": index, "url": candidate.url, "text": "", "controls": []}
            try:
                item["text"] = candidate.locator("body").inner_text(timeout=3000)
                item["controls"] = candidate.evaluate(
                    """() => Array.from(document.querySelectorAll('button, a, input, textarea, [role="button"]'))
                      .map(el => {
                        const r = el.getBoundingClientRect();
                        return {
                          tag: el.tagName,
                          text: (el.innerText || el.textContent || '').trim(),
                          placeholder: el.getAttribute('placeholder') || '',
                          value: el.value || '',
                          type: el.getAttribute('type') || '',
                          className: String(el.className || ''),
                          visible: r.width > 0 && r.height > 0,
                          rect: { x: r.x, y: r.y, width: r.width, height: r.height },
                        };
                      })
                      .filter(item => item.visible)"""
                )
            except Exception as exc:
                item["text"] = f"<read failed: {exc}>"
            snapshot["frames"].append(item)
        (out_dir / "snapshot.json").write_text(json.dumps(snapshot, ensure_ascii=False, indent=2), encoding="utf-8")
        page.screenshot(path=str(out_dir / "page.png"), full_page=True)
        print(f"打手打款账户探测完成：{out_dir}")
        context.close()
        browser.close()


if __name__ == "__main__":
    main()
