"""Memory resource for the Contiss API."""

from typing import List, Optional

from ..types import BundleResult, Memory, MemoryType, MemoryWriteResult, SearchMode, SearchResult
from .base import BaseResource


class MemoryResource(BaseResource):
    """Handles memory-related operations."""

    def write(
        self,
        org_id: str,
        project_id: str,
        content: str,
        type: MemoryType = "note",
        title: Optional[str] = None,
        tags: Optional[List[str]] = None,
        sources: Optional[List[str]] = None,
        confidence: float = 0.6,
        requires_review: bool = False,
        supersedes_id: Optional[str] = None,
    ) -> MemoryWriteResult:
        """Write a new memory to Contiss.

        Args:
            org_id: Organization UUID
            project_id: Project UUID
            content: The memory content to store
            type: Type of memory (fact, decision, plan, summary, note)
            title: Optional title for the memory
            tags: Optional list of tags for categorization
            sources: Optional list of source UUIDs
            confidence: Confidence score (0.0 to 1.0)
            requires_review: Whether this memory needs human review
            supersedes_id: UUID of memory this replaces (creates new version)

        Returns:
            MemoryWriteResult with the created memory info

        Raises:
            AuthenticationError: If not authenticated
            ValidationError: If parameters are invalid
            NotFoundError: If project doesn't exist or access denied
        """
        payload = {
            "org_id": org_id,
            "project_id": project_id,
            "content": content,
            "type": type,
            "confidence": confidence,
            "requires_review": requires_review,
        }

        if title:
            payload["title"] = title
        if tags:
            payload["tags"] = tags
        if sources:
            payload["sources"] = sources
        if supersedes_id:
            payload["supersedes_id"] = supersedes_id

        response = self._client.post("/memory/write", json=payload)
        return MemoryWriteResult(**response)

    def search(
        self,
        org_id: str,
        project_id: str,
        query: str,
        limit: int = 20,
        types: Optional[List[MemoryType]] = None,
        tags: Optional[List[str]] = None,
        search_mode: SearchMode = "hybrid",
    ) -> SearchResult:
        """Search memories using semantic or full-text search.

        Args:
            org_id: Organization UUID
            project_id: Project UUID
            query: Natural language search query
            limit: Maximum number of results (1-50)
            types: Optional list of memory types to filter by
            tags: Optional list of tags to filter by
            search_mode: Search mode (semantic, fulltext, or hybrid)

        Returns:
            SearchResult with matching memories

        Raises:
            AuthenticationError: If not authenticated
            ValidationError: If parameters are invalid
            NotFoundError: If project doesn't exist or access denied
        """
        payload = {
            "org_id": org_id,
            "project_id": project_id,
            "query": query,
            "limit": limit,
            "searchMode": search_mode,
        }

        if types:
            payload["types"] = types
        if tags:
            payload["tags"] = tags

        response = self._client.post("/memory/search", json=payload)
        return SearchResult(**response)

    def bundle(
        self,
        org_id: str,
        project_id: str,
        task: str,
        max_items: int = 12,
        max_chars: int = 6000,
        types: Optional[List[MemoryType]] = None,
        tags: Optional[List[str]] = None,
    ) -> BundleResult:
        """Get a bundled set of memories for a specific task.

        Args:
            org_id: Organization UUID
            project_id: Project UUID
            task: Task description to get context for
            max_items: Maximum number of memories to include (1-100)
            max_chars: Maximum total characters (500-50000)
            types: Optional list of memory types to include
            tags: Optional list of tags to filter by

        Returns:
            BundleResult with summarized and filtered memories

        Raises:
            AuthenticationError: If not authenticated
            ValidationError: If parameters are invalid
            NotFoundError: If project doesn't exist or access denied
        """
        payload = {
            "org_id": org_id,
            "project_id": project_id,
            "task": task,
            "limits": {"max_items": max_items, "max_chars": max_chars},
            "filters": {
                "types": types or ["fact", "decision", "plan", "summary"],
                "tags": tags or [],
            },
        }

        response = self._client.post("/memory/bundle", json=payload)
        return BundleResult(**response)
