"""直接测试页面并获取错误详情"""
import re
import json
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()

    # 登录教师账号
    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_load_state("networkidle", timeout=20000)
    page.wait_for_timeout(2000)
    print(f"登录后 URL: {page.url}")

    # 访问备课列表页并捕获错误响应体
    print("\n>>> 访问 /teacher/lesson-plans 并捕获错误...")

    # 监听页面错误
    page_errors = []
    def on_pageerror(err):
        page_errors.append(str(err))
        print(f"  [PAGE_ERROR] {err}")

    page.on("pageerror", on_pageerror)

    # 监听控制台
    console_msgs = []
    def on_console(msg):
        console_msgs.append(f"[{msg.type}] {msg.text}")
        if msg.type in ("error", "warning"):
            print(f"  [CONSOLE_{msg.type.upper()}] {msg.text}")

    page.on("console", on_console)

    try:
        response = page.goto(f"{BASE_URL}/teacher/lesson-plans", timeout=30000)
        print(f"HTTP 状态: {response.status if response else 'None'}")

        # 获取响应体
        if response and response.status >= 400:
            body = response.text()
            print(f"\n响应体前 2000 字符:")
            print(body[:2000])
        else:
            # 等待页面加载
            try:
                page.wait_for_load_state("domcontentloaded", timeout=10000)
            except:
                pass
            page.wait_for_timeout(2000)

            # 检查页面内容
            body_text = page.locator("body").text_content() or ""
            print(f"\n页面内容长度: {len(body_text)}")

            # 检查是否有 Next.js 错误页面
            if "Application error" in body_text or "Internal Server Error" in body_text:
                print("\n⚠️ 检测到应用错误")
                # 获取完整的 HTML
                html = page.content()
                # 找到错误信息
                error_matches = re.findall(r'(?:Application error|Internal Server Error|Error:)[^<]{0,1000}', html)
                for match in error_matches[:5]:
                    print(f"错误: {match}")

            page.screenshot(path="webtest/screenshots/lesson-preparation/diag3_list.png", full_page=True)

    except Exception as e:
        print(f"❌ 访问失败: {e}")

    print("\n>>> 页面错误:")
    for err in page_errors:
        print(f"  {err}")

    print("\n>>> 控制台错误/警告:")
    for msg in console_msgs:
        if msg.startswith("[error]") or msg.startswith("[warning]"):
            print(f"  {msg}")

    browser.close()
