from __future__ import annotations

import os
import sys
from pathlib import Path

from dotenv import load_dotenv
from playwright.sync_api import sync_playwright

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from e2e.pages.tenant_auth_page import TenantAuthPage


load_dotenv()


def main() -> None:
    auth_key = os.getenv("E2E_AUTH_KEY", "d59951e738c047c1baca7dd92da02704")
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=150)
        context = browser.new_context(viewport={"width": 1440, "height": 900})
        page = context.new_page()
        auth_page = TenantAuthPage(page, os.getenv("TENANT_HOME_URL", "https://test-lianlianyun.lianlianwz.com/home"))
        auth_page.login_main_account(
            os.getenv("E2E_CERTIFIED_TENANT_PHONE", "19159770995"),
            os.getenv("E2E_CERTIFIED_TENANT_PASSWORD", "test123456"),
        )
        auth_page.open_enterprise_auth_menu("授权密钥")
        frame = auth_page.auth_key_frame()
        auth_page.click_row_action(frame, auth_key, "管理授权")
        page.wait_for_timeout(2500)
        print(frame.locator("body").inner_text(timeout=5000)[:3000])
        items = frame.evaluate(
            """() => Array.from(document.querySelectorAll(
                '.ant-checkbox-wrapper, .ant-tree-checkbox, .ant-checkbox, input[type="checkbox"]'
            )).map(el => ({
                tag: el.tagName,
                text: (el.innerText || el.textContent || '').trim(),
                cls: String(el.className),
                checked: el.matches('input') ? el.checked : Boolean(el.querySelector('input')?.checked),
                disabled: el.matches('input') ? el.disabled : Boolean(el.querySelector('input')?.disabled),
                row: ((el.closest('label, .ant-tree-treenode, .ant-form-item, .ant-row, div') || el).innerText || '').trim(),
                rect: (() => { const r = el.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height}; })()
            })).filter(item => item.rect.width && item.rect.height)"""
        )
        for item in items:
            print(item)
        page.screenshot(path="runtime/auth_probe/wanyouji_permission_tree.png", full_page=True)
        browser.close()


if __name__ == "__main__":
    main()
