import os
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 yarkon.constants import PIPELINE_ROOT_PATHS


def get_pipeline_root_path_from_constants(repo_name):
    try:
        logger.info('Started get_pipeline_root_path_from_constants.')
        repo_name = repo_name.upper().replace('-', '_')
        logger.info(f'REPO_NAME: {repo_name}')
        pipeline_root_path = '.'
        if repo_name in PIPELINE_ROOT_PATHS:
            pipeline_root_path = PIPELINE_ROOT_PATHS[repo_name]
        pipeline_root_path = os.getenv('MS_ROOT_PATH', pipeline_root_path)  # path for artifact|s code

        return pipeline_root_path
    except Exception as e:
        exit_on_error_and_write_summary(f"error in get_pipeline_root_path_from_constants: Reason \n{e}")


def get_pipeline_ms_path_from_root_path(is_multi_service_repo, svc_name, ms_root_path = ''):
    try:
        logger.info(f'Started get_pipeline_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:
            pipeline_path = f'{ms_root_path}/{svc_name}' if ms_root_path else svc_name
        else:
            pipeline_path = ms_root_path if ms_root_path else '.'
        logger.info(f'MS_PATH is set to {pipeline_path}')
        return pipeline_path
    except Exception as e:
        exit_on_error_and_write_summary(f"error in get_pipeline_ms_path_from_root_path: Reason \n{e}")


def main():
    try:
        is_multi_service_repository = os.getenv("IS_MULTI_SERVICE_REPO", 'false') == 'true'
        repository_name = get_required_env_var('GITHUB_REPOSITORY')
        pipeline_name = get_required_env_var('SVC_NAME')
        ms_root_path = get_pipeline_root_path_from_constants(repository_name)
        ms_path = get_pipeline_ms_path_from_root_path(is_multi_service_repository, pipeline_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_pipeline_paths.py. Reason: {e}')


if __name__ == '__main__':
    main()
