from __future__ import annotations

from pathlib import Path

from playwright.sync_api import sync_playwright


def visible_text(page) -> str:
    return page.locator("body").inner_text(timeout=10000)


def main() -> None:
    Path("reports").mkdir(exist_ok=True)
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        page = browser.new_page()
        page.goto("https://test-saas-adminui.lianlianwz.com/pages/login/index", wait_until="domcontentloaded")
        page.wait_for_timeout(1500)
        page.locator("input[type='text']").first.fill("wangss")
        page.locator("input[type='password']").first.fill("123456")
        page.get_by_text("登录", exact=False).first.click()
        page.wait_for_load_state("domcontentloaded")
        page.wait_for_timeout(4000)

        for menu in ["商户管理", "开发者管理", "产品管理", "saas用户管理", "系统管理", "应用管理"]:
            print("\n==== MENU", menu, "====")
            page.get_by_text(menu, exact=True).first.click()
            page.wait_for_timeout(1000)
            text = visible_text(page)
            print(text[:8000])

        keywords = ["开通", "申请", "审核", "产品", "应用", "订阅", "商户应用", "解决方案"]
        print("\n==== KEYWORDS ====")
        for keyword in keywords:
            hits = page.evaluate(
                """keyword => Array.from(document.querySelectorAll('li,span,div,taro-view-core'))
                    .map((el, i) => {
                        const r = el.getBoundingClientRect();
                        return {
                            i,
                            text: (el.innerText || el.textContent || '').trim(),
                            cls: String(el.className),
                            x: Math.round(r.x),
                            y: Math.round(r.y),
                            w: Math.round(r.width),
                            h: Math.round(r.height),
                            visible: !!(r.width && r.height)
                        };
                    })
                    .filter(x => x.visible && x.text.includes(keyword))
                    .slice(0, 80)""",
                keyword,
            )
            print("KEYWORD", keyword)
            for hit in hits:
                print(hit)

        page.screenshot(path="reports/admin-all-menus-probe.png", full_page=True)
        browser.close()


if __name__ == "__main__":
    main()
