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
from e2e.pages.wanzhanggui_push_page import WANZHANGGUI_CONSOLE_URL


def dump(page, name: str) -> None:
    out_dir = Path("runtime/order_probe")
    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")
    nodes = page.evaluate(
        """() => Array.from(document.querySelectorAll('taro-view-core, div, span, a'))
          .map((el, index) => ({ index, text: (el.innerText || el.textContent || '').trim(), r: el.getBoundingClientRect() }))
          .filter(item => item.text && item.r.width > 0 && item.r.height > 0 && item.r.x >= 0 && item.r.x < 260)
          .map(item => `${item.index} | ${Math.round(item.r.x)},${Math.round(item.r.y)},${Math.round(item.r.width)},${Math.round(item.r.height)} | ${item.text}`)
          .join('\\n')"""
    )
    (out_dir / f"{name}_nodes.txt").write_text(nodes, encoding="utf-8")
    frames = "\n".join(frame.url for frame in page.frames)
    (out_dir / f"{name}_frames.txt").write_text(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")
    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")
    buttons = frame.evaluate(
        """() => Array.from(document.querySelectorAll('button, a'))
          .map((el, index) => ({ index, text: (el.innerText || el.textContent || '').trim(), r: el.getBoundingClientRect(), cls: String(el.className || '') }))
          .filter(item => item.text && item.r.width > 0 && item.r.height > 0)
          .map(item => `${item.index} | ${Math.round(item.r.x)},${Math.round(item.r.y)},${Math.round(item.r.width)},${Math.round(item.r.height)} | ${item.cls} | ${item.text}`)
          .join('\\n')"""
    )
    (out_dir / f"{name}_buttons.txt").write_text(buttons, encoding="utf-8")
    fields = frame.evaluate(
        """() => Array.from(document.querySelectorAll('input, textarea, .ant-select-selector'))
          .map((el, index) => ({ index, text: (el.innerText || el.textContent || '').trim(), placeholder: el.getAttribute('placeholder') || '', r: el.getBoundingClientRect(), cls: String(el.className || '') }))
          .filter(item => item.r.width > 0 && item.r.height > 0)
          .map(item => `${item.index} | ${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}_fields.txt").write_text(fields, encoding="utf-8")
    frame.locator("body").screenshot(path=out_dir / f"{name}.png")


def main() -> None:
    load_dotenv()
    phone = "19147509308"
    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(WANZHANGGUI_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(1500)
            dump(page, f"02_{index + 1}_点击_{menu}")

        for frame in page.frames:
            if "test-order-pc" in frame.url or "orderManage" in frame.url:
                dump_frame(frame, "03_订单管理_iframe")
                break

        for button_text in ["手工录单", "新增订单", "添加订单", "录单", "新 增", "新增"]:
            order_frame = next(
                (frame for frame in page.frames if "test-order-pc" in frame.url or "orderManage" in frame.url),
                None,
            )
            if not order_frame:
                continue
            clicked = order_frame.evaluate(
                """text => {
                    const buttons = Array.from(document.querySelectorAll('button, a'));
                    const target = buttons.find(el => (el.innerText || el.textContent || '').trim().includes(text));
                    if (!target) return false;
                    target.click();
                    return true;
                }""",
                button_text,
            )
            if clicked:
                page.wait_for_timeout(2500)
                dump(page, f"04_点击_{button_text}")
                for frame in page.frames:
                    if "test-order-pc" in frame.url or "orderManage" in frame.url:
                        dump_frame(frame, f"05_点击_{button_text}_iframe")
                break

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


if __name__ == "__main__":
    main()
