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 = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

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 / ".env")

    main_order_no = os.getenv("E2E_S_FLOW_MAIN_ORDER_NO", "").strip()
    source_order_no = os.getenv("E2E_S_FLOW_SOURCE_ORDER_NO", "").strip()
    store = account_store()
    order = next(
        (
            item
            for item in store.load_payload().get("dispatched_orders", [])
            if (main_order_no and item.get("main_order_no") == main_order_no)
            or (source_order_no and item.get("source_order_no") == source_order_no)
        ),
        None,
    )
    if not order:
        raise SystemExit(f"台账中未找到订单：main={main_order_no}; source={source_order_no}")

    source_order_no = order["source_order_no"]
    order_title = order.get("order_title", source_order_no)
    phones = order.get("wanyouji_phones") or []
    if not phones:
        raise SystemExit(f"订单台账缺少丸友集账号：{order}")
    wanyouji_phone = os.getenv("E2E_ORDER_WANYOUJI_PHONE", "").strip() or phones[0]
    account = store.find(phone=wanyouji_phone)
    if account is None:
        raise SystemExit(f"台账中未找到丸友集账号：{wanyouji_phone}")

    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=True)
        context = browser.new_context(viewport={"width": 1920, "height": 1080})
        page = context.new_page()
        try:
            fulfillment = WanyoujiFulfillmentPage(
                page,
                os.getenv("TENANT_HOME_URL", "https://test-lianlianyun.lianlianwz.com/home"),
            )
            fulfillment.login_main_account(account.phone, account.password)
            frame = fulfillment.open_workshop_order_list()
            text = fulfillment.search_workshop_order_list(frame, source_order_no, order_title)
            assert source_order_no in text or order_title in text, (
                f"S-FLOW-034 丸友集订单列表未找到订单；source_order_no={source_order_no}; "
                f"text={text[:1500]}"
            )
            assert "售后中" in text, (
                f"S-FLOW-034 丸友集订单列表状态不是售后中；source_order_no={source_order_no}; "
                f"text={text[:1500]}"
            )
            store.mark_order_consumed_by_flow_case(
                source_order_no=source_order_no,
                case_id="S-FLOW-034",
                status=order.get("status", "abnormal_sub_order_aftersale_pending"),
                current_flow_state=order.get("current_flow_state", "wanzhanggui_abnormal_sub_order_aftersale_pending"),
                wanyouji_abnormal_sub_order_aftersale_text=text[:1500],
                wanyouji_parent_status="售后中",
                wanyouji_visibility="workshop_order_list_visible",
                available_for_cases=order.get("available_for_cases", ["S-FLOW-036", "S-FLOW-035"]),
            )
            print(f"S-FLOW-034 丸友集状态回读通过：{account.phone} / {source_order_no}")
            print(text[:2000])
        finally:
            context.close()
            browser.close()


if __name__ == "__main__":
    main()
