"""Error recovery mechanisms."""

import traceback
from typing import Optional, Dict, Any
from src.core.logger import get_logger
from .state_manager import get_state_manager
from .health_monitor import get_health_monitor

logger = get_logger(__name__)


class RecoveryManager:
    """Manages error recovery and system resilience."""
    
    def __init__(self):
        """Initialize recovery manager."""
        self.state_manager = get_state_manager()
        self.health_monitor = get_health_monitor()
        self.logger = get_logger(__name__)
    
    def handle_error(self, error: Exception, context: str = ""):
        """Handle errors with recovery.
        
        Args:
            error: Exception object
            context: Error context
        """
        error_msg = f"{context}: {str(error)}"
        logger.error(error_msg)
        logger.debug(traceback.format_exc())
        
        # Save error state
        self.state_manager.save_state("last_error", {
            "message": str(error),
            "context": context,
            "traceback": traceback.format_exc(),
        })
        
        # Update health monitor
        self.health_monitor.record_error(context, error)
    
    def recover_orders(self) -> bool:
        """Recover order state after disconnection.
        
        Returns:
            True if recovery successful
        """
        try:
            from src.trading.order_manager import get_order_manager
            order_manager = get_order_manager()
            
            # Get pending/open orders
            open_orders = order_manager.get_open_orders()
            
            # Try to sync with exchange
            for order in open_orders:
                # Would sync order status with exchange
                pass
            
            return True
        except Exception as e:
            self.logger.error(f"Failed to recover orders: {e}")
            return False
    
    def recover_connections(self) -> bool:
        """Recover exchange connections.
        
        Returns:
            True if recovery successful
        """
        try:
            from src.exchanges.factory import ExchangeFactory
            from src.core.database import get_database, Exchange
            
            db = get_database()
            session = db.get_session()
            
            try:
                exchanges = session.query(Exchange).filter_by(enabled=True).all()
                for exchange in exchanges:
                    adapter = ExchangeFactory.create(exchange.id)
                    if adapter:
                        self.logger.info(f"Recovered connection to {exchange.name}")
            finally:
                session.close()
            
            return True
        except Exception as e:
            self.logger.error(f"Failed to recover connections: {e}")
            return False


# Global recovery manager
_recovery_manager: Optional[RecoveryManager] = None


def get_recovery_manager() -> RecoveryManager:
    """Get global recovery manager instance."""
    global _recovery_manager
    if _recovery_manager is None:
        _recovery_manager = RecoveryManager()
    return _recovery_manager

