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


load_dotenv()

AUTH_KEY = os.getenv("E2E_AUTH_KEY", "209ac64d9e2b4a609d9a434e7b0c6898")


def my_auth_frame(page):
    for frame in page.frames:
        if "/myAuth" in frame.url:
            return frame
    return page


def goto_my_auth(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(1800)


def click_button(frame, text: str) -> bool:
    try:
        return frame.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:
        return False


def print_state(frame, label: str) -> None:
    state = frame.evaluate(
        """() => ({
            text: document.body.innerText,
            inputs: Array.from(document.querySelectorAll('input, textarea')).map(el => ({
                placeholder: el.getAttribute('placeholder') || '',
                value: el.value || '',
                type: el.getAttribute('type') || '',
                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(),
                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-selector')).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(f"[{label}] text:\n{state['text'][:2500]}")
    print("[inputs]", state["inputs"])
    print("[buttons]", state["buttons"])
    print("[selects]", state["selects"])


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_WANZHANGGUI_TENANT_PHONE", "15555555555"),
            os.getenv("E2E_WANZHANGGUI_TENANT_PASSWORD", "wss123456"),
        )
        goto_my_auth(page)
        dump(page, "my_auth_before_activate")
        frame = my_auth_frame(page)
        print_state(frame, "my_auth_page")
        for text in ["激活密钥", "添加授权", "新增授权", "绑定授权", "激活"]:
            if click_button(frame, text):
                page.wait_for_timeout(1200)
                print(f"[clicked] {text}")
                break
        print_state(frame, "my_auth_modal")
        browser.close()


if __name__ == "__main__":
    main()
