"""调试 teacher 发送消息"""
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()

    # 登录 teacher
    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")
    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}")

    # 访问撰写页面
    print("\n访问 /messages/compose...")
    page.goto(f"{BASE_URL}/messages/compose", timeout=30000)
    page.wait_for_load_state("networkidle", timeout=15000)
    page.wait_for_timeout(2000)

    # 检查页面内容
    body = page.locator("body").text_content()
    print(f"页面内容 (前 1000 字符):")
    print(body[:1000] if body else "(空)")

    # 检查收件人选择器
    print("\n检查收件人选择器...")
    select_trigger = page.locator('button[role="combobox"]').first
    print(f"button[role=combobox] count: {page.locator('button[role=\"combobox\"]').count()}")
    print(f"[role=combobox] count: {page.locator('[role=\"combobox\"]').count()}")

    # 检查所有 button 元素
    buttons = page.locator("button").all()
    print(f"\n页面按钮数: {len(buttons)}")
    for i, btn in enumerate(buttons[:10]):
        try:
            text = btn.text_content()
            role = btn.get_attribute("role")
            type_ = btn.get_attribute("type")
            print(f"  button[{i}]: role={role}, type={type_}, text={text[:50] if text else '(空)'}")
        except Exception:
            pass

    # 截图
    page.screenshot(path="tests/webapp/screenshots/announcements_messages/debug_teacher_compose.png", full_page=True)
    print("\n截图已保存")

    browser.close()
