"""Query endpoint request/response schemas."""

from uuid import UUID

from pydantic import BaseModel, Field, field_validator


class SourceReference(BaseModel):
    """Source reference for an answer."""

    file: str = Field(..., description="Source document filename")
    sheet: str = Field(..., description="Source sheet name")
    location: str = Field(..., description="Cell range (e.g., 'A42:D42')")
    context: str = Field(..., description="Text content from the source")


class TagFilters(BaseModel):
    """Tag filtering options for retrieval."""

    contains_any: list[str] | None = Field(
        None,
        description="Match records with ANY of these tags",
        examples=[["req:functional", "req:interface"]],
    )
    contains_all: list[str] | None = Field(
        None,
        description="Match records with ALL of these tags",
        examples=[["topic:authentication"]],
    )


class QueryRequest(BaseModel):
    """Request body for POST /query endpoint."""

    query: str = Field(
        ...,
        min_length=1,
        max_length=1000,
        description="Natural language query",
        examples=["What does item code 2024-4_0019 appear in?"],
    )
    document_ids: list[UUID] | None = Field(
        None,
        description="Optional filter to search only specific documents",
    )
    tag_filters: TagFilters | None = Field(
        None,
        description="Optional semantic tag filtering (e.g., req:functional, risk:security)",
    )
    include_context: bool = Field(
        True,
        description="Include source references in response",
    )

    @field_validator("query")
    @classmethod
    def query_not_empty(cls, v: str) -> str:
        """Validate query is not empty after stripping whitespace."""
        if not v.strip():
            raise ValueError("Query cannot be empty")
        return v.strip()


class QueryResponse(BaseModel):
    """Response body for POST /query endpoint."""

    query: str = Field(..., description="Original query text")
    answer: str = Field(..., description="Generated answer")
    confidence: float = Field(
        ...,
        ge=0.0,
        le=1.0,
        description="Confidence score (0.0-1.0)",
    )
    sources: list[SourceReference] = Field(
        ...,
        description="Source references for the answer",
    )
    processing_time_ms: int = Field(
        ...,
        description="Total processing time in milliseconds",
    )
