from __future__ import annotations

import os
import re
import sys
from pathlib import Path

from dotenv import load_dotenv
from playwright.sync_api import sync_playwright

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

from e2e.pages.wanzhanggui_order_page import ManualOrderData, WanzhangguiOrderPage
from e2e.utils.account_store import account_store


def main() -> None:
    load_dotenv()
    source_order_no = sys.argv[1] if len(sys.argv) > 1 else os.getenv("E2E_S_FLOW_SOURCE_ORDER_NO", "")
    if not source_order_no:
        raise SystemExit("usage: probe_wanzhanggui_find_main_order_no.py E2EORDER...")

    store = account_store()
    payload = store.load_payload()
    order_record = next(
        (item for item in payload.get("dispatched_orders", []) if item.get("source_order_no") == source_order_no),
        None,
    )
    if not order_record:
        raise SystemExit(f"source order not found in ledger: {source_order_no}")

    wanzhanggui_phone = order_record.get("wanzhanggui_phone") or os.getenv("E2E_WANZHANGGUI_TENANT_PHONE", "19147509308")
    wanzhanggui_password = os.getenv("E2E_WANZHANGGUI_TENANT_PASSWORD", "test123456")
    tenant_home_url = os.getenv("TENANT_HOME_URL", "https://test-lianlianyun.lianlianwz.com/home")
    width = int(os.getenv("E2E_VIEWPORT_WIDTH", "1920"))
    height = int(os.getenv("E2E_VIEWPORT_HEIGHT", "1080"))

    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=False, args=[f"--window-size={width},{height}"])
        context = browser.new_context(viewport={"width": width, "height": height}, screen={"width": width, "height": height})
        page = context.new_page()
        order_page = WanzhangguiOrderPage(page, tenant_home_url)
        order_page.login_main_account(wanzhanggui_phone, wanzhanggui_password)
        frame = order_page.open_order_management()
        order = ManualOrderData(
            source_order_no=source_order_no,
            order_title=order_record.get("order_title", source_order_no),
            strategy_name="",
            strategy_type=order_record.get("strategy_type", ""),
        )
        order_page.search_order_if_possible(frame, source_order_no)
        page.wait_for_timeout(2000)
        text = frame.locator("body").inner_text(timeout=5000)
        row_text = order_page.extract_main_order_no(text, order)
        if not row_text:
            matches = re.findall(r"BO\d{20}", text)
            row_text = matches[0] if matches else ""
        browser.close()

    if not row_text:
        raise SystemExit(f"full BO main order number not found for {source_order_no}")

    store.mark_task_order_status(
        source_order_no=source_order_no,
        status=order_record.get("status", "without_dispatch"),
        main_order_no=row_text,
    )
    print(row_text)


if __name__ == "__main__":
    main()
