"""AegisTrade AI Alert Notification Engine."""
from __future__ import annotations

import json
from collections import deque
from datetime import datetime, timezone
from typing import Any, Optional

from backend.app.audit.logger import audit_logger
from backend.app.config.settings import settings


class AlertLevel:
    INFO = "INFO"
    WARNING = "WARNING"
    CRITICAL = "CRITICAL"


class AlertEngine:
    """Dispatches notifications to log, internal buffer, and optional Telegram/webhooks."""

    def __init__(self) -> None:
        self.recent_alerts: deque[dict[str, Any]] = deque(maxlen=100)

    def emit(self, level: str, title: str, message: str, context: Optional[dict[str, Any]] = None) -> None:
        alert_payload = {
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "level": level,
            "title": title,
            "message": message,
            "context": context or {},
        }
        self.recent_alerts.append(alert_payload)

        # Log appropriately
        log_msg = f"[{level}] {title}: {message} | Context: {json.dumps(context or {})}"
        if level == AlertLevel.CRITICAL:
            audit_logger.critical(log_msg)
        elif level == AlertLevel.WARNING:
            audit_logger.warning(log_msg)
        else:
            audit_logger.info(log_msg)

    def get_recent(self) -> list[dict[str, Any]]:
        return list(self.recent_alerts)


alert_engine = AlertEngine()
