"""调试 admin 访问 /announcements 的 500 错误"""
from playwright.sync_api import sync_playwright
import re

BASE_URL = "http://localhost:3000"

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    context = browser.new_context(viewport={"width": 1440, "height": 900}, locale="zh-CN")
    page = context.new_page()

    # 收集控制台错误
    errors = []
    page_errors = []
    def on_console(msg):
        if msg.type == "error":
            errors.append(msg.text)
    def on_pageerror(err):
        page_errors.append(str(err))
    page.on("console", on_console)
    page.on("pageerror", on_pageerror)

    # 登录 admin
    page.goto(f"{BASE_URL}/login", timeout=30000)
    page.wait_for_load_state("networkidle", timeout=15000)
    page.locator('input[name="email"]').fill("admin@xiaoxue.edu.cn")
    page.locator('input[name="password"]').fill("123456")
    login_btn = page.get_by_role("button", name=re.compile(r"Sign In with Email", re.I))
    login_btn.click()
    page.wait_for_timeout(3000)
    page.wait_for_load_state("networkidle", timeout=15000)
    print(f"登录后 URL: {page.url}")

    # 访问 /announcements
    print("\n访问 /announcements...")
    response = page.goto(f"{BASE_URL}/announcements", timeout=30000)
    print(f"HTTP 状态: {response.status if response else 'None'}")
    page.wait_for_load_state("networkidle", timeout=15000)
    page.wait_for_timeout(2000)
    print(f"最终 URL: {page.url}")

    # 获取页面内容
    body = page.locator("body").text_content()
    print(f"\n页面内容 (前 2000 字符):")
    print(body[:2000] if body else "(空)")

    # 截图
    page.screenshot(path="tests/webapp/screenshots/announcements_messages/debug_announcements_admin.png", full_page=True)

    print(f"\n控制台错误 ({len(errors)} 条):")
    for e in errors[:10]:
        print(f"  - {e[:200]}")

    print(f"\n页面错误 ({len(page_errors)} 条):")
    for e in page_errors[:10]:
        print(f"  - {e[:300]}")

    browser.close()
