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 github.github_apis import get_changed_files
from github.utils import list_to_comma_separated_string


def handle_include_exclude(full_name:str, include_files=None, exclude_files=None) -> bool:
    try:
        if exclude_files:
            parse_exclude = [x.strip() for x in exclude_files.split(',')]
            for path in parse_exclude:
                if full_name.startswith(path):
                    logger.info(f'Excluding file: {full_name}')
                    return False
        if include_files:
            parse_include = [x.strip() for x in include_files.split(',')]
            for path in parse_include:
                if full_name.startswith(path):
                    logger.info(f'Including file: {full_name}')
                    return True
        else:
            return True
    except Exception as e:
        exit_on_error_and_write_summary(f'{e} occurred while handling include/exclude files')


def handle_changed_files(full_repo_name, pr_number, exclude_files=None, include_files=None) -> list:
    """
      Based on the PR id, get list of changed files
    """
    # see https://docs.github.com/en/rest/pulls/pulls?apiVersion=2022-11-28#list-pull-requests-files
    try:
        files = []
        pr_files = get_changed_files(full_repo_name=full_repo_name, pr_number=pr_number)
        if not pr_files:
            exit_on_error_and_write_summary(f"couldn't get the list of files that belongs to PR {pr_number}")
        for file_details in pr_files:
            full_name = file_details['filename']
            logger.info(full_name)
            if include_files or exclude_files:
                if handle_include_exclude(full_name, include_files, exclude_files):
                    files.append(full_name)
            else:
                files.append(full_name)
        return files
    except Exception as e:
        exit_on_error_and_write_summary(f'ERROR. Exception: {e} occurred while fetching the list of files that belongs to PR {pr_number}')


if __name__ == '__main__':
    pr_number = get_required_env_var("PR_NUMBER")
    repo_name = get_required_env_var("REPO_NAME")
    include = os.getenv("INCLUDE")  # files or dirs to include
    exclude = os.getenv("EXCLUDE")  # files or dirs to exclude
    list_of_changed_files = handle_changed_files(
        full_repo_name=repo_name,
        pr_number=pr_number,
        exclude_files=exclude,
        include_files=include
    )
    changed_files = list_to_comma_separated_string(list_of_changed_files)
    logger.info(f'Changed files: {changed_files}')
    write_github_env(changed_files, 'CHANGED_FILES')
