"""Storage abstraction for search toolset."""

from __future__ import annotations

import sys
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Protocol, runtime_checkable

from .types import ExtractedContent, SearchResult

if TYPE_CHECKING:
    from .._shared.metrics import UsageMetrics


@runtime_checkable
class SearchStorageProtocol(Protocol):
    """Protocol for search storage implementations.

    Any class that has `search_results` and `extracted_contents` properties can be used
    as storage for the search toolset.

    Example:
        ```python
        class MyCustomStorage:
            def __init__(self):
                self._search_results: dict[str, SearchResult] = {}
                self._extracted_contents: dict[str, ExtractedContent] = {}

            @property
            def search_results(self) -> dict[str, SearchResult]:
                return self._search_results

            @search_results.setter
            def search_results(self, value: SearchResult) -> None:
                self._search_results[value.result_id] = value

            @property
            def extracted_contents(self) -> dict[str, ExtractedContent]:
                return self._extracted_contents

            @extracted_contents.setter
            def extracted_contents(self, value: ExtractedContent) -> None:
                self._extracted_contents[value.content_id] = value
        ```
    """

    @property
    def search_results(self) -> dict[str, SearchResult]:
        """Get the current dictionary of search results (result_id -> SearchResult)."""
        ...

    @search_results.setter
    def search_results(self, value: SearchResult) -> None:
        """Add or update a search result in the dictionary."""
        ...

    @property
    def extracted_contents(self) -> dict[str, ExtractedContent]:
        """Get the current dictionary of extracted contents (content_id -> ExtractedContent)."""
        ...

    @extracted_contents.setter
    def extracted_contents(self, value: ExtractedContent) -> None:
        """Add or update an extracted content in the dictionary."""
        ...


@dataclass
class SearchStorage:
    """Default in-memory search storage.

    Simple implementation that stores search results and extracted contents in memory.
    Use this for standalone agents or testing.

    Example:
        ```python
        from pydantic_ai_toolsets import create_search_toolset, SearchStorage

        storage = SearchStorage()
        toolset = create_search_toolset(storage=storage)

        # After agent runs, access search results and extracted contents directly
        print(storage.search_results)
        print(storage.extracted_contents)

        # With metrics tracking
        storage = SearchStorage(track_usage=True)
        toolset = create_search_toolset(storage=storage)
        print(storage.metrics.total_tokens())
        ```
    """

    _search_results: dict[str, SearchResult] = field(default_factory=dict)
    _extracted_contents: dict[str, ExtractedContent] = field(default_factory=dict)
    _metrics: UsageMetrics | None = field(default=None)

    def __init__(self, *, track_usage: bool = False) -> None:
        """Initialize storage with optional metrics tracking.

        Args:
            track_usage: If True, enables usage metrics collection.
        """
        self._search_results = {}
        self._extracted_contents = {}
        self._metrics = None
        if track_usage:
            import os

            toolsets_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            if toolsets_dir not in sys.path:
                sys.path.insert(0, toolsets_dir)
            from .._shared.metrics import UsageMetrics

            self._metrics = UsageMetrics()

    @property
    def search_results(self) -> dict[str, SearchResult]:
        """Get the current dictionary of search results."""
        return self._search_results

    @search_results.setter
    def search_results(self, value: SearchResult) -> None:
        """Add or update a search result in the dictionary."""
        self._search_results[value.result_id] = value

    @property
    def extracted_contents(self) -> dict[str, ExtractedContent]:
        """Get the current dictionary of extracted contents."""
        return self._extracted_contents

    @extracted_contents.setter
    def extracted_contents(self, value: ExtractedContent) -> None:
        """Add or update an extracted content in the dictionary."""
        self._extracted_contents[value.content_id] = value

    @property
    def metrics(self) -> UsageMetrics | None:
        """Get usage metrics if tracking is enabled."""
        return self._metrics

    def get_statistics(self) -> dict[str, int | float]:
        """Get summary statistics about search operations.

        Returns:
            Dictionary with search and extraction counts.
        """
        unique_queries = len(set(r.query for r in self._search_results.values()))
        unique_urls = len(set(c.url for c in self._extracted_contents.values()))
        total_extracted_chars = sum(len(c.content) for c in self._extracted_contents.values())

        return {
            "total_searches": unique_queries,
            "total_results": len(self._search_results),
            "total_extractions": len(self._extracted_contents),
            "unique_urls": unique_urls,
            "total_extracted_chars": total_extracted_chars,
        }

    def clear(self) -> None:
        """Clear all search results, extracted contents, and reset metrics."""
        self._search_results.clear()
        self._extracted_contents.clear()
        if self._metrics:
            self._metrics.clear()
