"""
Risk assessment utilities for BADAS predictions.

Converts raw probabilities to human-readable risk levels and provides
statistical analysis of prediction results.
"""

import numpy as np
from dataclasses import dataclass
from typing import Any, Dict, List, Optional


@dataclass
class RiskConfig:
    """Configuration for risk level assessment.

    Three risk tiers with configurable probability boundaries:
        low    : [0,             medium_threshold)
        medium : [medium_threshold, high_threshold)
        high   : [high_threshold,  1]

    Attributes:
        medium_threshold: Boundary between low and medium (default 0.5 = 50%)
        high_threshold:   Boundary between medium and high (default 0.75 = 75%)
        use_emoji:        True = colored circles 🟢/🟠/🔴, False = letters G/O/R
    """
    medium_threshold: float = 0.5
    high_threshold: float = 0.75
    use_emoji: bool = True


def create_risk_assessment(
    probability: float,
    config: Optional[RiskConfig] = None,
) -> Dict[str, Any]:
    """
    Create risk assessment from probability.

    Args:
        probability: Collision probability (0-1)
        config: Risk configuration (thresholds and display mode).
                Uses RiskConfig defaults if not provided.

    Returns:
        Dictionary with risk level and metadata
    """
    if config is None:
        config = RiskConfig()

    if probability < config.medium_threshold:
        level = "low"
        color = "green"
        emoji_char = "🟢"
        letter = "G"
        description = "Normal driving conditions"
    elif probability < config.high_threshold:
        level = "medium"
        color = "orange"
        emoji_char = "🟠"
        letter = "O"
        description = "Caution recommended"
    else:
        level = "high"
        color = "red"
        emoji_char = "🔴"
        letter = "R"
        description = "High collision risk"

    indicator = emoji_char if config.use_emoji else letter

    return {
        "probability": probability,
        "level": level,
        "color": color,
        "emoji": indicator,
        "description": description,
        "percentage": f"{probability * 100:.1f}%"
    }


def analyze_prediction_statistics(
    predictions: List[Dict[str, Any]],
    config: Optional[RiskConfig] = None,
) -> Dict[str, Any]:
    """
    Analyze prediction statistics for insights.

    Args:
        predictions: List of prediction dictionaries from predict_video
        config: Risk configuration for threshold-aware distribution stats.
                Uses RiskConfig defaults if not provided.

    Returns:
        Dictionary with statistical analysis
    """
    if not predictions:
        return {}

    if config is None:
        config = RiskConfig()

    probs = np.array([p["probability"] for p in predictions])
    raw_probs = np.array([p["raw_probability"] for p in predictions])
    latencies = np.array([p["latency_ms"] for p in predictions])

    stats = {
        "smoothed": {
            "mean": float(np.mean(probs)),
            "std": float(np.std(probs)),
            "min": float(np.min(probs)),
            "max": float(np.max(probs)),
            "median": float(np.median(probs))
        },
        "raw": {
            "mean": float(np.mean(raw_probs)),
            "std": float(np.std(raw_probs)),
            "min": float(np.min(raw_probs)),
            "max": float(np.max(raw_probs)),
            "median": float(np.median(raw_probs))
        },
        "latency": {
            "mean_ms": float(np.mean(latencies)),
            "std_ms": float(np.std(latencies)),
            "min_ms": float(np.min(latencies)),
            "max_ms": float(np.max(latencies))
        },
        "smoothing_effect": {
            "variance_reduction": 1 - np.var(probs) / np.var(raw_probs) if np.var(raw_probs) > 0 else 0,
            "mean_abs_diff": float(np.mean(np.abs(probs - raw_probs))),
            "max_abs_diff": float(np.max(np.abs(probs - raw_probs)))
        },
        "risk_distribution": {
            "low": float(np.sum(probs < config.medium_threshold) / len(probs)),
            "medium": float(np.sum((probs >= config.medium_threshold) & (probs < config.high_threshold)) / len(probs)),
            "high": float(np.sum(probs >= config.high_threshold) / len(probs))
        },
        "peak_risk": {
            "probability": float(np.max(probs)),
            "timestamp": predictions[int(np.argmax(probs))]["timestamp"],
            "frame_index": predictions[int(np.argmax(probs))]["frame_index"]
        },
        "total_predictions": len(predictions)
    }

    return stats


__all__ = [
    'RiskConfig',
    'create_risk_assessment',
    'analyze_prediction_statistics',
]
