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", "484c847f4cca44eda0a8536e85beadca")
    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()
        print("[before]")
        print(frame.locator("body").inner_text(timeout=5000)[:2500])
        auth_page.click_frame_button(frame, "激活密钥")
        auth_page.select_modal_option(frame, 0, "丸掌柜")
        key_input = frame.locator(".ant-modal input[placeholder='请输入授权密钥']")
        key_input.fill(auth_key)
        print("[input value]", key_input.input_value(timeout=1000))
        print("[modal before verify]")
        print(frame.locator("body").inner_text(timeout=5000)[:3000])
        auth_page.click_frame_button(frame, "验证密钥")
        page.wait_for_timeout(3000)
        print("[after verify]")
        print(frame.locator("body").inner_text(timeout=5000)[:4000])
        inputs = frame.locator("input").evaluate_all(
            """els => els.map(el => ({
                placeholder: el.getAttribute('placeholder') || '',
                value: el.value || '',
                disabled: !!el.disabled,
                rect: (() => { const r = el.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height}; })()
            }))"""
        )
        print("[inputs]", inputs)
        page.screenshot(path="runtime/auth_probe/activate_specific_after_verify.png", full_page=True)
        browser.close()


if __name__ == "__main__":
    main()
