"""SkyPilot passthrough helpers for the Mithril CLI."""

from __future__ import annotations

import importlib
import sys
from contextlib import suppress

from mithril.sky import ensure_local_api_server_version_matches_client

SKY_ALIAS_COMMANDS: tuple[str, ...] = (
    "exec",
    "status",
    "start",
    "down",
    "stop",
    "logs",
    "queue",
)


def run_sky(*args: str) -> int:
    """Run sky CLI with given arguments.

    Note: sky.cli is not part of skypilot's public API, but it's the stable
    entry point for the `sky` command (defined in skypilot's setup.py). We
    invoke it directly to avoid requiring `sky` to be on PATH (e.g., when
    installed via `uv tool`).
    """
    try:
        ensure_local_api_server_version_matches_client()
        sky_cli = importlib.import_module("sky.client.cli.command").cli
        sky_cli.main(args=list(args), standalone_mode=False)
    except SystemExit as e:
        return e.code if isinstance(e.code, int) else 1
    except Exception as e:  # noqa: BLE001
        # SkyPilot is Click-based and may raise ClickException; avoid importing click
        # directly and rely on duck-typing to preserve decent error output.
        show = getattr(e, "show", None)
        if callable(show):
            with suppress(Exception):
                show()
            exit_code = getattr(e, "exit_code", 1)
            return exit_code if isinstance(exit_code, int) else 1

        print(f"Error: {e}", file=sys.stderr)
        return 1
    else:
        return 0
