from __future__ import annotations

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_task_001_external_order_dispatch_to_player import login_player_sub_account_by_sms
from e2e.utils.account_store import account_store
from e2e.utils.bug_reporter import BugReporter


ROOT = Path(__file__).resolve().parents[1]
OUT_DIR = ROOT / "runtime" / "probes" / "s_flow_044_player_hall_verify"


def main() -> None:
    sys.stdout.reconfigure(encoding="utf-8")
    source_order_no = os.getenv("E2E_S_FLOW_SOURCE_ORDER_NO", "E2EORDER0701165959").strip()
    player_phone = os.getenv("E2E_TASK_PLAYER_PHONE", "19873945913").strip()
    settings = settings_fixture.__wrapped__()
    store = account_store()
    order = next(
        item
        for item in store.load_payload().get("dispatched_orders", [])
        if item.get("source_order_no") == source_order_no
    )
    player = store.find(phone=player_phone)
    assert player is not None, f"台账中未找到打手账号：{player_phone}"

    width = int(os.getenv("E2E_VIEWPORT_WIDTH", "1900"))
    height = int(os.getenv("E2E_VIEWPORT_HEIGHT", "1000"))
    run_dir = OUT_DIR / f"{datetime.now().strftime('%Y%m%d-%H%M%S')}-{player_phone}-{source_order_no}"
    run_dir.mkdir(parents=True, exist_ok=True)
    print(f"player={player.phone} source={source_order_no} title={order.get('order_title', '')}")
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(
            headless=False,
            slow_mo=200,
            args=[f"--window-size={width},{height}"],
        )
        context = browser.new_context(viewport={"width": width, "height": height}, screen={"width": width, "height": height})
        page = context.new_page()
        bug_reporter = BugReporter(page, case_id="S-FLOW-044-HALL-VERIFY")
        player_page = login_player_sub_account_by_sms(page, settings, bug_reporter, player)
        fulfillment_page = WanyoujiFulfillmentPage(player_page, settings.tenant_home_url, bug_reporter)
        try:
            text = fulfillment_page.verify_order_in_player_hall(
                source_order_no,
                order.get("order_title", source_order_no),
            )
            print("FOUND_IN_HALL")
            print(text[:2000].replace("\n", " | "))
        except AssertionError as exc:
            print(f"VERIFY_FAILED: {exc}")
            dump_player_hall(fulfillment_page, source_order_no, order.get("order_title", source_order_no), run_dir)
            raise
        finally:
            player_page.screenshot(path=run_dir / "final.png", full_page=True)
            print(f"probe_dir={run_dir}")
        context.close()
        browser.close()


def dump_player_hall(
    fulfillment_page: WanyoujiFulfillmentPage,
    source_order_no: str,
    order_title: str,
    run_dir: Path,
) -> None:
    lines: list[str] = []
    page = fulfillment_page.page
    lines.append(f"page_url={page.url}")
    lines.append("PAGE_TEXT:")
    lines.append(page.locator("body").inner_text(timeout=5000)[:3000])
    lines.append("\nFRAMES:")
    for index, frame in enumerate(page.frames):
        try:
            text = frame.locator("body").inner_text(timeout=3000)
        except Exception as exc:
            text = f"<read failed: {exc}>"
        lines.append(f"\n--- frame[{index}] url={frame.url} ---")
        lines.append(text[:3000])

    tabs = ["全部", "公池单", "私单", "指派单", "待接单", "抢单大厅"]
    keywords = [source_order_no, order_title]
    for index, frame in enumerate(page.frames):
        if "about:blank" in frame.url:
            continue
        for tab in tabs:
            try:
                clicked = fulfillment_page.click_order_hall_tab(frame, tab)
                page.wait_for_timeout(1000)
                fulfillment_page.search_order_if_possible(frame, source_order_no)
                text = frame.locator("body").inner_text(timeout=5000)
            except Exception as exc:
                lines.append(f"\n--- frame[{index}] tab={tab} failed={exc} ---")
                continue
            found = any(keyword and keyword in text for keyword in keywords)
            lines.append(f"\n--- frame[{index}] tab={tab} clicked={clicked} found={found} url={frame.url} ---")
            lines.append(text[:3000])
            if found:
                (run_dir / f"found-frame{index}-{tab}.txt").write_text(text, encoding="utf-8")
    (run_dir / "dump.txt").write_text("\n".join(lines), encoding="utf-8")


if __name__ == "__main__":
    main()
