import logging
import os

import sentry_sdk

from errorboosterclient.logbroker import LogbrokerClient
from errorboosterclient.sentry import ErrorBoosterTransport

from intranet.trip.sftp.src.config import settings


logger = logging.getLogger(__name__)


def send_event(event: dict):
    event['source'] = os.getenv('DEPLOY_UNIT_ID')
    with LogbrokerClient() as logbroker:
        with logbroker.get_producer(
            source='trip',
            topic=settings.LOGBROKER_ERROR_BOOSTER_TOPIC
        ) as producer:
            producer.write(event)


def init_error_booster():
    logger.info('initializing sentry sdk for sending to error booster')
    sentry_sdk.init(
        transport=ErrorBoosterTransport(
            project=settings.ERROR_BOOSTER_PROJECT_ID,
            sender=send_event,
        ),
        environment=settings.ENV_TYPE,
        release=os.getenv('DEPLOY_DOCKER_IMAGE', '').split(':')[-1],
        shutdown_timeout=20,
        with_locals=False,
    )
    logger.info('initialized')
