# Copyright (c) 2020 CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com

import os
import boto3
import simplejson as json
import sentry_sdk
from typing import Dict, Any

import pyfaaster.aws.tools as faaster_aws_tools
import czc.constants as constants

logger = faaster_aws_tools.setup_logging(constants.PROJECT_NAME)

sm = boto3.client('secretsmanager')
NAMESPACE = os.environ['NAMESPACE']


def _get_sentry_dsn():
    secret = sm.get_secret_value(SecretId=f'cz-{NAMESPACE}-feature-setup-secrets')
    secret_dict = json.loads(secret['SecretString'])
    logger.debug(f'retrieved secrets {secret_dict}')
    return secret_dict['sentry_dsn']


def send(message: Dict, sentry_dsn: str = None, tags: Dict = {}) -> Any:
    sentry_dsn = sentry_dsn if sentry_dsn else _get_sentry_dsn()
    sentry_sdk.init(sentry_dsn)
    logger.debug(f'Sending to sentry {message}')
    with sentry_sdk.push_scope() as scope:
        for key, value in tags.items():
            scope.set_tag(key, value)
        scope.level = 'fatal'
        scope.set_tag('feature', constants.PROJECT_NAME)
        scope.set_tag('namespace', NAMESPACE)
        scope.set_context('message', message)
        response = sentry_sdk.capture_message(f'{constants.PROJECT_NAME} alarm')
        sentry_sdk.flush()
        logger.debug(f'Sentry response {response}')
    return response
