from __future__ import annotations

import os
from pathlib import Path

from dotenv import load_dotenv
from playwright.sync_api import sync_playwright

from probe_solution_console_entry import login_and_select_main


load_dotenv()

ENTERPRISE_CONSOLE_URL = "https://test-merchant-lianlianyun.lianlianwz.com/productConsole?productCode=P20250421171352724060"


def dump(page, label: str) -> None:
    out = Path("runtime/auth_probe")
    out.mkdir(parents=True, exist_ok=True)
    text = page.locator("body").inner_text(timeout=5000)
    (out / f"{label}.txt").write_text(f"URL: {page.url}\n\n{text}", encoding="utf-8")
    page.screenshot(path=str(out / f"{label}.png"), full_page=True)
    print(f"[{label}] {page.url}\n{text[:2500]}\n{'-' * 80}")


def close_modal_if_any(page) -> None:
    for text in ["×", "取消", "关闭"]:
        try:
            page.get_by_text(text, exact=True).last.click(timeout=800)
            page.wait_for_timeout(500)
            return
        except Exception:
            pass


def click_sidebar_row_right(page, text: str) -> bool:
    box = page.evaluate(
        """text => {
            const nodes = Array.from(document.querySelectorAll('taro-view-core, div, span'));
            const rows = nodes
              .map(el => ({ text: (el.innerText || el.textContent || '').trim(), r: el.getBoundingClientRect() }))
              .filter(item => item.r.x >= 0 && item.r.x < 210 && item.r.y > 40)
              .filter(item => item.r.width > 70 && item.r.width < 210 && item.r.height > 24)
              .filter(item => item.text === text || item.text.split(/\\s+/).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,
    )
    print(f"[sidebar box {text}] {box}")
    if not box:
        return False
    page.mouse.click(box["x"] + box["width"] - 16, box["y"] + box["height"] / 2)
    page.wait_for_load_state("domcontentloaded")
    page.wait_for_timeout(1200)
    return True


def click_sidebar_text(page, text: str) -> bool:
    box = page.evaluate(
        """text => {
            const nodes = Array.from(document.querySelectorAll('taro-view-core, div, span'));
            const items = nodes
              .map(el => ({ text: (el.innerText || el.textContent || '').trim(), r: el.getBoundingClientRect() }))
              .filter(item => item.r.x >= 0 && item.r.x < 210 && item.r.y > 40 && item.r.width > 20 && item.r.height > 14)
              .filter(item => item.text === text || item.text.includes(text))
              .sort((a, b) => (a.r.width * a.r.height) - (b.r.width * b.r.height));
            const target = items[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,
    )
    print(f"[sidebar text {text}] {box}")
    if not box:
        return False
    page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
    page.wait_for_load_state("domcontentloaded")
    page.wait_for_timeout(1500)
    return True


def print_sidebar_items(page) -> None:
    items = page.evaluate(
        """() => Array.from(document.querySelectorAll('taro-view-core, div, span'))
          .map(el => ({ text: (el.innerText || el.textContent || '').trim(), r: el.getBoundingClientRect(), cls: String(el.className) }))
          .filter(item => item.text && item.r.x < 230 && item.r.y > 40 && item.r.height > 10)
          .slice(0, 120)
          .map(item => `${Math.round(item.r.x)},${Math.round(item.r.y)},${Math.round(item.r.width)}x${Math.round(item.r.height)} ${item.text} | ${item.cls}`)"""
    )
    print("[sidebar items]")
    for item in items:
        print(item)


def probe(label: str, phone: str, password: str) -> None:
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=100)
        context = browser.new_context(viewport={"width": 1440, "height": 900})
        page = context.new_page()
        login_and_select_main(page, phone, password)
        page.goto(ENTERPRISE_CONSOLE_URL, wait_until="domcontentloaded")
        page.wait_for_timeout(3000)
        dump(page, f"{label}_enterprise_start")
        print_sidebar_items(page)
        close_modal_if_any(page)
        for menu in ["企业", "企微管理"]:
            if click_sidebar_row_right(page, menu):
                dump(page, f"{label}_expand_{menu}")
                print_sidebar_items(page)
        for menu in ["授权管理", "授权密钥", "我的授权", "管理授权"]:
            if click_sidebar_text(page, menu):
                dump(page, f"{label}_{menu}")
                print_sidebar_items(page)
        browser.close()


def main() -> None:
    probe(
        "wanyouji",
        os.getenv("E2E_CERTIFIED_TENANT_PHONE", "19361091624"),
        os.getenv("E2E_CERTIFIED_TENANT_PASSWORD", "test123456"),
    )
    probe(
        "wanzhanggui",
        os.getenv("E2E_WANZHANGGUI_TENANT_PHONE", "15555555555"),
        os.getenv("E2E_WANZHANGGUI_TENANT_PASSWORD", "wss123456"),
    )


if __name__ == "__main__":
    main()
