from actions_logging.app_logging import logger
from github.env import exit_on_error_and_write_summary, get_required_env_var
from terragrunt.tg_common import get_deploy_config_from_default_branch
from terragrunt.constants import DEPLOY_CONFIG_PATH


def get_deployers():
    try:
        deploy_config = get_deploy_config_from_default_branch()
        deployers = deploy_config.get('deployers')
        if not deployers:
            exit_on_error_and_write_summary(f"Deployers users list is empty. exiting")
        if not isinstance(deployers, list):
            exit_on_error_and_write_summary(f"Malformed deployers user data: should be a list of strings. exiting")
        return deployers
    except Exception as e:
        exit_on_error_and_write_summary(f"Couldn't get deployers list due to error: {e}")

def main():
    user = get_required_env_var('USER')
    repo = get_required_env_var('REPO')

    deployers = get_deployers()
    logger.info(f"Users allowed to deploy: {deployers}")
    if user not in deployers:
        exit_on_error_and_write_summary(f"Current user {user} is not on deployers users list in deploy config on default branch for this repository, submit a PR to {DEPLOY_CONFIG_PATH} 'deployers' property list to update permissions")

    logger.info(f"User {user} allowed to deploy infrastructure resources from {repo}")

if __name__ == "__main__":
    main()
