# 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
from typing import Optional

import boto3

from czc import json
from czc.api.environment import TestKeyEnvironment
from czc.logging import get_logger

events_client = boto3.client('events')

logger = get_logger()


def get_event_bus_name(namespace: Optional[str] = None) -> str:
    ns = namespace or os.environ['NAMESPACE']
    return f'cz-{ns}-events-primary'


def publish_event(namespace, detail_type, source, event_detail, event_detail_schema=None):
    validated_event_detail = event_detail_schema(event_detail) if event_detail_schema else event_detail
    entries = [
        {
            'Source': source,
            'DetailType': detail_type,
            'EventBusName': get_event_bus_name(namespace),
            'Detail': json.dumps(TestKeyEnvironment.add_test_key_parameter(validated_event_detail)),
        }
    ]

    logger.debug(f'Sending event bridge entries {entries}')

    response = events_client.put_events(Entries=entries)
    return response['Entries']
