import json
import os
from actions_logging.app_logging import logger
from github.env import exit_on_error_and_write_summary, get_required_env_var

GLOBAL_PREFIX = ".github/env_files"

def load_env_json(file_path):
    if not os.path.exists(file_path):
        return {}
    with open(file_path, 'r') as file:
        try:
            return json.load(file)
        except json.JSONDecodeError:
            raise RuntimeError(f"The file {file} contains invalid JSON.")
        except Exception as e:
            raise Exception(f"An error occurred: {e}")

def update_script_json(file_path, content):
    with open(file_path, 'w') as file:
        json.dump(content, file, indent=4)

def update_script_js_str(file_path, content):
    with open(file_path, 'w') as file:
        file.write(content)

def merge_env_and_script_files(merge_content):
    """
    Update Auth0 scripts for auth0 deploy cli.

    Args:
        merge_content (dict): A dictionary represents the merge content.

    Returns:
        file: Script file on json

    Example:
        >>> {
        ... "name": "set-apiBaseUrl",
        ... "code": "local/actions/set-apiBaseUrl/code.js",
        ... "runtime": "node18-actions",
        ... "status": "built",
        ... "dependencies": [],
        ... "secrets": [
        ...     {
        ...         "name": "apiBaseUrl",
        ...         "value": "https://api.perimeter81.localhost/api"
        ...     }
        ... ]}
    """
    
    for key, value in merge_content.items():
        if isinstance(value, dict):
            # Replace the content with the new content (shallow merge)
            base_content = load_env_json(key)
            base_content.update(value)
            update_script_json(key, base_content)
            logger.info(f"Updated content for {key}:")
            logger.info(json.dumps(base_content, indent=4))
        elif isinstance(value, str):
            update_script_js_str(key, value)
            logger.info(f"Updated content for {key}:")
            logger.info(value)
        logger.info("\n")

def main():
    # Environment files
    env_name = get_required_env_var('ENV_NAME')
    env_file_path = os.path.join(GLOBAL_PREFIX, f'{env_name}.json')
    
    # Load merge content from the file
    merge_content = None
    try:
        with open(env_file_path, 'r') as merge_file:
            merge_content = json.load(merge_file)
    except FileNotFoundError:
        exit_on_error_and_write_summary(f"Error: The file {env_file_path} does not exist.")
    except json.JSONDecodeError:
        exit_on_error_and_write_summary(f"Error: The file {env_file_path} is not valid JSON.")
    except Exception as e:
        exit_on_error_and_write_summary(f"An unexpected error occurred: {e}")
    
    # Merge the contents and update the files
    if merge_content is not None:
        merge_env_and_script_files(merge_content)
    else:
        logger.warning("The merge content is blank, no need to update scripts")

if __name__ == '__main__':
    main()