from __future__ import annotations

import os

from dotenv import load_dotenv
from playwright.sync_api import sync_playwright

from probe_auth_key_form import goto_auth_key
from probe_solution_console_entry import login_and_select_main


load_dotenv()


def main() -> None:
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=100)
        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)
        page.wait_for_timeout(3000)
        print(f"[main] {page.url}")
        for index, frame in enumerate(page.frames):
            try:
                text = frame.locator("body").inner_text(timeout=3000)
            except Exception as exc:
                text = f"<no body: {exc}>"
            print(f"\n[frame {index}] name={frame.name!r} url={frame.url}")
            print(text[:2000])
            try:
                buttons = frame.locator("button").evaluate_all(
                    """els => els.map(el => ({
                        text: (el.innerText || el.textContent || '').trim(),
                        disabled: !!el.disabled,
                        rect: (() => { const r = el.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height}; })()
                    }))"""
                )
                print("[buttons]", buttons)
            except Exception as exc:
                print("[buttons error]", exc)
        browser.close()


if __name__ == "__main__":
    main()
