#!/bin/bash
# werkmeister CLI (alias w9r) - Multi-feature concurrent development orchestrator
# TypeScript port: the wrapper only resolves WERKMEISTER_ROOT + node and execs dist/main.js.
set -euo pipefail

# Load machine-global config exports (generated by `werkmeister config` from
# ~/.werkmeister/config.yaml) so the CLI inherits WERKMEISTER_* without a per-client env block.
[ -f "$HOME/.werkmeister/env.sh" ] && . "$HOME/.werkmeister/env.sh"

# The running checkout is authoritative for WERKMEISTER_ROOT — re-derive and export
# AFTER sourcing env.sh so a stale value there can never win.
WERKMEISTER_ROOT="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"
export WERKMEISTER_ROOT

# Running out of npx's cache (`npx werkmeister setup`) — install
# globally and hand off, rather than running from here.
#
# WERKMEISTER_ROOT above resolved to ~/.npm/_npx/<hash>/..., which npm garbage-
# collects and re-hashes on every version change. `setup` and `config` persist
# that path into ~/.werkmeister/config.yaml and env.sh, and the compose generator
# bakes it into every workspace's compose.yml as a bind mount, so running
# from the cache pins permanent state to a directory that is going to vanish.
# Bootstrapping is the one thing npx is right for here: install, then exec the
# stable copy. The re-exec cannot loop — the global path has no _npx in it.
case "$WERKMEISTER_ROOT" in
  */_npx/*)
    # Install the exact version npx resolved, not @latest: `npx pkg@1.2.3 setup`
    # must not silently onboard the machine onto a different release.
    pkg="$(node -p "const p=require('$WERKMEISTER_ROOT/package.json'); p.name + '@' + p.version" 2>/dev/null || echo "werkmeister")"
    echo "Bootstrapping: installing $pkg globally (npx's cache is not a stable install location)..." >&2
    if ! npm install -g "$pkg" >&2; then
        echo "Error: global install failed. Install it yourself, then re-run:" >&2
        echo "  npm install -g $pkg && werkmeister $*" >&2
        exit 1
    fi
    global_bin="$(npm prefix -g)/bin/werkmeister"
    if [ ! -x "$global_bin" ]; then
        echo "Error: installed $pkg but found no werkmeister binary at $global_bin." >&2
        exit 1
    fi
    echo "Installed. Continuing as $global_bin" >&2
    exec "$global_bin" "$@"
    ;;
esac

entry="$WERKMEISTER_ROOT/dist/main.js"
if [ ! -f "$entry" ]; then
    echo "Error: CLI not built — missing $entry (run 'pnpm install && pnpm run build')." >&2
    exit 1
fi

# Resolution order: $WERKMEISTER_NODE → node on PATH → newest nvm install.
node_bin="${WERKMEISTER_NODE:-}"
if [ -z "$node_bin" ] && command -v node >/dev/null 2>&1; then
    node_bin="$(command -v node)"
fi
if [ -z "$node_bin" ]; then
    nvm_root="${NVM_DIR:-$HOME/.nvm}/versions/node"
    newest="$(ls -d "$nvm_root"/v* 2>/dev/null | sort -V | tail -1 || true)"
    [ -n "$newest" ] && node_bin="$newest/bin/node"
fi
if [ -z "$node_bin" ] || [ ! -x "$node_bin" ]; then
    echo "Error: could not locate a node runtime. Set WERKMEISTER_NODE=/path/to/node." >&2
    exit 1
fi

# `mcp` and `dashboard` are sibling apps, not CLI subcommands. `mcp` is the stdio
# proxy an MCP client (Claude Desktop, the werkmeister plugin) spawns; it forwards
# every call to the daemon, the same app's HTTP mode, which `werkmeister connect`
# starts as a managed WebApp (SW-344). Extra args are forwarded, so an explicit
# --stdio from an older .mcp.json stays harmless.
# `dashboard` runs the localhost browser dashboard in the foreground (the same
# server `connect` starts on 3001).
#
# Only apps/cli is published to npm (see its package.json `files`), so on a
# global install these siblings are absent. apps/werkmeister-mcp is bundled into this
# package as dist/mcp.js and dist/mcp-proxy.js (esbuild.mjs), so `mcp` always has a target. The
# dashboard is checkout-only.
# SW-186 moved these five under `internal`; the old spellings warn until REMOVE_IN
# (keep in step with src/main.ts). stderr only: stdout is JSON-RPC or hook output.
deprecated() {
    echo "werkmeister: '$1' is deprecated and will be removed in 0.58.0; use 'werkmeister internal $2'. Run 'werkmeister machine migrate' to update hooks and permission rules." >&2
}
verb=""
case "${1:-}" in
    internal)
        case "${2:-}" in mcp|dashboard|gate|pr-guard|agent-state) verb="$2"; shift 2 ;; esac
        ;;
    hooks)
        case "${2:-}" in gate|pr-guard|agent-state) verb="$2"; deprecated "hooks $2" "$2"; shift 2 ;; esac
        ;;
    mcp|dashboard)
        verb="$1"; deprecated "$1" "$1"; shift
        ;;
esac

case "$verb" in
    mcp)
        app_entry="$(cd "$WERKMEISTER_ROOT/.." && pwd)/werkmeister-mcp/dist/proxy.js"
        [ -f "$app_entry" ] || app_entry="$WERKMEISTER_ROOT/dist/mcp-proxy.js"
        if [ ! -f "$app_entry" ]; then
            echo "Error: 'mcp' is not available -- missing $app_entry (run 'pnpm run build')." >&2
            exit 1
        fi
        exec "$node_bin" "$app_entry" "$@"
        ;;
    dashboard)
        app_entry="$(cd "$WERKMEISTER_ROOT/.." && pwd)/werkmeister-dashboard/dist/main.js"
        if [ ! -f "$app_entry" ]; then
            echo "Error: the workspaces dashboard ships with a werkmeister checkout only -- missing $app_entry." >&2
            exit 1
        fi
        exec "$node_bin" "$app_entry" "$@"
        ;;
    # The hook entry points skip the commander/yaml import chain: `gate` fires on
    # every Edit/Write, `pr-guard` on every Bash call, `agent-state` on every tool call.
    gate) exec "$node_bin" "$WERKMEISTER_ROOT/dist/lib/gate.js" ;;
    pr-guard) exec "$node_bin" "$WERKMEISTER_ROOT/dist/lib/pr_guard.js" ;;
    agent-state) exec "$node_bin" "$WERKMEISTER_ROOT/dist/lib/agent_state.js" ;;
esac

exec "$node_bin" "$entry" "$@"
