#!/usr/bin/env bash

set -euo pipefail

RHO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PI_DIR="$RHO_ROOT/repos/pi"
PI_DIST_CLI="$PI_DIR/packages/coding-agent/dist/cli.js"
PI_SRC_CLI="$PI_DIR/packages/coding-agent/src/cli.ts"
PI_TSX="$PI_DIR/node_modules/.bin/tsx"
RHO_PI_ENTRYPOINT=()
RHO_EXTENSION_ARGS=()
RHO_REMAINING_ARGS=()

rho_die() {
  printf '%s\n' "$*" >&2
  exit 1
}

rho_require_user() {
  local user="${1:-}"
  [[ -n "$user" ]] || rho_die "usage: $(basename "$0") <user> [prompt or args...]"
}

rho_prepare_user() {
  local user="$1"
  export RHO_USER="$user"
  export RHO_USER_DIR="$RHO_ROOT/users/$user"
  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"
  mkdir -p "$RHO_AGENT_DIR" "$RHO_SESSION_DIR"
}

rho_prepare_pi_env() {
  export PI_CODING_AGENT_DIR="$RHO_AGENT_DIR"
}

rho_parse_extension_flags() {
  RHO_EXTENSION_ARGS=()

  while [[ $# -gt 0 ]]; do
    case "$1" in
      -e|--extension)
        [[ $# -ge 2 ]] || rho_die "missing path after $1"
        RHO_EXTENSION_ARGS+=("$1" "$2")
        shift 2
        ;;
      *)
        break
        ;;
    esac
  done

  RHO_REMAINING_ARGS=("$@")
}

rho_pi_entrypoint() {
  if [[ -f "$PI_DIST_CLI" ]]; then
    RHO_PI_ENTRYPOINT=(node "$PI_DIST_CLI")
    return 0
  fi

  if [[ -x "$PI_TSX" && -f "$PI_SRC_CLI" ]]; then
    RHO_PI_ENTRYPOINT=("$PI_TSX" "$PI_SRC_CLI")
    return 0
  fi

  rho_die "pi is not ready. Run 'cd $PI_DIR && npm install' first. If you want the built CLI, also run 'npm run build --workspace @mariozechner/pi-coding-agent'."
}

rho_run_pi() {
  rho_pi_entrypoint

  (
    cd "${RHO_WORKSPACE:-$RHO_ROOT}"
    exec "${RHO_PI_ENTRYPOINT[@]}" "$@"
  )
}

rho_run_tsx_script() {
  local script="$1"
  shift

  [[ -x "$PI_TSX" ]] || rho_die "pi is not ready. Run 'cd $PI_DIR && npm install' first."

  (
    cd "$PI_DIR"
    exec "$PI_TSX" "$script" "$@"
  )
}

rho_run_node_script() {
  local script="$1"
  shift

  (
    cd "$RHO_ROOT"
    exec node --disable-warning=ExperimentalWarning "$script" "$@"
  )
}
