import requests
import base64
import os
import json
from env_files.constants import GLOBAL_FILE
from actions_logging.app_logging import logger


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

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


token = os.getenv("GLOBAL_CICD_GIT_TOKEN")
headers = {
    "Authorization": f"Bearer {token}",
    "Accept": "application/vnd.github.v3+json"
}


def get_file_from_github(file_path):
    api_url = f"https://api.github.com/repos/{owner}/{repo}/contents/{file_path}"
    response = requests.get(api_url, headers=headers)
    if response.status_code == 200:
        file_content = response.json()["content"]
        # File content is base64 encoded. You can decode it if necessary.
        decoded_content = base64.b64decode(file_content).decode("utf-8")
        json_data = json.loads(decoded_content)
        for key in json_data:
            data[key] = json_data[key]
    else:
        logger.info("Error fetching the file:", response.status_code, response.text)


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]


data = {}

owner = "perimeter-81"
repo = "common_files"
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_file_from_github(global_path)
logger.info("pulled global common file")
get_file_from_github(env_file_path)
logger.info("pulled global common env file")
get_data_from_file(global_ms_file)
logger.info(f"merged the local {GLOBAL_FILE} file")
get_data_from_file(ms_env_file)
logger.info("saved all to the local env file")

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