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

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

SANDBOX="$ROOT_DIR/sandbox/rho-request-review"
REPO="$SANDBOX/repo"
OWNER_HOME="$SANDBOX/owner-rho-home"
COLLAB_HOME="$SANDBOX/collab-rho-home"
OWNER_ID="rho://id/github/rho-owner"
COLLAB_ID="rho://id/github/rho-collab"
REQUEST_ID="req-review"
DATASET_UUID="dataset-review"
REQUEST_DIR="rho/messages/inbox/rho-owner/$REQUEST_ID"

rm -rf "$SANDBOX"
mkdir -p "$REPO"

git -C "$REPO" init >/dev/null
git -C "$REPO" config user.name "Rho Request Review Test"
git -C "$REPO" config user.email "request-review@example.test"
git -C "$REPO" config commit.gpgsign false

RHO_HOME="$OWNER_HOME" ./rho id init \
  --github rho-owner \
  --display-name "Rho Owner" \
  --generate-ssh-key >/dev/null
RHO_HOME="$COLLAB_HOME" ./rho id init \
  --github rho-collab \
  --display-name "Rho Collaborator" \
  --generate-ssh-key >/dev/null
RHO_HOME="$COLLAB_HOME" ./rho id export \
  --identity "$COLLAB_ID" \
  --out "$SANDBOX/rho-collab-public.yaml" >/dev/null
RHO_HOME="$OWNER_HOME" ./rho id import "$SANDBOX/rho-collab-public.yaml" >/dev/null

./rho repo init \
  --root "$REPO" \
  --repo-id rho://repo/local/request-review \
  --owner "$OWNER_ID" >/dev/null

mkdir -p "$REPO/workspace" "$REPO/$REQUEST_DIR" "$REPO/datasets/$DATASET_UUID/mock"
cat > "$REPO/workspace/sum_prices.py" <<'PY'
import csv
import sys
from decimal import Decimal

total = Decimal("0")
with open(sys.argv[1], newline="") as f:
    for row in csv.DictReader(f):
        total += Decimal(row["price"])
print(f"{total:.2f}")
PY
cat > "$REPO/datasets/$DATASET_UUID/mock/prices-mock.csv" <<'CSV'
date,symbol,price
2026-01-01,A,100.01
2026-01-02,B,200.02
2026-01-03,C,300.03
2026-01-04,D,512.97
CSV
CODE_DIGEST="$(shasum -a 256 "$REPO/workspace/sum_prices.py" | awk '{print $1}')"
test -n "$CODE_DIGEST"

cat > "$REPO/$REQUEST_DIR/request.yaml" <<EOF
version: 1
request:
  id: $REQUEST_ID
  from: $COLLAB_ID
  to: $OWNER_ID
  type: private-analysis
  dataset_uuid: $DATASET_UUID
  code_path: rho://repo/workspace/sum_prices.py
  code_sha256: $CODE_DIGEST
  requested_tier: real
EOF
RHO_HOME="$COLLAB_HOME" ./rho crypto sign \
  "$REPO/$REQUEST_DIR/request.yaml" \
  --identity "$COLLAB_ID" \
  --out "$REPO/$REQUEST_DIR/request.rhosig.yaml" >/dev/null

RHO_HOME="$OWNER_HOME" ./rho request review "$REQUEST_ID" \
  --root "$REPO" \
  > "$SANDBOX/review-output.txt"
grep -q "rho request review" "$SANDBOX/review-output.txt"
grep -q "signature: verified" "$SANDBOX/review-output.txt"
grep -q "dataset_uuid: $DATASET_UUID" "$SANDBOX/review-output.txt"
grep -q "code_digest: verified" "$SANDBOX/review-output.txt"
grep -q "1113.03" "$SANDBOX/review-output.txt"
grep -q "mock_run: passed" "$SANDBOX/review-output.txt"

echo "inspect sandbox: $SANDBOX"
find "$SANDBOX" \
  -path "*/.git" -prune -o \
  -maxdepth 7 -type f -print | sort
echo "rho request review e2e passed"
