import os
import yaml
from actions_logging.app_logging import logger
from github.env import exit_on_error_and_write_summary, write_github_env, get_required_env_var
from lambdas.constants import DOMAIN_REPO_ROOT_FOLDER



def get_lambda_root_path_from_repos_yaml(repo_name):
    repo_name = repo_name.split('/')[1]
    try:
        lambda_root_path = '.'
        with open("repos.yaml", 'r') as file:
            data = yaml.safe_load(file)
        repo_data = data.get(repo_name)
        if not repo_data:
            raise ValueError("Repository data is empty.")
        if isinstance(repo_data, list):
            lambda_root_path = DOMAIN_REPO_ROOT_FOLDER
        return lambda_root_path
    except Exception as e:
        exit_on_error_and_write_summary(f"Error in get_lambda_root_path_from_repos_yaml: {e}")



def get_lambda_ms_path_from_root_path(is_multi_service_repo, svc_name, ms_root_path = ''):
    try:
        logger.info(f'Started get_lambda_ms_path_from_root_path, \
                    is_multi_service_repo: {is_multi_service_repo} \
                    svc_name: {svc_name}, ms_root_path: {ms_root_path}.')

        if is_multi_service_repo:
            lambda_path = f'{ms_root_path}/{svc_name}' if ms_root_path else svc_name
        else:
            lambda_path = ms_root_path if ms_root_path else '.'
        logger.info(f'MS_PATH is set to {lambda_path}')
        return lambda_path
    except Exception as e:
        exit_on_error_and_write_summary(f"error in get_lambda_ms_path_from_root_path: {e}")


def main():
    try:
        is_multi_service_repository = os.getenv("IS_MULTI_SERVICE_REPO", 'false') == 'true'
        repository_name = get_required_env_var('GITHUB_REPOSITORY')
        lambda_name = get_required_env_var('SVC_NAME')
        ms_root_path = get_lambda_root_path_from_repos_yaml(repository_name)
        ms_path = get_lambda_ms_path_from_root_path(is_multi_service_repository, lambda_name, ms_root_path)

        logger.info(f'MS_PATH is set to {ms_path}.')
        logger.info(f'MS_ROOT_PATH is set to {ms_root_path}.')
        write_github_env(ms_path, 'MS_PATH')
        write_github_env(ms_root_path, 'MS_ROOT_PATH')
    except Exception as e:
        exit_on_error_and_write_summary(f'Error get_lambda_paths.py: {e}')


if __name__ == '__main__':
    main()
