"""Pydantic models for Benchmark validation."""

from typing import Any, Dict, List, Optional
from pydantic import Field, field_validator

from .base import ToothFairyModel


class BenchmarkCreateModel(ToothFairyModel):
    """Validation model for creating a benchmark."""

    name: str = Field(..., min_length=1, max_length=255, description="Benchmark name")
    description: Optional[str] = Field(default=None, description="Benchmark description")
    questions: Optional[List[Dict[str, Any]]] = Field(default=None, description="List of test questions")
    files: Optional[List[str]] = Field(default=None, description="List of document IDs")

    @field_validator("questions")
    @classmethod
    def validate_questions(cls, v: Optional[List[Dict[str, Any]]]) -> Optional[List[Dict[str, Any]]]:
        if v is not None:
            for i, q in enumerate(v):
                if not isinstance(q, dict):
                    raise ValueError(f"Question {i} must be a dictionary")
                if "question" not in q:
                    raise ValueError(f"Question {i} must have a 'question' field")
        return v

    def to_api_payload(self) -> dict:
        payload = {"name": self.name}
        if self.description is not None:
            payload["description"] = self.description
        if self.questions is not None:
            payload["questions"] = self.questions
        if self.files is not None:
            payload["files"] = self.files
        return payload


class BenchmarkUpdateModel(ToothFairyModel):
    """Validation model for updating a benchmark."""

    benchmark_id: str = Field(..., min_length=1, description="Benchmark ID to update")
    name: Optional[str] = Field(default=None, min_length=1, max_length=255)
    description: Optional[str] = Field(default=None)
    questions: Optional[List[Dict[str, Any]]] = Field(default=None)
    files: Optional[List[str]] = Field(default=None)

    @field_validator("questions")
    @classmethod
    def validate_questions(cls, v: Optional[List[Dict[str, Any]]]) -> Optional[List[Dict[str, Any]]]:
        if v is not None:
            for i, q in enumerate(v):
                if not isinstance(q, dict):
                    raise ValueError(f"Question {i} must be a dictionary")
                if "question" not in q:
                    raise ValueError(f"Question {i} must have a 'question' field")
        return v

    def to_api_payload(self) -> dict:
        payload = {"id": self.benchmark_id}
        if self.name is not None:
            payload["name"] = self.name
        if self.description is not None:
            payload["description"] = self.description
        if self.questions is not None:
            payload["questions"] = self.questions
        if self.files is not None:
            payload["files"] = self.files
        return payload