import json
import os
import sys
from env_files.constants import GLOBAL_FILE

env_name = os.getenv('ENV_NAME')
service_name = os.getenv('SVC_NAME')
if env_name not in ['staging', 'production']:
    dir_name = 'dev'
    os.environ['DOMAIN_NAME'] = f"p81-{env_name}.com"
    os.environ['ENVIRONMENT_SHORT'] = env_name
    os.environ['NAMESPACE'] = f"devops.{env_name}.corp.safersoftware.net"
else:
    if env_name == "staging":
        os.environ['DOMAIN_NAME'] = "perimeter81.biz"
        os.environ['ENVIRONMENT_SHORT'] = "stg"
    else:
        os.environ['DOMAIN_NAME'] = "perimeter81.com"
        os.environ['ENVIRONMENT_SHORT'] = "prod"
    dir_name = env_name


replace_dict = {  # key stands for env var in gh workflow and values for %<key from teamcity to replace>%
    "ENV_NAME": ["env.ENVIRONMENT", "ENVIRONMENT"],
    "DOMAIN_NAME": ["DOMAIN_NAME"],
    "ENVIRONMENT_SHORT": ["ENVIRONMENT_SHORT"],
    "NODE_VERSION": ["env.NODE_VERSION"],
    "NAMESPACE": ["NAMESPACE"]
}

file_path_extend = [""]
is_sx = sys.argv[1]
if is_sx == 'true':
    svc_name = os.getenv('SVC_NAME')
    print(f"now what {svc_name}")
    if svc_name == "saferx-backend":
        file_path_extend = ["saferx-backend/", "saferx-backend-cli/"]
    elif svc_name == "sx-core-dns":
        file_path_extend = ["sx-core-dns-private/", "sx-core-dns-public/"]
file_paths = []
file_path_prefix = ".github/env_files"
if service_name == "common":
    file_path_prefix = "common_env_files"
for extend in file_path_extend:
    file_paths.append(f"{file_path_prefix}/{extend}{dir_name}/{env_name}.json")
    file_paths.append(f"{file_path_prefix}/{extend}{GLOBAL_FILE}")


for file_path in file_paths:
    file_exist = os.path.exists(file_path)
    print(f"file {file_path} exists: {file_exist}")
    if not os.path.exists(file_path):
        print(f"file {file_path} does not exist!, taking template.json")
        file_path = file_path.replace(f"{env_name}.json" , "template.json" )
    print("doing some magic on", file_path)
    with open(file_path, 'r') as file:
        json_file = json.load(file)
    for key in json_file:
        for env_var in replace_dict:
            env_var_value = os.getenv(env_var)
            for tc_var_name in replace_dict[env_var]:
                pattern = f"%{tc_var_name}%"
                if pattern in json_file[key]:
                    json_file[key] = json_file[key].replace(pattern, env_var_value)
                    print(f"{pattern} found and replaced with {env_var_value}")
    with open(file_path, 'w') as file:
        json.dump(json_file, file, indent=4)
