"""Pydantic models for Miruvor SDK."""
from typing import Any, Dict, List, Optional, Union

from pydantic import BaseModel, Field, field_validator


# Request models
class StoreRequest(BaseModel):
    """Request to store a memory."""

    text: str = Field(..., max_length=10000, description="Memory content")
    tags: List[str] = Field(default_factory=list, description="Tags (max 20)")
    metadata: Dict[str, Any] = Field(default_factory=dict, description="Metadata")

    @field_validator("text")
    @classmethod
    def validate_text(cls, v: str) -> str:
        if not v or not v.strip():
            raise ValueError("Text cannot be empty")
        return v.strip()

    @field_validator("tags")
    @classmethod
    def validate_tags(cls, v: List[str]) -> List[str]:
        if len(v) > 20:
            raise ValueError("Maximum 20 tags allowed")
        return v


class IngestRequest(BaseModel):
    """Request to ingest content with LLM enhancement."""

    content: Union[str, dict] = Field(..., description="Raw text or structured data")
    priority: str = Field("normal", description="Priority: urgent, high, normal, low")
    metadata: Dict[str, Any] = Field(default_factory=dict, description="Metadata")
    enable_consolidation: bool = Field(True, description="Enable memory consolidation")
    enable_background_linking: bool = Field(True, description="Enable async linking")

    @field_validator("content")
    @classmethod
    def validate_content(cls, v: Union[str, dict]) -> Union[str, dict]:
        if isinstance(v, str):
            if not v or not v.strip():
                raise ValueError("Content cannot be empty")
        elif isinstance(v, dict):
            if not v:
                raise ValueError("Content dictionary cannot be empty")
        return v

    @field_validator("priority")
    @classmethod
    def validate_priority(cls, v: str) -> str:
        allowed = {"urgent", "high", "normal", "low"}
        if v.lower() not in allowed:
            raise ValueError(f"Priority must be one of: {', '.join(allowed)}")
        return v.lower()


# Response models
class StoreResponse(BaseModel):
    """Response from storing a memory."""

    memory_id: str
    storage_time_ms: float
    synapses_created: int
    status: str
    persistence_enabled: bool
    caching_enabled: bool


class IngestResponse(BaseModel):
    """Response from ingesting content."""

    success: bool
    message_id: Optional[str] = None
    memory_ids: List[str] = Field(default_factory=list)
    chunks_created: int = 0
    duplicates_skipped: int = 0
    consolidations: int = 0
    processing_time_ms: float = 0.0
    status: str = "queued"
    priority: str = "normal"
    message: str


class Memory(BaseModel):
    """A retrieved memory with score."""

    memory_id: str
    score: float
    data: Dict[str, Any]


class RetrieveResponse(BaseModel):
    """Response from pattern completion retrieval."""

    query: str
    results: List[Memory]
    retrieval_method: str
    num_results: int
