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 Page, sync_playwright

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

from e2e.pages.wanyouji_member_page import WanyoujiMemberData, WanyoujiMemberPage
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


OUT_DIR = Path("runtime/probes/player_confirm_login_action")


def main() -> None:
    load_dotenv(ROOT_DIR / ".env")
    source_order_no = os.getenv("E2E_DELIVERY_SOURCE_ORDER_NO", "E2EORDER0609120015").strip()
    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=order["task_player_phone"])
    if player is None:
        raise SystemExit(f"未找到打手账号：{order['task_player_phone']}")

    class Settings:
        tenant_home_url = "https://test-lianlianyun.lianlianwz.com/home"
        verification_code_mode = os.getenv("E2E_VERIFICATION_CODE_MODE", "feishu")
        verification_code_static = os.getenv("E2E_VERIFICATION_CODE_STATIC", "")
        manual_code_file = os.getenv("E2E_MANUAL_CODE_FILE", "runtime/sms_code.txt")
        manual_code_timeout_seconds = int(os.getenv("E2E_MANUAL_CODE_TIMEOUT_SECONDS", "180"))
        manual_code_poll_interval_seconds = int(os.getenv("E2E_MANUAL_CODE_POLL_INTERVAL_SECONDS", "2"))
        feishu_app_id = os.getenv("FEISHU_APP_ID", "")
        feishu_app_secret = os.getenv("FEISHU_APP_SECRET", "")
        feishu_chat_id = os.getenv("FEISHU_CHAT_ID", "")
        feishu_timeout_seconds = int(os.getenv("FEISHU_TIMEOUT_SECONDS", "60"))
        feishu_poll_interval_seconds = int(os.getenv("FEISHU_POLL_INTERVAL_SECONDS", "3"))

    OUT_DIR.mkdir(parents=True, exist_ok=True)
    run_dir = OUT_DIR / f"{datetime.now().strftime('%Y%m%d-%H%M%S')}-{source_order_no}"
    run_dir.mkdir(parents=True, exist_ok=True)

    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=False, slow_mo=100)
        context = browser.new_context(viewport={"width": 1920, "height": 1080})
        page = context.new_page()
        try:
            player_browser_page = login_player_sub_account_by_sms(page, Settings(), None, player)
            fulfillment = WanyoujiFulfillmentPage(player_browser_page, Settings.tenant_home_url)
            frame = fulfillment.open_player_my_orders(source_order_no=source_order_no)
            fulfillment.search_player_my_orders(frame, source_order_no, order["order_title"])
            fulfillment.open_player_order_operation(frame, source_order_no, order["order_title"])
            print(f"已打开确认上号弹框：{source_order_no}")
            print(f"观察目录：{run_dir.resolve()}")
            observe(page, run_dir, seconds=180)
        finally:
            context.close()
            browser.close()


def observe(page: Page, run_dir: Path, seconds: int) -> None:
    for index in range(seconds // 2):
        page.wait_for_timeout(2000)
        prefix = run_dir / f"{index + 1:03d}-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
        try:
            snapshot = {
                "url": page.url,
                "text": page.locator("body").inner_text(timeout=2000),
                "frames": [],
            }
            for frame in page.frames:
                try:
                    text = frame.locator("body").inner_text(timeout=1000)
                    modal = frame.evaluate(
                        """() => Array.from(document.querySelectorAll('.ant-modal'))
                          .filter(el => {
                            const r = el.getBoundingClientRect();
                            return r.width > 0 && r.height > 0;
                          })
                          .map(root => ({
                            text: root.innerText || root.textContent || '',
                            html: root.outerHTML.slice(0, 8000),
                          }))"""
                    )
                except Exception as exc:
                    text = f"<read failed: {exc}>"
                    modal = []
                snapshot["frames"].append({"url": frame.url, "text": text[:3000], "modal": modal})
            page.screenshot(path=prefix.with_suffix(".png"), full_page=True)
            prefix.with_suffix(".json").write_text(json.dumps(snapshot, ensure_ascii=False, indent=2), encoding="utf-8")
        except Exception as exc:
            prefix.with_suffix(".error.txt").write_text(str(exc), encoding="utf-8")


if __name__ == "__main__":
    main()
