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

if [[ "${RUN_LIVE_PI:-0}" != "1" ]]; then
  echo "live Pi e2e skipped; set RUN_LIVE_PI=1 to run with real provider credentials"
  exit 0
fi

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

PI_DIR="$ROOT_DIR/repos/pi"

if [[ ! -x "$PI_DIR/node_modules/.bin/tsx" && ! -f "$PI_DIR/packages/coding-agent/dist/cli.js" ]]; then
  echo "pi is not ready. Run 'cd repos/pi && pnpm install' first." >&2
  exit 1
fi

SANDBOX="$ROOT_DIR/sandbox/live-pi-tool-call"
UUID="33333333-4444-5555-6666-777777777777"
OWNER="agent1"
PEER="agent2"
REQUEST_ID="req-$UUID"
RUN_ACTION_ID="act-live-pi-run-real-$UUID"
RELEASE_ACTION_ID="act-live-pi-release-$UUID"
RUN_ID="run-live-pi-run-real-$UUID"
RUN_STDOUT="$SANDBOX/shared/.rho/runs/$RUN_ID/stdout.txt"
RELEASE_OUTPUT="$SANDBOX/shared/results/$REQUEST_ID/output.txt"
PROVIDER="${RHO_PI_PROVIDER:-openai-codex}"
MODEL="${RHO_PI_MODEL:-gpt-5.4}"
SANDBOX_RUNNER="${RHO_LIVE_SANDBOX_RUNNER:-gondolin}"

rm -rf "$SANDBOX"
mkdir -p "$SANDBOX/shared/workspace" "$SANDBOX/agent-control/outbox" "$SANDBOX/host-control/outbox" "$SANDBOX/host-control/inbox"

copy_pi_agent_config() {
  local target="$1"
  mkdir -p "$target"
  if [[ -n "${RHO_PI_AUTH_JSON:-}" ]]; then
    cp "$RHO_PI_AUTH_JSON" "$target/auth.json"
  elif [[ -f "${RHO_PI_AGENT_CONFIG_DIR:-$HOME/.pi/agent}/auth.json" ]]; then
    cp "${RHO_PI_AGENT_CONFIG_DIR:-$HOME/.pi/agent}/auth.json" "$target/auth.json"
  fi
  for name in settings.json models.json; do
    if [[ -f "${RHO_PI_AGENT_CONFIG_DIR:-$HOME/.pi/agent}/$name" ]]; then
      cp "${RHO_PI_AGENT_CONFIG_DIR:-$HOME/.pi/agent}/$name" "$target/$name"
    fi
  done
}

if [[ "${RHO_PI_USE_GLOBAL_AGENT_DIR:-0}" != "1" ]]; then
  copy_pi_agent_config "$SANDBOX/pi-users/$PEER/agent"
  copy_pi_agent_config "$SANDBOX/pi-users/$OWNER/agent"
fi

cargo run --quiet --bin rho -- dataset \
  --name prices-live-pi-test \
  --real prototype/tests/scenarios/two-console-demo/assets/datasets/prices-real.csv \
  --mock prototype/tests/scenarios/two-console-demo/assets/datasets/prices-mock.csv \
  --owner "$OWNER" \
  --share-dir "$SANDBOX/users/$OWNER/datasets/share" \
  --private-dir "$SANDBOX/users/$OWNER/datasets/private" \
  --uuid "$UUID" \
  --description "Live Pi controlled action e2e test"

cargo run --quiet --bin rho -- publish \
  "$OWNER" "$UUID" \
  --source-root "$SANDBOX/users" \
  --target-root "$SANDBOX/shared/datasets"

cargo run --quiet --bin rho -- tools install-minimal \
  --shared-root "$SANDBOX/shared" \
  --owner "$OWNER"

PROMPT="Write a Python 3 standard-library script to $SANDBOX/shared/workspace/sum_prices.py. The script must read a CSV with columns date,symbol,price, sum the price column exactly, and print only the final numeric total. Then call request_controlled_action exactly once with action_id $RUN_ACTION_ID, request_id $REQUEST_ID, tool_id run_real, requested_by $PEER, requested_for $OWNER, action_type run_real_data, script_path /output/sum_prices.py, output_path /results/private/stdout.txt, and concise summary and reason. Do not run the script and do not write any other files."

RHO_USERS_ROOT="$SANDBOX/pi-users" \
RHO_CONTROL_ROOT="$SANDBOX/agent-control" \
./rho \
  --extension "$ROOT_DIR/extensions/rho-controlled-action-bridge.ts" \
  --provider "$PROVIDER" \
  --model "$MODEL" \
  "$PEER" \
  "$PROMPT"

test -f "$SANDBOX/shared/workspace/sum_prices.py"
test -f "$SANDBOX/agent-control/outbox/$RUN_ACTION_ID.json"
grep -q '"tool_id": "run_real"' "$SANDBOX/agent-control/outbox/$RUN_ACTION_ID.json"
grep -q '"/output/sum_prices.py"' "$SANDBOX/agent-control/outbox/$RUN_ACTION_ID.json"

cargo run --quiet --bin rho -- request create-run \
  --shared-root "$SANDBOX/shared" \
  --id "$REQUEST_ID" \
  --from "$PEER" \
  --to "$OWNER" \
  --tool-id run_real \
  --dataset-uuid "$UUID" \
  --code-path "$SANDBOX/shared/workspace/sum_prices.py" \
  --command "python3 sum_prices.py DATASET_CSV" \
  --tier real

cargo run --quiet --bin rho -- run import-action \
  --agent-control-root "$SANDBOX/agent-control" \
  --control-root "$SANDBOX/host-control" \
  --action-id "$RUN_ACTION_ID" \
  --map "/output=$SANDBOX/shared/workspace" \
  --map "/results/private=$SANDBOX/shared/.rho/runs/$RUN_ID"

cargo run --quiet --bin rho -- run grant-action \
  --shared-root "$SANDBOX/shared" \
  --control-root "$SANDBOX/host-control" \
  --action-id "$RUN_ACTION_ID" \
  --granted-by "$OWNER" \
  --input "code:$SANDBOX/shared/workspace/sum_prices.py"

RUN_STATUS_PATH="$(RHO_SANDBOX_RUNNER="$SANDBOX_RUNNER" cargo run --quiet --bin rho -- run controlled-action \
  --shared-root "$SANDBOX/shared" \
  --control-root "$SANDBOX/host-control" \
  --action-id "$RUN_ACTION_ID" \
  --private-root "$SANDBOX/users/$OWNER/datasets/private")"
grep -q "completed" "$RUN_STATUS_PATH"
test "$(cat "$RUN_STDOUT")" = "1113.03"

mkdir -p "$SANDBOX/agent-control/inbox"
cp "$RUN_STATUS_PATH" "$SANDBOX/agent-control/inbox/$RUN_ACTION_ID.status.json"

RELEASE_PROMPT="Call get_controlled_action_status for action_id $RUN_ACTION_ID. If it is completed, call request_controlled_action exactly once with action_id $RELEASE_ACTION_ID, request_id $REQUEST_ID, tool_id publish_results, requested_by $OWNER, requested_for $OWNER, action_type release_results, input_path /results/private/stdout.txt, output_path /release/shared/output.txt, and concise summary and reason. Do not write any files yourself."

RHO_USERS_ROOT="$SANDBOX/pi-users" \
RHO_CONTROL_ROOT="$SANDBOX/agent-control" \
./rho \
  --extension "$ROOT_DIR/extensions/rho-controlled-action-bridge.ts" \
  --provider "$PROVIDER" \
  --model "$MODEL" \
  "$OWNER" \
  "$RELEASE_PROMPT"

test -f "$SANDBOX/agent-control/outbox/$RELEASE_ACTION_ID.json"
grep -q '"tool_id": "publish_results"' "$SANDBOX/agent-control/outbox/$RELEASE_ACTION_ID.json"

cargo run --quiet --bin rho -- run import-action \
  --agent-control-root "$SANDBOX/agent-control" \
  --control-root "$SANDBOX/host-control" \
  --action-id "$RELEASE_ACTION_ID" \
  --map "/results/private=$SANDBOX/shared/.rho/runs/$RUN_ID" \
  --map "/release/shared=$SANDBOX/shared/results/$REQUEST_ID"

cargo run --quiet --bin rho -- run grant-action \
  --shared-root "$SANDBOX/shared" \
  --control-root "$SANDBOX/host-control" \
  --action-id "$RELEASE_ACTION_ID" \
  --granted-by "$OWNER" \
  --input "artifact:$RUN_STDOUT"

RELEASE_STATUS_PATH="$(cargo run --quiet --bin rho -- run controlled-action \
  --shared-root "$SANDBOX/shared" \
  --control-root "$SANDBOX/host-control" \
  --action-id "$RELEASE_ACTION_ID" \
  --private-root "$SANDBOX/users/$OWNER/datasets/private")"
grep -q "completed" "$RELEASE_STATUS_PATH"
test "$(cat "$RELEASE_OUTPUT")" = "1113.03"

echo "inspect sandbox: $SANDBOX"
find "$SANDBOX/agent-control" "$SANDBOX/host-control" "$SANDBOX/shared/.rho" -maxdepth 3 -type f | sort
echo "live Pi tool-call e2e passed"
