"""Alert management."""

from typing import Dict, Optional, List
from sqlalchemy import select
from src.core.database import get_database, Alert
from src.core.logger import get_logger

logger = get_logger(__name__)


class AlertManager:
    """Manages alerts."""
    
    def __init__(self):
        """Initialize alert manager."""
        self.db = get_database()
        self.logger = get_logger(__name__)
    
    async def create_alert(
        self,
        name: str,
        alert_type: str,
        condition: Dict
    ) -> Alert:
        """Create a new alert.
        
        Args:
            name: Alert name
            alert_type: Alert type (price, indicator, risk, system)
            condition: Alert condition configuration
            
        Returns:
            Alert object
        """
        async with self.db.get_session() as session:
            try:
                alert = Alert(
                    name=name,
                    alert_type=alert_type,
                    condition=condition,
                    enabled=True
                )
                session.add(alert)
                await session.commit()
                await session.refresh(alert)
                return alert
            except Exception as e:
                await session.rollback()
                logger.error(f"Failed to create alert: {e}")
                raise
    
    async def list_alerts(self, enabled_only: bool = False) -> List[Alert]:
        """List all alerts.
        
        Args:
            enabled_only: Only return enabled alerts
            
        Returns:
            List of alerts
        """
        async with self.db.get_session() as session:
            stmt = select(Alert)
            if enabled_only:
                stmt = stmt.where(Alert.enabled == True)
            result = await session.execute(stmt)
            return result.scalars().all()


# Global alert manager
_alert_manager: Optional[AlertManager] = None


def get_alert_manager() -> AlertManager:
    """Get global alert manager instance."""
    global _alert_manager
    if _alert_manager is None:
        _alert_manager = AlertManager()
    return _alert_manager
