import os
import json
from env_files.constants import GLOBAL_FILE

env_name = os.getenv("ENV_NAME").lower()

if env_name not in ["production", "staging"]:
    folder = "dev"
else:
    folder = env_name

data = {}

def get_data_from_file(file_path):
    env_file = open(file_path)
    json_data = json.load(env_file)
    env_file.close()
    for key in json_data:
        data[key] = json_data[key]


env_file_path = f"common_env_files/{folder}/{env_name}.json"
global_path = f"common_env_files/{GLOBAL_FILE}"


ms_env_file = f".github/env_files/{folder}/{env_name}.json"
if not os.path.isfile(ms_env_file):
    if not os.path.isdir(".github/env_files"):
        os.makedirs(".github/env_files")
    if not os.path.isdir(f".github/env_files/{folder}"):
        os.makedirs(f".github/env_files/{folder}")
    f = open(ms_env_file, 'a')
    f.close()

global_ms_file = f".github/env_files/{GLOBAL_FILE}"


get_data_from_file(global_ms_file)
print(f"merged the local {GLOBAL_FILE} file")
get_data_from_file(ms_env_file)
print("saved all to the local env file")

with open(ms_env_file, 'w') as finel_file:
    json.dump(data, finel_file, indent=4)