from __future__ import annotations

import json
import os
from pathlib import Path

from playwright.sync_api import sync_playwright

from e2e.conftest import settings as settings_fixture
from e2e.pages.wanzhanggui_order_page import WanyoujiFulfillmentPage
from e2e.utils.account_store import account_store
from e2e.utils.bug_reporter import BugReporter


def resolve_order() -> dict:
    target = os.getenv("E2E_S_FLOW_MAIN_ORDER_NO", "BO20260623112007360151").strip()
    payload = account_store().load_payload()
    for item in payload.get("dispatched_orders", []):
        if item.get("main_order_no") == target or item.get("source_order_no") == target:
            return item
    raise AssertionError(f"runtime/e2e_accounts.json 未找到订单：{target}")


def main() -> None:
    settings = settings_fixture.__wrapped__()
    order = resolve_order()
    phones = order.get("wanyouji_phones") or []
    assert phones, f"订单台账缺少 wanyouji_phones；order={order}"
    account = account_store().find(phone=phones[0])
    assert account is not None, f"台账中未找到丸友集账号：{phones[0]}"

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    strategy_type = order.get("strategy_type", "单平台指定")
    expected_scope = "私单" if strategy_type == "单平台指定" else "公池单/私单"

    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=True)
        context = browser.new_context(viewport={"width": settings.viewport_width, "height": settings.viewport_height})
        page = context.new_page()
        reporter = BugReporter(page, case_id="FLOW-046-HALL-VERIFY")
        fulfillment_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, reporter)
        fulfillment_page.login_main_account(account.phone, account.password)
        text = fulfillment_page.verify_order_reached_hall(
            source_order_no,
            order_title,
            expected_scope,
            main_order_no=main_order_no,
            expected_status="待接单",
        )
        result = {
            "main_order_no": main_order_no,
            "source_order_no": source_order_no,
            "order_title": order_title,
            "wanyouji_phone": account.phone,
            "expected_scope": expected_scope,
            "matched_text": text[:2000],
        }
        out = Path("runtime/probes/flow_046_continue_dispatch_hall_verify.json")
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
        print(json.dumps(result, ensure_ascii=False, indent=2))
        context.close()
        browser.close()


if __name__ == "__main__":
    main()
