"""
MUMLA API Models
"""

from datetime import datetime
from typing import Any

from pydantic import BaseModel, Field

from mumla.app.core import MemoryType, ScopeType, SourceType, StatusType


# Request Models
class MemoryStoreRequest(BaseModel):
    type: MemoryType
    title: str = Field(max_length=100)
    content: str = Field(max_length=10000)
    scope_type: ScopeType
    scope_id: str
    actor_id: str
    source: SourceType
    source_ref: str | None = None
    confidence: float = Field(ge=0.0, le=1.0, default=0.8)
    tags: list[str] = Field(default_factory=list)
    ttl_seconds: int | None = None
    user_confirmed: bool = False


class MemoryBatchItem(BaseModel):
    """Single memory item for batch write"""

    type: MemoryType
    title: str = Field(max_length=100)
    content: str = Field(max_length=10000)
    source: SourceType
    source_ref: str | None = None
    confidence: float = Field(ge=0.0, le=1.0, default=0.8)
    tags: list[str] = Field(default_factory=list)
    ttl_seconds: int | None = None
    id: str | None = None  # Optional custom ID


class MemoryBatchWriteRequest(BaseModel):
    """Request to write multiple memories in batch"""

    memories: list[MemoryBatchItem] = Field(
        ..., min_length=1, max_length=100, description="1-100 memories per batch"
    )
    scope_type: ScopeType
    scope_id: str
    actor_id: str
    user_confirmed: bool = False


class BatchRememberItem(BaseModel):
    """Single memory item in a batch-remember request"""

    content: str = Field(..., max_length=10000, description="Memory content")
    type: str = Field(
        "fact",
        description="Memory type: fact, decision, instruction, commitment, event, etc.",
    )
    title: str | None = Field(
        None, max_length=100, description="Memory title (defaults to truncated content)"
    )
    confidence: float = Field(0.8, ge=0.0, le=1.0, description="Confidence score (0-1)")
    tags: list[str] | None = Field(None, description="Tags for this memory")


class BatchRememberRequest(BaseModel):
    """Request body for batch-remember endpoint"""

    memories: list[BatchRememberItem] = Field(
        ...,
        min_length=1,
        max_length=100,
        description="List of memories to store (max 100)",
    )


class MemoryUpdateRequest(BaseModel):
    """Request to update an existing memory"""

    namespace: str = Field(..., description="Namespace containing the memory")
    updates: dict[str, Any] = Field(
        ..., description="Fields to update (title, content, confidence, tags, etc.)"
    )
    user_confirmed: bool = False


class MemorySearchRequest(BaseModel):
    query: str
    scope_type: ScopeType | None = None
    scope_id: str | None = None
    memory_types: list[MemoryType] | None = None
    tags: list[str] | None = None
    limit: int = Field(default=10, ge=1, le=100)


class ScopeDefinition(BaseModel):
    """Individual scope for multi-scope search"""

    scope_type: ScopeType
    scope_id: str


class MemoryMultiScopeSearchRequest(BaseModel):
    """Request to search across multiple scopes simultaneously"""

    query: str
    scopes: list[ScopeDefinition] = Field(
        ..., min_length=1, max_length=10, description="1-10 scopes to search across"
    )
    memory_types: list[MemoryType] | None = None
    tags: list[str] | None = None
    min_confidence: float | None = Field(None, ge=0.0, le=1.0)
    status_filter: list[str] | None = None
    min_similarity_score: float | None = Field(
        None, ge=0.0, le=1.0, description="Minimum similarity score threshold"
    )
    limit: int = Field(default=10, ge=1, le=100)


class MemoryAnswerRequest(BaseModel):
    query: str
    scope_type: ScopeType | None = None
    scope_id: str | None = None


class NamespaceCreateRequest(BaseModel):
    scope_type: ScopeType
    scope_id: str


class ContextSummarizationRequest(BaseModel):
    """Request to summarize context in a scope"""

    scope_type: ScopeType
    scope_id: str
    actor_id: str
    summary_title: str = Field(default="Context Summary", max_length=100)
    memory_types: list[MemoryType] | None = None
    max_memories: int = Field(default=50, ge=1, le=100)
    link_to_originals: bool = True


class CustomSummarizationRequest(BaseModel):
    """Request to summarize specific memories by ID"""

    memory_ids: list[str] = Field(..., min_length=1, max_length=100)
    namespace: str
    scope_type: ScopeType
    scope_id: str
    actor_id: str
    summary_title: str = Field(default="Custom Summary", max_length=100)


class ConversationCompressionRequest(BaseModel):
    """Request to compress old conversation history"""

    scope_type: ScopeType
    scope_id: str
    actor_id: str
    days_to_compress: int = Field(default=7, ge=1, le=365)
    keep_recent_count: int = Field(default=10, ge=0, le=50)


# Response Models
class MemoryResponse(BaseModel):
    id: str
    type: MemoryType
    title: str
    content: str
    scope_type: ScopeType
    scope_id: str
    actor_id: str
    source: SourceType
    source_ref: str | None
    confidence: float
    status: StatusType
    tags: list[str]
    created_at: datetime
    updated_at: datetime | None
    expires_at: datetime | None


class MemoryStoreResponse(BaseModel):
    id: str
    status: str
    action: str
    reason: str
    namespace: str


class MemoryBatchWriteResult(BaseModel):
    """Result for a single memory in batch operation"""

    id: str
    status: str
    action: str
    reason: str | None = None
    error: str | None = None


class MemoryBatchWriteResponse(BaseModel):
    """Response from batch write operation"""

    total_submitted: int
    successful: int
    failed: int
    namespace: str
    results: list[MemoryBatchWriteResult]


class MemoryUpdateResponse(BaseModel):
    """Response from memory update operation"""

    id: str
    namespace: str
    status: str
    action: str
    reason: str
    updated_fields: list[str]


class MemorySearchResponse(BaseModel):
    results: list[dict[str, Any]]
    total_found: int
    query: str
    execution_time: float


class MemoryAnswerResponse(BaseModel):
    answer: str
    sources: list[str]
    confidence: float
    namespace: str


class NamespaceResponse(BaseModel):
    namespace: str
    scope_type: ScopeType
    scope_id: str
    created: bool


class NamespaceListResponse(BaseModel):
    namespaces: list[str]
    total: int


class SummarizationResponse(BaseModel):
    """Response from context summarization"""

    summary_id: str
    namespace: str
    status: str
    summarized_count: int
    original_memory_ids: list[str]
    summary_preview: str


class CompressionResponse(BaseModel):
    """Response from conversation compression"""

    compressed: bool
    reason: str | None = None
    summary_id: str | None = None
    compressed_count: int | None = None
    compression_date: str | None = None
    original_memory_ids: list[str] | None = None


class ErrorResponse(BaseModel):
    error: str
    message: str
    details: dict[str, Any] | None = None


class HealthResponse(BaseModel):
    status: str
    service: str
    version: str
    moorcheh_connected: bool
