"""
Mock trace platform for testing.

In-memory storage that implements TracePlatform protocol.
"""

from __future__ import annotations

from typing import Any, Dict, List, Optional, Tuple


class MockPlatform:
    """In-memory trace platform for testing."""

    def __init__(self) -> None:
        self._traces: Dict[str, Dict[str, Any]] = {}

    def add_trace(self, trace: Dict[str, Any]) -> None:
        """Add a trace to the mock store."""
        trace_id = trace.get("trace_id", trace.get("id", ""))
        if not trace_id:
            raise ValueError("Trace must have 'trace_id' or 'id' field")
        self._traces[trace_id] = trace

    def query_traces(
        self,
        filter: Dict[str, Any],
        limit: int = 100,
        time_range: Optional[Tuple[str, str]] = None,
    ) -> List[Dict[str, Any]]:
        """Query traces matching filter criteria."""
        results = []
        for trace in self._traces.values():
            if self._matches_filter(trace, filter):
                results.append(trace)
            if len(results) >= limit:
                break
        return results

    def get_trace(self, trace_id: str) -> Dict[str, Any]:
        """Get a single trace by ID."""
        if trace_id not in self._traces:
            raise KeyError(f"Trace not found: {trace_id}")
        return self._traces[trace_id]

    def test_connection(self) -> bool:
        """Always returns True for mock platform."""
        return True

    def get_platform_name(self) -> str:
        return "mock"

    def clear(self) -> None:
        """Remove all traces."""
        self._traces.clear()

    def _matches_filter(self, trace: Dict[str, Any], filter: Dict[str, Any]) -> bool:
        """Check if trace matches all filter criteria."""
        metadata = trace.get("metadata", {})
        for key, value in filter.items():
            # Check in trace top-level
            if key in trace and trace[key] == value:
                continue
            # Check in metadata
            if key in metadata and metadata[key] == value:
                continue
            # Check with releaseops. prefix
            prefixed_key = f"releaseops.{key}"
            if prefixed_key in metadata and metadata[prefixed_key] == value:
                continue
            return False
        return True
