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 TENANT_HOME_URL, login_and_select_main, click_solution_console


load_dotenv()


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[:2000]}\n{'-' * 80}")


def click_visible_text(page, text: str) -> bool:
    try:
        locator = page.get_by_text(text, exact=False).first
        locator.click(timeout=3000)
        page.wait_for_load_state("domcontentloaded")
        page.wait_for_timeout(1500)
        return True
    except Exception:
        return False


def click_left_menu_item(page, text: str) -> bool:
    box = page.evaluate(
        """text => {
            const nodes = Array.from(document.querySelectorAll('taro-view-core, div, span'));
            const candidates = nodes
              .map(el => ({ text: (el.innerText || el.textContent || '').trim(), r: el.getBoundingClientRect() }))
              .filter(item => item.text === text || item.text.includes(text))
              .filter(item => item.r.x < 220 && item.r.width > 20 && item.r.height > 16)
              .sort((a, b) => (a.r.width * a.r.height) - (b.r.width * b.r.height));
            const target = candidates[0];
            if (!target) return null;
            return { x: target.r.x, y: target.r.y, width: target.r.width, height: target.r.height };
        }""",
        text,
    )
    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 probe(solution: 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)
        click_solution_console(page, solution)
        page = context.pages[-1]
        dump(page, f"{solution}_console_start")
        if click_visible_text(page, "企业管理"):
            dump(page, f"{solution}_企业管理")
        for text in ["企业", "授权管理", "授权密钥", "我的授权", "管理授权"]:
            if click_left_menu_item(page, text) or click_visible_text(page, text):
                dump(page, f"{solution}_{text}")
        browser.close()


def main() -> None:
    probe(
        "丸友集",
        os.getenv("E2E_CERTIFIED_TENANT_PHONE", "19361091624"),
        os.getenv("E2E_CERTIFIED_TENANT_PASSWORD", "test123456"),
    )
    probe(
        "丸掌柜",
        os.getenv("E2E_WANZHANGGUI_TENANT_PHONE", "15555555555"),
        os.getenv("E2E_WANZHANGGUI_TENANT_PASSWORD", "wss123456"),
    )


if __name__ == "__main__":
    main()
