from typing import Literal, Optional

from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from auth import get_current_user
from database import get_db
from models import User
from schemas import (
    DailyQuizResponse,
    QuizAnswerRequest,
    QuizAnswerResponse,
    QuizStatsResponse,
)
from services.quiz_service import quiz_service

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


@router.get("/daily", response_model=DailyQuizResponse)
def daily_quiz(
    track: Literal["accumulation", "book"] = Query("accumulation"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    result = quiz_service.get_daily_quiz(db, current_user, track=track)
    return DailyQuizResponse(**result)


@router.get("/spell", response_model=DailyQuizResponse)
def spell_quiz(
    track: Literal["accumulation", "book"] = Query("accumulation"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    result = quiz_service.get_spell_quiz(db, current_user, track=track)
    return DailyQuizResponse(**result)


@router.post("/answer", response_model=QuizAnswerResponse)
def submit_answer(
    data: QuizAnswerRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    result = quiz_service.submit_answer(
        db,
        current_user,
        data.word_id,
        data.question_type,
        data.user_answer,
        data.correct_answer,
        data.duration_seconds or 0,
    )
    return QuizAnswerResponse(**result)


@router.get("/stats", response_model=QuizStatsResponse)
def quiz_stats(
    track: Literal["accumulation", "book"] = Query("accumulation"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    return quiz_service.get_stats(db, current_user, track=track)
