from typing import Any, Dict
from jazzmine.logging.sinks.base_sink import BaseSink
from jazzmine.logging.exceptions import LoggerDependencyError


class SentryLogger(BaseSink):
    """Sentry sink using official SDK"""
    
    def initialize(self) -> None:
        try:
            import sentry_sdk
        except ImportError:
            raise LoggerDependencyError(
                "sentry-sdk is required for Sentry sink. Install: pip install sentry-sdk"
            )
        
        dsn = self.sink_config.get('dsn')
        environment = self.sink_config.get('environment', 'production')
        traces_sample_rate = self.sink_config.get('traces_sample_rate', 0.0)
        
        sentry_sdk.init(
            dsn=dsn,
            environment=environment,
            traces_sample_rate=traces_sample_rate,
        )
        
        self.sentry = sentry_sdk
        self._initialized = True
    
    def shutdown(self) -> None:
        if self._initialized:
            self.sentry.flush()
    
    def log(self, level: str, msg: str, **kwargs) -> None:
        if not self._initialized:
            return
        
        level_map = {
            'debug': 'debug',
            'info': 'info',
            'warning': 'warning',
            'error': 'error',
            'critical': 'fatal'
        }
        
        sentry_level = level_map.get(level, 'info')
        
        with self.sentry.push_scope() as scope:
            scope.set_level(sentry_level)
            for key, value in kwargs.items():
                scope.set_extra(key, value)
            
            if level in ('error', 'critical'):
                self.sentry.capture_message(msg, level=sentry_level)
            else:
                self.sentry.capture_message(msg, level=sentry_level)
    
    async def alog(self, level: str, msg: str, **kwargs) -> None:
        # Sentry SDK handles async internally
        self.log(level, msg, **kwargs)
