from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from .. import models, schemas
from ..database import get_db
from ..deps import get_current_user

router = APIRouter()


@router.get("/types", response_model=List[schemas.ExamTypeResponse])
def list_exam_types(db: Session = Depends(get_db)):
    return db.query(models.ExamType).all()


@router.get("/subjects", response_model=List[schemas.SubjectResponse])
def list_subjects(
    exam_type_id: Optional[int] = None,
    db: Session = Depends(get_db),
):
    q = db.query(models.Subject)
    if exam_type_id:
        q = q.filter(models.Subject.exam_type_id == exam_type_id)
    return q.all()


@router.get("/", response_model=List[schemas.ExamSummary])
def list_exams(
    exam_type_id: Optional[int] = None,
    subject_id: Optional[int] = None,
    db: Session = Depends(get_db),
    _: models.User = Depends(get_current_user),
):
    q = db.query(models.Exam).filter(models.Exam.is_published == True)
    if exam_type_id:
        q = q.filter(models.Exam.exam_type_id == exam_type_id)
    if subject_id:
        q = q.filter(models.Exam.subject_id == subject_id)
    exams = q.order_by(models.Exam.created_at.desc()).all()
    result = []
    for e in exams:
        result.append(schemas.ExamSummary(
            id=e.id,
            title=e.title,
            subject=schemas.SubjectResponse.model_validate(e.subject),
            exam_type=schemas.ExamTypeResponse.model_validate(e.exam_type),
            year=e.year,
            duration_minutes=e.duration_minutes,
            total_points=e.total_points,
            question_count=len(e.questions),
            is_published=e.is_published,
        ))
    return result


@router.get("/{exam_id}", response_model=schemas.ExamDetail)
def get_exam(
    exam_id: str,
    db: Session = Depends(get_db),
    _: models.User = Depends(get_current_user),
):
    exam = db.query(models.Exam).filter(
        models.Exam.id == exam_id,
        models.Exam.is_published == True,
    ).first()
    if not exam:
        raise HTTPException(status_code=404, detail="Examen negăsit")

    questions = []
    for q in exam.questions:
        options = [
            schemas.OptionResponse(id=o.id, option_label=o.option_label, option_text=o.option_text)
            for o in q.options
        ]
        questions.append(schemas.QuestionResponse(
            id=q.id,
            question_number=q.question_number,
            question_type=q.question_type,
            question_text=q.question_text,
            points=q.points,
            order_index=q.order_index,
            options=options,
        ))

    return schemas.ExamDetail(
        id=exam.id,
        title=exam.title,
        subject=schemas.SubjectResponse.model_validate(exam.subject),
        exam_type=schemas.ExamTypeResponse.model_validate(exam.exam_type),
        year=exam.year,
        duration_minutes=exam.duration_minutes,
        total_points=exam.total_points,
        instructions=exam.instructions,
        questions=questions,
    )
