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_apply_001_create_bill import resolve_player_settlement_order_and_account
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__()
    order, player = resolve_player_settlement_order_and_account()
    out_dir = Path("runtime/probes/player_settlement_apply") / (
        datetime.now().strftime("%Y%m%d-%H%M%S") + f"-{order['source_order_no']}"
    )
    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-APPLY-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()
        player_page.click_player_income_order_tab(frame)
        player_page.search_player_income_order_for_settlement(
            frame,
            order["source_order_no"],
            order["order_title"],
            order.get("expected_player_amount", "70"),
        )
        player_page.open_player_income_detail_if_possible(
            frame,
            order["source_order_no"],
            order["order_title"],
            order.get("expected_player_amount", "70"),
        )
        page.wait_for_timeout(2000)
        snapshot = {
            "order": order,
            "player": player.phone,
            "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"], .ant-checkbox, [role="checkbox"]'))
                      .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()
