#!/usr/bin/env bash
# Worktree reap, IR-150 discipline. Removes only trees classified reapable on evidence:
# detached rigs, branches merged into main, branches patch-id-equivalent to main.
# No --force anywhere: a refusal means unverified content and the tree stays standing.
set -uo pipefail
cd /c/Users/decid/Documents/projects/spt-core || exit 1
S="C:/Users/decid/AppData/Local/Temp/claude/C--Users-decid-Documents-projects-spt-core/df88576d-82a7-4c8e-9bcf-d04f5d4754e5/scratchpad"

echo "=== WRITER CENSUS (pre) ==="
for img in cargo.exe rustc.exe Runner.Worker.exe spt.exe; do
  echo "-- $img"; tasklist //FI "IMAGENAME eq $img" //FO CSV //NH 2>/dev/null | head -5
done

echo "=== CLASSIFY (fresh, at $(git rev-parse --short HEAD)) ==="
git branch --merged main --format='%(refname)' | sort > "$S/merged2.txt"
git worktree list --porcelain > "$S/wt2.txt"
awk '/^worktree /{w=$2; b="-"} /^branch /{b=$2} /^detached/{b="DETACHED"} /^$/{if(w!="")print w"\t"b; w=""}' "$S/wt2.txt" > "$S/pairs2.txt"

: > "$S/reap-list.txt"
while IFS=$'\t' read -r w b; do
  case "$w" in */spt-core) continue;; esac
  case "$w" in *".worktrees"*) ;; *) continue;; esac
  if [ "$b" = "DETACHED" ]; then
    echo "$w" >> "$S/reap-list.txt"
  elif grep -qxF "$b" "$S/merged2.txt"; then
    echo "$w" >> "$S/reap-list.txt"
  else
    out=$(git cherry main "$b" 2>/dev/null); rc=$?
    [ $rc -ne 0 ] && continue
    if [ "$(printf '%s\n' "$out" | grep -c '^+')" -eq 0 ]; then echo "$w" >> "$S/reap-list.txt"; fi
  fi
done < "$S/pairs2.txt"
echo "reapable: $(wc -l < "$S/reap-list.txt")"

echo "=== SIZES BEFORE (over the reap set only) ==="
mapfile -t SET < "$S/reap-list.txt"
APP=$(du -sb --apparent-size "${SET[@]}" 2>/dev/null | awk '{s+=$1} END{print s+0}')
ALLOC=$(du -sB1 "${SET[@]}" 2>/dev/null | awk '{s+=$1} END{print s+0}')
ESC=$(find "${SET[@]}" -type f -links +1 -printf '%i %n %s\n' 2>/dev/null | sort | uniq -c | awk '$1 < $3 { n++; b += $4 } END { print (n+0)" "(b+0) }')
echo "apparent:  $APP"
echo "allocated: $ALLOC"
echo "escaped:   $ESC   (inodes bytes)"
echo "NOTE: population behind that escaped figure:"
find "${SET[@]}" -type f -links +1 -printf '%i %n\n' 2>/dev/null | sort -u | wc -l | sed 's/^/  distinct multi-link inodes: /'
find "${SET[@]}" -type f -links +1 2>/dev/null | wc -l | sed 's/^/  files at nlink>1:          /'

FREE_BEFORE=$(df -B1 /c | awk 'NR==2{print $4}')
echo "free before: $FREE_BEFORE"
echo "t0=$(date -u +%FT%TZ)"

echo "=== REMOVE ==="
ok=0; refused=0
for w in "${SET[@]}"; do
  if git worktree remove "$w" 2>>"$S/reap-err.txt"; then
    ok=$((ok+1))
  else
    refused=$((refused+1)); echo "REFUSED $w" | tee -a "$S/reap-refused.txt"
  fi
done
git worktree prune
echo "removed=$ok refused=$refused"

FREE_AFTER=$(df -B1 /c | awk 'NR==2{print $4}')
echo "t1=$(date -u +%FT%TZ)"
echo "free after:  $FREE_AFTER"
echo "delta:       $((FREE_AFTER - FREE_BEFORE))"
echo "expected ~:  $ALLOC  (allocated minus escaped bytes)"

echo "=== WRITER CENSUS (post) ==="
for img in cargo.exe rustc.exe Runner.Worker.exe; do
  echo "-- $img"; tasklist //FI "IMAGENAME eq $img" //FO CSV //NH 2>/dev/null | head -5
done
echo "worktrees remaining: $(git worktree list | wc -l)"
