from __future__ import annotations

import os
import sys
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))

from e2e.pages.wanzhanggui_order_page import WanyoujiFulfillmentPage
from e2e.utils.account_store import account_store


def main() -> None:
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(encoding="utf-8")
    load_dotenv(ROOT_DIR / ".env")
    store = account_store()
    source_order_no = os.getenv("E2E_DELIVERY_SOURCE_ORDER_NO", "").strip()
    if not source_order_no:
        candidates = [
            item
            for item in store.load_payload().get("dispatched_orders", [])
            if item.get("status") in {"task_player_accepted", "delivery_submitted"}
        ]
        candidates = sorted(candidates, key=lambda item: item.get("updated_at", item.get("created_at", "")), reverse=True)
        if not candidates:
            raise SystemExit("台账中没有可用于主账号验收探测的已接单/已交付订单")
        source_order_no = candidates[0]["source_order_no"]

    order = next(
        (
            item
            for item in store.load_payload().get("dispatched_orders", [])
            if item.get("source_order_no") == source_order_no
        ),
        None,
    )
    if not order:
        raise SystemExit(f"台账中未找到订单：{source_order_no}")

    owner_phone = order.get("task_wanyouji_phone") or (order.get("wanyouji_phones") or [""])[0]
    owner = store.find(phone=owner_phone)
    if owner is None:
        raise SystemExit(f"台账中未找到丸友集主账号：{owner_phone}")

    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:
            fulfillment = WanyoujiFulfillmentPage(page, "https://test-lianlianyun.lianlianwz.com/home")
            fulfillment.login_main_account(owner.phone, owner.password)
            frame = fulfillment.open_workshop_order_list()
            text = fulfillment.search_workshop_order_list(frame, source_order_no, order.get("order_title", ""))
            assert source_order_no in text or order.get("order_title", "") in text, (
                f"主账号订单列表未找到交付后的订单：{source_order_no}; text={text[:1500]}"
            )
            assert "待验收" in text or "申请上游验收" in text, (
                f"主账号订单列表未看到待验收/申请上游验收状态：{source_order_no}; text={text[:1500]}"
            )
            store.mark_task_order_status(
                source_order_no=source_order_no,
                status="delivery_submitted",
                delivery_checked_by_wanyouji_owner=owner.phone,
            )
            print(f"主账号验收探测通过：{owner.phone} / {source_order_no}")
            print(text[:2000])
        finally:
            context.close()
            browser.close()


if __name__ == "__main__":
    main()
