#!/usr/bin/env bash
# Round-trip checks for scripts/review-note, in a throwaway temp repo.
set -euo pipefail

root=$(cd "$(dirname "$0")/.." && pwd -P)
rn="$root/scripts/review-note"
fail() { echo "FAIL: $*" >&2; exit 1; }
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

git init -q -b main "$tmp/repo"
cd "$tmp/repo"
git config user.email test@example.com
git config user.name test

echo one > a.txt && git add a.txt && git commit -qm one
echo two > b.txt && git add b.txt && git commit -qm two

note="$tmp/note1"
cat > "$note" <<'EOF'
branch: main
round: 1
verdict: request-changes
previous: none
findings:
  - id: F1
    severity: blocker
    file: a.txt:1
    title: fix me
    status: open
## Details

Fix it.
EOF

if "$rn" show >/dev/null 2>&1; then fail "show should exit 1 without a note"; fi

sed '/^verdict:/d' "$note" > "$tmp/no-verdict"
if "$rn" write "$tmp/no-verdict" >/dev/null 2>&1; then fail "write should refuse a missing verdict"; fi
sed 's/^verdict: request-changes/verdict: maybe/' "$note" > "$tmp/bad-verdict"
if "$rn" write "$tmp/bad-verdict" >/dev/null 2>&1; then fail "write should refuse a bad verdict"; fi

"$rn" write "$note"
"$rn" show | grep -q '^verdict: request-changes$' || fail "show should print the note"

if "$rn" write "$note" >/dev/null 2>&1; then fail "write should refuse an existing note"; fi

sed 's/^verdict: request-changes/verdict: approve/' "$note" > "$tmp/note1b"
"$rn" write "$tmp/note1b" --force
"$rn" show | grep -q '^verdict: approve$' || fail "show should print the replaced note"

# latest finds the note by branch, even from a newer unreviewed tip
echo three > c.txt && git add c.txt && git commit -qm three
"$rn" latest main | grep -q '^verdict: approve$' || fail "latest should find the round 1 note"

# a note for another branch must not leak into the result
sed -e 's/^branch: main/branch: other/' -e 's/^round: 1/round: 9/' "$tmp/note1b" > "$tmp/other"
"$rn" write "$tmp/other"
"$rn" latest main | grep -q '^verdict: approve$' || fail "latest should ignore other branches"

# round 2 on the new tip wins and carries previous (replaces the
# other-branch note on the same commit, so --force)
PREV=$(git rev-parse HEAD~1)
sed -e 's/^round: 1/round: 2/' -e "s/^previous: none/previous: $PREV/" "$tmp/note1b" > "$tmp/note2"
"$rn" write "$tmp/note2" --force
"$rn" latest main | grep -q '^round: 2$' || fail "latest should pick the highest round"
"$rn" latest main | grep -q "^previous: $PREV$" || fail "round 2 should carry previous"

if "$rn" latest nosuch >/dev/null 2>&1; then fail "latest should exit 1 for an unknown branch"; fi

echo "ok: show/write/latest"
