# Copyright (c) 2025 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 czc.api.v2.exceptions import ServiceError


def environ_aware(required=None, optional=None):
    """Decorator that will add each environment variable in reqs and opts
    to kwargs. The variables in reqs will be checked for existence
    and throw if the environmental variable is missing.

    Args:
        required (iterable): required environment vars
        optional (iterable): optional environment vars

    Returns:
        function (func): a function that is environ aware
    """

    def environ_handler(handler):
        def function_wrapper(*args, **kwargs):
            for r in required if required else []:
                value = os.environ.get(r)
                if not value:
                    raise ServiceError(f'{r} environment variable missing.')
                kwargs[r] = value

            for o in optional if optional else []:
                kwargs[o] = os.environ.get(o)

            return handler(*args, **kwargs)

        return function_wrapper

    return environ_handler


namespace_aware = environ_aware(['NAMESPACE'], [])
