"""Root CLI group with ColonCommandGroup, factory creation, and error boundary."""

from __future__ import annotations

import sys

import click

from kuberoku._version import __version__
from kuberoku.branding import TOOL_NAME
from kuberoku.cli.addons import addons
from kuberoku.cli.apps import apps
from kuberoku.cli.clusters import clusters
from kuberoku.cli.config import config
from kuberoku.cli.deploy import deploy
from kuberoku.cli.domains import domains
from kuberoku.cli.plugins import plugins
from kuberoku.cli.ps import ps
from kuberoku.cli.releases import releases
from kuberoku.cli.services import services
from kuberoku.exceptions import KuberokuError
from kuberoku.factory import KuberokuFactory
from kuberoku.plugins.loader import load_plugins


class ColonCommandGroup(click.Group):
    """Click group that resolves colon commands to subcommands.

    Both `kuberoku apps:create` and `kuberoku apps create` work identically.
    This overrides resolve_command() — Click's intended extension point for
    custom command resolution.
    """

    def resolve_command(
        self, ctx: click.Context, args: list[str]
    ) -> tuple[str | None, click.Command | None, list[str]]:
        # If the first arg contains a colon, split into group + subcommand args
        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(cls=ColonCommandGroup)
@click.version_option(__version__, prog_name=TOOL_NAME)
@click.pass_context
def cli(ctx: click.Context) -> None:
    """Heroku-like DX on vanilla Kubernetes."""
    ctx.ensure_object(dict)
    if "factory" not in ctx.obj:
        ctx.obj["factory"] = KuberokuFactory()


# ── Mount command groups ─────────────────────────────────────────

cli.add_command(addons)
cli.add_command(apps)
cli.add_command(clusters)
cli.add_command(config)
cli.add_command(deploy)
cli.add_command(domains)
cli.add_command(plugins)
cli.add_command(ps)
cli.add_command(releases)
cli.add_command(services)

# ── Load third-party plugins ─────────────────────────────────────

load_plugins(cli)


# ── Entry point with error boundary ─────────────────────────────


def run() -> None:
    """Entry point for kuberoku CLI. Single error boundary."""
    try:
        cli(standalone_mode=False)
    except SystemExit as e:
        sys.exit(e.code)
    except click.Abort:
        click.echo("Aborted.", err=True)
        sys.exit(1)
    except click.ClickException as e:
        e.show()
        sys.exit(e.exit_code)
    except KuberokuError as e:
        click.echo(f"Error: {e}", err=True)
        sys.exit(1)
    except Exception as e:
        click.echo(f"Internal error: {e}", err=True)
        click.echo(
            f"\n{TOOL_NAME} {__version__} | Python {sys.version.split()[0]}",
            err=True,
        )
        click.echo(
            f"Debug info: KUBEROKU_DEBUG=1 {TOOL_NAME} <your command>",
            err=True,
        )
        sys.exit(2)
