import os
from actions_logging.app_logging import logger
from env_files.create_common_env_and_get_diff_from_current import render_common_env_file_or_download_it
from env_files.handle_env_vars_on_deploy import handle_dot_env_and_history_update
from common.common import calculate_md5_file_checksum
from github.env import get_required_env_var, exit_on_error_and_write_summary
from env_files.constants import (
    COMMON_ENV_FILES_PATH, 
    COMMON_FILE_MD5_CHECKSUM, 
    COMMON_ENV_FILES_VERSION_HISTORY_DIR,
    COMMON
)


def main():
    """
    This script handles the deployment of common.env file for the given environment after approval.
    It will recreate the common.env file and check if the md5 checksum of the file matches the previous one.
    If the checksums match, it will upload the common.env file to S3 and update the version history.
    """
    try:
        logger.info("starting to handle common env file after approval")
        env_name = get_required_env_var("ENV_NAME")
        git_env_version = os.getenv("ENV_FILE_VERSION", "")  # can be in format: v$semver-ENV (e.g. v1.0.0-ENV)
        rebuild_env_file = os.getenv("REBUILD_ENV_FILE", "") == "true"
        previous_md5_checksum = get_required_env_var(COMMON_FILE_MD5_CHECKSUM)
        logger.info(f"previous md5 checksum: {previous_md5_checksum}")

        logger.info(f"handling common env file for {env_name}")
        file_name = render_common_env_file_or_download_it(env_name, git_env_version)
        generated_md5_checksum = calculate_md5_file_checksum(file_name)
        logger.info(f"generated md5 checksum: {generated_md5_checksum}")

        if previous_md5_checksum != generated_md5_checksum:
            raise RuntimeError(f"md5 checksums do not match from previous job")

        logger.info("md5 checksums match, will upload the common env file to s3")
        handle_dot_env_and_history_update(env_name=env_name,
                                          svc_name=COMMON,
                                          git_env_version=git_env_version,
                                          rebuild_env_file=rebuild_env_file,
                                          is_multi_service_repo=False,
                                          version_history_folder=COMMON_ENV_FILES_VERSION_HISTORY_DIR,
                                          env_files_path=COMMON_ENV_FILES_PATH)
    except Exception as e:
        exit_on_error_and_write_summary(f"An error occurred in handle_common_env_file.main: {e}")


if __name__ == '__main__':
    main()
