"""
Base notification interface for health check alerts.
"""

from abc import ABC, abstractmethod
from typing import Dict, Any, Optional
import logging

from ..core.checker import HealthCheckResult

logger = logging.getLogger(__name__)


class BaseNotifier(ABC):
    """Base class for all notification systems."""
    
    def __init__(self, config: Dict[str, Any]):
        """
        Initialize notifier with configuration.
        
        Args:
            config: Notification configuration dictionary
        """
        self.config = config
        self.enabled = config.get('enabled', False)
        self.logger = logging.getLogger(f'{__name__}.{self.__class__.__name__}')
    
    @abstractmethod
    def send_alert(self, result: HealthCheckResult) -> bool:
        """
        Send alert notification for a health check result.
        
        Args:
            result: Health check result that triggered the alert
            
        Returns:
            True if alert was sent successfully, False otherwise
        """
        pass
    
    @abstractmethod
    def test_connection(self, service_name: Optional[str] = None) -> bool:
        """
        Test the notification system connection.
        
        Args:
            service_name: Optional name of the service for identification in test messages
            
        Returns:
            True if connection is working, False otherwise
        """
        pass
    
    def format_message(self, template: str, result: HealthCheckResult) -> str:
        """
        Format message using template and result data.
        
        Args:
            template: Message template string
            result: Health check result
            
        Returns:
            Formatted message string
        """
        try:
            return template.format(
                name=result.service_name,
                url=result.url,
                status=result.status.upper(),
                error=result.error_message or 'No error details',
                response_time=f"{result.response_time * 1000:.2f}ms",
                timestamp=result.timestamp.strftime('%Y-%m-%d %H:%M:%S'),
                status_code=result.status_code or 'N/A'
            )
        except Exception as e:
            self.logger.error(f"Error formatting message: {e}")
            return f"Service {result.service_name} is {result.status}. Error: {result.error_message}"
    
    def is_enabled(self) -> bool:
        """Check if notifier is enabled."""
        return self.enabled
    
    def on_service_down(self, result: HealthCheckResult) -> bool:
        """
        Called when a service goes down.
        
        Args:
            result: Health check result showing service is down
            
        Returns:
            True if alert was sent successfully
        """
        if not self.enabled:
            self.logger.debug(f"{self.__class__.__name__} is disabled, skipping alert")
            return False
        
        return self.send_alert(result)
    
    def on_service_recovery(self, result: HealthCheckResult) -> bool:
        """
        Called when a service recovers.
        
        Args:
            result: Health check result showing service is healthy
            
        Returns:
            True if recovery notification was sent successfully
        """
        # Default implementation doesn't send recovery notifications
        # Subclasses can override this behavior
        return True