from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from loguru import logger
from typing import List, Dict
from src.config.config import settings

class SlackNotifier:
    def __init__(self):
        self.client = WebClient(token=settings.SLACK_WEBHOOK_URL)
        logger.info("Slack 알림 시스템 초기화 완료")

    def send_alert(self, alerts: List[Dict]) -> bool:
        if not alerts:
            return True

        try:
            for alert in alerts:
                message = self._format_alert_message(alert)
                self.client.chat_postMessage(
                    channel="#gpu-monitoring",
                    text=message,
                    blocks=self._create_alert_blocks(alert)
                )
            return True
        except SlackApiError as e:
            logger.error(f"Slack 알림 전송 실패: {str(e)}")
            return False
        except Exception as e:
            logger.error(f"알림 전송 중 예상치 못한 오류 발생: {str(e)}")
            return False

    def _format_alert_message(self, alert: Dict) -> str:
        alert_type = alert.get('type', 'unknown')
        message = alert.get('message', '알림 메시지 없음')
        
        emoji_map = {
            'temperature': '🌡️',
            'memory': '💾',
            'coolant_level': '💧',
            'coolant_temp': '🌡️',
            'pump_status': '⚙️',
            'leak': '⚠️'
        }
        
        emoji = emoji_map.get(alert_type, '⚠️')
        return f"{emoji} *{alert_type.upper()}* - {message}"

    def _create_alert_blocks(self, alert: Dict) -> List[Dict]:
        return [
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": self._format_alert_message(alert)
                }
            },
            {
                "type": "context",
                "elements": [
                    {
                        "type": "mrkdwn",
                        "text": f"발생 시간: {alert.get('timestamp', 'N/A')}"
                    }
                ]
            }
        ] 