from __future__ import annotations

import os
from pathlib import Path

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, dump
from probe_solution_console_entry import login_and_select_main


load_dotenv()


def goto_auth_key(page) -> None:
    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(1500)


def auth_frame(page):
    for frame in page.frames:
        if "/secret" in frame.url or "/auth" in frame.url:
            return frame
    return page


def click_button_in_frames(page, text: str) -> bool:
    for target in [page, *page.frames]:
        try:
            clicked = target.evaluate(
                """text => {
                    const buttons = Array.from(document.querySelectorAll('button'));
                    const target = buttons.find(el => (el.innerText || el.textContent || '').includes(text));
                    if (!target) return false;
                    target.click();
                    return true;
                }""",
                text,
            )
        except Exception:
            clicked = False
        if clicked:
            page.wait_for_timeout(1500)
            return True
    return False


def print_form_state(page, label: str) -> None:
    target = auth_frame(page)
    out = Path("runtime/auth_probe")
    out.mkdir(parents=True, exist_ok=True)
    state = target.evaluate(
        """() => ({
            url: location.href,
            text: document.body.innerText,
            inputs: Array.from(document.querySelectorAll('input, textarea')).map(el => ({
                placeholder: el.getAttribute('placeholder') || '',
                value: el.value || '',
                type: el.getAttribute('type') || '',
                disabled: !!el.disabled,
                rect: (() => { const r = el.getBoundingClientRect(); return { x:r.x, y:r.y, width:r.width, height:r.height }; })()
            })),
            buttons: Array.from(document.querySelectorAll('button')).map(el => ({
                text: (el.innerText || el.textContent || '').trim(),
                disabled: !!el.disabled,
                rect: (() => { const r = el.getBoundingClientRect(); return { x:r.x, y:r.y, width:r.width, height:r.height }; })()
            })),
            selects: Array.from(document.querySelectorAll('.ant-select, [class*="select"]')).slice(0, 30).map(el => ({
                text: (el.innerText || el.textContent || '').trim(),
                cls: String(el.className),
                rect: (() => { const r = el.getBoundingClientRect(); return { x:r.x, y:r.y, width:r.width, height:r.height }; })()
            }))
        })"""
    )
    (out / f"{label}.json").write_text(str(state), encoding="utf-8")
    print(f"[{label}] text:\n{state['text'][:2500]}")
    print("[inputs]", state["inputs"])
    print("[buttons]", state["buttons"])
    print("[selects]", state["selects"][:10])


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()
        login_and_select_main(
            page,
            os.getenv("E2E_CERTIFIED_TENANT_PHONE", "19361091624"),
            os.getenv("E2E_CERTIFIED_TENANT_PASSWORD", "test123456"),
        )
        goto_auth_key(page)
        dump(page, "auth_key_before_generate")
        if not click_button_in_frames(page, "生成授权密钥"):
            raise AssertionError("未点击到生成授权密钥按钮")
        dump(page, "auth_key_generate_modal")
        print_form_state(page, "auth_key_generate_modal_state")
        browser.close()


if __name__ == "__main__":
    main()
