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 WanyoujiFulfillmentPage
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()
    owner_phone = os.getenv("E2E_TASK_WANYOUJI_PHONE", "19844527868").strip()
    owner_password = os.getenv("E2E_TASK_WANYOUJI_PASSWORD", "test123456").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/apply_upstream_acceptance_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-APPLY-ONLY")
        owner_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)

        owner_page.login_main_account(owner_phone, owner_password)
        result_text = owner_page.apply_upstream_acceptance(source_order_no, order_title)

        snapshot = {
            "source_order_no": source_order_no,
            "order_title": order_title,
            "owner_phone": owner_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()
