from __future__ import annotations

import os

from dotenv import load_dotenv
from playwright.sync_api import sync_playwright

from probe_auth_key_form import auth_frame, click_button_in_frames, goto_auth_key
from probe_solution_console_entry import login_and_select_main


load_dotenv()


def click_select_and_print(frame, index: int) -> None:
    selects = frame.locator(".ant-modal .ant-select-selector")
    selects.nth(index).click()
    frame.page.wait_for_timeout(1200)
    options = frame.locator(".ant-select-dropdown:not(.ant-select-dropdown-hidden) .ant-select-item-option-content")
    values = []
    for i in range(options.count()):
        try:
            values.append(options.nth(i).inner_text(timeout=1000).strip())
        except Exception:
            pass
    print(f"[modal select {index}] {values}")
    frame.page.keyboard.press("Escape")
    frame.page.wait_for_timeout(500)


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)
        if not click_button_in_frames(page, "生成授权密钥"):
            raise AssertionError("未点击到生成授权密钥按钮")
        frame = auth_frame(page)
        for index in range(frame.locator(".ant-modal .ant-select-selector").count()):
            click_select_and_print(frame, index)
        browser.close()


if __name__ == "__main__":
    main()
