"""
Knowledge Context Type.

Represents RAG results from the Knowledge Base MCP server.
"""

from dataclasses import dataclass, field
from datetime import UTC, datetime
from typing import Any

from .base import BaseContext, ContextPriority, ContextType


@dataclass(eq=False)
class KnowledgeContext(BaseContext):
    """
    Context from knowledge base / RAG retrieval.

    Knowledge context represents chunks retrieved from the
    Knowledge Base MCP server, including:
    - Code snippets
    - Documentation
    - Previous conversations
    - External knowledge

    Each chunk includes relevance scoring from the search.
    """

    # Knowledge-specific fields
    collection: str = field(default="default")
    file_type: str | None = field(default=None)
    chunk_index: int = field(default=0)
    relevance_score: float = field(default=0.0)
    search_query: str = field(default="")

    def get_type(self) -> ContextType:
        """Return KNOWLEDGE context type."""
        return ContextType.KNOWLEDGE

    def to_dict(self) -> dict[str, Any]:
        """Convert to dictionary with knowledge-specific fields."""
        base = super().to_dict()
        base.update(
            {
                "collection": self.collection,
                "file_type": self.file_type,
                "chunk_index": self.chunk_index,
                "relevance_score": self.relevance_score,
                "search_query": self.search_query,
            }
        )
        return base

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> "KnowledgeContext":
        """Create KnowledgeContext from dictionary."""
        return cls(
            id=data.get("id", ""),
            content=data["content"],
            source=data["source"],
            timestamp=datetime.fromisoformat(data["timestamp"])
            if isinstance(data.get("timestamp"), str)
            else data.get("timestamp", datetime.now(UTC)),
            priority=data.get("priority", ContextPriority.NORMAL.value),
            metadata=data.get("metadata", {}),
            collection=data.get("collection", "default"),
            file_type=data.get("file_type"),
            chunk_index=data.get("chunk_index", 0),
            relevance_score=data.get("relevance_score", 0.0),
            search_query=data.get("search_query", ""),
        )

    @classmethod
    def from_search_result(
        cls,
        result: dict[str, Any],
        query: str,
    ) -> "KnowledgeContext":
        """
        Create KnowledgeContext from a Knowledge Base search result.

        Args:
            result: Search result from Knowledge Base MCP
            query: Search query used

        Returns:
            KnowledgeContext instance
        """
        return cls(
            content=result.get("content", ""),
            source=result.get("source_path", "unknown"),
            collection=result.get("collection", "default"),
            file_type=result.get("file_type"),
            chunk_index=result.get("chunk_index", 0),
            relevance_score=result.get("score", 0.0),
            search_query=query,
            metadata={
                "chunk_id": result.get("id"),
                "content_hash": result.get("content_hash"),
            },
        )

    @classmethod
    def from_search_results(
        cls,
        results: list[dict[str, Any]],
        query: str,
    ) -> list["KnowledgeContext"]:
        """
        Create multiple KnowledgeContexts from search results.

        Args:
            results: List of search results
            query: Search query used

        Returns:
            List of KnowledgeContext instances
        """
        return [cls.from_search_result(r, query) for r in results]

    def is_code(self) -> bool:
        """Check if this is code content."""
        code_types = {
            "python",
            "javascript",
            "typescript",
            "go",
            "rust",
            "java",
            "c",
            "cpp",
        }
        return self.file_type is not None and self.file_type.lower() in code_types

    def is_documentation(self) -> bool:
        """Check if this is documentation content."""
        doc_types = {"markdown", "rst", "txt", "md"}
        return self.file_type is not None and self.file_type.lower() in doc_types

    def get_formatted_source(self) -> str:
        """
        Get a formatted source string for display.

        Returns:
            Formatted source string
        """
        parts = [self.source]
        if self.file_type:
            parts.append(f"({self.file_type})")
        if self.collection != "default":
            parts.insert(0, f"[{self.collection}]")
        return " ".join(parts)
