"""Storage abstraction for self-refinement."""

from __future__ import annotations

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

from .types import Feedback, RefinementOutput

if TYPE_CHECKING:
    from .._shared.metrics import UsageMetrics


@runtime_checkable
class SelfRefineStorageProtocol(Protocol):
    """Protocol for self-refinement storage implementations.

    Any class that has `outputs` and `feedbacks` properties can be used
    as storage for the self-refinement toolset.

    Example:
        ```python
        class MyCustomStorage:
            def __init__(self):
                self._outputs: dict[str, RefinementOutput] = {}
                self._feedbacks: dict[str, Feedback] = {}

            @property
            def outputs(self) -> dict[str, RefinementOutput]:
                return self._outputs

            @outputs.setter
            def outputs(self, value: RefinementOutput) -> None:
                self._outputs[value.output_id] = value

            @property
            def feedbacks(self) -> dict[str, Feedback]:
                return self._feedbacks

            @feedbacks.setter
            def feedbacks(self, value: Feedback) -> None:
                self._feedbacks[value.feedback_id] = value
        ```
    """

    @property
    def outputs(self) -> dict[str, RefinementOutput]:
        """Get the current dictionary of outputs (output_id -> RefinementOutput)."""
        ...

    @outputs.setter
    def outputs(self, value: RefinementOutput) -> None:
        """Add or update an output in the dictionary."""
        ...

    @property
    def feedbacks(self) -> dict[str, Feedback]:
        """Get the current dictionary of feedbacks (feedback_id -> Feedback)."""
        ...

    @feedbacks.setter
    def feedbacks(self, value: Feedback) -> None:
        """Add or update a feedback in the dictionary."""
        ...


@dataclass
class SelfRefineStorage:
    """Default in-memory self-refinement storage.

    Simple implementation that stores outputs and feedbacks in memory.
    Use this for standalone agents or testing.

    Example:
        ```python
        from pydantic_ai_toolsets import create_self_refine_toolset, SelfRefineStorage

        storage = SelfRefineStorage()
        toolset = create_self_refine_toolset(storage=storage)

        # After agent runs, access outputs and feedbacks directly
        print(storage.outputs)
        print(storage.feedbacks)

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

    _outputs: dict[str, RefinementOutput] = field(default_factory=dict)
    _feedbacks: dict[str, Feedback] = 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._outputs = {}
        self._feedbacks = {}
        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 outputs(self) -> dict[str, RefinementOutput]:
        """Get the current dictionary of outputs."""
        return self._outputs

    @outputs.setter
    def outputs(self, value: RefinementOutput) -> None:
        """Add or update an output in the dictionary."""
        self._outputs[value.output_id] = value

    @property
    def feedbacks(self) -> dict[str, Feedback]:
        """Get the current dictionary of feedbacks."""
        return self._feedbacks

    @feedbacks.setter
    def feedbacks(self, value: Feedback) -> None:
        """Add or update a feedback in the dictionary."""
        self._feedbacks[value.feedback_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 self-refinement operations.

        Returns:
            Dictionary with output and feedback counts.
        """
        total_outputs = len(self._outputs)
        final_outputs = sum(1 for o in self._outputs.values() if o.is_final)
        max_iteration = max((o.iteration for o in self._outputs.values()), default=0)
        avg_quality = None
        quality_scores = [o.quality_score for o in self._outputs.values() if o.quality_score is not None]
        if quality_scores:
            avg_quality = sum(quality_scores) / len(quality_scores)

        stats: dict[str, int | float] = {
            "total_outputs": total_outputs,
            "final_outputs": final_outputs,
            "max_iteration": max_iteration,
            "total_feedbacks": len(self._feedbacks),
        }
        if avg_quality is not None:
            stats["avg_quality_score"] = avg_quality

        return stats

    def clear(self) -> None:
        """Clear all outputs, feedbacks, and reset metrics."""
        self._outputs.clear()
        self._feedbacks.clear()
        if self._metrics:
            self._metrics.clear()
