"""诊断登录流程"""
import re
from playwright.sync_api import sync_playwright

BASE_URL = "http://localhost:3000"

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    context = browser.new_context()
    page = context.new_page()

    # 监听控制台
    page.on("console", lambda msg: print(f"[console.{msg.type}] {msg.text}"))
    page.on("pageerror", lambda err: print(f"[pageerror] {err}"))

    print(">>> 访问登录页...")
    page.goto(f"{BASE_URL}/login", timeout=30000)
    page.wait_for_load_state("networkidle", timeout=15000)
    page.wait_for_timeout(1000)

    print(f"\n登录页 URL: {page.url}")
    print(f"登录页标题: {page.title()}")

    # 查看所有按钮
    buttons = page.locator('button').all()
    print(f"\n=== 页面按钮 ({len(buttons)}) ===")
    for i, btn in enumerate(buttons):
        try:
            text = btn.text_content() or ""
            visible = btn.is_visible()
            print(f"  [{i}] text='{text.strip()}' visible={visible}")
        except Exception as e:
            print(f"  [{i}] error: {e}")

    # 查看所有输入框
    inputs = page.locator('input').all()
    print(f"\n=== 页面输入框 ({len(inputs)}) ===")
    for i, inp in enumerate(inputs):
        try:
            name = inp.get_attribute('name') or ''
            type_ = inp.get_attribute('type') or ''
            placeholder = inp.get_attribute('placeholder') or ''
            print(f"  [{i}] name='{name}' type='{type_}' placeholder='{placeholder}'")
        except Exception as e:
            print(f"  [{i}] error: {e}")

    # 查看所有链接
    links = page.locator('a').all()
    print(f"\n=== 页面链接 ({len(links)}) ===")
    for i, link in enumerate(links[:20]):
        try:
            text = link.text_content() or ""
            href = link.get_attribute('href') or ''
            print(f"  [{i}] text='{text.strip()}' href='{href}'")
        except Exception as e:
            print(f"  [{i}] error: {e}")

    # 截图
    page.screenshot(path="webtest/diag5_login.png", full_page=True)
    print("\n截图已保存: webtest/diag5_login.png")

    browser.close()
