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

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from e2e.conftest import settings as settings_fixture
from e2e.pages.wanzhanggui_order_page import WanyoujiFulfillmentPage
from e2e.pages.wanzhanggui_push_page import WANZHANGGUI_CONSOLE_URL


def dump_overlay(frame) -> dict:
    return frame.evaluate(
        """() => {
            const roots = Array.from(document.querySelectorAll('.ant-modal, .ant-drawer'))
              .filter(el => {
                const r = el.getBoundingClientRect();
                return r.width > 0 && r.height > 0;
              });
            const root = roots[roots.length - 1] || document;
            const info = el => {
              const r = el.getBoundingClientRect();
              let label = '';
              for (let node = el.parentElement; node && node !== root; node = node.parentElement) {
                const text = (node.innerText || node.textContent || '').replace(/\\s+/g, ' ').trim();
                if (text && text.length < 140) {
                  label = text;
                  break;
                }
              }
              return {
                tag: el.tagName,
                placeholder: el.getAttribute('placeholder') || '',
                value: el.value || '',
                type: el.getAttribute('type') || '',
                disabled: Boolean(el.disabled),
                readOnly: Boolean(el.readOnly),
                label,
                rect: { x: r.x, y: r.y, w: r.width, h: r.height },
              };
            };
            return {
              url: location.href,
              text: (root.innerText || root.textContent || '').replace(/\\s+/g, '\\n').trim(),
              inputs: Array.from(root.querySelectorAll('input, textarea')).map(info).filter(item => item.rect.w > 0 && item.rect.h > 0),
              selects: Array.from(root.querySelectorAll('.ant-select, .ant-select-selector, [role="combobox"]'))
                .map(el => {
                  const r = el.getBoundingClientRect();
                  return {
                    text: (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim(),
                    cls: String(el.className || ''),
                    rect: { x: r.x, y: r.y, w: r.width, h: r.height },
                  };
                }).filter(item => item.rect.w > 0 && item.rect.h > 0),
              buttons: Array.from(root.querySelectorAll('button, a, [role="button"]'))
                .map(el => {
                  const r = el.getBoundingClientRect();
                  return {
                    text: (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim(),
                    disabled: Boolean(el.disabled),
                    rect: { x: r.x, y: r.y, w: r.width, h: r.height },
                  };
                }).filter(item => item.rect.w > 0 && item.rect.h > 0),
            };
        }"""
    )


def main() -> None:
    sys.stdout.reconfigure(encoding="utf-8")
    cfg = settings_fixture.__wrapped__()
    phone = os.getenv("E2E_WANZHANGGUI_TENANT_PHONE", cfg.wanzhanggui_tenant_phone)
    password = os.getenv("E2E_WANZHANGGUI_TENANT_PASSWORD", cfg.wanzhanggui_tenant_password)
    out = Path("runtime/probes/wanzhanggui_payment_config_modal") / datetime.now().strftime("%Y%m%d-%H%M%S")
    out.mkdir(parents=True, exist_ok=True)

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=120)
        context = browser.new_context(viewport={"width": cfg.viewport_width, "height": cfg.viewport_height})
        page = context.new_page()
        wzg = WanyoujiFulfillmentPage(page, cfg.tenant_home_url)
        wzg.login_main_account(phone, password)
        page.goto(WANZHANGGUI_CONSOLE_URL, wait_until="domcontentloaded")
        wzg.wait_for_enterprise_console_shell()
        wzg.click_sidebar_text_scrolled("结算中心", right_edge=True)
        page.wait_for_timeout(1200)
        wzg.click_sidebar_text_scrolled("结算账单-丸掌柜")
        page.wait_for_timeout(3500)
        frame = next(
            frame
            for frame in page.frames
            if frame != page.main_frame and "线上打款配置" in frame.locator("body").inner_text(timeout=3000)
        )
        (out / "before.txt").write_text(frame.locator("body").inner_text(timeout=5000), encoding="utf-8")
        clicked = frame.get_by_text("线上打款配置", exact=True).first.click(force=True, timeout=3000)
        page.wait_for_timeout(2000)
        (out / "clicked.txt").write_text(str(clicked), encoding="utf-8")
        (out / "modal.json").write_text(json.dumps(dump_overlay(frame), ensure_ascii=False, indent=2), encoding="utf-8")
        page.screenshot(path=str(out / "page.png"), full_page=True)
        context.close()
        browser.close()
    print(out)


if __name__ == "__main__":
    main()
