import argparse
from sys import exit

from glean_config.config import Glean_config

def main():
    parser = argparse.ArgumentParser("Glean_config")
    parser.add_argument(
        '-f',
        '--file',
        dest='toml_file',
        help='path to toml config file (optional: uses GLEAN_CONFIG_FILE env var or fileless mode if not provided)',
        default=None
    )
    parser.add_argument(
        '-a',
        '--add',
        dest='add_kvp',
        help='add a kvp to file in the form "key::value"'
    )

    parser.add_argument(
        '-k',
        '--show_key',
        dest='key',
        help='display key value'
    )

    args = parser.parse_args()

    # Get config instance (may use file, env var, or fileless mode)
    config = Glean_config.get_instance(args.toml_file)



    # Validate and process the add_kvp argument
    try:
        validate_parameters(args, config)
    except ValueError as ve:
        print(ve)
        exit(1)

    # Removed redundant call to config.get_toml()

def validate_parameters(args, config):
    if args.add_kvp:

        if "::" not in args.add_kvp:

            raise ValueError("Error: The key-value pair must be in the form 'key::value'.")
        key, value = args.add_kvp.split('::', 1)
        config[key] = value


    # Validate and process the key argument
    if args.key:
        if args.key not in config.get_config():
            raise ValueError(f"Error: The key '{args.key}' does not exist in the configuration.")

        print(f"{args.key}: {config[args.key]}")
        exit(0)


    config.save(force=True)
    print(config.get_toml())


if __name__=="__main__":
    main()

