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

CONFIG_FILE_DIR = "config"
TEMPLATE_FILE = "template.json"

# Function to create JSON config based on environment variables
def create_env_config_json(env_name, auth0_client_id, auth0_client_secret, auth0_api_key, auth0_domain):
    """
    Generate configuration file for auth0 deploy cli.

    Args:
        env_name (str): A string represents the environment to deploy.
        auth0_client_id (str): A string represents the Auth0 Client ID.
        auth0_client_secret (str): A string represents the Auth0 Client Secret.
        auth0_api_key (str): A string represents the Auth0 API Key.
        auth0_domain (str): A string represents the Auth0 Domain.

    Returns:
        file: Configuration file on json

    Example:
         "AUTH0_DOMAIN": "***",
         "AUTH0_CLIENT_ID": "***",
         "AUTH0_CLIENT_SECRET": "***",
         "AUTH0_ALLOW_DELETE": true,
         "AUTH0_INCLUDED_ONLY": [
           "actions",
           "triggers",
           "rules",
           "tenant"
         ],
         "AUTH0_KEYWORD_REPLACE_MAPPINGS": {
           "AUTH0_P81API_KEY": "***"
    """

    template_file_path = os.path.join(CONFIG_FILE_DIR, TEMPLATE_FILE)

    try:
        with open(template_file_path, "r") as file:
            config = json.load(file)
    except FileNotFoundError:
        exit_on_error_and_write_summary("Template JSON file not found.")
    except json.JSONDecodeError:
        exit_on_error_and_write_summary("Error decoding JSON from the template file.")
    except Exception as e:
            raise Exception(f"An error occurred: {e}")
    
    try:
        config["AUTH0_DOMAIN"] = auth0_domain
        config["AUTH0_CLIENT_ID"] = auth0_client_id
        config["AUTH0_CLIENT_SECRET"] = auth0_client_secret
        config["AUTH0_KEYWORD_REPLACE_MAPPINGS"]["AUTH0_P81API_KEY"] = auth0_api_key
    except KeyError as e:
        exit_on_error_and_write_summary(f"Missing key in the JSON template: {e}")
    
    # Create the file path
    output_file = os.path.join(CONFIG_FILE_DIR, f"{env_name}.json")

    try:
        logger.info(f"Writing config to JSON file {output_file}...")
        with open(output_file, "w") as file:
            json.dump(config, file, indent=2)
    except Exception as e:
        exit_on_error_and_write_summary(f"Could not write config to the json file due to the following error: {e}")

    try:
        logger.info(f"Reading and printing config of JSON file {output_file}...")
        with open(output_file, "r") as file:
            logger.info(file.read())
    except Exception as e:
        exit_on_error_and_write_summary(f"Could not read or pring config file due to the following error: {e}")
    

def main():
    env_name = get_required_env_var('ENV_NAME')
    env_name_upper = env_name.upper()
    auth0_domain = get_required_env_var(f'ENV_{env_name_upper}_AUTH0_DOMAIN')
    auth0_client_id = get_required_env_var(f'ENV_{env_name_upper}_AUTH0_CLIENT_ID')
    auth0_client_secret = get_required_env_var(f'ENV_{env_name_upper}_AUTH0_CLIENT_SECRET')
    auth0_api_key = get_required_env_var(f'ENV_{env_name_upper}_AUTH0_P81API_KEY')

    create_env_config_json(env_name, auth0_client_id, auth0_client_secret, auth0_api_key,auth0_domain)


if __name__ == "__main__":
    main()
    