import sys

from actions_logging.app_logging import logger
from github.env import exit_on_error_and_write_summary
from github.github_apis import get_github_path_data
import os
import base64


def save_file(content: str, file_path: str, overwrite: bool = False) -> None:
    """Save decoded content to a file. By default, it ensures no overwrite, but allows overwrite if flag is set."""
    if os.path.exists(file_path) and not overwrite:
        exit_on_error_and_write_summary(f"File {file_path} already exists. Not allowing overwrite.")
    try:
        with open(file_path, "w") as file:
            file.write(content)
        logger.info(f"File {file_path} written successfully.")
    except Exception as e:
        logger.error(f"Failed to write file {file_path}: {e}")


def process_github_items(repo_name: str, items: list, output_folder: str, ref: str = None) -> None:
    """Process the list of items returned by the GitHub API, handling files and directories."""
    for item in items:
        item_type = item.get("type")
        item_path = item.get("path")
        logger.debug(f"Processing item: {item_type} - {item_path}")
        local_path = os.path.join(output_folder, item_path)
        if item_type == "file":
            if item_path:
                res_data = get_github_path_data(repo_name, item_path, ref=ref)
                encoded_content = res_data["content"]
                decoded_content = base64.b64decode(encoded_content).decode("utf-8")
                os.makedirs(os.path.dirname(local_path), exist_ok=True)
                save_file(decoded_content, local_path)
            else:
                logger.error(f"No download URL for file: {item_path}")

        elif item_type == "dir":
            get_folder_contents_from_github(repo_name, item_path, ref=ref, output_folder=output_folder)


def get_folder_contents_from_github(repo_name: str, folder_path: str, ref: str = None, output_folder: str = "downloads") -> None:
    """Fetch the contents of a folder from a GitHub repository and save them locally."""
    try:
        if not os.path.exists(output_folder):
            os.makedirs(output_folder)
        logger.info(f"Fetching contents of folder: {folder_path} from repo: {repo_name} at ref: {ref} to: {output_folder}")
        items = get_github_path_data(repo_name, folder_path, ref=ref)
        process_github_items(repo_name, items, output_folder, ref=ref)

    except Exception as e:
        exit_on_error_and_write_summary(f"Error fetching the folder contents: {e}")


def main():
    repo_name = sys.argv[1]
    folder_path = sys.argv[2]
    ref = sys.argv[3] if len(sys.argv) > 3 else None
    output_folder = sys.argv[4] if len(sys.argv) > 4 else "downloads"
    get_folder_contents_from_github(repo_name, folder_path, ref=ref, output_folder=output_folder)


if __name__ == '__main__':
    main()
