from __future__ import annotations

import json
import os
import sys
from pathlib import Path

from playwright.sync_api import sync_playwright


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

from e2e.conftest import settings as load_settings
from e2e.pages.wanzhanggui_order_page import WanzhangguiOrderPage


def main() -> None:
    main_order_no = os.getenv("E2E_S_FLOW_MAIN_ORDER_NO", "").strip()
    assert main_order_no.startswith("BO"), "需要设置 E2E_S_FLOW_MAIN_ORDER_NO=BO..."

    settings = load_settings.__wrapped__()
    out_dir = ROOT / "runtime" / "probes" / "main_appeal_status"
    out_dir.mkdir(parents=True, exist_ok=True)

    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=False, slow_mo=80)
        context = browser.new_context(viewport={"width": 1920, "height": 1080})
        page = context.new_page()
        order_page = WanzhangguiOrderPage(page, settings.tenant_home_url, None)
        order_page.login_main_account(settings.wanzhanggui_tenant_phone, settings.wanzhanggui_tenant_password)

        frame = order_page.open_main_order_appeal_list()
        order_page.search_order_by_labels(frame, main_order_no, ["订单号", "主单号", "订单编号"])
        text = frame.locator("body").inner_text(timeout=5000)
        target_text = order_page.order_text_after_keyword(text, main_order_no)

        snapshot = {
            "main_order_no": main_order_no,
            "contains": main_order_no in text,
            "target_text": target_text[:2000],
            "page_text": text[:5000],
        }
        (out_dir / f"{main_order_no}.json").write_text(json.dumps(snapshot, ensure_ascii=False, indent=2), encoding="utf-8")
        page.screenshot(path=str(out_dir / f"{main_order_no}.png"), full_page=True)
        browser.close()

    print(json.dumps(snapshot, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
