"""Knowledge Vault API schemas."""

from __future__ import annotations

from datetime import datetime

from pydantic import BaseModel, Field, field_validator


class VaultRegisterRequest(BaseModel):
    """Request payload to register one vault path."""

    path: str = Field(..., min_length=1, max_length=4096)

    @field_validator("path")
    @classmethod
    def _normalize_path(cls, value: str) -> str:
        text = value.strip()
        if not text:
            raise ValueError("path cannot be empty")
        return text


class VaultPathRead(BaseModel):
    """Registered vault path with indexing stats."""

    id: int
    path: str
    enabled: bool
    created_at: datetime
    file_count: int = 0
    chunk_count: int = 0
    last_indexed_at: datetime | None = None


class VaultPathToggleRequest(BaseModel):
    """Request payload to enable or disable one registered path."""

    enabled: bool


class VaultPathsResponse(BaseModel):
    """List response for registered paths."""

    paths: list[VaultPathRead]
    is_running: bool = False
    last_run_at: datetime | None = None
    last_finished_at: datetime | None = None
    last_stats: dict[str, int] | None = None
    last_errors: list[str] = Field(default_factory=list)


class VaultIndexRequest(BaseModel):
    """Request payload to trigger index run."""

    path_id: int | None = Field(default=None, ge=1)


class VaultIndexResponse(BaseModel):
    """Index run response."""

    started_at: datetime
    finished_at: datetime
    stats: dict[str, int]
    errors: list[str]


class VaultStatusResponse(BaseModel):
    """Global vault status response."""

    paths: int
    enabled_paths: int
    files: int
    chunks: int
    enabled_files: int = 0
    enabled_chunks: int = 0
    last_indexed_at: datetime | None = None
    enabled_last_indexed_at: datetime | None = None
    needs_index: bool = False
    is_running: bool
    last_run_at: datetime | None = None
    last_finished_at: datetime | None = None
    last_stats: dict[str, int] | None = None
    last_errors: list[str] = Field(default_factory=list)


class VaultSearchHitRead(BaseModel):
    """Search hit response model."""

    file_path: str
    chunk_id: int
    snippet: str
    rank: float


class VaultSearchResponse(BaseModel):
    """Search response model."""

    query: str
    results: list[VaultSearchHitRead]
