from datetime import datetime
from actions_logging.app_logging import logger
from env_files.build_and_upload_dotenv import build_and_upload_dot_envs
from env_files.get_semver_for_new_tag import get_version_and_changes
from env_files.handle_env_vars_changes import get_pr_scope_and_validate_global_rule
from env_files.utils import get_all_env_files_names
from env_files.version_history import create_envs_initial_history, update_envs_history, \
    upload_services_version_histories_to_s3
from git.constants import RELEASE_TAGS_FILE
from github.env import exit_on_error_and_write_summary, write_github_env, write_github_output
from env_files.constants import COMMON_ENV_FILES_PATH, VERSION_SUFFIX, INIT_MESSAGE, \
    COMMON_ENV_FILES_VERSION_HISTORY_DIR


def main():
    """
    Main function to handle common env files on merged PR.
    it will create version of common.env files and upload them to s3.
    it will also create version history files for each env file and upload them to s3.
    and finally it will create a git tag for the new version.
    """
    try:
        logger.info_green("starting to validate changes and create version history files")
        get_pr_scope_and_validate_global_rule(COMMON_ENV_FILES_PATH, False)
        logger.info("the changes in env files are valid. will create versions and version_history.txt create release notes and export ro github env")
        git_tag_version, changes = get_version_and_changes(COMMON_ENV_FILES_PATH)
        git_tag = f"{git_tag_version}{VERSION_SUFFIX}"
        logger.info(f"got git tag version: {git_tag_version} and changes")
        logger.debug(f"changes: {changes}")
        all_env_files = get_all_env_files_names(COMMON_ENV_FILES_PATH)
        logger.debug(f"got all env files: {all_env_files}")
        if changes == INIT_MESSAGE:  # first time:
            all_env_files_versions = create_envs_initial_history(env_files=all_env_files,
                                                                 is_multi_service_repo=False,
                                                                 env_vars_git_tag=git_tag,
                                                                 version_history_folder=COMMON_ENV_FILES_VERSION_HISTORY_DIR)
            logger.debug(f"after init history all_env_files_versions: {all_env_files_versions}")
        else:
            all_env_files_versions = update_envs_history(env_files=all_env_files,
                                                         env_files_base_path=COMMON_ENV_FILES_PATH,
                                                         env_vars_git_tag=git_tag,
                                                         changes=changes,
                                                         is_multi_service_repo=False,
                                                         version_history_folder=COMMON_ENV_FILES_VERSION_HISTORY_DIR)
            logger.debug(f"after update history all_env_files_versions: {all_env_files_versions}")
        logger.info("version_history.txt updated or created for all envs")

        build_and_upload_dot_envs(all_env_files_versions, False, env_file_path=COMMON_ENV_FILES_PATH)
        logger.info("env files uploaded to s3")
        upload_services_version_histories_to_s3(False, version_history_folder=COMMON_ENV_FILES_VERSION_HISTORY_DIR)
        logger.info("version_history.txt uploaded to s3")

        release_tmp_file_name = f'tmp_release_notes_{int(datetime.now().timestamp())}.txt'
        with open(release_tmp_file_name, 'w') as f:
            f.write(f"## {git_tag}\n")
            f.write(f"### Changes\n")
            f.write(f"{changes}\n")

        write_github_output(release_tmp_file_name, RELEASE_TAGS_FILE)
        write_github_output(git_tag, 'ENV_FILE_VERSION')
    except Exception as e:
        exit_on_error_and_write_summary(f"An error occurred in handle_common_env_on_merged_pr.main: {e}")


if __name__ == '__main__':
    main()
