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", "E2EORDER0609120015")
    order_title = os.getenv("E2E_DELIVERY_ORDER_TITLE", f"E2E手工录单{source_order_no[-10:]}")
    owner_phone = os.getenv("E2E_TASK_WANYOUJI_PHONE", "19844527868")
    owner_password = os.getenv("E2E_TASK_WANYOUJI_PASSWORD", "test123456")
    run_dir = Path("runtime/probes/delivery_002_suborder_approval") / (
        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-PROBE")
        owner_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
        owner_page.login_main_account(owner_phone, owner_password)
        frame = owner_page.open_workshop_order_list()
        owner_page.search_workshop_order_list(frame, source_order_no, order_title)
        owner_page.click_row_action(frame, source_order_no, order_title, ["操作"])
        page.wait_for_timeout(2000)
        snapshot = frame.evaluate(
            """() => {
                const nodes = Array.from(document.querySelectorAll('button, a, [role="button"], span, div'))
                  .map((el, index) => {
                    const r = el.getBoundingClientRect();
                    return {
                      index,
                      tag: el.tagName,
                      text: (el.innerText || el.textContent || '').trim(),
                      cls: String(el.className || ''),
                      role: el.getAttribute('role') || '',
                      aria: el.getAttribute('aria-label') || '',
                      title: el.getAttribute('title') || '',
                      x: Math.round(r.x), y: Math.round(r.y),
                      w: Math.round(r.width), h: Math.round(r.height),
                      visible: r.width > 0 && r.height > 0,
                    };
                  })
                  .filter(item => item.visible)
                  .filter(item =>
                    item.text.includes('审批') ||
                    item.text.includes('验收') ||
                    item.text.includes('通过') ||
                    item.text.includes('操作') ||
                    item.text.includes('详情') ||
                    item.aria ||
                    item.title
                  );
                return {
                  url: location.href,
                  text: document.body.innerText,
                  nodes,
                  html: document.body.innerHTML,
                };
            }"""
        )
        (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()
