# 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 TYPE_CHECKING, Optional

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

if TYPE_CHECKING:
    from mypy_boto3_events.type_defs import PutEventsRequestEntryTypeDef

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
    entry: PutEventsRequestEntryTypeDef = {
        'Source': source,
        'DetailType': detail_type,
        'EventBusName': get_event_bus_name(namespace),
        'Detail': json.dumps(TestKeyEnvironment.add_test_key_parameter(validated_event_detail)),
    }
    entries = [entry]

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

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