"""Help command for the Mithril CLI."""

from __future__ import annotations

from importlib.metadata import version

from cyclopts import App
from rich.console import Console

from mithril._mcli import run as run_rust
from mithril.cli.commands.launch import launch
from mithril.cli.utils.skypilot_passthrough import SKY_ALIAS_COMMANDS, run_sky

RUST_COMMANDS = {"ssh", "instance", "k8s"}


def print_help() -> None:
    """Print top-level help.

    We route some commands directly to SkyPilot for passthrough, so we keep the
    top-level help text explicit and stable.
    """
    ver = version("mithril-client")
    help_text = f"""[dim]Mithril CLI {ver}[/dim]

[dim]❊ Quickstart:[/dim]
  [bold]1. ml setup[/bold]                  First-time setup
  [bold]2. ml launch --gpus H100:8[/bold]   Spin up a GPU instance
  [bold]3. ml status[/bold]                 Check running clusters
  [bold]4. ml down[/bold]                   Tear down when you're done

[dim]❊ Workload:[/dim]
  launch    Launch a cluster and run a task.
  exec      Execute a command or open an interactive shell on a cluster.
  status    Show cluster and job status.
  logs      Stream job logs.
  queue     Show the job queue.
  start     Start a stopped cluster.
  stop      Stop/pause a cluster.
  down      Delete a cluster.

[dim]❊ Infrastructure:[/dim]
  instance  Manage compute instances.
  k8s       Manage Kubernetes clusters.
  ssh       SSH into an instance.

[dim]❊ Utilities:[/dim]
  sky       Direct SkyPilot access.
  setup     Configure credentials.
  help      Show help manual.
"""
    Console(highlight=False).print(help_text)


def help_cmd(command: tuple[str, ...] = ()) -> None:
    """Show help for `ml` or a specific command.

    For SkyPilot passthrough commands, this forwards to SkyPilot's help output.
    For Rust commands (ssh, instance, k8s), this delegates to the Rust CLI.
    """
    if not command:
        print_help()
        return

    cmd_name, *rest = command

    # Rust commands: delegate to Rust CLI for help
    if cmd_name in RUST_COMMANDS:
        args = ["ml", cmd_name, *rest, "--help"]
        raise SystemExit(run_rust(args))

    # SkyPilot passthrough commands
    if cmd_name == "sky":
        args = [*rest, "--help"] if rest else ["--help"]
        raise SystemExit(run_sky(*args))

    if cmd_name in SKY_ALIAS_COMMANDS:
        args = [cmd_name, *rest, "--help"] if rest else [cmd_name, "--help"]
        raise SystemExit(run_sky(*args))

    # First-class Python commands: render help via Cyclopts.
    app = App(
        name="ml",
        version=version("mithril-client"),
        version_flags=["--version"],
        help_formatter="plain",
    )
    app.command(launch)

    app([cmd_name, *rest, "--help"])
