"""AI session telemetry collector.

Accumulates per-call metrics (tokens, cost, latency) and fix outcomes
across the entire AI session so they can be attached to result metadata
at the end of the pipeline.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any


@dataclass
class AITelemetry:
    """Accumulator for AI session metrics.

    Attributes:
        total_api_calls: Number of AI provider API calls made.
        total_input_tokens: Sum of input tokens across all calls.
        total_output_tokens: Sum of output tokens across all calls.
        total_cost_usd: Cumulative estimated cost in USD.
        total_latency_ms: Cumulative latency in milliseconds.
        successful_fixes: Number of fixes that were applied successfully.
        failed_fixes: Number of fixes that failed to apply.
    """

    total_api_calls: int = 0
    total_input_tokens: int = 0
    total_output_tokens: int = 0
    total_cost_usd: float = 0.0
    total_latency_ms: float = 0.0
    successful_fixes: int = 0
    failed_fixes: int = 0

    def record_call(
        self,
        *,
        input_tokens: int,
        output_tokens: int,
        cost: float,
        latency_ms: float,
    ) -> None:
        """Record a single AI provider API call.

        Args:
            input_tokens: Input tokens consumed by the call.
            output_tokens: Output tokens generated by the call.
            cost: Estimated cost in USD for the call.
            latency_ms: Latency in milliseconds for the call.
        """
        self.total_api_calls += 1
        self.total_input_tokens += input_tokens
        self.total_output_tokens += output_tokens
        self.total_cost_usd += cost
        self.total_latency_ms += latency_ms

    def to_dict(self) -> dict[str, Any]:
        """Serialize telemetry to a JSON-compatible dictionary.

        Returns:
            Dictionary with all telemetry fields, cost rounded to
            6 decimal places and latency rounded to 1 decimal place.
        """
        return {
            "api_calls": self.total_api_calls,
            "input_tokens": self.total_input_tokens,
            "output_tokens": self.total_output_tokens,
            "cost_usd": round(self.total_cost_usd, 6),
            "latency_ms": round(self.total_latency_ms, 1),
            "successful_fixes": self.successful_fixes,
            "failed_fixes": self.failed_fixes,
        }
