import os
import shutil
from github.env import exit_on_error_and_write_summary, get_required_env_var
from actions_logging.app_logging import logger
from common.common import run_command
from collections import Counter
from aws.env_info import get_env_bucket
from aws.s3_apis.s3 import download_file_from_s3, upload_file_to_s3
from aws.constants import STG_PROD_ENVS, PROD_ACCOUNT_ENVS
from master.calculate_version import get_version
from github.get_file_from_github import get_file_from_github

def envsubst(file):
    '''
        Similar to shell "envsubst" command. Receives file and changes each env variable occurrence with value from your current environment.
        e.g ${ENV_NAME} in file will be changed to value you exported to your environment as ENV_NAME.
    '''
    try:
        with open(file, "r") as config:
            content = config.read()
            expanded_content = os.path.expandvars(content)
        with open(file, "w") as config:
            config.write(expanded_content)
    except Exception as e:
        exit_on_error_and_write_summary(f"Error during envsubst: {e}")

def add_broker(broker, config_file):
    '''
        Function to add each broker to brokers array inside config file
    '''
    broker = broker.replace('\n', '')
    run_command(f"""yq '.kafka.brokers += ["{broker}"]' {config_file} > temp.yaml""")
    shutil.move("temp.yaml", config_file)

def export_envs(file):
    try:
        with open(file, "r") as infile:
            for line in infile:
                key, value = line.split("=", 1)
                os.environ[key] = value.replace('\n', '')
    except Exception as e:
        exit_on_error_and_write_summary(f"Error exporting environment variables: {e}")


def main():
    env_name = get_required_env_var("ENV_NAME")
    svc_name = get_required_env_var("SVC_NAME")
    repo_name = get_required_env_var("GITHUB_REPOSITORY")
    version = os.getenv("VERSION_TO_DEPLOY", '')

    try:
        config_file = "yarkon_gw_config.yaml"
        if get_version(version):
            get_file_from_github(repo_name, config_file, os.path.dirname(config_file), version)
        elif env_name in STG_PROD_ENVS and not version:
            exit_on_error_and_write_summary(f"Staging and Production environment deployment require artifact version")

        bucket = get_env_bucket(env_name)

        env_name_to_assume = env_name if env_name not in PROD_ACCOUNT_ENVS else ""
        download_file_from_s3(bucket, f"{svc_name}.env", f"{svc_name}.env", env_name_to_assume)
        export_envs(f"{svc_name}.env")

        kafka_brokers = os.getenv("KAFKA_BROKERS")
        brokers_array = kafka_brokers.split(",")

        for broker in brokers_array:
            add_broker(broker, config_file)
        
        envsubst(config_file)

        logger.info_green(f"Successfully created {config_file}")
        upload_file_to_s3(bucket, config_file, f"{svc_name}/{config_file}", env_name_to_assume)
        run_command(f"rm {svc_name}.env")
    except Exception as e:
        exit_on_error_and_write_summary(f"Failed to convert configuration file: {e}")


if __name__ == "__main__":
    main()
