#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"

case "${1:-}" in
  agent-run)
    shift
    exec python3 "$ROOT_DIR/scripts/rho-agent-run.py" "$@"
    ;;
  add|dataset|publish|message|request|tools|run|approve|result|id|crypto|repo|status|gh|commit|env|install-shell|"")
    exec cargo run --quiet --bin rho -- "$@"
    ;;
esac

PI_MONO_DIR="$ROOT_DIR/repos/pi-mono"
PI_DIST_CLI="$PI_MONO_DIR/packages/coding-agent/dist/cli.js"
PI_SRC_CLI="$PI_MONO_DIR/packages/coding-agent/src/cli.ts"
PI_TSX="$PI_MONO_DIR/node_modules/.bin/tsx"

if [[ -f "$PI_DIST_CLI" ]]; then
  PI_ENTRYPOINT=(node "$PI_DIST_CLI")
elif [[ -x "$PI_TSX" && -f "$PI_SRC_CLI" ]]; then
  PI_ENTRYPOINT=("$PI_TSX" "$PI_SRC_CLI")
else
  echo "pi-mono is not ready. Run 'cd $PI_MONO_DIR && pnpm install' first." >&2
  exit 1
fi

EXTENSION_ARGS=()
while [[ $# -gt 0 ]]; do
  case "$1" in
    -e|--extension)
      [[ $# -ge 2 ]] || { echo "missing path after $1" >&2; exit 2; }
      EXTENSION_ARGS+=("$1" "$2")
      shift 2
      ;;
    *)
      break
      ;;
  esac
done

PI_PASSTHROUGH_ARGS=()
while [[ $# -gt 0 ]]; do
  case "$1" in
    --provider|--model|--thinking)
      [[ $# -ge 2 ]] || { echo "missing value after $1" >&2; exit 2; }
      PI_PASSTHROUGH_ARGS+=("$1" "$2")
      shift 2
      ;;
    *)
      break
      ;;
  esac
done

USER_NAME="${1:-}"
[[ -n "$USER_NAME" ]] || { echo "usage: rho [--extension path] [--provider name] [--model id] <user> <prompt...>" >&2; exit 2; }
shift
[[ $# -gt 0 ]] || { echo "usage: rho [--extension path] [--provider name] [--model id] <user> <prompt...>" >&2; exit 2; }

USER_ROOT="${RHO_USERS_ROOT:-$ROOT_DIR/sandbox/pi-users}"
export RHO_USER="$USER_NAME"
export RHO_USER_DIR="$USER_ROOT/$USER_NAME"
export RHO_AGENT_DIR="$RHO_USER_DIR/agent"
export RHO_SESSION_DIR="$RHO_USER_DIR/sessions"
export RHO_SESSION_FILE="$RHO_USER_DIR/session.jsonl"
if [[ "${RHO_PI_USE_GLOBAL_AGENT_DIR:-0}" == "1" ]]; then
  export PI_CODING_AGENT_DIR="${PI_CODING_AGENT_DIR:-$HOME/.pi/agent}"
else
  export PI_CODING_AGENT_DIR="$RHO_AGENT_DIR"
fi
mkdir -p "$RHO_AGENT_DIR" "$RHO_SESSION_DIR"

PROMPT="$*"
exec "${PI_ENTRYPOINT[@]}" \
  "${EXTENSION_ARGS[@]}" \
  "${PI_PASSTHROUGH_ARGS[@]}" \
  --print \
  --session "$RHO_SESSION_FILE" \
  "$PROMPT"
