"""诊断登录流程 - 详细版"""
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()

    # 监听响应
    def on_response(response):
        url = response.url
        if '/api/auth' in url or '/login' in url or '/teacher' in url:
            print(f"[response] {response.status} {url[:100]}")

    page.on("response", on_response)
    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("\n>>> 填写表单...")
    page.locator('input[name="email"]').fill("t_chinese_1@xiaoxue.edu.cn")
    page.locator('input[name="password"]').fill("123456")

    print(">>> 点击登录按钮...")
    page.get_by_role("button", name=re.compile(r"Sign In with Email", re.I)).click()

    # 等待跳转
    try:
        page.wait_for_url("**/teacher/**", timeout=15000)
        print(f"✓ 跳转成功: {page.url}")
    except Exception:
        print(f"✗ 未跳转到 /teacher/*，当前 URL: {page.url}")

    page.wait_for_timeout(3000)
    print(f"最终 URL: {page.url}")

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

    # 检查页面内容
    body_text = page.locator('body').text_content() or ""
    print(f"\n页面文本前 500 字符: {body_text[:500]}")

    browser.close()
