"""Easy smoothing configuration with presets and recommendations."""

from typing import Optional, Dict, Any
from enum import Enum


class SmoothingPreset(Enum):
    """Predefined smoothing presets for common scenarios."""
    NONE = "none"
    LIGHT = "light"
    MEDIUM = "medium"
    HEAVY = "heavy"
    ULTRA = "ultra"


class SmoothingConfig:
    """Easy-to-configure smoothing settings.
    
    Just pick a preset or customize!
    
    Example:
        ```python
        import eye as eye
        
        # Use preset
        config = eye.SmoothingConfig(eye.SmoothingPreset.HEAVY)
        
        # Get recommendation
        config = eye.SmoothingConfig.get_recommendation("highway")
        
        # Custom alpha
        config = eye.SmoothingConfig(eye.SmoothingPreset.MEDIUM, custom_alpha=0.25)
        
        # Use with ExponentialSmoothing
        smoother = eye.ExponentialSmoothing(alpha=config.alpha)
        ```
    """
    
    PRESETS = {
        SmoothingPreset.NONE: {
            'enabled': False,
            'alpha': 1.0,
            'description': 'No smoothing (raw detections)'
        },
        SmoothingPreset.LIGHT: {
            'enabled': True,
            'alpha': 0.5,
            'description': 'Light smoothing (fast response, minimal jitter reduction)'
        },
        SmoothingPreset.MEDIUM: {
            'enabled': True,
            'alpha': 0.3,
            'description': 'Medium smoothing (balanced - RECOMMENDED)'
        },
        SmoothingPreset.HEAVY: {
            'enabled': True,
            'alpha': 0.15,
            'description': 'Heavy smoothing (slow response, max jitter reduction)'
        },
        SmoothingPreset.ULTRA: {
            'enabled': True,
            'alpha': 0.05,
            'description': 'Ultra smooth (very slow response, cinematic look)'
        }
    }
    
    def __init__(
        self,
        preset: SmoothingPreset = SmoothingPreset.MEDIUM,
        custom_alpha: Optional[float] = None
    ):
        """
        Args:
            preset: Preset smoothing level
            custom_alpha: Override alpha (0-1, lower = smoother)
        """
        self.preset = preset
        self.config = self.PRESETS[preset].copy()
        
        if custom_alpha is not None:
            self.config['alpha'] = custom_alpha
            self.config['enabled'] = True
    
    @property
    def enabled(self) -> bool:
        """Is smoothing enabled?"""
        return self.config['enabled']
    
    @property
    def alpha(self) -> float:
        """Smoothing alpha value."""
        return self.config['alpha']
    
    @property
    def description(self) -> str:
        """Description of current settings."""
        return self.config['description']
    
    @classmethod
    def get_recommendation(cls, use_case: str) -> 'SmoothingConfig':
        """Get recommended smoothing for use case.
        
        Args:
            use_case: Scenario name (highway, city, sports, surveillance, etc.)
        
        Returns:
            SmoothingConfig with recommended preset
        
        Example:
            >>> # For Dakar racing (fast vehicles)
            >>> config = SmoothingConfig.get_recommendation("highway")
            >>> smoother = eye.ExponentialSmoothing(alpha=config.alpha)
        """
        recommendations = {
            # Traffic scenarios
            'highway': SmoothingPreset.LIGHT,  # Fast vehicles (Dakar!)
            'racing': SmoothingPreset.LIGHT,  # Racing vehicles
            'dakar': SmoothingPreset.LIGHT,  # Dakar racing
            'city': SmoothingPreset.MEDIUM,  # Mixed speeds
            'parking': SmoothingPreset.HEAVY,  # Slow, stable
            
            # People scenarios
            'pedestrians': SmoothingPreset.MEDIUM,  # Walking
            'crowd': SmoothingPreset.HEAVY,  # Dense, slow
            'running': SmoothingPreset.LIGHT,  # Fast motion
            
            # Sports
            'sports': SmoothingPreset.LIGHT,  # Fast, dynamic
            'soccer': SmoothingPreset.LIGHT,
            'basketball': SmoothingPreset.LIGHT,
            
            # Surveillance
            'surveillance': SmoothingPreset.HEAVY,  # Stable, professional
            'security': SmoothingPreset.HEAVY,
            
            # Drones/aerial
            'drone': SmoothingPreset.ULTRA,  # Camera shake
            'aerial': SmoothingPreset.ULTRA,
            
            # Warehouse/retail
            'warehouse': SmoothingPreset.MEDIUM,
            'retail': SmoothingPreset.MEDIUM,
            
            # Default
            'default': SmoothingPreset.MEDIUM
        }
        
        preset = recommendations.get(use_case.lower(), SmoothingPreset.MEDIUM)
        return cls(preset)
    
    def __repr__(self) -> str:
        return f"SmoothingConfig(preset={self.preset.value}, alpha={self.alpha}, enabled={self.enabled})"


def get_smoothing_guide() -> Dict[str, Any]:
    """Get complete smoothing configuration guide.
    
    Returns:
        Dictionary with presets, parameters, and tips
    
    Example:
        >>> guide = eye.get_smoothing_guide()
        >>> print(guide['tips'])
    """
    return {
        'presets': {
            preset.value: {
                'alpha': config['alpha'],
                'description': config['description'],
                'use_for': _get_use_cases_for_preset(preset)
            }
            for preset, config in SmoothingConfig.PRESETS.items()
        },
        'parameters': {
            'alpha': {
                'range': '0.0 - 1.0',
                'low': 'Very smooth, slow response (0.05-0.15)',
                'medium': 'Balanced (0.2-0.4)',
                'high': 'Fast response, less smooth (0.5-0.8)'
            }
        },
        'tips': [
            'Start with MEDIUM preset (alpha=0.3)',
            'Lower alpha for more smoothing but slower tracking',
            'Higher alpha for faster response but more jitter',
            'Use ULTRA for drone/handheld footage',
            'Use LIGHT for fast-moving objects (Dakar, sports)',
            'Use HEAVY for surveillance/security cameras'
        ]
    }


def _get_use_cases_for_preset(preset: SmoothingPreset) -> list:
    """Get use cases for a preset."""
    mapping = {
        SmoothingPreset.NONE: ['Debugging', 'Raw data analysis'],
        SmoothingPreset.LIGHT: ['Fast vehicles', 'Sports', 'Running', 'Highway', 'Dakar racing'],
        SmoothingPreset.MEDIUM: ['City traffic', 'Pedestrians', 'Warehouse', 'General use'],
        SmoothingPreset.HEAVY: ['Surveillance', 'Parking lots', 'Crowds', 'Security'],
        SmoothingPreset.ULTRA: ['Drones', 'Handheld cameras', 'Cinematic footage']
    }
    return mapping.get(preset, [])
