#!/bin/sh
# check-index — asserts SKILLS_INDEX.md lists exactly the skills that exist.
#
# The index is hand-maintained and drifts silently in both directions: a skill
# ships with no row (`dream` and `experiment-spec` did — their rows lived on
# branches squash-merged after a directory reorg, so the SKILL.md landed and
# the row did not, #15), or a row outlives the skill it names. Neither errors
# anywhere; the library just misreports itself to every harness that reads it.
#
# Usage: check-index [checkout-root]   (defaults to this script's repo root)

set -u

ROOT=${1:-$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)}
INDEX="$ROOT/SKILLS_INDEX.md"
fail=0

if [ ! -f "$INDEX" ]; then
  echo "ERROR: missing SKILLS_INDEX.md" >&2
  exit 1
fi

# A row is a table line whose first cell is the skill name in backticks.
listed=$(sed -n 's/^|[[:space:]]*`\([^`]*\)`.*/\1/p' "$INDEX" | sort -u)

for dir in "$ROOT"/skills/*/; do
  name=$(basename "$dir")
  [ -f "$dir/SKILL.md" ] || continue
  printf '%s\n' "$listed" | grep -qx "$name" || {
    echo "ERROR: skills/$name has no row in SKILLS_INDEX.md" >&2
    fail=1
  }
done

for name in $listed; do
  [ -f "$ROOT/skills/$name/SKILL.md" ] || {
    echo "ERROR: SKILLS_INDEX.md lists '$name', which has no skills/$name/SKILL.md" >&2
    fail=1
  }
done

exit $fail
