# 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

from typing import Any, Dict

import boto3
import sentry_sdk
import simplejson as json

import czc.constants as constants
from czc.exceptions import NamespaceMissingException
from czc.logging import get_logger

logger = get_logger()


def _get_sentry_dsn(namespace: str = None) -> str:
    final_namespace = namespace or constants.NAMESPACE
    if final_namespace:
        sm = boto3.client('secretsmanager')
        secret = sm.get_secret_value(SecretId=f'cz-{final_namespace}-feature-setup-secrets')
        secret_dict = json.loads(secret['SecretString'])
        logger.debug(f'retrieved secrets {secret_dict}')
        return secret_dict['sentry_dsn']
    else:
        raise NamespaceMissingException("A namespace was not provided and one could not be found in the environment")


def send(message: Dict, sentry_dsn: str = None, tags: Dict = None, namespace: str = None) -> Any:
    tags = tags or {}
    sentry_dsn = sentry_dsn if sentry_dsn else _get_sentry_dsn(namespace=namespace)
    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', constants.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
