from __future__ import annotations

import sys
from pathlib import Path

from dotenv import load_dotenv
from playwright.sync_api import sync_playwright

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

from e2e.pages.tenant_auth_page import TenantAuthPage


WANYOUJI_CONSOLE_URL = "https://test-merchant-lianlianyun.lianlianwz.com/productConsole?productCode=P20250814095939369041"


def dump(page, name: str) -> None:
    out_dir = Path("runtime/order_probe/wanyouji")
    out_dir.mkdir(parents=True, exist_ok=True)
    (out_dir / f"{name}.txt").write_text(page.locator("body").inner_text(timeout=5000), encoding="utf-8")
    (out_dir / f"{name}_frames.txt").write_text("\n".join(frame.url for frame in page.frames), encoding="utf-8")
    page.screenshot(path=out_dir / f"{name}.png", full_page=True)


def dump_frame(frame, name: str) -> None:
    out_dir = Path("runtime/order_probe/wanyouji")
    out_dir.mkdir(parents=True, exist_ok=True)
    (out_dir / f"{name}.txt").write_text(frame.locator("body").inner_text(timeout=5000), encoding="utf-8")
    fields = frame.evaluate(
        """() => Array.from(document.querySelectorAll('input, textarea, .ant-select-selector, button, a'))
          .map((el, index) => ({ index, text: (el.innerText || el.textContent || '').trim(), placeholder: el.getAttribute('placeholder') || '', r: el.getBoundingClientRect(), tag: el.tagName, cls: String(el.className || '') }))
          .filter(item => item.r.width > 0 && item.r.height > 0)
          .map(item => `${item.index} | ${item.tag} | ${Math.round(item.r.x)},${Math.round(item.r.y)},${Math.round(item.r.width)},${Math.round(item.r.height)} | ${item.cls} | ${item.placeholder} | ${item.text}`)
          .join('\\n')"""
    )
    (out_dir / f"{name}_nodes.txt").write_text(fields, encoding="utf-8")
    try:
        frame.locator("body").screenshot(path=out_dir / f"{name}.png", timeout=5000)
    except Exception:
        pass


def main() -> None:
    load_dotenv()
    phone = "19038951373"
    password = "test123456"
    tenant_home_url = "https://test-lianlianyun.lianlianwz.com/home"
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=False, slow_mo=250)
        context = browser.new_context(viewport={"width": 1440, "height": 900})
        page = context.new_page()
        tenant_page = TenantAuthPage(page, tenant_home_url)
        tenant_page.login_main_account(phone, password)
        page.goto(WANYOUJI_CONSOLE_URL, wait_until="domcontentloaded")
        tenant_page.wait_for_enterprise_console_shell()
        dump(page, "01_丸友集控制台")

        for index, menu in enumerate(["工作室履约应用", "抢单大厅"]):
            tenant_page.click_sidebar_text(menu, right_edge=index == 0)
            page.wait_for_timeout(2000)
            dump(page, f"02_{index + 1}_点击_{menu}")

        for frame in page.frames:
            if frame.url != page.url and "about:blank" not in frame.url:
                dump_frame(frame, f"03_iframe_{len(frame.url)}")

        page.wait_for_timeout(5000)
        context.close()
        browser.close()


if __name__ == "__main__":
    main()
