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

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

export RUN_LIVE_PI=1
export RHO_PI_USE_GLOBAL_AGENT_DIR="${RHO_PI_USE_GLOBAL_AGENT_DIR:-0}"
export RHO_PI_AGENT_CONFIG_DIR="${RHO_PI_AGENT_CONFIG_DIR:-$HOME/.pi/agent}"
export RHO_PI_PROVIDER="${RHO_PI_PROVIDER:-openai-codex}"
export RHO_PI_MODEL="${RHO_PI_MODEL:-gpt-5.4}"
export RHO_LIVE_SANDBOX_RUNNER="${RHO_LIVE_SANDBOX_RUNNER:-gondolin}"

if [[ "$RHO_PI_USE_GLOBAL_AGENT_DIR" == "1" && ! -f "${PI_CODING_AGENT_DIR:-$RHO_PI_AGENT_CONFIG_DIR}/auth.json" ]]; then
  echo "Pi auth.json does not exist: ${PI_CODING_AGENT_DIR:-$HOME/.pi/agent}/auth.json" >&2
  exit 1
fi

if [[ "$RHO_PI_USE_GLOBAL_AGENT_DIR" != "1" && ! -f "$RHO_PI_AGENT_CONFIG_DIR/auth.json" && -z "${RHO_PI_AUTH_JSON:-}" ]]; then
  echo "Pi auth.json does not exist: $RHO_PI_AGENT_CONFIG_DIR/auth.json" >&2
  echo "Set RHO_PI_AGENT_CONFIG_DIR or RHO_PI_AUTH_JSON." >&2
  exit 1
fi

if [[ -n "${RHO_PI_AUTH_JSON:-}" && ! -f "$RHO_PI_AUTH_JSON" ]]; then
  echo "RHO_PI_AUTH_JSON does not exist: $RHO_PI_AUTH_JSON" >&2
  exit 1
fi

PI_MONO_DIR="$ROOT_DIR/repos/pi-mono"
GONDOLIN_DIR="$ROOT_DIR/repos/gondolin"

if [[ ! -x "$PI_MONO_DIR/node_modules/.bin/tsx" && ! -f "$PI_MONO_DIR/packages/coding-agent/dist/cli.js" ]]; then
  echo "pi-mono dependencies are missing. Run 'cd repos/pi-mono && npm install' first." >&2
  exit 1
fi

if [[ ! -f "$PI_MONO_DIR/packages/ai/dist/index.js" || ! -f "$PI_MONO_DIR/packages/coding-agent/dist/cli.js" ]]; then
  echo "building pi-mono packages for live test..."
  npm --prefix "$PI_MONO_DIR" run build
fi

if [[ "$RHO_LIVE_SANDBOX_RUNNER" == "gondolin" ]]; then
  if [[ ! -d "$GONDOLIN_DIR" ]]; then
    echo "gondolin submodule is missing at $GONDOLIN_DIR" >&2
    exit 1
  fi
  if [[ ! -f "$GONDOLIN_DIR/node_modules/@earendil-works/gondolin/bin/gondolin.ts" ]]; then
    echo "gondolin dependencies are missing. Run 'cd repos/gondolin && pnpm install' first." >&2
    echo "To use the local fake runner instead: RHO_LIVE_SANDBOX_RUNNER=fake ./test-live.sh" >&2
    exit 1
  fi
fi

bash tests/e2e/live-pi-tool-call.sh
RHO_LOCAL_GIT_PI_LIVE=1 bash tests/e2e/local-git-pi-sandbox-encrypted.sh
