# -*- coding: utf-8 -*-
# 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 functools
import os
from typing import TypeVar, Callable, Any, cast

from czc.internal_api.client import invoked as invokes_internal_api

F = TypeVar('F', bound=Callable[..., Any])

FEATURE_BILLING_API: Any = {
    'namespace': lambda x: os.environ.get('BILLING_NAMESPACE') or os.environ['NAMESPACE'],
    'feature': 'billing',
    'account_id': lambda: os.environ.get('CORE_ACCOUNT_ID')
}


def _set_iapi_caller(handler: F) -> F:
    @functools.wraps(handler)
    def handler_wrapper(**kwargs):
        iapi_caller = f"cz-{os.environ['NAMESPACE']}-{os.environ.get('FEATURE', 'UNKNOWN')}"
        return handler(__iapi_caller__=iapi_caller, **kwargs)

    return cast(F, handler_wrapper)


def invokes_billing_api(api: str) -> Callable[[F], F]:
    def decorator(handler: F) -> F:
        @_set_iapi_caller
        @invokes_internal_api(**FEATURE_BILLING_API, api=api)
        @functools.wraps(handler)
        def handler_wrapper(**kwargs):
            return handler(**kwargs)

        return cast(F, handler_wrapper)

    return decorator
