"""Storage abstraction for chain of thoughts."""

from __future__ import annotations

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

from .types import Thought

if TYPE_CHECKING:
    from .._shared.metrics import UsageMetrics


@runtime_checkable
class CoTStorageProtocol(Protocol):
    """Protocol for chain of thoughts storage implementations.

    Any class that has a `thoughts` property (read returns list, write appends Thought)
    can be used as storage for the CoT toolset.

    Example:
        ```python
        class MyCustomStorage:
            def __init__(self):
                self._thoughts: list[Thought] = []

            @property
            def thoughts(self) -> list[Thought]:
                return self._thoughts

            @thoughts.setter
            def thoughts(self, value: Thought) -> None:
                self._thoughts.append(value)
        ```
    """

    @property
    def thoughts(self) -> list[Thought]:
        """Get the current list of thoughts."""
        ...

    @thoughts.setter
    def thoughts(self, value: Thought) -> None:
        """Append a single thought to the list."""
        ...


@dataclass
class CoTStorage:
    """Default in-memory chain of thoughts storage.

    Simple implementation that stores thoughts in memory.
    Use this for standalone agents or testing.

    Attributes:
        _thoughts: Internal list of recorded thoughts.
        _metrics: Optional usage metrics tracker (enabled via track_usage parameter).

    Example:
        ```python
        from pydantic_ai_toolsets import create_cot_toolset, CoTStorage

        storage = CoTStorage()
        toolset = create_cot_toolset(storage=storage)

        # After agent runs, access thoughts directly
        print(storage.thoughts)

        # With metrics tracking
        storage = CoTStorage(track_usage=True)
        toolset = create_cot_toolset(storage=storage)
        # After agent runs
        print(storage.metrics.total_tokens())
        ```
    """

    _thoughts: list[Thought] = field(default_factory=list)
    _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._thoughts = []
        self._metrics = None
        if track_usage:
            # Import here to avoid circular imports and keep it optional
            # Add toolsets directory to path if needed
            import os

            from .._shared.metrics import UsageMetrics

            self._metrics = UsageMetrics()

    @property
    def thoughts(self) -> list[Thought]:
        """Get the current list of thoughts."""
        return self._thoughts

    @thoughts.setter
    def thoughts(self, value: Thought) -> None:
        """Append a single thought to the list."""
        self._thoughts.append(value)

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

        Returns:
            UsageMetrics instance if track_usage=True was set, otherwise None.
        """
        return self._metrics

    def get_statistics(self) -> dict[str, int | float]:
        """Get summary statistics about the chain of thoughts.

        Returns:
            Dictionary with thought counts and metadata.
        """
        total = len(self._thoughts)
        revisions = sum(1 for t in self._thoughts if t.is_revision)
        branches = len(set(t.branch_id for t in self._thoughts if t.branch_id))
        final = sum(1 for t in self._thoughts if not t.next_thought_needed)

        return {
            "total_thoughts": total,
            "revisions": revisions,
            "branches": branches,
            "final_thoughts": final,
        }

    def clear(self) -> None:
        """Clear all thoughts and reset metrics."""
        self._thoughts.clear()
        if self._metrics:
            self._metrics.clear()
