from __future__ import annotations

import os

from dotenv import load_dotenv
from playwright.sync_api import sync_playwright

from probe_enterprise_auth_menu import ENTERPRISE_CONSOLE_URL, click_sidebar_row_right, click_sidebar_text
from probe_solution_console_entry import login_and_select_main


load_dotenv()


def main() -> 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,
            os.getenv("E2E_WANZHANGGUI_TENANT_PHONE", "15555555555"),
            os.getenv("E2E_WANZHANGGUI_TENANT_PASSWORD", "wss123456"),
        )
        page.goto(ENTERPRISE_CONSOLE_URL, wait_until="domcontentloaded")
        page.wait_for_timeout(2500)
        click_sidebar_row_right(page, "企业")
        click_sidebar_text(page, "授权管理")
        click_sidebar_text(page, "我的授权")
        page.wait_for_timeout(3500)
        for index, frame in enumerate(page.frames):
            try:
                text = frame.locator("body").inner_text(timeout=3000)
            except Exception as exc:
                text = f"<no body: {exc}>"
            print(f"\n[frame {index}] url={frame.url}")
            print(text[:2500])
            try:
                buttons = frame.locator("button").evaluate_all(
                    """els => els.map(el => ({
                        text: (el.innerText || el.textContent || '').trim(),
                        rect: (() => { const r = el.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height}; })()
                    }))"""
                )
                print("[buttons]", buttons)
            except Exception as exc:
                print("[buttons error]", exc)
        browser.close()


if __name__ == "__main__":
    main()
