# Copyright (c) 2021 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 collections.abc import Callable

import pyfaaster.common.utils as utils
from aws_lambda_powertools.middleware_factory import lambda_handler_decorator
from aws_lambda_powertools.utilities.data_classes import APIGatewayProxyEvent

from czc.api.environment import TestKeyEnvironment
from czc.api.v2.constants import CLOUDZERO_TEST_KEY, CLOUDZERO_TEST_KEY_HEADER
from czc.logging import get_logger

logger = get_logger()


@lambda_handler_decorator(trace_execution=True)
def test_key_aware(handler: Callable, event: APIGatewayProxyEvent, context, **kwargs):
    """Make this Lambda Handler Test Key Aware

    Parameters
    ----------

    Returns
    -------
    Callable
        Decorated Lambda Handler
    """
    with TestKeyEnvironment(event.get_header_value(CLOUDZERO_TEST_KEY_HEADER)):
        return handler(event, context, **kwargs)


@lambda_handler_decorator(trace_execution=True)
def web_test_key_aware(handler: Callable, event, context, **kwargs):
    """Make this Web API Lambda Handler Test Key Aware

    Parameters
    ----------

    Returns
    -------
    Callable
        Decorated Lambda Handler
    """
    if cloudzero_test_key_value := utils.deep_get(event, 'headers', CLOUDZERO_TEST_KEY_HEADER, ignore_case=True):
        os.environ[CLOUDZERO_TEST_KEY] = cloudzero_test_key_value
        logger.info(f'{CLOUDZERO_TEST_KEY_HEADER} present! Using {cloudzero_test_key_value}')
    else:
        logger.info(f'{CLOUDZERO_TEST_KEY_HEADER} not present! Resetting {CLOUDZERO_TEST_KEY}.')
        if CLOUDZERO_TEST_KEY in os.environ:
            logger.info(f'Removing {CLOUDZERO_TEST_KEY} from environment.')
            os.environ.pop(CLOUDZERO_TEST_KEY)
    return handler(event, context, **kwargs)
