import click
import traceback

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

from .command import ReportCommand, REPORT_COLUMNS


def register_report_command(wurk):
    @wurk.command()
    @click.argument("option", required=False, default=None, type=click.Choice(['bee', 'cron',]))
    @click.option("--slug", "key", help="Filter by slug")
    @click.option("--start", help="Optional start date/time")
    @click.option("--end", help="Optional end date/time")
    @click.option("--page", type=int, default=0, help="Pagination page number (default: 0)")
    @click.option("--page-limit", type=int, default=20, help="Records per page (default: 20)")
    @click.option(
        "--sort", type=click.Choice(REPORT_COLUMNS), default='id', help="Sort by column (default: 'id')"
    )
    @click.option(
        "--sort-order", type=click.Choice(['asc', 'desc']), default='asc', help='Sort direction (default: asc)'
    )
    @click.option(
        "-d", "--drone", "drones", multiple=True, help="Slug or ID of drone(s) to report on (repeatable)"
    )
    @click.pass_context
    def report(ctx, option, key, start, end, page, page_limit, sort, sort_order, drones):
        """Report on Wurker Bees"""

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

            load_plugins(logger=logger)

            cmd = ReportCommand(logger=logger)
            cmd.run(
                option=option,
                key=key,
                start=start,
                end=end,
                page=page,
                page_limit=page_limit,
                sort=sort,
                sort_order=sort_order,
                drones=drones,
            )

        except CommandNotReady as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException(f"The 'wurk report' 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))
