#!/usr/bin/env python3
"""
Alert Manager
Manages alerts and notifications
"""

import logging
import json
from typing import Dict, List, Optional
from datetime import datetime, timedelta

logger = logging.getLogger(__name__)

class AlertManager:
    """Manages alerts and notifications"""
    
    def __init__(self, config: Dict):
        self.config = config
        self.alert_history = []
        self.alert_cooldowns = {}  # Prevent spam
        
    def check_event(self, event: Dict, event_type: str):
        """Check if event should trigger an alert"""
        # Critical alerts
        if event_type == 'ClaimChallenged':
            self.send_alert('CRITICAL', f"Claim challenged: {event}")
        
        # Large value transfers
        if 'amount' in event:
            amount = event['amount']
            if amount > self.config.get('large_transfer_threshold', 10 * 10**18):  # 10 ETH default
                self.send_alert('WARNING', f"Large transfer detected: {amount / 10**18} ETH")
        
        # Check for unusual patterns
        self._check_patterns(event, event_type)
    
    def send_alert(self, level: str, message: str):
        """Send an alert"""
        # Check cooldown
        alert_key = f"{level}:{message[:50]}"
        if alert_key in self.alert_cooldowns:
            last_sent = self.alert_cooldowns[alert_key]
            if datetime.now() - last_sent < timedelta(minutes=5):
                return  # Still in cooldown
        
        # Record alert
        alert = {
            'timestamp': datetime.now().isoformat(),
            'level': level,
            'message': message
        }
        self.alert_history.append(alert)
        self.alert_cooldowns[alert_key] = datetime.now()
        
        # Log alert
        if level == 'CRITICAL':
            logger.critical(f"ALERT: {message}")
        elif level == 'WARNING':
            logger.warning(f"ALERT: {message}")
        else:
            logger.info(f"ALERT: {message}")
        
        # Send notifications (email, Slack, etc.)
        self._send_notifications(level, message)
    
    def _check_patterns(self, event: Dict, event_type: str):
        """Check for unusual patterns"""
        # Placeholder for pattern detection
        # Could detect:
        # - Rapid succession of events
        # - Unusual amounts
        # - Suspicious addresses
        pass
    
    def _send_notifications(self, level: str, message: str):
        """Send notifications via configured channels"""
        # Email notifications
        if self.config.get('email_enabled', False):
            self._send_email(level, message)
        
        # Slack notifications
        if self.config.get('slack_enabled', False):
            self._send_slack(level, message)
        
        # PagerDuty for critical alerts
        if level == 'CRITICAL' and self.config.get('pagerduty_enabled', False):
            self._send_pagerduty(message)
    
    def _send_email(self, level: str, message: str):
        """Send email notification"""
        # Placeholder - implement email sending
        pass
    
    def _send_slack(self, level: str, message: str):
        """Send Slack notification"""
        # Placeholder - implement Slack webhook
        pass
    
    def _send_pagerduty(self, message: str):
        """Send PagerDuty alert"""
        # Placeholder - implement PagerDuty integration
        pass
    
    def get_recent_alerts(self, limit: int = 100) -> List[Dict]:
        """Get recent alerts"""
        return self.alert_history[-limit:]

