"""CLI commands for plugins — list, install, uninstall, search."""

from __future__ import annotations

import click

from kuberoku.cli.output import info, render_table, success


class _ColonGroup(click.Group):
    """Resolve colon-separated subcommands."""

    def resolve_command(
        self,
        ctx: click.Context,
        args: list[str],
    ) -> tuple[str | None, click.Command | None, list[str]]:
        cmd_name = args[0] if args else None
        if cmd_name and ":" in cmd_name:
            parts = cmd_name.split(":", 1)
            args = [parts[0], parts[1]] + args[1:]
        return super().resolve_command(ctx, args)


@click.group("plugins", cls=_ColonGroup, invoke_without_command=True)
@click.pass_context
def plugins(ctx: click.Context) -> None:
    """Manage plugins."""
    if ctx.invoked_subcommand is not None:
        return

    # Default: list installed plugins
    factory = ctx.obj["factory"]
    plugin_list = factory.plugins.list_installed()

    if not plugin_list:
        info("No plugins installed.")
        return

    render_table(
        list(plugin_list),
        columns=["name", "package", "version", "description"],
    )


@plugins.command("install")
@click.argument("package")
@click.pass_context
def install_cmd(ctx: click.Context, package: str) -> None:
    """Install a plugin from PyPI."""
    factory = ctx.obj["factory"]
    plugin = factory.plugins.install(package, on_step=lambda msg: info(msg))
    success(f"Installed plugin '{plugin.name}' ({plugin.package} {plugin.version}).")


@plugins.command("uninstall")
@click.argument("package")
@click.pass_context
def uninstall_cmd(ctx: click.Context, package: str) -> None:
    """Uninstall a plugin."""
    factory = ctx.obj["factory"]
    factory.plugins.uninstall(package, on_step=lambda msg: info(msg))
    success(f"Uninstalled '{package}'.")


@plugins.command("search")
@click.argument("query")
@click.pass_context
def search_cmd(ctx: click.Context, query: str) -> None:
    """Search PyPI for kuberoku plugins."""
    factory = ctx.obj["factory"]
    results = factory.plugins.search(query)

    if not results:
        info(f"No plugins found matching '{query}'.")
        return

    render_table(
        list(results),
        columns=["name", "package", "version", "description", "installed"],
    )
