#!/usr/bin/env python3
"""Resolve how to invoke Lark CLI.

Cloud environments often have no admin permissions, so we prefer running the
official CLI via `npx -y -p @larksuite/cli lark-cli ...`.

This module returns a *command prefix* (list of argv items), not a path.
"""

from __future__ import annotations

import shutil
from pathlib import Path
from typing import List, Optional, Sequence


def resolve_lark_cli_prefix(_base_dir: Path) -> list[str]:
    """Return argv prefix to execute lark-cli.

    Preferred:
      npx -y -p @larksuite/cli lark-cli

    Fallback (if npx missing):
      lark-cli (on PATH)
    """
    npx = shutil.which("npx")
    if npx:
        return [npx, "-y", "-p", "@larksuite/cli", "lark-cli"]

    lark_cli = shutil.which("lark-cli")
    if lark_cli:
        return [lark_cli]

    raise FileNotFoundError(
        "missing Lark CLI runner: npx or lark-cli not found on PATH. "
        "expected to run via: npx -y -p @larksuite/cli lark-cli ..."
    )


def as_prefix(cli_bin: str, cli_prefix: Optional[Sequence[str]]) -> List[str]:
    """Back-compat helper for orchestrators.

    - If --lark-cli-prefix is provided, use it.
    - Else, use --lark-cli-bin as a single executable path.
    """
    if cli_prefix:
        return list(cli_prefix)
    return [cli_bin]
