"""
Notification service for anomaly alerts

This module provides functionality to send notifications when anomalies
are detected in trading performance.
"""

import logging
from typing import List, Dict, Any, Optional

logger = logging.getLogger(__name__)


class NotificationService:
    """
    Service for sending notifications about anomalies and alerts

    This class provides methods to send notifications through various channels
    when anomalies are detected in trading performance.
    """

    def __init__(
        self,
        feishu_webhook: Optional[str] = None,
        email_config: Optional[Dict[str, str]] = None,
    ):
        """
        Initialize notification service

        Args:
            feishu_webhook: Feishu webhook URL for notifications
            email_config: Email configuration dictionary
        """
        self.feishu_webhook = feishu_webhook
        self.email_config = email_config
        self.notification_history: List[Dict[str, Any]] = []

    def send_anomaly_alert(self, anomalies: List[str], context: Dict[str, Any]) -> bool:
        """
        Send alert for detected anomalies

        Args:
            anomalies: List of anomaly descriptions
            context: Additional context information (metrics, period, etc.)

        Returns:
            True if notification was sent successfully, False otherwise
        """
        if not anomalies:
            logger.debug("No anomalies to report")
            return True

        message = self._format_anomaly_message(anomalies, context)

        # Record notification
        notification_record = {
            "type": "anomaly_alert",
            "anomalies": anomalies,
            "context": context,
            "message": message,
            "timestamp": context.get("timestamp", 0),
        }
        self.notification_history.append(notification_record)

        # Send through configured channels
        success = True

        if self.feishu_webhook:
            success = success and self._send_feishu(message)

        if self.email_config:
            success = success and self._send_email(message, context)

        # Always log the anomalies
        logger.warning(f"Anomalies detected: {', '.join(anomalies)}")

        return success

    def _format_anomaly_message(self, anomalies: List[str], context: Dict[str, Any]) -> str:
        """
        Format anomaly alert message

        Args:
            anomalies: List of anomaly descriptions
            context: Context information

        Returns:
            Formatted message string
        """
        period = context.get("period", "unknown")
        metrics = context.get("metrics", {})

        message_parts = [
            "⚠️ Trading Performance Anomalies Detected",
            f"\nPeriod: {period}",
            f"\nTotal Anomalies: {len(anomalies)}",
            "\n\nDetected Issues:",
        ]

        for i, anomaly in enumerate(anomalies, 1):
            message_parts.append(f"{i}. {anomaly}")

        if metrics:
            message_parts.append("\n\nCurrent Metrics:")
            if hasattr(metrics, "win_rate"):
                message_parts.append(f"- Win Rate: {metrics.win_rate*100:.2f}%")
            if hasattr(metrics, "profit_factor"):
                message_parts.append(f"- Profit Factor: {metrics.profit_factor:.2f}")
            if hasattr(metrics, "max_drawdown"):
                message_parts.append(f"- Max Drawdown: {metrics.max_drawdown*100:.2f}%")
            if hasattr(metrics, "sharpe_ratio"):
                message_parts.append(f"- Sharpe Ratio: {metrics.sharpe_ratio:.2f}")

        message_parts.append("\n\nPlease review the trading strategy.")

        return "\n".join(message_parts)

    def _send_feishu(self, message: str) -> bool:
        """
        Send notification via Feishu webhook

        Args:
            message: Message to send

        Returns:
            True if successful, False otherwise
        """
        if not self.feishu_webhook:
            return False

        try:
            import requests

            payload = {"msg_type": "text", "content": {"text": message}}

            response = requests.post(self.feishu_webhook, json=payload, timeout=10)

            if response.status_code == 200:
                logger.info("Feishu notification sent successfully")
                return True
            else:
                logger.error(f"Failed to send Feishu notification: {response.status_code}")
                return False

        except Exception as e:
            logger.error(f"Error sending Feishu notification: {str(e)}")
            return False

    def _send_email(self, message: str, context: Dict[str, Any]) -> bool:
        """
        Send notification via email

        Args:
            message: Message to send
            context: Context information

        Returns:
            True if successful, False otherwise
        """
        if not self.email_config:
            return False

        try:
            import smtplib
            from email.mime.text import MIMEText
            from email.mime.multipart import MIMEMultipart

            smtp_server = self.email_config.get("smtp_server")
            smtp_port = self.email_config.get("smtp_port", 587)
            from_address = self.email_config.get("from_address")
            to_address = self.email_config.get("to_address")
            password = self.email_config.get("password")

            if not all([smtp_server, from_address, to_address, password]):
                logger.error("Incomplete email configuration")
                return False

            # Create message
            msg = MIMEMultipart()
            msg["From"] = from_address
            msg["To"] = to_address
            msg["Subject"] = f"Trading Anomaly Alert - {context.get('period', 'Unknown')}"

            msg.attach(MIMEText(message, "plain"))

            # Send email
            with smtplib.SMTP(smtp_server, smtp_port) as server:
                server.starttls()
                server.login(from_address, password)
                server.send_message(msg)

            logger.info("Email notification sent successfully")
            return True

        except Exception as e:
            logger.error(f"Error sending email notification: {str(e)}")
            return False

    def get_notification_history(self, limit: Optional[int] = None) -> List[Dict[str, Any]]:
        """
        Get notification history

        Args:
            limit: Maximum number of records to return (None for all)

        Returns:
            List of notification records
        """
        if limit:
            return self.notification_history[-limit:]
        return self.notification_history
