from __future__ import annotations

import json
import os
import sys
from pathlib import Path

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.conftest import settings as load_settings
from e2e.pages.wanzhanggui_order_page import WanzhangguiOrderPage


def main() -> None:
    main_order_no = os.getenv("E2E_S_FLOW_MAIN_ORDER_NO", "").strip()
    assert main_order_no.startswith("BO"), "需要设置 E2E_S_FLOW_MAIN_ORDER_NO=BO..."

    settings = load_settings.__wrapped__()
    out_dir = ROOT / "runtime" / "probes" / "wanzhanggui_order_by_main_no"
    out_dir.mkdir(parents=True, exist_ok=True)

    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=False, slow_mo=80)
        context = browser.new_context(viewport={"width": 1920, "height": 1080})
        page = context.new_page()
        order_page = WanzhangguiOrderPage(page, settings.tenant_home_url, None)
        order_page.login_main_account(settings.wanzhanggui_tenant_phone, settings.wanzhanggui_tenant_password)

        frame = order_page.open_order_management()
        searched = order_page.search_order_by_labels(frame, main_order_no, ["主单号"])
        filter_inputs = frame.evaluate(
            """() => Array.from(document.querySelectorAll('input'))
              .map((el, index) => ({
                index,
                value: el.value || '',
                placeholder: el.getAttribute('placeholder') || '',
                rect: (() => {
                  const r = el.getBoundingClientRect();
                  return { x: Math.round(r.x), y: Math.round(r.y), w: Math.round(r.width), h: Math.round(r.height) };
                })()
              }))
              .filter(item => item.rect.w > 0 && item.rect.h > 0)
              .slice(0, 30)"""
        )
        text = frame.locator("body").inner_text(timeout=5000)
        target_text = order_page.near_order_text(text, main_order_no)
        snapshot = {
            "main_order_no": main_order_no,
            "searched": searched,
            "contains": main_order_no in text,
            "filter_inputs": filter_inputs,
            "target_text": target_text[:2500],
            "page_text": text[:5000],
        }
        (out_dir / f"{main_order_no}.json").write_text(json.dumps(snapshot, ensure_ascii=False, indent=2), encoding="utf-8")
        page.screenshot(path=str(out_dir / f"{main_order_no}.png"), full_page=True)
        browser.close()

    sys.stdout.reconfigure(encoding="utf-8")
    print(json.dumps(snapshot, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
