import click
import traceback

from wurker.settings import conf
from wurker.cli.base import CommandNotReady

from .command import SeedCommand


def register_seed_command(admin):

    @admin.command()
    @click.option("--only", type=click.Choice(['wurker', 'local']),
                  help="Only seed (or drop) the given database")
    @click.option("--drop", is_flag=True, help="Drop the given schema instead")
    @click.pass_context
    def seed(ctx, only, drop):
        """Seed Wurker database from Stinger"""

        error = None
        try:
            logger = ctx.obj.get("logger")
            cmd = SeedCommand(only=only, drop=drop, logger=logger)
            error = cmd.run()
        except CommandNotReady as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException("The 'wurk admin seed' command is not ready. "
                                       f"Run 'wurk admin stinger sting' first. {ex}")
        except Exception as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException(str(ex))

        if error:
            click.echo(f"ERROR: {error}")
