#!/usr/bin/env bash
# Usage: AGENT_BROWSER=/path/to/agent-browser bash rebuild.sh /path/to/repo /path/to/output
# Requires git, vp, Node, Python 3, ImageMagick, Chrome, agent-browser.
# Output must be a new, empty directory. No existing application state is read.
set -euo pipefail
repo=$(realpath "$1")
output=$(realpath -m "$2")
script_dir=$(cd -- "$(dirname -- "$0")" && pwd)
head_sha=9bba919f67acc77515c2409c2d1ce5997688d08a
base_sha=$(git -C "$repo" merge-base origin/main "$head_sha")
mkdir "$output"
git -C "$repo" worktree add "$output/head" "$head_sha"
git -C "$repo" worktree add "$output/base" "$base_sha"
# Install sequentially. Each server creates its own database at its own migration level.
(cd "$output/head" && vp i > "$output/head-install.log" 2>&1)
(cd "$output/base" && vp i > "$output/base-install.log" 2>&1)
pids=()
cleanup() { for pid in "${pids[@]}"; do kill -TERM "$pid" 2>/dev/null || true; done; }
trap cleanup EXIT
for side in before after; do
  checkout=base
  if [ "$side" = after ]; then checkout=head; fi
  (
    cd "$output/$checkout"
    exec env T3CODE_DEV_SEED=0 vp run dev
  ) > "$output/$side-server.log" 2>&1 &
  pids+=("$!")
  # Readiness is the server's pairing URL, never a fixed startup delay.
  config=$(node --input-type=module - "$output/$side-server.log" <<'JS'
import {readFile} from 'node:fs/promises';
const file=process.argv[2];
const limit=Date.now()+180000;
while(Date.now()<limit){
  const log=await readFile(file,'utf8').catch(()=> '');
  const url=log.match(/pairingUrl: (http[^\s]+)/)?.[1];
  if(url){console.log(url);process.exit(0)}
  await new Promise(r=>setTimeout(r,200));
}
throw Error('Server did not become ready; inspect its private log');
JS
  )
  origin=${config%%/pair*}
  node "$script_dir/driver.mjs" --origin "$origin" --pairing-url "$config" \
    --out "$output" --side "$side" --session "attachment-evidence-$side-$$" \
    > "$output/$side-private-run.json" 2> "$output/$side-private-driver.log"
done
printf '%s\n' 'Open every PNG before sharing. Only share PNGs, observations.json, driver.mjs and this script.'
printf '%s\n' 'Server logs and private-run JSON contain pairing credentials or local paths: keep them private.'
# Worktrees and evidence stay available for inspection; remove them after uploading.
