"""直接访问页面获取服务端错误"""
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[:1000]}"))
    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.locator('input[name="email"]').fill("t_chinese_1@xiaoxue.edu.cn")
    page.locator('input[name="password"]').fill("123456")
    page.get_by_role("button", name=re.compile(r"Sign In with Email", re.I)).click()
    page.wait_for_timeout(5000)
    print(f"登录后 URL: {page.url}")

    # 访问备课列表页
    print("\n>>> 访问 /teacher/lesson-plans...")
    response = page.goto(f"{BASE_URL}/teacher/lesson-plans", timeout=30000, wait_until="domcontentloaded")
    print(f"HTTP 状态: {response.status if response else 'None'}")
    page.wait_for_timeout(5000)

    # 检查页面是否显示错误
    body_text = page.locator('body').text_content() or ""
    print(f"\n页面文本前 1000 字符:\n{body_text[:1000]}")

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

    browser.close()
