"""
错题记录模型
"""
from sqlalchemy import Column, Integer, ForeignKey, Text, DateTime, func
from sqlalchemy.orm import relationship
from datetime import datetime
from app.models.base import BaseModel


class ExamMistake(BaseModel):
    """错题记录表"""
    __tablename__ = "exam_mistakes"
    
    # 核心关联字段
    user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True, comment="用户ID")
    exam_id = Column(Integer, ForeignKey("exams.id", ondelete="CASCADE"), nullable=False, index=True, comment="考试ID")
    round = Column(Integer, nullable=True, default=1, comment="考试轮次(1/2/3)")
    question_id = Column(Integer, ForeignKey("questions.id", ondelete="SET NULL"), nullable=True, index=True, comment="题目ID（AI生成的题目可能为空）")
    knowledge_point_id = Column(Integer, ForeignKey("knowledge_points.id", ondelete="SET NULL"), nullable=True, index=True, comment="关联的知识点ID")
    
    # 题目核心信息
    question_content = Column(Text, nullable=False, comment="题目内容")
    correct_answer = Column(Text, nullable=False, comment="正确答案")
    user_answer = Column(Text, nullable=True, comment="用户答案")
    question_type = Column(Text, nullable=True, index=True, comment="题型(single/multiple/judge/blank/essay)")
    
    # 掌握状态和统计字段
    mastery_status = Column(Text, nullable=False, default='unmastered', index=True, comment="掌握状态: unmastered-未掌握, mastered-已掌握")
    difficulty = Column(Text, nullable=False, default='medium', index=True, comment="题目难度: easy-简单, medium-中等, hard-困难")
    wrong_count = Column(Integer, nullable=False, default=1, comment="错误次数统计")
    mastered_at = Column(DateTime, nullable=True, comment="标记掌握时间")
    
    # 审计字段（继承自BaseModel，但这里重写以匹配数据库实际结构）
    created_at = Column(DateTime, nullable=False, server_default=func.now(), comment="创建时间（北京时间）")
    updated_at = Column(DateTime, nullable=False, server_default=func.now(), onupdate=func.now(), comment="更新时间（北京时间）")
    
    # 关系
    user = relationship("User", backref="exam_mistakes")
    exam = relationship("Exam", backref="mistakes")
    question = relationship("Question", backref="mistake_records")
    knowledge_point = relationship("KnowledgePoint", backref="mistake_records")
    
    def __repr__(self):
        return f"<ExamMistake(id={self.id}, user_id={self.user_id}, exam_id={self.exam_id})>"
