"""
课评表单本地服务器
- 启动后提供表单页面 + POST 提交接口
- 表单提交数据自动保存为 JSON 文件，AI 自动检测处理
- 版本: v1.0 | 2026-05-20
"""
import http.server
import json
import os
import sys
import io
import urllib.parse
import re
from pathlib import Path

# 解决 Windows GBK 终端编码问题
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')

PORT = 8088
PROJECT_ROOT = Path(__file__).resolve().parent.parent
TMP_DIR = PROJECT_ROOT / ".claude" / ".tmp"
TEMPLATE_DIR = PROJECT_ROOT / ".claude" / "skills" / "keping-simplified" / "assets"
TEMPLATE_FILE = TEMPLATE_DIR / "form_template.html"
CLASS_MEMORY = PROJECT_ROOT / ".claude" / "memory" / "class"


def get_class_students(class_name):
    """读取班级下的学生列表（正式学生+补课学生）"""
    class_dir = CLASS_MEMORY / class_name
    if not class_dir.exists():
        return [], []

    regular = []
    makeup = []

    for item in sorted(class_dir.iterdir()):
        if item.is_dir() and item.name not in ("summaries", "补课"):
            profile_file = item / "profile.md"
            regular.append({"name": item.name, "has_profile": profile_file.exists()})
        elif item.name == "补课" and item.is_dir():
            for makeup_student in sorted(item.iterdir()):
                if makeup_student.is_dir():
                    makeup.append({"name": makeup_student.name, "has_profile": False})

    return regular, makeup


def get_student_profile(class_name, student_name):
    """读取学生画像"""
    profile_path = CLASS_MEMORY / class_name / student_name / "profile.md"
    if profile_path.exists():
        content = profile_path.read_text(encoding="utf-8")
        # 提取前100字作为摘要
        return content[:150].strip()
    return ""


def load_form_template():
    """读取表单模板"""
    if TEMPLATE_FILE.exists():
        return TEMPLATE_FILE.read_text(encoding="utf-8")
    return None


def build_form_html(params):
    """根据参数注入动态数据到表单模板"""
    template = load_form_template()
    if not template:
        return "<h1>模板文件未找到</h1>"

    class_name = params.get("class", ["未知班级"])[0]
    week = params.get("week", ["1"])[0]
    course_code = params.get("course", ["UNKNOWN-001"])[0]
    course_theme = params.get("theme", ["未知主题"])[0]
    course_knowledge = params.get("knowledge", [""])[0]
    date_str = params.get("date", ["2026-01-01"])[0]

    # 读取班级学生
    regular_students, makeup_students = get_class_students(class_name)

    # 构建学生数据 JS
    students_js = []
    for s in regular_students:
        profile = get_student_profile(class_name, s["name"])
        students_js.append({
            "name": s["name"],
            "status": "出勤",
            "performance": "",
            "profile": profile
        })

    # 补课学生作为可选列表
    makeup_names = [m["name"] for m in makeup_students]

    # 课程信息
    course_info = {
        "code": course_code,
        "title": course_theme,
        "knowledge": course_knowledge.split(",") if course_knowledge else ["暂无"],
        "duration": "60分钟"
    }

    # 注入数据：替换模板中的占位配置
    html = template

    # 替换初始班级/周数/日期信息
    html = html.replace('"发现世界-周四19点"', f'"{class_name}"')
    html = html.replace('"第11周 | 2026-05-16"', f'"第{week}周 | {date_str}"')
    html = html.replace('currentWeek = 11', f'currentWeek = {week}')
    html = html.replace('"2026-05-16"', f'"{date_str}"')
    html = html.replace('"DISC-011"', f'"{course_code}"')
    html = html.replace('"蜥蜴"', f'"{course_theme}"')
    html = html.replace(
        '["关节连接","可动结构","仿生设计"]',
        json.dumps(course_info["knowledge"], ensure_ascii=False)
    )
    html = html.replace('"📚 课程目标：DISC-011 蜥蜴"',
                        f'"📚 课程目标：{course_code} {course_theme}"')

    # 替换学生模板数据
    old_students_json = json.dumps([
        {"name": "梁家铭", "status": "出勤", "performance": ""},
        {"name": "简思瑜", "status": "出勤", "performance": ""},
        {"name": "简思霖", "status": "请假", "performance": ""},
        {"name": "罗钧龄", "status": "出勤", "performance": ""},
        {"name": "黄晓瑜", "status": "出勤", "performance": ""},
        {"name": "黄馨宸", "status": "请假", "performance": ""}
    ], ensure_ascii=False)

    new_students_json = json.dumps(students_js, ensure_ascii=False)
    html = html.replace(old_students_json, new_students_json)

    # 注入补课学生可选项
    html = html.replace(
        "</script>",
        f"""
const makeupStudents = {json.dumps(makeup_names, ensure_ascii=False)};
const classDir = "{class_name}";
</script>"""
    )

    return html


class FormHandler(http.server.BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        """静默日志"""
        pass

    def do_GET(self):
        parsed = urllib.parse.urlparse(self.path)

        if parsed.path == "/" or parsed.path == "/form":
            params = urllib.parse.parse_qs(parsed.query)
            html = build_form_html(params)
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Access-Control-Allow-Origin", "*")
            self.end_headers()
            self.wfile.write(html.encode("utf-8"))
        else:
            self.send_response(404)
            self.end_headers()

    def do_POST(self):
        if self.path == "/api/submit":
            content_length = int(self.headers.get("Content-Length", 0))
            body = self.rfile.read(content_length)
            data = json.loads(body)

            # 保存到临时目录
            TMP_DIR.mkdir(parents=True, exist_ok=True)
            class_name = data.get("class", "unknown")
            safe_name = re.sub(r'[<>:"/\\|?*]', '_', class_name)
            output_file = TMP_DIR / f"evaluation_input_{safe_name}.json"

            with open(output_file, "w", encoding="utf-8") as f:
                json.dump(data, f, ensure_ascii=False, indent=2)

            # 同时写一个信号文件通知 AI
            signal_file = TMP_DIR / "EVALUATION_READY.txt"
            signal_file.write_text(
                f"班级: {class_name}\n"
                f"提交时间: {data.get('date', '')}\n"
                f"数据文件: {output_file}\n",
                encoding="utf-8"
            )

            resp = {
                "success": True,
                "message": f"已保存！班级：{class_name}，共 {len(data.get('students', []))} 人",
                "file": str(output_file)
            }

            self.send_response(200)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.send_header("Access-Control-Allow-Origin", "*")
            self.end_headers()
            self.wfile.write(json.dumps(resp, ensure_ascii=False).encode("utf-8"))
        else:
            self.send_response(404)
            self.end_headers()

    def do_OPTIONS(self):
        """CORS preflight"""
        self.send_response(200)
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")
        self.end_headers()


def main():
    print(f"🚀 课评表单服务器启动中...")
    print(f"   端口: {PORT}")
    print(f"   临时目录: {TMP_DIR}")

    # 确保临时目录存在
    TMP_DIR.mkdir(parents=True, exist_ok=True)

    server = http.server.HTTPServer(("127.0.0.1", PORT), FormHandler)
    print(f"✅ 服务器已启动: http://localhost:{PORT}/form")
    print(f"   按 Ctrl+C 停止服务器")

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\n🛑 服务器已停止")
        server.server_close()


if __name__ == "__main__":
    main()