import json
import click
import traceback

from wurker.settings import conf

from .command import ConfigCommand


def register_config_command(admin):

    # The 'admin.config' subgroup
    @admin.group("config")
    @click.pass_context
    def config(ctx):
        """Configure local Wurker instance"""
        pass


    @config.command()
    @click.argument("table_key", required=False)
    @click.pass_context
    def get(ctx, table_key):
        """Show config (empty for all, or 'table[.key]')"""

        # Parse the table_key option into table and key
        table = key = ''
        if table_key:
            parts = table_key.split('.')
            table = parts[0]
            if len(parts) > 1:
                key = parts[1]

        logger = ctx.obj.get("logger")
        cmd = ConfigCommand(logger=logger)

        try:
            result = cmd.get(table=table, key=key)
        except Exception as ex:
            raise click.ClickException(str(ex))

        click.echo(json.dumps(result, indent=2))


    @config.command()
    @click.argument("key_values", nargs=-1)
    @click.pass_context
    def set(ctx, key_values):
        """Set config values like: table.key=value [table.key=value]"""

        config_updates = {}

        for key_value in key_values:
            if "=" not in key_value:
                raise click.BadArgumentUsage(f"Invalid argument: '{key_value}'. Expected format 'table.key=value'.")

            table_key, value = key_value.split("=", 1)

            # Parse the table_key option into table and key
            parts = table_key.split('.')
            if len(parts) != 2:
                raise click.BadArgumentUsage(f"Invalid argument: '{table_key}'. Expected format 'table.key'.")

            table, key = parts

            if table not in config_updates:
                config_updates[table] = {}

            config_updates[table][key] = value

        logger = ctx.obj.get("logger")
        cmd = ConfigCommand(logger=logger)

        for table, table_cfg in config_updates.items():
            for key, value in table_cfg.items():
                try:
                    cmd.set(table, key, value)
                except Exception as ex:
                    if conf.debug:
                        click.echo(traceback.format_exc(), err=True)
                    raise click.ClickException(str(ex))


    @config.command()
    @click.pass_context
    def reset(ctx):
        """Reset etc/wurker.toml to default values"""

        logger = ctx.obj.get("logger")
        cmd = ConfigCommand(logger=logger)

        try:
            cmd.reset()
        except Exception as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException(str(ex))
