#!/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/id/github/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
RHO_HOME="$OWNER_HOME" ./rho repo protect-path \
  "rho/messages/inbox/id/github/rho-owner/**" \
  --root "$REPO" \
  --rho-bin "$ROOT_DIR/rho" \
  --recipient "$OWNER_ID" >/dev/null

mkdir -p "$REPO/workspace" "$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"

RHO_HOME="$COLLAB_HOME" ./rho request submit-run "$REQUEST_ID" \
  --root "$REPO" \
  --from "$COLLAB_ID" \
  --to "$OWNER_ID" \
  --tool-id run_real \
  --dataset-uuid "$DATASET_UUID" \
  --code-path rho://repo/workspace/sum_prices.py \
  --tier real \
  > "$SANDBOX/submit-output.txt"
grep -q "request: $REQUEST_ID" "$SANDBOX/submit-output.txt"
grep -q "staged encrypted request files" "$SANDBOX/submit-output.txt"
grep -q "path: $REQUEST_DIR/request.yaml" "$SANDBOX/submit-output.txt"
grep -q "signature: $REQUEST_DIR/request.rhosig.yaml" "$SANDBOX/submit-output.txt"
grep -q "$CODE_DIGEST" "$REPO/$REQUEST_DIR/request.yaml"
grep -q "purpose: rho.request" "$REPO/$REQUEST_DIR/request.rhosig.yaml"

git -C "$REPO" show ":$REQUEST_DIR/request.yaml" > "$SANDBOX/request-index.yaml"
git -C "$REPO" show ":$REQUEST_DIR/request.rhosig.yaml" > "$SANDBOX/request-signature-index.yaml"
grep -q "kind: rho_recipient_envelope" "$SANDBOX/request-index.yaml"
grep -q "kind: rho_recipient_envelope" "$SANDBOX/request-signature-index.yaml"
grep -q "$COLLAB_ID" "$SANDBOX/request-index.yaml"
grep -q "$COLLAB_ID" "$SANDBOX/request-signature-index.yaml"
if grep -q "$CODE_DIGEST" "$SANDBOX/request-index.yaml"; then
  echo "submitted request leaked plaintext digest in staged blob" >&2
  exit 1
fi
git -C "$REPO" show ":$REQUEST_DIR/request.yaml" > "$REPO/$REQUEST_DIR/request.yaml"
git -C "$REPO" show ":$REQUEST_DIR/request.rhosig.yaml" > "$REPO/$REQUEST_DIR/request.rhosig.yaml"
grep -q "kind: rho_recipient_envelope" "$REPO/$REQUEST_DIR/request.yaml"
grep -q "kind: rho_recipient_envelope" "$REPO/$REQUEST_DIR/request.rhosig.yaml"

awk '
  /^[[:space:]]+ciphertext_base64:/ && !done {
    prefix = substr($0, 1, index($0, "ciphertext_base64:") - 1)
    value = $2
    first = substr(value, 1, 1)
    replacement = first == "A" ? "B" : "A"
    print prefix "ciphertext_base64: " replacement substr(value, 2)
    done = 1
    next
  }
  { print }
' "$SANDBOX/request-index.yaml" > "$REPO/$REQUEST_DIR/request.yaml"
if RHO_HOME="$OWNER_HOME" RHO_IDENTITY="$OWNER_ID" ./rho request review "$REQUEST_ID" \
  --root "$REPO" \
  > "$SANDBOX/review-tampered-request-stdout.txt" \
  2> "$SANDBOX/review-tampered-request-stderr.txt"; then
  echo "request review accepted tampered encrypted request ciphertext" >&2
  exit 1
fi
grep -q "recipient envelope decrypt failed for $OWNER_ID" "$SANDBOX/review-tampered-request-stderr.txt"
grep -q "decrypt" "$SANDBOX/review-tampered-request-stderr.txt"
grep -q "rho crypto smudge failed for $REQUEST_DIR/request.yaml" "$SANDBOX/review-tampered-request-stderr.txt"
git -C "$REPO" show ":$REQUEST_DIR/request.yaml" > "$REPO/$REQUEST_DIR/request.yaml"
git -C "$REPO" show ":$REQUEST_DIR/request.rhosig.yaml" > "$REPO/$REQUEST_DIR/request.rhosig.yaml"

RHO_HOME="$OWNER_HOME" RHO_IDENTITY="$OWNER_ID" ./rho request review "$REQUEST_ID" \
  --root "$REPO" \
  --summary-out "$REPO/rho/request-reviews/$REQUEST_ID/review.yaml" \
  > "$SANDBOX/review-output.txt"
grep -q "rho request review" "$SANDBOX/review-output.txt"
grep -q "refreshed protected file: $REQUEST_DIR/request.yaml" "$SANDBOX/review-output.txt"
grep -q "refreshed protected file: $REQUEST_DIR/request.rhosig.yaml" "$SANDBOX/review-output.txt"
grep -q "signature: verified" "$SANDBOX/review-output.txt"
grep -q "review_summary: $REPO/rho/request-reviews/$REQUEST_ID/review.yaml" "$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"
test -f "$REPO/rho/request-reviews/$REQUEST_ID/review.yaml"
grep -q "request_id: $REQUEST_ID" "$REPO/rho/request-reviews/$REQUEST_ID/review.yaml"
grep -q "status: verified" "$REPO/rho/request-reviews/$REQUEST_ID/review.yaml"
grep -q "digest_status: verified" "$REPO/rho/request-reviews/$REQUEST_ID/review.yaml"
grep -q "status: passed" "$REPO/rho/request-reviews/$REQUEST_ID/review.yaml"
grep -q "stdout: '1113.03'" "$REPO/rho/request-reviews/$REQUEST_ID/review.yaml"
grep -q "request:" "$REPO/$REQUEST_DIR/request.yaml"
grep -q "signature:" "$REPO/$REQUEST_DIR/request.rhosig.yaml"
if grep -q "kind: rho_recipient_envelope" "$REPO/$REQUEST_DIR/request.yaml"; then
  echo "request review left request envelope in working tree" >&2
  exit 1
fi
if grep -q "kind: rho_recipient_envelope" "$REPO/$REQUEST_DIR/request.rhosig.yaml"; then
  echo "request review left signature envelope in working tree" >&2
  exit 1
fi

mv "$REPO/$REQUEST_DIR/request.rhosig.yaml" "$REPO/$REQUEST_DIR/request.context.rhosig.yaml"
RHO_HOME="$COLLAB_HOME" ./rho crypto sign \
  "$REPO/$REQUEST_DIR/request.yaml" \
  --identity "$COLLAB_ID" \
  --out "$REPO/$REQUEST_DIR/request.rhosig.yaml" >/dev/null
if RHO_HOME="$OWNER_HOME" RHO_IDENTITY="$OWNER_ID" ./rho request review "$REQUEST_ID" \
  --root "$REPO" \
  >"$SANDBOX/review-legacy-signature-stdout.txt" \
  2>"$SANDBOX/review-legacy-signature-stderr.txt"; then
  echo "request review accepted a legacy request signature without context" >&2
  exit 1
fi
grep -q "signature verification failed" "$SANDBOX/review-legacy-signature-stderr.txt"
mv "$REPO/$REQUEST_DIR/request.context.rhosig.yaml" "$REPO/$REQUEST_DIR/request.rhosig.yaml"

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