"""
考试模块API路由
"""
from typing import Optional
import logging

from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.ext.asyncio import AsyncSession

from ...core.deps import get_db, get_current_user
from ...core.config import settings
from ...models.user import User
from ...models.exam import ExamStatus
from ...schemas.base import BaseResponse, PaginatedResponse
from ...schemas.exam import (
    ExamStartRequest, ExamSubmitRequest,
    ExamSessionResponse, ExamResultResponse, 
    ExamRecordResponse, MistakeResponse
)
from ...services.exam_service import ExamService

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/exams", tags=["exams"])


@router.post("/start", response_model=BaseResponse[ExamSessionResponse])
async def start_exam(
    request: ExamStartRequest,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """
    开始考试（动态组卷）
    
    - **course_id**: 课程ID（可选）
    - **exam_name**: 考试名称
    - **question_count**: 题目数量（1-100）
    - **time_limit**: 考试时长（分钟，可选）
    - **difficulty**: 难度等级（1-5，可选）
    - **knowledge_points**: 知识点范围（可选）
    - **question_types**: 题型范围（可选）
    """
    service = ExamService(db)
    
    try:
        exam_session = await service.start_exam(
            user_id=current_user.id,
            request=request,
            exam_workflow_id=settings.DIFY_EXAM_WORKFLOW_ID
        )
        
        return BaseResponse(
            data=exam_session,
            message="考试开始成功"
        )
    except Exception as e:
        logger.error(f"Start exam failed: user_id={current_user.id}, error={str(e)}")
        raise


@router.post("/{exam_id}/submit", response_model=BaseResponse[ExamResultResponse])
async def submit_exam(
    exam_id: int,
    request: ExamSubmitRequest,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """
    提交考试
    
    - **answers**: 答案列表
    - **force_submit**: 是否强制提交（忽略未答题目）
    """
    service = ExamService(db)
    
    try:
        exam_result = await service.submit_exam(
            user_id=current_user.id,
            exam_id=exam_id,
            request=request,
            eval_workflow_id=settings.DIFY_EVAL_WORKFLOW_ID
        )
        
        return BaseResponse(
            data=exam_result,
            message="考试提交成功"
        )
    except Exception as e:
        logger.error(f"Submit exam failed: exam_id={exam_id}, user_id={current_user.id}, error={str(e)}")
        raise


@router.get("/{exam_id}", response_model=BaseResponse[ExamSessionResponse])
async def get_exam_detail(
    exam_id: int,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """
    获取考试详情
    
    返回考试会话信息和题目列表（不包含答案）
    """
    service = ExamService(db)
    
    exam_session = await service.get_exam_detail(
        user_id=current_user.id,
        exam_id=exam_id
    )
    
    return BaseResponse(data=exam_session)


@router.get("/records", response_model=BaseResponse[PaginatedResponse[ExamRecordResponse]])
async def get_exam_records(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    status: Optional[ExamStatus] = Query(None, description="考试状态筛选"),
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """
    获取考试记录列表（分页）
    
    - **page**: 页码（从1开始）
    - **page_size**: 每页数量（1-100）
    - **status**: 考试状态筛选（可选）
    """
    service = ExamService(db)
    
    result = await service.get_exam_records(
        user_id=current_user.id,
        page=page,
        page_size=page_size,
        status=status
    )
    
    return BaseResponse(data=result)


@router.get("/{exam_id}/result", response_model=BaseResponse[ExamResultResponse])
async def get_exam_result(
    exam_id: int,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """
    获取考试结果
    
    返回详细的考试成绩、统计信息和答案详情
    """
    service = ExamService(db)
    
    exam_result = await service.get_exam_result(
        user_id=current_user.id,
        exam_id=exam_id
    )
    
    return BaseResponse(data=exam_result)


@router.get("/mistakes", response_model=BaseResponse[PaginatedResponse[MistakeResponse]])
async def get_mistakes(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    is_mastered: Optional[bool] = Query(None, description="是否已掌握"),
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """
    获取错题列表（分页）
    
    - **page**: 页码（从1开始）
    - **page_size**: 每页数量（1-100）
    - **is_mastered**: 是否已掌握（可选）
    """
    service = ExamService(db)
    
    result = await service.get_mistakes(
        user_id=current_user.id,
        page=page,
        page_size=page_size,
        is_mastered=is_mastered
    )
    
    return BaseResponse(data=result)
