#!/usr/bin/env bash
# Open a customer's Hermes runtime (Fly) in Hermes Desktop or a browser.
# Admin-only: requires the Sellable Fly org token.
set -euo pipefail

WRAPPER_SOURCE="${BASH_SOURCE[0]}"
while [ -h "$WRAPPER_SOURCE" ]; do
  WRAPPER_DIR="$(cd -P -- "$(dirname -- "$WRAPPER_SOURCE")" && pwd)"
  WRAPPER_SOURCE="$(readlink "$WRAPPER_SOURCE")"
  if [[ "$WRAPPER_SOURCE" != /* ]]; then
    WRAPPER_SOURCE="$WRAPPER_DIR/$WRAPPER_SOURCE"
  fi
done
WRAPPER_DIR="$(cd -P -- "$(dirname -- "$WRAPPER_SOURCE")" && pwd)"
WRAPPER_ROOT="$(cd -- "$WRAPPER_DIR/../.." && pwd)"
export SELLABLE_ADMIN_ROOT="${SELLABLE_ADMIN_ROOT:-$WRAPPER_ROOT}"
export SELLABLE_ADMIN_HOME="${SELLABLE_ADMIN_HOME:-$HOME/.sellable-admin}"

SCRIPT="$SELLABLE_ADMIN_ROOT/mcp/scripts/agent-console.mjs"
if [ ! -f "$SCRIPT" ]; then
  echo "agent-console: not found at $SCRIPT" >&2
  exit 1
fi

# The CLI imports compiled helpers from mcp/dist; build once if missing.
if [ ! -f "$SELLABLE_ADMIN_ROOT/mcp/dist/lib/agentConsole.js" ]; then
  echo "agent-console: building admin mcp (first run)…" >&2
  (cd "$SELLABLE_ADMIN_ROOT/mcp" && npm run build >/dev/null 2>&1) || {
    echo "agent-console: build failed — run 'npm run build' in $SELLABLE_ADMIN_ROOT/mcp" >&2
    exit 1
  }
fi

exec node "$SCRIPT" "$@"
