import os
from typing import List

from actions_logging.app_logging import logger
from common.common import raise_with_context, run_command
from github.env import exit_on_error_and_write_summary, get_required_env_var


def add_files_to_zip(zip_name: str, files_array: List[str]) -> None:
    """
    Add files to a zip archive.

    Args:
        zip_name (str): The name of the zip file.
        files_array (list[str]): List of file paths to add to the zip archive.
    """
    try:
        files_str = " ".join(files_array)
        logger.info(f"Adding {files_array} files to {zip_name}.")
        run_command(f"zip -u {zip_name} {files_str}")
        logger.info_green(f"Adding {files_array} files to {zip_name} done.")
    except Exception as e:
        raise_with_context(e)


def main():
    try:
        env_file = ".env"
        if not os.path.isfile(env_file):
            raise_with_context(None, FileNotFoundError(f".env file {env_file} not found."))

        is_downloaded = get_required_env_var("BUILD_ARTIFACT") == "false"
        svc_name = get_required_env_var("SVC_NAME")
        zip_name = f"{svc_name}.zip" if is_downloaded else get_required_env_var("ZIP_FILE")

        if not os.path.isfile(zip_name):
            raise_with_context(None, FileNotFoundError(f"Zip file {zip_name} not found."))
        add_files_to_zip(zip_name, [env_file])

    except Exception as e:
        exit_on_error_and_write_summary(f"Error in add_dot_env_to_java_lambda.py: {e}")


if __name__ == "__main__":
    main()
