"""Shared npm-binary resolution (G-09, #552): PREFER a locally-installed
binary (no network, no npx process wrapper) over `npx --yes` (which may hit
the registry on a cold cache and always adds a wrapper process that forks the
real work one level down). Generalizes the #371 guard resolver to every
binary this adapter spawns — bridge, guard, gates, observe, context, hub.

owner: RStack developed by Richardson Gunde; Tau adapter contributed by Jeomon
"""
from __future__ import annotations

import os
import shutil
from pathlib import Path
from typing import Optional


def _resolve_bin_argv(bin_name: str, cwd: str) -> tuple[Optional[list[str]], bool]:
    """Resolve how to invoke an rstack npm bin (`rstack-agents`,
    `rstack-bridge`, `rstack-business`). Returns (argv_prefix, needs_network);
    (None, False) means the binary cannot be invoked at all.

    Resolution order: the calling project's node_modules/.bin (what
    `npm install rstack-agents` creates), then PATH (a global install), then
    `npx --yes` (on-demand registry fetch — the pre-G-09 behavior, kept as the
    zero-install fallback). Only checks `cwd`, not a package-tree-relative
    path — this adapter has no fixed install location of its own (see the
    package docstring), so there is no second directory to check beyond the
    project the binary is actually being run against.
    """
    binary = f"{bin_name}.cmd" if os.name == "nt" else bin_name
    candidate = Path(cwd) / "node_modules" / ".bin" / binary
    if candidate.is_file():
        return ([str(candidate)], False)
    on_path = shutil.which(bin_name)
    if on_path:
        return ([on_path], False)
    npx = shutil.which("npx")
    if npx:
        return ([npx, "--yes", bin_name], True)
    return (None, False)
