"""
Automatic intensity calculation for variance-aware anomaly visibility.

Ensures anomalies achieve minimum 4x separation ratio regardless of variance settings.
Eliminates guesswork and guarantees compelling visual results in CloudZero charts.
"""

from typing import Dict, Any


def calculate_anomaly_intensity(
    anomaly_type: str, 
    variance_config: Dict[str, Any],
    separation_target: float = 4.0
) -> float:
    """
    Calculate minimum intensity for clear anomaly visibility above variance noise.
    
    Args:
        anomaly_type: Type of anomaly (e.g., "daily_spike", "hourly_step_up")
        variance_config: Variance configuration with daily_variance_pct, hourly_variance_pct
        separation_target: Minimum separation ratio (default: 4.0x)
        
    Returns:
        Calculated intensity value that ensures target separation
        
    Raises:
        ValueError: For unsupported anomaly types
    """
    # Extract variance settings with defaults
    daily_variance_pct = variance_config.get("daily_variance_pct", 100)
    hourly_variance_pct = variance_config.get("hourly_variance_pct", 200)
    
    # Calculate variance factor (how much variance can amplify costs)
    # With 100% variance, costs can reach 2x base (100% + 100% = 200% of original)
    max_variance_multiplier = 1.0 + (max(daily_variance_pct, hourly_variance_pct) / 100.0)
    
    # Base intensities for clear separation without variance
    base_intensities = {
        "daily_spike": 3.0,
        "daily_step_up": 2.0, 
        "daily_step_down": 0.4,  # Reduction anomaly
        "hourly_spike": 4.0,
        "hourly_step_up": 2.5,
        "hourly_step_down": 0.3,  # Reduction anomaly
    }
    
    if anomaly_type not in base_intensities:
        raise ValueError(f"Unsupported anomaly type: {anomaly_type}")
    
    base_intensity = base_intensities[anomaly_type]
    
    # For reduction anomalies (step_down), calculate differently
    if "step_down" in anomaly_type:
        # Reduction anomalies: ensure final cost is clearly below variance range
        # Target: even with max variance boost, reduced cost stays well below normal range
        variance_adjusted_intensity = base_intensity / max_variance_multiplier
        
        # Ensure significant reduction (minimum 60% reduction even with high variance)
        return min(variance_adjusted_intensity, 0.4)
    
    # For increase anomalies: ensure anomaly signal rises well above variance ceiling
    # Formula: base_intensity * variance_factor * separation_target
    variance_compensation = max_variance_multiplier * separation_target
    calculated_intensity = base_intensity * variance_compensation
    
    # Apply reasonable limits to prevent extreme values
    max_intensity = 50.0  # Practical upper limit
    return min(calculated_intensity, max_intensity)


def get_separation_target(anomaly_type: str) -> float:
    """
    Get appropriate separation target for anomaly type.
    
    Different anomaly types may need different separation ratios for optimal visibility.
    """
    separation_targets = {
        "daily_spike": 4.0,      # Must stand out clearly in daily view
        "daily_step_up": 3.0,    # Permanent change, slightly lower target
        "daily_step_down": 3.0,  # Permanent change, slightly lower target  
        "hourly_spike": 5.0,     # Must be obvious in hourly drill-down
        "hourly_step_up": 3.0,   # Permanent change from specific hour
        "hourly_step_down": 3.0, # Permanent change from specific hour
    }
    
    return separation_targets.get(anomaly_type, 4.0)


def validate_intensity_effectiveness(
    anomaly_type: str,
    calculated_intensity: float,
    variance_config: Dict[str, Any]
) -> Dict[str, Any]:
    """
    Validate that calculated intensity will achieve target separation.
    
    Returns validation results with warnings if separation may be insufficient.
    """
    target_separation = get_separation_target(anomaly_type)
    max_variance_pct = max(
        variance_config.get("daily_variance_pct", 0),
        variance_config.get("hourly_variance_pct", 0)
    )
    
    # Estimate actual separation ratio
    max_variance_multiplier = 1.0 + (max_variance_pct / 100.0)
    estimated_separation = calculated_intensity / max_variance_multiplier
    
    validation_result = {
        "intensity": calculated_intensity,
        "target_separation": target_separation,
        "estimated_separation": estimated_separation,
        "max_variance_pct": max_variance_pct,
        "is_sufficient": estimated_separation >= target_separation,
        "warnings": []
    }
    
    if estimated_separation < target_separation:
        validation_result["warnings"].append(
            f"Calculated intensity {calculated_intensity:.1f} may not achieve "
            f"target {target_separation:.1f}x separation with {max_variance_pct}% variance"
        )
    
    if calculated_intensity > 20.0:
        validation_result["warnings"].append(
            f"High intensity {calculated_intensity:.1f} may create unrealistic cost spikes"
        )
    
    return validation_result