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", "209ac64d9e2b4a609d9a434e7b0c6898")
    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_WANZHANGGUI_TENANT_PHONE", "15555555555"),
            os.getenv("E2E_WANZHANGGUI_TENANT_PASSWORD", "wss123456"),
        )
        auth_page.open_enterprise_auth_menu("我的授权")
        frame = auth_page.my_auth_frame()
        auth_page.click_row_action(frame, auth_key, "查看")
        page.wait_for_timeout(2500)
        text = frame.locator("body").inner_text(timeout=5000)
        print(text[:3000])
        states = frame.evaluate(
            """() => Array.from(document.querySelectorAll('label, .ant-checkbox-wrapper, .ant-tree-checkbox, .ant-checkbox'))
              .map(el => ({
                text: (el.innerText || el.textContent || '').trim(),
                cls: String(el.className),
                checked: !!el.querySelector('input[type="checkbox"]')?.checked,
                inputChecked: el.matches('input[type="checkbox"]') ? el.checked : null,
                rect: (() => { const r = el.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height}; })()
              }))
              .filter(item => item.text.includes('创建订单') || item.text.includes('订单') || item.cls.includes('checked'))
            """
        )
        print(states)
        page.screenshot(path="runtime/auth_probe/wanzhanggui_auth_detail.png", full_page=True)
        browser.close()


if __name__ == "__main__":
    main()
