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 settings_fixture
from e2e.pages.wanzhanggui_order_page import WanzhangguiOrderPage


def visible_controls(frame) -> list[dict]:
    return frame.evaluate(
        """() => Array.from(document.querySelectorAll('button, a, [role="button"], span'))
          .map((el, index) => {
            const clickable = el.closest('button, a, [role="button"]') || el;
            const r = el.getBoundingClientRect();
            return {
              index,
              text: (el.innerText || el.textContent || '').trim(),
              tag: el.tagName,
              className: String(el.className || ''),
              disabled: Boolean(clickable.disabled),
              rect: { 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 && item.text)
          .slice(0, 300)"""
    )


def main() -> None:
    settings = settings_fixture.__wrapped__()
    main_order_no = os.getenv("E2E_S_FLOW_MAIN_ORDER_NO", "BO20260624221734190151").strip()
    source_order_no = os.getenv("E2E_S_FLOW_SOURCE_ORDER_NO", "E2EORDER0624221654").strip()
    order_title = os.getenv("E2E_S_FLOW_ORDER_TITLE", source_order_no).strip()
    phone = os.getenv("E2E_ORDER_WANZHANGGUI_PHONE", settings.wanzhanggui_tenant_phone).strip()
    password = os.getenv("E2E_ORDER_WANZHANGGUI_PASSWORD", settings.wanzhanggui_tenant_password).strip()

    out_dir = ROOT / "runtime" / "probes" / "s_flow_060_sub_aftersale_record"
    out_dir.mkdir(parents=True, exist_ok=True)

    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=False, slow_mo=80)
        page = browser.new_page(viewport={"width": settings.viewport_width, "height": settings.viewport_height})
        order_page = WanzhangguiOrderPage(page, settings.tenant_home_url, None)
        order_page.login_main_account(phone, password)

        frame = order_page.open_order_management()
        order_page.search_order_by_best_identity(
            frame,
            main_order_no=main_order_no,
            source_order_no=source_order_no,
            order_title=order_title,
        )
        before_list_text = frame.locator("body").inner_text(timeout=5000)
        opened = order_page.open_main_order_detail_from_list(
            frame,
            main_order_no=main_order_no,
            source_order_no=source_order_no,
            order_title=order_title,
        )
        detail_text = order_page.visible_modal_text(frame) or frame.locator("body").inner_text(timeout=5000)
        detail_controls = visible_controls(frame)

        clicked_record = order_page.click_sub_order_row_action_by_status(frame, ["售后中"], ["售后记录"])
        page.wait_for_timeout(1800)
        after_record_text = order_page.visible_modal_text(frame) or frame.locator("body").inner_text(timeout=5000)
        after_record_controls = visible_controls(frame)
        has_cancel = any(
            ("取消售后" in item["text"] or "撤销售后" in item["text"])
            for item in after_record_controls
        ) or "取消售后" in after_record_text or "撤销售后" in after_record_text

        snapshot = {
            "main_order_no": main_order_no,
            "source_order_no": source_order_no,
            "opened": opened,
            "before_list_contains": main_order_no in before_list_text or source_order_no in before_list_text,
            "clicked_record": clicked_record,
            "has_cancel_in_record": has_cancel,
            "detail_text": detail_text[:5000],
            "detail_controls": detail_controls,
            "after_record_text": after_record_text[:5000],
            "after_record_controls": after_record_controls,
        }
        (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()
