#!/usr/bin/env bash

set -euo pipefail

source "$(cd "$(dirname "$0")" && pwd)/scripts/rho-common.sh"

if [[ "${1:-}" == "run" ]]; then
  shift
  [[ $# -gt 0 ]] || rho_die "usage: rho run <config.yaml> [--dry-run] [--print-config] [--var NAME=value] [--allow-host HOST] [--pre-hook CMD] [--post-hook CMD] [-- extra-args...]"
  rho_run_node_script "$RHO_ROOT/repos/pi-mono/scripts/rho-run.mjs" "$@"
  exit $?
fi

if [[ "${1:-}" == "request" ]]; then
  shift
  exec python3 "$RHO_ROOT/scripts/rho-request.py" "$@"
fi

if [[ "${1:-}" == "approve" ]]; then
  shift
  exec python3 "$RHO_ROOT/scripts/rho-request.py" approve "$@"
fi

if [[ "${1:-}" == "agent-run" ]]; then
  shift
  exec python3 "$RHO_ROOT/scripts/rho-agent-run.py" "$@"
fi

rho_parse_extension_flags "$@"
set -- "${RHO_REMAINING_ARGS[@]}"

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

rho_require_user "${1:-}"
USER_NAME="$1"
shift

[[ $# -gt 0 ]] || rho_die "usage: rho <user> <prompt...>"

rho_prepare_user "$USER_NAME"
rho_prepare_pi_env

PROMPT="$*"
PI_ARGS=()

if (( ${#RHO_EXTENSION_ARGS[@]} > 0 )); then
  PI_ARGS+=("${RHO_EXTENSION_ARGS[@]}")
fi

if (( ${#PI_PASSTHROUGH_ARGS[@]} > 0 )); then
  PI_ARGS+=("${PI_PASSTHROUGH_ARGS[@]}")
fi

PI_ARGS+=(
  --print
  --session "$RHO_SESSION_FILE"
  "$PROMPT"
)

rho_run_pi "${PI_ARGS[@]}"
