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

tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT

repo="$tmpdir/repo"
jsonl="$tmpdir/journal.jsonl"
journal_sh="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/../lib/journal.sh"

git -C "$tmpdir" init repo >/dev/null 2>&1
git -C "$repo" config user.email "test@example.com"
git -C "$repo" config user.name "Test User"
echo "content" > "$repo/README.md"
git -C "$repo" add README.md
git -C "$repo" commit -m "initial" >/dev/null
git -C "$repo" branch -M main
REACHABLE_HEAD=$(git -C "$repo" rev-parse HEAD)

BOGUS_HEAD="deadbeef0000000000000000000000000000dead"
TS1="2026-01-01T00:00:00Z"
TS2="2026-01-02T00:00:00Z"

cat > "$jsonl" <<EOF
{"v":"runstate/v1","slug":"test","task":"T1","wave":1,"state":"leased","base":"$REACHABLE_HEAD","head":"$REACHABLE_HEAD","rc":0,"ts":"$TS1"}
{"v":"runstate/v1","slug":"test","task":"T1","wave":1,"state":"committed","base":"$REACHABLE_HEAD","head":"$BOGUS_HEAD","rc":0,"ts":"$TS2"}
EOF

bash "$journal_sh" reconcile "$jsonl" "$repo" main

last_line=""
while IFS= read -r line || [[ -n "$line" ]]; do
  [[ -z "$line" ]] && continue
  task=$(echo "$line" | jq -r '.task // empty')
  if [[ "$task" == "T1" ]]; then
    last_line="$line"
  fi
done < "$jsonl"

if [[ -z "$last_line" ]]; then
  echo "FAIL: no record found for task T1"
  exit 1
fi

state=$(echo "$last_line" | jq -r '.state')
head=$(echo "$last_line" | jq -r '.head')

if [[ "$state" == "leased" && "$head" == "$REACHABLE_HEAD" ]]; then
  echo "PASS"
  exit 0
else
  echo "FAIL: expected state=leased head=$REACHABLE_HEAD, got state=$state head=$head"
  exit 1
fi
