#!/usr/bin/env bash
# IR-14 four-answer worktree census, 2026-08-30 edition. Read-only.
cd /c/Users/decid/Documents/projects/spt-core || exit 1
echo "=== COUNTS (each with its command, per IR-14) ==="
echo "entries under .worktrees      : $(ls -A .worktrees | wc -l)   [ls -A .worktrees | wc -l]"
echo "directories under .worktrees  : $(ls -dA .worktrees/*/ 2>/dev/null | wc -l)   [ls -dA .worktrees/*/]"
echo "git worktree list (incl root) : $(git worktree list | wc -l)   [git worktree list]"
echo "registered under .worktrees   : $(git worktree list --porcelain | grep -c '^worktree .*worktrees')   [--porcelain grep]"
echo
echo "=== REGISTERED WORKTREES: path | sha | ref | landed | dirty | untracked | target ==="
git worktree list --porcelain | awk '/^worktree /{print $2}' | grep worktrees | while read -r wt; do
  sha=$(git -C "$wt" rev-parse --short HEAD 2>/dev/null)
  ref=$(git -C "$wt" rev-parse --abbrev-ref HEAD 2>/dev/null)
  if git merge-base --is-ancestor "$sha" origin/main 2>/dev/null; then landed=LANDED
  elif [ -z "$(git cherry origin/main "$sha" 2>/dev/null | grep '^+')" ]; then landed=LANDED-BY-CHERRY
  else landed=UNLANDED; fi
  dirty=$(git -C "$wt" status -s 2>/dev/null | grep -cv '^??')
  untr=$(git -C "$wt" status -s 2>/dev/null | grep -c '^??')
  tgt="none"
  if [ -e "$wt/target" ]; then
    # fsutil reparsepoint query exits 0 for junctions
    if fsutil reparsepoint query "$(cygpath -w "$wt/target")" >/dev/null 2>&1; then tgt="JUNCTION"
    else tgt="realdir:$(du -s "$wt/target" 2>/dev/null | cut -f1)KB"; fi
  fi
  echo "$(basename "$wt") | $sha | $ref | $landed | dirty=$dirty | untracked=$untr | target=$tgt"
done
echo
echo "=== UNREGISTERED DIRECTORIES (in .worktrees, not in git worktree list) ==="
reg=$(git worktree list --porcelain | awk '/^worktree /{print $2}' | grep worktrees | xargs -I{} basename {} | sort)
all=$(ls -dA .worktrees/*/ 2>/dev/null | xargs -I{} basename {} | sort)
comm -23 <(echo "$all") <(echo "$reg") | while read -r d; do
  files=$(find ".worktrees/$d" -type f 2>/dev/null | wc -l)
  bytes=$(du -s ".worktrees/$d" 2>/dev/null | cut -f1)
  owner="no-claim"; [ -f ".worktrees/$d/POOL-OWNER.json" ] && owner="POOL-OWNER.json"
  deepest=$(find ".worktrees/$d" -type d 2>/dev/null | tail -1)
  echo "$d | files=$files | ${bytes}KB | $owner | deepest=$deepest"
done
echo
echo "=== INBOUND JUNCTIONS under .worktrees (reparse points at any <wt>/target) ==="
for wt in .worktrees/*/; do
  t="${wt}target"
  if [ -e "$t" ] && fsutil reparsepoint query "$(cygpath -w "$t")" >/dev/null 2>&1; then
    echo "JUNCTION: $t"
  fi
done
echo
echo "=== LOOSE FILES in .worktrees root ==="
find .worktrees -maxdepth 1 -type f | sed 's|.worktrees/||'
echo
echo "=== census complete $(date -u +%FT%TZ) ==="
