#!/usr/bin/env bash
# CHECK-commit-census — verify 2026-10-26-commit-census.tsv against git.
# Exits 0 only if every row (date -> count) in the TSV matches a fresh git
# re-derivation and no git day is missing from the table. Non-zero otherwise.
set -u

DIR=$(cd "$(dirname "$0")" && pwd)
tsv="$DIR/2026-10-26-commit-census.tsv"
repo="$DIR/.."
[ -f "$tsv" ] || { echo "FAIL: $tsv missing"; exit 1; }

fail=0

# Re-derive the expected per-day counts from git at a pinned revision
# (the census in this artifact was taken as of commit 957143e). awk 'NF' keeps
# output newline-terminated so sort/uniq cannot drop the final record.
PINNED=957143e
cd "$repo" || { echo "FAIL: cannot cd $repo"; exit 1; }
expected=$(git log "$PINNED" --pretty=format:%ad --date=short | awk 'NF' | sort | uniq -c | sort -k2)

# Per-row comparison: date (col 2 of expected) vs count (col 2 of TSV).
while IFS=$'\t' read -r d c; do
  [ -z "$d" ] && continue
  case "$d" in date) continue;; esac
  exp=$(echo "$expected" | awk -v d="$d" '$2==d {print $1}')
  if [ "$exp" != "$c" ]; then
    echo "FAIL: $d expected $exp, got $c"
    fail=1
  fi
done < "$tsv"

# Total comparison.
exp_total=$(echo "$expected" | awk '{s+=$1} END {print s}')
act_total=$(awk -F'\t' 'NR>1 && $2!="" {s+=$2} END {print s}' "$tsv")
if [ "$exp_total" != "$act_total" ]; then
  echo "FAIL: total expected $exp_total, got $act_total"
  fail=1
fi

# Every git day must appear in the table (no missing rows).
missing=$(comm -23 \
  <(echo "$expected" | awk '{print $2}' | sort) \
  <(awk -F'\t' 'NR>1 && $2!="" {print $1}' "$tsv" | sort) | tr '\n' ' ')
if [ -n "$missing" ]; then
  echo "FAIL: rows missing from table: $missing"
  fail=1
fi

if [ "$fail" -eq 0 ]; then
  nrows=$(awk -F'\t' 'NR>1 && $2!="" {n++} END {print n+0}' "$tsv")
  echo "PASS: $tsv verified against git ($act_total commits, $nrows rows)"
  exit 0
else
  echo "FAIL: one or more rows mismatch"
  exit 1
fi
