from __future__ import annotations

import os
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


load_dotenv()

WZG_CONSOLE_URL = "https://test-merchant-lianlianyun.lianlianwz.com/productConsole?productCode=P20251204180120231330"
OUT_DIR = Path("runtime/push_probe")


def dump(page, name: str) -> None:
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    name = safe_name(name)
    page.wait_for_timeout(1500)
    text = page.locator("body").inner_text(timeout=5000)
    (OUT_DIR / f"{name}.txt").write_text(f"URL: {page.url}\n\n{text}", encoding="utf-8")
    page.screenshot(path=str(OUT_DIR / f"{name}.png"), full_page=True)
    print(f"[{name}] {page.url}\n{text[:2500]}")


def click_sidebar_text(page, text: str, right_edge: bool = False) -> bool:
    box = page.evaluate(
        """({ text, rightEdge }) => {
            const nodes = Array.from(document.querySelectorAll('taro-view-core, div, span'));
            const rows = nodes
              .map(el => ({ el, text: (el.innerText || el.textContent || '').trim(), r: el.getBoundingClientRect() }))
              .filter(item => item.r.x >= 0 && item.r.x < 240 && item.r.y > 40)
              .filter(item => item.r.width > 20 && item.r.width < 240 && item.r.height > 14)
              .filter(item => item.text === text || item.text.split(/\\s+/).includes(text) || item.text.includes(text))
              .sort((a, b) => {
                if (a.text === text && b.text !== text) return -1;
                if (b.text === text && a.text !== text) return 1;
                return (a.r.width * a.r.height) - (b.r.width * b.r.height);
              });
            const target = rows[0];
            if (!target) return null;
            return { x: target.r.x, y: target.r.y, width: target.r.width, height: target.r.height, text: target.text };
        }""",
        {"text": text, "rightEdge": right_edge},
    )
    print(f"[click {text}] {box}")
    if not box:
        return False
    x = box["x"] + box["width"] - 16 if right_edge else box["x"] + box["width"] / 2
    page.mouse.click(x, box["y"] + box["height"] / 2)
    page.wait_for_load_state("domcontentloaded")
    page.wait_for_timeout(1800)
    return True


def dump_menu_candidates(page, name: str) -> None:
    items = page.evaluate(
        """() => Array.from(document.querySelectorAll('taro-view-core, div, span'))
            .map(el => ({ text: (el.innerText || el.textContent || '').trim(), r: el.getBoundingClientRect() }))
            .filter(item => item.text && item.r.x >= 0 && item.r.x < 260 && item.r.y > 40)
            .filter(item => item.r.width > 20 && item.r.height > 10)
            .map(item => ({ text: item.text, x: item.r.x, y: item.r.y, w: item.r.width, h: item.r.height }))
        """
    )
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    name = safe_name(name)
    (OUT_DIR / f"{name}_menu.json").write_text(str(items), encoding="utf-8")
    for item in items[:120]:
        print(item)


def safe_name(name: str) -> str:
    return name.replace("/", "_").replace("\\", "_").replace(":", "_")


def main() -> None:
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=120)
        context = browser.new_context(viewport={"width": 1440, "height": 900})
        page = context.new_page()
        auth_page = TenantAuthPage(page, os.getenv("TENANT_HOME_URL", "https://test-lianlianyun.lianlianwz.com/home"))
        auth_page.login_main_account(
            os.getenv("E2E_WANZHANGGUI_TENANT_PHONE", "15555555555"),
            os.getenv("E2E_WANZHANGGUI_TENANT_PASSWORD", "wss123456"),
        )
        page.goto(WZG_CONSOLE_URL, wait_until="domcontentloaded")
        page.wait_for_timeout(3000)
        dump(page, "wzg_console")
        dump_menu_candidates(page, "wzg_console")

        for menu in ["履约工作室/平台", "商家管理", "丸掌柜自营收单应用", "工作台"]:
            if click_sidebar_text(page, menu, right_edge=True):
                dump(page, f"after_{menu}")
                dump_menu_candidates(page, f"after_{menu}")

        browser.close()


if __name__ == "__main__":
    main()
