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

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

SANDBOX="$ROOT_DIR/sandbox/git-branch-pr"
UUID="44444444-5555-6666-7777-888888888888"
REQUEST_ID="req-$UUID"
REQUEST_BRANCH="user2/request-analysis-$UUID"
RELEASE_BRANCH="user1/release-result-$UUID"
USER1_ID="rho://id/github/rho-user1"
USER2_ID="rho://id/github/rho-user2"
ACTION_ID="act-git-run-real-$UUID"
RUN_ID="run-git-run-real-$UUID"

plan() {
  cat <<EOF
git-branch-pr fixture scenario

This is the fast, non-live version of the two-account GitHub flow.
It uses a local bare repo as the remote and cached agent outputs.

Topology:
  $SANDBOX/remote.git
  $SANDBOX/user1
  $SANDBOX/user2
  $SANDBOX/user1-rho-home
  $SANDBOX/user2-rho-home

Branches:
  main
  $REQUEST_BRANCH
  $RELEASE_BRANCH

Current strict fixture:
  1. user1 runs rho repo init and initializes a GitHub-backed Rho identity.
  2. user1 exports a public participant bundle and pushes main.
  3. user2 clones, initializes identity, verifies/trusts user1 via a fake provider page.
  4. user2 creates a request branch with cached analysis code and an encrypted signed request bundle.
  5. user1 fetches the request branch, verifies/trusts user2, opens the bundle, and verifies the request signature.
  6. user1 imports the repo-portable controlled action, grants it, and runs it against real data.
  7. user1 pushes an encrypted signed release bundle, then user2 fetches, opens, and verifies it.

Still future:
  - live Pi replacing cached fixture files
EOF
}

setup_clone_identity() {
  local clone_dir="$1"
  local name="$2"
  local email="$3"
  git -C "$clone_dir" config user.name "$name"
  git -C "$clone_dir" config user.email "$email"
  git -C "$clone_dir" config commit.gpgsign false
}

provider_page_for_claim() {
  local participant_file="$1"
  local provider_file="$2"
  local claim
  claim="$(sed -n 's/^    claim: //p' "$participant_file")"
  cat > "$provider_file" <<EOF
<html><body><a href="https://example.com">$claim</a></body></html>
EOF
}

run_fixture() {
  rm -rf "$SANDBOX"
  mkdir -p "$SANDBOX"

  git init --bare "$SANDBOX/remote.git" >/dev/null

  git clone "$SANDBOX/remote.git" "$SANDBOX/user1" >/dev/null
  setup_clone_identity "$SANDBOX/user1" "Rho User One" "user1@example.test"
  git -C "$SANDBOX/user1" switch -c main >/dev/null

  ./rho repo init \
    --root "$SANDBOX/user1" \
    --repo-id rho://repo/local/git-branch-pr \
    --owner "$USER1_ID" >/dev/null

  RHO_HOME="$SANDBOX/user1-rho-home" ./rho id init \
    --github rho-user1 \
    --display-name "Rho User One" \
    --generate-ssh-key >/dev/null
  RHO_HOME="$SANDBOX/user1-rho-home" ./rho id export \
    --identity "$USER1_ID" \
    --out "$SANDBOX/user1/rho/participants/rho-user1.yaml" >/dev/null

  git -C "$SANDBOX/user1" add .gitattributes .gitignore rho
  git -C "$SANDBOX/user1" commit -m "Initialize rho collaboration space" >/dev/null
  git -C "$SANDBOX/user1" push -u origin main >/dev/null
  git -C "$SANDBOX/remote.git" symbolic-ref HEAD refs/heads/main

  git clone "$SANDBOX/remote.git" "$SANDBOX/user2" >/dev/null
  setup_clone_identity "$SANDBOX/user2" "Rho User Two" "user2@example.test"
  git -C "$SANDBOX/user2" switch -c "$REQUEST_BRANCH" >/dev/null

  RHO_HOME="$SANDBOX/user2-rho-home" ./rho id init \
    --github rho-user2 \
    --display-name "Rho User Two" \
    --generate-ssh-key >/dev/null
  RHO_HOME="$SANDBOX/user2-rho-home" ./rho id import \
    "$SANDBOX/user2/rho/participants/rho-user1.yaml" >/dev/null
  provider_page_for_claim \
    "$SANDBOX/user2/rho/participants/rho-user1.yaml" \
    "$SANDBOX/github-rho-user1.html"
  RHO_HOME="$SANDBOX/user2-rho-home" ./rho id verify-github \
    --identity "$USER1_ID" \
    --provider-file "$SANDBOX/github-rho-user1.html" >/dev/null
  RHO_HOME="$SANDBOX/user2-rho-home" ./rho id trust "$USER1_ID" >/dev/null
  RHO_HOME="$SANDBOX/user2-rho-home" ./rho id export \
    --identity "$USER2_ID" \
    --out "$SANDBOX/user2/rho/participants/rho-user2.yaml" >/dev/null

  mkdir -p \
    "$SANDBOX/user2/workspace" \
    "$SANDBOX/user2/rho/messages/inbox/rho-user1" \
    "$SANDBOX/user2-request-staging/rho/requests" \
    "$SANDBOX/user2-request-staging/rho/control/outbox"
  cp prototype/tests/scenarios/two-console-demo/assets/workspace/sum_prices.py "$SANDBOX/user2/workspace/sum_prices.py"
  cat > "$SANDBOX/user2-request-staging/rho/requests/$REQUEST_ID.yaml" <<EOF
version: 1
request:
  id: $REQUEST_ID
  from: $USER2_ID
  to: $USER1_ID
  type: protected-analysis
  code_path: rho://repo/workspace/sum_prices.py
  action_path: rho://repo/rho/control/outbox/act-git-run-real-$UUID.json
  created_at: "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
EOF
  cat > "$SANDBOX/user2-request-staging/rho/control/outbox/act-git-run-real-$UUID.json" <<EOF
{
  "version": 1,
  "kind": "controlled_action",
  "action": {
    "action_id": "act-git-run-real-$UUID",
    "request_id": "$REQUEST_ID",
    "tool_id": "run_real",
    "requested_by": "$USER2_ID",
    "requested_for": "$USER1_ID",
    "action_type": "run_real_data",
    "summary": "Run generated sum_prices.py against real data.",
    "reason": "Fixture-controlled action proposal for the future encrypted branch PR flow.",
    "script_path": "rho://repo/workspace/sum_prices.py",
    "output_path": "rho://run/run-git-run-real-$UUID/stdout.txt"
  }
}
EOF
  RHO_HOME="$SANDBOX/user2-rho-home" ./rho crypto sign \
    "$SANDBOX/user2-request-staging/rho/requests/$REQUEST_ID.yaml" \
    --identity "$USER2_ID" \
    --out "$SANDBOX/user2-request-staging/rho/requests/$REQUEST_ID.rhosig.yaml" >/dev/null
  tar --format ustar -cf "$SANDBOX/user2-request-bundle.tar" -C "$SANDBOX/user2-request-staging" rho
  REQUEST_BUNDLE_REPO_PATH="rho/messages/inbox/rho-user1/$REQUEST_ID.request.tar.rhoenc"
  REQUEST_BUNDLE_PATH="$SANDBOX/user2/$REQUEST_BUNDLE_REPO_PATH"
  RHO_HOME="$SANDBOX/user2-rho-home" ./rho crypto seal \
    "$SANDBOX/user2-request-bundle.tar" \
    --recipient "$USER1_ID" \
    --out "$REQUEST_BUNDLE_PATH" \
    --repo-root "$SANDBOX/user2" \
    --path "$REQUEST_BUNDLE_REPO_PATH" \
    --purpose rho.bundle >/dev/null
  grep -q "kind: rho_recipient_envelope" "$REQUEST_BUNDLE_PATH"
  grep -q "context:" "$REQUEST_BUNDLE_PATH"
  grep -q "repo_id: rho://repo/local/git-branch-pr" "$REQUEST_BUNDLE_PATH"
  grep -q "path: $REQUEST_BUNDLE_REPO_PATH" "$REQUEST_BUNDLE_PATH"
  grep -q "purpose: rho.bundle" "$REQUEST_BUNDLE_PATH"
  grep -q "$USER1_ID" "$REQUEST_BUNDLE_PATH"
  grep -q "$USER2_ID" "$REQUEST_BUNDLE_PATH"
  if grep -q "protected-analysis" "$REQUEST_BUNDLE_PATH"; then
    echo "encrypted request bundle leaked plaintext" >&2
    exit 1
  fi
  mkdir -p "$SANDBOX/user2-request-self-open"
  RHO_HOME="$SANDBOX/user2-rho-home" ./rho crypto open \
    "$REQUEST_BUNDLE_PATH" \
    --identity "$USER2_ID" \
    --out "$SANDBOX/user2-request-self-open/request-bundle.tar" \
    --repo-root "$SANDBOX/user2" \
    --path "$REQUEST_BUNDLE_REPO_PATH" \
    --purpose rho.bundle >/dev/null
  cmp "$SANDBOX/user2-request-bundle.tar" "$SANDBOX/user2-request-self-open/request-bundle.tar"

  git -C "$SANDBOX/user2" add rho workspace
  git -C "$SANDBOX/user2" commit -m "Request protected analysis run" >/dev/null
  git -C "$SANDBOX/user2" push -u origin "$REQUEST_BRANCH" >/dev/null

  git -C "$SANDBOX/user1" fetch origin "$REQUEST_BRANCH:$REQUEST_BRANCH" >/dev/null
  git -C "$SANDBOX/user1" worktree add "$SANDBOX/user1-review" "$REQUEST_BRANCH" >/dev/null
  setup_clone_identity "$SANDBOX/user1-review" "Rho User One" "user1@example.test"

  RHO_HOME="$SANDBOX/user1-rho-home" ./rho id import \
    "$SANDBOX/user1-review/rho/participants/rho-user2.yaml" >/dev/null
  provider_page_for_claim \
    "$SANDBOX/user1-review/rho/participants/rho-user2.yaml" \
    "$SANDBOX/github-rho-user2.html"
  RHO_HOME="$SANDBOX/user1-rho-home" ./rho id verify-github \
    --identity "$USER2_ID" \
    --provider-file "$SANDBOX/github-rho-user2.html" >/dev/null
  RHO_HOME="$SANDBOX/user1-rho-home" ./rho id trust "$USER2_ID" >/dev/null
  mkdir -p "$SANDBOX/user1-request-open"
  if RHO_HOME="$SANDBOX/user1-rho-home" ./rho crypto open \
    "$SANDBOX/user1-review/$REQUEST_BUNDLE_REPO_PATH" \
    --identity "$USER1_ID" \
    --out "$SANDBOX/user1-request-open/wrong-path.tar" \
    --repo-root "$SANDBOX/user1-review" \
    --path "$REQUEST_BUNDLE_REPO_PATH.transplanted" \
    --purpose rho.bundle 2>"$SANDBOX/request-context-error.txt"; then
    echo "opened request bundle with wrong envelope context" >&2
    exit 1
  fi
  grep -q "recipient envelope context mismatch" "$SANDBOX/request-context-error.txt"
  RHO_HOME="$SANDBOX/user1-rho-home" ./rho crypto open \
    "$SANDBOX/user1-review/$REQUEST_BUNDLE_REPO_PATH" \
    --identity "$USER1_ID" \
    --out "$SANDBOX/user1-request-open/request-bundle.tar" \
    --repo-root "$SANDBOX/user1-review" \
    --path "$REQUEST_BUNDLE_REPO_PATH" \
    --purpose rho.bundle >/dev/null
  ./rho crypto extract-tar \
    "$SANDBOX/user1-request-open/request-bundle.tar" \
    --out-dir "$SANDBOX/user1-request-open" >/dev/null
  RHO_HOME="$SANDBOX/user1-rho-home" ./rho crypto verify \
    "$SANDBOX/user1-request-open/rho/requests/$REQUEST_ID.yaml" \
    --signature "$SANDBOX/user1-request-open/rho/requests/$REQUEST_ID.rhosig.yaml" \
    --identity "$USER2_ID" >/dev/null

  mkdir -p "$SANDBOX/user1-exec/workspace" "$SANDBOX/user1-exec/control/outbox" "$SANDBOX/user1-exec/control/inbox"
  cp "$SANDBOX/user1-review/workspace/sum_prices.py" "$SANDBOX/user1-exec/workspace/sum_prices.py"
  cargo run --quiet --bin rho -- dataset \
    --name prices-git-branch-pr \
    --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 "$USER1_ID" \
    --share-dir "$SANDBOX/user1-private/users/$USER1_ID/datasets/share" \
    --private-dir "$SANDBOX/user1-private/users/$USER1_ID/datasets/private" \
    --uuid "$UUID" \
    --description "Git branch PR fixture dataset" >/dev/null
  cargo run --quiet --bin rho -- publish \
    "$USER1_ID" "$UUID" \
    --source-root "$SANDBOX/user1-private/users" \
    --target-root "$SANDBOX/user1-exec/datasets" >/dev/null
  cargo run --quiet --bin rho -- tools install-minimal \
    --shared-root "$SANDBOX/user1-exec" \
    --owner "$USER1_ID" >/dev/null
  cargo run --quiet --bin rho -- request create-run \
    --shared-root "$SANDBOX/user1-exec" \
    --id "$REQUEST_ID" \
    --from "$USER2_ID" \
    --to "$USER1_ID" \
    --tool-id run_real \
    --dataset-uuid "$UUID" \
    --code-path "$SANDBOX/user1-exec/workspace/sum_prices.py" \
    --command "python3 sum_prices.py DATASET_CSV" \
    --tier real >/dev/null

  cargo run --quiet --bin rho -- run import-action \
    --source "$SANDBOX/user1-request-open/rho/control/outbox/$ACTION_ID.json" \
    --control-root "$SANDBOX/user1-exec/control" \
    --action-id "$ACTION_ID" \
    --repo-root "$SANDBOX/user1-exec" \
    --run-root "$SANDBOX/user1-exec/.rho/runs" >/dev/null
  grep -q "$SANDBOX/user1-exec/workspace/sum_prices.py" "$SANDBOX/user1-exec/control/outbox/$ACTION_ID.json"
  grep -q "$SANDBOX/user1-exec/.rho/runs/$RUN_ID/stdout.txt" "$SANDBOX/user1-exec/control/outbox/$ACTION_ID.json"

  RHO_SANDBOX_RUNNER=fake cargo run --quiet --bin rho -- run grant-action \
    --shared-root "$SANDBOX/user1-exec" \
    --control-root "$SANDBOX/user1-exec/control" \
    --action-id "$ACTION_ID" \
    --granted-by "$USER1_ID" \
    --input "code:$SANDBOX/user1-exec/workspace/sum_prices.py" >/dev/null
  STATUS_PATH="$(RHO_SANDBOX_RUNNER=fake cargo run --quiet --bin rho -- run controlled-action \
    --shared-root "$SANDBOX/user1-exec" \
    --control-root "$SANDBOX/user1-exec/control" \
    --action-id "$ACTION_ID" \
    --private-root "$SANDBOX/user1-private/users/$USER1_ID/datasets/private")"
  grep -q "completed" "$STATUS_PATH"
  test "$(cat "$SANDBOX/user1-exec/.rho/runs/$RUN_ID/stdout.txt")" = "1113.03"

  grep -q "trusted" "$SANDBOX/user1-rho-home/trust/github/rho-user2.yaml"
  grep -q "verified_at:" "$SANDBOX/user1-rho-home/peers/github/rho-user2.yaml"
  grep -q "rho://repo/local/git-branch-pr" "$SANDBOX/user1-review/rho/repo.yaml"
  grep -q "id: run_real" "$SANDBOX/user1-review/rho/tools/run_real.yaml"
  grep -q "BEGIN SSH SIGNATURE" "$SANDBOX/user1-request-open/rho/requests/$REQUEST_ID.rhosig.yaml"
  grep -q "rho://repo/workspace/sum_prices.py" "$SANDBOX/user1-request-open/rho/requests/$REQUEST_ID.yaml"
  test ! -e "$SANDBOX/user1-review/rho/requests/$REQUEST_ID.yaml"
  grep -q "runner: fake" "$SANDBOX/user1-exec/.rho/runs/$RUN_ID.yaml"

  git -C "$SANDBOX/user1" worktree add -b "$RELEASE_BRANCH" "$SANDBOX/user1-release" main >/dev/null
  setup_clone_identity "$SANDBOX/user1-release" "Rho User One" "user1@example.test"
  mkdir -p \
    "$SANDBOX/user1-release/rho/messages/inbox/rho-user2" \
    "$SANDBOX/user1-release-staging/results/$REQUEST_ID" \
    "$SANDBOX/user1-release-staging/rho/results"
  cp "$SANDBOX/user1-exec/.rho/runs/$RUN_ID/stdout.txt" \
    "$SANDBOX/user1-release-staging/results/$REQUEST_ID/output.txt"
  cat > "$SANDBOX/user1-release-staging/rho/results/$REQUEST_ID.yaml" <<EOF
version: 1
result:
  request_id: $REQUEST_ID
  from: $USER1_ID
  to: $USER2_ID
  output_path: rho://repo/results/$REQUEST_ID/output.txt
  output_sha256: "$(shasum -a 256 "$SANDBOX/user1-release-staging/results/$REQUEST_ID/output.txt" | awk '{print $1}')"
  source_run_id: $RUN_ID
  source_branch: $REQUEST_BRANCH
  created_at: "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
EOF
  RHO_HOME="$SANDBOX/user1-rho-home" ./rho crypto sign \
    "$SANDBOX/user1-release-staging/rho/results/$REQUEST_ID.yaml" \
    --identity "$USER1_ID" \
    --out "$SANDBOX/user1-release-staging/rho/results/$REQUEST_ID.rhosig.yaml" >/dev/null
  tar --format ustar -cf "$SANDBOX/user1-release-bundle.tar" -C "$SANDBOX/user1-release-staging" results rho
  RESULT_BUNDLE_REPO_PATH="rho/messages/inbox/rho-user2/$REQUEST_ID.result.tar.rhoenc"
  RESULT_BUNDLE_PATH="$SANDBOX/user1-release/$RESULT_BUNDLE_REPO_PATH"
  RHO_HOME="$SANDBOX/user1-rho-home" ./rho crypto seal \
    "$SANDBOX/user1-release-bundle.tar" \
    --recipient "$USER2_ID" \
    --out "$RESULT_BUNDLE_PATH" \
    --repo-root "$SANDBOX/user1-release" \
    --path "$RESULT_BUNDLE_REPO_PATH" \
    --purpose rho.bundle >/dev/null
  grep -q "kind: rho_recipient_envelope" "$RESULT_BUNDLE_PATH"
  grep -q "context:" "$RESULT_BUNDLE_PATH"
  grep -q "repo_id: rho://repo/local/git-branch-pr" "$RESULT_BUNDLE_PATH"
  grep -q "path: $RESULT_BUNDLE_REPO_PATH" "$RESULT_BUNDLE_PATH"
  grep -q "purpose: rho.bundle" "$RESULT_BUNDLE_PATH"
  grep -q "$USER1_ID" "$RESULT_BUNDLE_PATH"
  grep -q "$USER2_ID" "$RESULT_BUNDLE_PATH"
  if grep -q "1113.03" "$RESULT_BUNDLE_PATH"; then
    echo "encrypted result bundle leaked plaintext" >&2
    exit 1
  fi
  mkdir -p "$SANDBOX/user1-result-self-open"
  RHO_HOME="$SANDBOX/user1-rho-home" ./rho crypto open \
    "$RESULT_BUNDLE_PATH" \
    --identity "$USER1_ID" \
    --out "$SANDBOX/user1-result-self-open/result-bundle.tar" \
    --repo-root "$SANDBOX/user1-release" \
    --path "$RESULT_BUNDLE_REPO_PATH" \
    --purpose rho.bundle >/dev/null
  cmp "$SANDBOX/user1-release-bundle.tar" "$SANDBOX/user1-result-self-open/result-bundle.tar"
  git -C "$SANDBOX/user1-release" add rho/messages
  git -C "$SANDBOX/user1-release" commit -m "Release protected analysis result" >/dev/null
  git -C "$SANDBOX/user1-release" push -u origin "$RELEASE_BRANCH" >/dev/null

  git -C "$SANDBOX/user2" fetch origin "$RELEASE_BRANCH:$RELEASE_BRANCH" >/dev/null
  git -C "$SANDBOX/user2" worktree add "$SANDBOX/user2-release-review" "$RELEASE_BRANCH" >/dev/null
  setup_clone_identity "$SANDBOX/user2-release-review" "Rho User Two" "user2@example.test"
  mkdir -p "$SANDBOX/user2-result-open"
  RHO_HOME="$SANDBOX/user2-rho-home" ./rho crypto open \
    "$SANDBOX/user2-release-review/$RESULT_BUNDLE_REPO_PATH" \
    --identity "$USER2_ID" \
    --out "$SANDBOX/user2-result-open/result-bundle.tar" \
    --repo-root "$SANDBOX/user2-release-review" \
    --path "$RESULT_BUNDLE_REPO_PATH" \
    --purpose rho.bundle >/dev/null
  ./rho crypto extract-tar \
    "$SANDBOX/user2-result-open/result-bundle.tar" \
    --out-dir "$SANDBOX/user2-result-open" >/dev/null
  RHO_HOME="$SANDBOX/user2-rho-home" ./rho crypto verify \
    "$SANDBOX/user2-result-open/rho/results/$REQUEST_ID.yaml" \
    --signature "$SANDBOX/user2-result-open/rho/results/$REQUEST_ID.rhosig.yaml" \
    --identity "$USER1_ID" >/dev/null
  test "$(cat "$SANDBOX/user2-result-open/results/$REQUEST_ID/output.txt")" = "1113.03"
  grep -q "rho://repo/results/$REQUEST_ID/output.txt" "$SANDBOX/user2-result-open/rho/results/$REQUEST_ID.yaml"
  grep -q "BEGIN SSH SIGNATURE" "$SANDBOX/user2-result-open/rho/results/$REQUEST_ID.rhosig.yaml"
  test ! -e "$SANDBOX/user2-release-review/rho/results/$REQUEST_ID.yaml"

  echo "inspect sandbox: $SANDBOX"
  find "$SANDBOX" \
    -path "*/.git" -prune -o \
    -path "*/remote.git" -prune -o \
    -maxdepth 7 -type f -print | sort
  echo "git branch pr fixture e2e passed"
}

if [[ "${1:-}" == "--plan" ]]; then
  plan
  exit 0
fi

run_fixture
