"""验证 lesson-plans 修复后的页面状态"""
import urllib.request
import urllib.error
import json
import re

BASE_URL = "http://localhost:3000"

# 1. 先登录 teacher
login_data = "email=t_chinese_1%40xiaoxue.edu.cn&password=123456".encode()
req = urllib.request.Request(
    f"{BASE_URL}/api/auth/callback/credentials",
    data=login_data,
    method="POST",
    headers={
        "Content-Type": "application/x-www-form-urlencoded",
    },
)

import http.cookiejar
cookie_jar = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie_jar))

try:
    resp = opener.open(req, timeout=15)
    print(f"登录回调状态: {resp.status}")
except urllib.error.HTTPError as e:
    print(f"登录回调 HTTP 错误: {e.code}")
except Exception as e:
    print(f"登录回调异常: {e}")

# 2. 访问登录页获取 cookie
try:
    resp = opener.open(f"{BASE_URL}/login", timeout=15)
    print(f"登录页状态: {resp.status}")
except Exception as e:
    print(f"登录页异常: {e}")

# 3. 提交登录表单
login_data = "email=t_chinese_1%40xiaoxue.edu.cn&password=123456&csrfToken=&callbackUrl=http%3A%2F%2Flocalhost%3A3000%2Fteacher%2Fdashboard&json=true".encode()
req = urllib.request.Request(
    f"{BASE_URL}/api/auth/callback/credentials",
    data=login_data,
    method="POST",
    headers={
        "Content-Type": "application/x-www-form-urlencoded",
    },
)
try:
    resp = opener.open(req, timeout=15)
    body = resp.read().decode("utf-8", errors="replace")
    print(f"登录 API 状态: {resp.status}")
except urllib.error.HTTPError as e:
    body = e.read().decode("utf-8", errors="replace")
    print(f"登录 API HTTP 错误: {e.code}")
except Exception as e:
    print(f"登录 API 异常: {e}")

# 4. 访问 lesson-plans 页面
print("\n=== 访问 /teacher/lesson-plans ===")
try:
    req = urllib.request.Request(f"{BASE_URL}/teacher/lesson-plans")
    resp = opener.open(req, timeout=30)
    body = resp.read().decode("utf-8", errors="replace")
    print(f"状态码: {resp.status}")
    print(f"内容长度: {len(body)}")

    # 检查是否有错误
    if "Failed to call" in body:
        match = re.search(r"Failed to call[^<]{0,200}", body)
        print(f"❌ 发现错误: {match.group(0) if match else 'Failed to call'}")
    elif "useTranslations" in body and "was not found" in body:
        print("❌ 发现 useTranslations 上下文错误")
    else:
        print("✅ 未发现 useTranslations 错误")

    # 检查页面内容
    if "备课" in body or "Lesson Plan" in body or "lesson-plans/new" in body:
        print("✅ 页面包含备课相关内容")
    else:
        print("⚠️ 页面未包含备课内容")

    # 检查是否重定向到登录页
    if "/login" in body[:2000] and "callbackUrl" in body[:2000]:
        print("⚠️ 可能重定向到登录页")

except urllib.error.HTTPError as e:
    body = e.read().decode("utf-8", errors="replace")
    print(f"HTTP 错误: {e.code}")
    print(f"响应体 (前 1000 字符): {body[:1000]}")
    if "Failed to call" in body:
        match = re.search(r"Failed to call[^<]{0,300}", body)
        if match:
            print(f"\n❌ 错误详情: {match.group(0)}")
except Exception as e:
    print(f"异常: {e}")

# 5. 访问 lesson-plans/new 页面
print("\n=== 访问 /teacher/lesson-plans/new ===")
try:
    req = urllib.request.Request(f"{BASE_URL}/teacher/lesson-plans/new")
    resp = opener.open(req, timeout=30)
    body = resp.read().decode("utf-8", errors="replace")
    print(f"状态码: {resp.status}")
    print(f"内容长度: {len(body)}")

    if "Failed to call" in body:
        match = re.search(r"Failed to call[^<]{0,200}", body)
        print(f"❌ 发现错误: {match.group(0) if match else 'Failed to call'}")
    else:
        print("✅ 未发现 useTranslations 错误")

    if "模板" in body or "Template" in body or "template" in body:
        print("✅ 页面包含模板相关内容")

except urllib.error.HTTPError as e:
    body = e.read().decode("utf-8", errors="replace")
    print(f"HTTP 错误: {e.code}")
    print(f"响应体 (前 1000 字符): {body[:1000]}")
except Exception as e:
    print(f"异常: {e}")

print("\n=== 验证完成 ===")
