"""
ThreatRadar - Security and threat detection
"""

from datetime import datetime
from enum import Enum
import logging

logger = logging.getLogger(__name__)


class ThreatLevel(Enum):
    NORMAL = 0
    LOW = 1
    MEDIUM = 2
    HIGH = 3
    CRITICAL = 4


class ThreatRadar:
    """Threat detection system"""
    
    def __init__(self):
        self.threats_detected = []
        self.sensitivity = 0.7
        
    def analyze_system_metrics(self, metrics: dict) -> dict:
        threats = []
        
        # Check CPU
        if metrics.get('cpu_percent', 0) > 80:
            threats.append({
                'type': 'high_cpu',
                'level': ThreatLevel.MEDIUM,
                'description': f"High CPU usage: {metrics['cpu_percent']}%"
            })
        
        # Check memory
        if metrics.get('memory_percent', 0) > 90:
            threats.append({
                'type': 'high_memory',
                'level': ThreatLevel.HIGH,
                'description': f"High memory usage: {metrics['memory_percent']}%"
            })
        
        analysis = {
            'timestamp': datetime.now().isoformat(),
            'threats_detected': threats,
            'threat_count': len(threats),
            'overall_level': self._calculate_overall_level(threats)
        }
        
        if threats:
            self.threats_detected.extend(threats)
            logger.warning(f"Threats detected: {len(threats)}")
        
        return analysis
    
    def _calculate_overall_level(self, threats: list) -> ThreatLevel:
        if not threats:
            return ThreatLevel.NORMAL
        
        max_level = max((t['level'].value for t in threats), default=0)
        
        if max_level >= 4:
            return ThreatLevel.CRITICAL
        elif max_level >= 3:
            return ThreatLevel.HIGH
        elif max_level >= 2:
            return ThreatLevel.MEDIUM
        else:
            return ThreatLevel.LOW
