import click
import traceback

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

from .command import RunCommand


def register_run_command(wurk):
    @wurk.command()
    @click.argument(
        "option", required=False, default=None,
        type=click.Choice(['bee', 'cron', 'ondemand', 'scheduled', 'supervised',])
    )
    @click.option("--slug", "key", help="Filter by slug (only: cron, bee)")
    @click.pass_context
    def run(ctx, option, key):
        """Run Wurker Bees"""

        try:
            logger = ctx.obj.get("logger")

            load_plugins(logger=logger)

            cmd = RunCommand(logger=logger)
            error = cmd.run(option=option, key=key)
            if error:
                click.echo(f"ERROR: {error}", err=True)
        except CommandNotReady as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException(f"The 'wurk run' command is not ready. Run 'wurk admin --help'. {ex}")
        except Exception as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException(str(ex))
