"""
Model config analyzer for attribution.

Analyzes model configuration (temperature, max_tokens) to assess
influence on agent behavior using simple heuristics.
"""

from __future__ import annotations

from typing import Any, Dict, List

from llmhq_releaseops.attribution.models import Influence


class ModelConfigAnalyzer:
    """Analyzes model configuration to assess influence on behavior."""

    def analyze(
        self,
        action: str,
        model_config: Dict[str, Any],
        trace_context: Dict[str, Any] = None,
    ) -> List[Influence]:
        """
        Assess how model config may have influenced behavior.

        Generally low confidence — model config is rarely the primary cause.

        Args:
            action: What agent did.
            model_config: Model settings from bundle.
            trace_context: Additional context.

        Returns:
            Usually 0-2 Influence objects.
        """
        if not model_config:
            return []

        influences = []
        trace_context = trace_context or {}

        # Temperature influence
        temperature = model_config.get("temperature")
        if temperature is not None:
            influence = self._analyze_temperature(temperature, action)
            if influence:
                influences.append(influence)

        # Max tokens / truncation
        max_tokens = model_config.get("max_tokens")
        if max_tokens is not None:
            influence = self._analyze_max_tokens(max_tokens, trace_context)
            if influence:
                influences.append(influence)

        # Model version
        model = model_config.get("model", "")
        provider = model_config.get("provider", "")
        if model:
            influences.append(Influence(
                artifact_type="model_config",
                artifact_ref=f"{provider}/{model}" if provider else model,
                location="model",
                content_snippet=f"model={model}, provider={provider}",
                confidence=0.3,
                reasoning=f"Model {model} has specific capabilities that may influence behavior",
                confidence_reason="model config is indirect influence only",
            ))

        return sorted(influences, key=lambda i: i.confidence, reverse=True)

    def _analyze_temperature(self, temperature: float, action: str) -> Influence:
        """Assess temperature influence."""
        if temperature > 0.7:
            return Influence(
                artifact_type="model_config",
                artifact_ref="temperature",
                location="temperature",
                content_snippet=f"temperature={temperature}",
                confidence=0.4,
                reasoning=f"High temperature ({temperature}) allows more creative/varied responses",
                confidence_reason="temperature is indirect influence on randomness",
            )
        elif temperature < 0.3:
            return Influence(
                artifact_type="model_config",
                artifact_ref="temperature",
                location="temperature",
                content_snippet=f"temperature={temperature}",
                confidence=0.4,
                reasoning=f"Low temperature ({temperature}) favors deterministic responses",
                confidence_reason="temperature is indirect influence on determinism",
            )
        return None

    def _analyze_max_tokens(
        self, max_tokens: int, trace_context: Dict[str, Any]
    ) -> Influence:
        """Check if response may have been truncated."""
        output_tokens = trace_context.get("output_tokens", 0)
        if output_tokens and output_tokens >= max_tokens * 0.95:
            return Influence(
                artifact_type="model_config",
                artifact_ref="max_tokens",
                location="max_tokens",
                content_snippet=f"max_tokens={max_tokens}, output_tokens={output_tokens}",
                confidence=0.6,
                reasoning=f"Response likely truncated at {max_tokens} tokens (used {output_tokens})",
                confidence_reason="output near max_tokens limit suggests truncation",
            )
        return None
