"""Mithril CLI."""

from __future__ import annotations

import sys
from importlib.metadata import version

from cyclopts import App, Group

from mithril.cli.commands.help import help_cmd, print_help
from mithril.cli.commands.launch import launch
from mithril.cli.utils.skypilot_passthrough import SKY_ALIAS_COMMANDS, run_sky

_PACKAGE_NAME = "mithril-client"


def cli(argv: list[str] | None = None) -> int:
    """CLI router; returns an exit code."""
    argv = list(sys.argv[1:] if argv is None else argv)

    if not argv or argv[0] in {"-h", "--help"}:
        print_help()
        return 0

    if argv[0] == "--version":
        print(version(_PACKAGE_NAME))
        return 0

    cmd, rest = argv[0], argv[1:]

    if cmd == "sky":
        # Preserve Click-like behavior: `ml sky` shows SkyPilot help.
        args = rest or ["--help"]
        return run_sky(*args)

    if cmd in SKY_ALIAS_COMMANDS:
        return run_sky(cmd, *rest)

    # Our first-class commands.
    app = App(
        name="ml",
        version=version(_PACKAGE_NAME),
        version_flags=["--version"],
        # Match SkyPilot's Click-style help output more closely by disabling the
        # rich "boxed table" help renderer.
        help_formatter="plain",
        help_format="plaintext",
        # Use "Options" heading to match clap's style
        group_parameters=Group("Options", sort_key=0),
    )
    app.command(help_cmd, name="help")
    app.command(launch)

    try:
        app(argv)
    except SystemExit as e:
        return e.code if isinstance(e.code, int) else 1
    else:
        return 0


def main() -> None:
    """Entry point."""
    raise SystemExit(cli())


if __name__ == "__main__":
    main()
