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 select_option(frame, select_index: int, option_text: str) -> None:
    frame.locator(".ant-modal .ant-select-selector").nth(select_index).click()
    frame.page.wait_for_timeout(800)
    frame.locator(".ant-select-dropdown:not(.ant-select-dropdown-hidden) .ant-select-item-option-content").filter(
        has_text=option_text
    ).first.click()
    frame.page.wait_for_timeout(800)


def table_rows(frame) -> list[str]:
    rows = []
    loc = frame.locator(".ant-table-tbody tr")
    for index in range(loc.count()):
        text = loc.nth(index).inner_text(timeout=1000).strip()
        if text and "No data" not in text:
            rows.append(text)
    return rows


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)
        frame = auth_frame(page)
        print("[before rows]", table_rows(frame))
        if not click_button_in_frames(page, "生成授权密钥"):
            raise AssertionError("未点击到生成授权密钥按钮")
        select_option(frame, 0, "丸友集")
        click_button_in_frames(page, "生成密钥")
        page.wait_for_timeout(3000)
        print("[after text]", frame.locator("body").inner_text(timeout=5000)[:2500])
        print("[after rows]", table_rows(frame))
        browser.close()


if __name__ == "__main__":
    main()
