"""Clean performance metrics dataclasses - no C extensions, no complexity.

This module provides simple, immutable dataclasses for storing performance metrics.
All data is collected from Django's built-in systems (connection.queries, etc.)
"""

from dataclasses import dataclass, field
from typing import List, Dict, Any, Optional


@dataclass(frozen=True)
class QueryInfo:
    """Information about a single database query."""

    sql: str
    duration_seconds: float
    stack_trace: Optional[List[str]] = None

    @property
    def duration_ms(self) -> float:
        """Query duration in milliseconds."""
        return self.duration_seconds * 1000


@dataclass
class PerformanceMetrics:
    """Performance metrics collected during a monitoring session.

    This is a pure data container with no logic beyond simple computed properties.
    All metric collection is done by MetricsCollector.
    """

    # Timing
    response_time_ms: float

    # Memory
    memory_mb: float

    # Database
    query_count: int

    # Fields with defaults must come after fields without defaults
    memory_baseline_mb: float = 80.0  # Typical Django baseline
    queries: List[QueryInfo] = field(default_factory=list)
    cache_hits: int = 0
    cache_misses: int = 0
    operation_name: str = ""
    operation_type: str = "general"

    @property
    def memory_overhead_mb(self) -> float:
        """Memory overhead above baseline."""
        return max(0, self.memory_mb - self.memory_baseline_mb)

    @property
    def cache_hit_ratio(self) -> float:
        """Cache hit ratio (0.0-1.0)."""
        total = self.cache_hits + self.cache_misses
        return self.cache_hits / total if total > 0 else 0.0

    @property
    def total_query_time_ms(self) -> float:
        """Total time spent in database queries."""
        return sum(q.duration_ms for q in self.queries)

    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary for serialization."""
        return {
            "operation_name": self.operation_name,
            "operation_type": self.operation_type,
            "response_time_ms": self.response_time_ms,
            "memory_mb": self.memory_mb,
            "memory_overhead_mb": self.memory_overhead_mb,
            "query_count": self.query_count,
            "total_query_time_ms": self.total_query_time_ms,
            "cache_hits": self.cache_hits,
            "cache_misses": self.cache_misses,
            "cache_hit_ratio": self.cache_hit_ratio,
        }
