"""Health monitoring and self-healing."""

from datetime import datetime, timedelta
from typing import Dict, List, Optional
from src.core.logger import get_logger

logger = get_logger(__name__)


class HealthMonitor:
    """Monitors system health."""
    
    def __init__(self):
        """Initialize health monitor."""
        self.logger = get_logger(__name__)
        self.errors: List[Dict] = []
        self.connections: Dict[str, bool] = {}
        self.last_check: Optional[datetime] = None
    
    def record_error(self, context: str, error: Exception):
        """Record an error.
        
        Args:
            context: Error context
            error: Exception object
        """
        self.errors.append({
            "timestamp": datetime.utcnow(),
            "context": context,
            "error": str(error),
        })
        
        # Keep only last 100 errors
        if len(self.errors) > 100:
            self.errors = self.errors[-100:]
    
    def check_health(self) -> Dict[str, bool]:
        """Check system health.
        
        Returns:
            Dictionary of component -> healthy
        """
        health = {
            "database": self._check_database(),
            "exchanges": self._check_exchanges(),
        }
        
        self.last_check = datetime.utcnow()
        return health
    
    def _check_database(self) -> bool:
        """Check database connection.
        
        Returns:
            True if healthy
        """
        try:
            from src.core.database import get_database
            db = get_database()
            session = db.get_session()
            session.execute("SELECT 1")
            session.close()
            return True
        except Exception:
            return False
    
    def _check_exchanges(self) -> bool:
        """Check exchange connections.
        
        Returns:
            True if at least one exchange is connected
        """
        # Simplified - would check actual connections
        return len(self.connections) > 0
    
    def get_error_rate(self, minutes: int = 60) -> float:
        """Get error rate over time period.
        
        Args:
            minutes: Time period in minutes
            
        Returns:
            Errors per minute
        """
        since = datetime.utcnow() - timedelta(minutes=minutes)
        recent_errors = [e for e in self.errors if e["timestamp"] >= since]
        return len(recent_errors) / minutes if minutes > 0 else 0.0


# Global health monitor
_health_monitor: Optional[HealthMonitor] = None


def get_health_monitor() -> HealthMonitor:
    """Get global health monitor instance."""
    global _health_monitor
    if _health_monitor is None:
        _health_monitor = HealthMonitor()
    return _health_monitor

