from __future__ import annotations

import json
import os
import sys
from datetime import datetime
from pathlib import Path

from playwright.sync_api import sync_playwright

sys.path.insert(0, os.getcwd())

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


def main() -> None:
    sys.stdout.reconfigure(encoding="utf-8")
    settings = settings_fixture.__wrapped__()
    source_order_no = os.getenv("E2E_DELIVERY_SOURCE_ORDER_NO", "").strip()
    order_title = os.getenv("E2E_DELIVERY_ORDER_TITLE", "").strip()
    wanzhanggui_phone = os.getenv("E2E_TASK_WANZHANGGUI_PHONE", settings.wanzhanggui_tenant_phone).strip()
    wanzhanggui_password = os.getenv("E2E_TASK_WANZHANGGUI_PASSWORD", settings.wanzhanggui_tenant_password).strip()
    assert source_order_no, "请通过 E2E_DELIVERY_SOURCE_ORDER_NO 指定要完结的来源单号"
    if not order_title:
        order_title = f"E2E手工录单{source_order_no[-10:]}"

    run_dir = Path("runtime/probes/complete_upstream_order_only") / (
        datetime.now().strftime("%Y%m%d-%H%M%S") + f"-{source_order_no}"
    )
    run_dir.mkdir(parents=True, exist_ok=True)

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        context = browser.new_context(viewport={"width": settings.viewport_width, "height": settings.viewport_height})
        page = context.new_page()
        bug_reporter = BugReporter(page, case_id="E2E-DELIVERY-002-COMPLETE-ONLY")
        wanzhanggui_page = WanzhangguiOrderPage(page, settings.tenant_home_url, bug_reporter)

        wanzhanggui_page.login_main_account(wanzhanggui_phone, wanzhanggui_password)
        result_text = wanzhanggui_page.complete_upstream_order(source_order_no, order_title)

        snapshot = {
            "source_order_no": source_order_no,
            "order_title": order_title,
            "wanzhanggui_phone": wanzhanggui_phone,
            "result_text": result_text,
            "page_url": page.url,
            "body_text": page.locator("body").inner_text(timeout=5000),
        }
        (run_dir / "snapshot.json").write_text(json.dumps(snapshot, ensure_ascii=False, indent=2), encoding="utf-8")
        page.screenshot(path=str(run_dir / "page.png"), full_page=True)
        print(f"上游验收完结探测完成：{run_dir}")
        context.close()
        browser.close()


if __name__ == "__main__":
    main()
