#!/bin/sh
# Validate index bytes, not unstaged working files. CI uses the same validators.
# --no-verify still bypasses local hooks. Semantic review remains mandatory.
set -eu
ROOT=$(git rev-parse --show-toplevel)
TMPD=$(mktemp -d "${TMPDIR:-/tmp}/kit-hook.XXXXXX")
TMPD=$(CDPATH= cd -- "$TMPD" && pwd -P)
trap 'rm -rf "$TMPD"' EXIT HUP INT TERM
mkdir "$TMPD/index"
# Read raw index blobs: checkout-index can run smudge/ident/EOL conversions.
# Git quotes filenames containing tabs/newlines; reject those representations.
git -C "$ROOT" -c core.quotePath=false ls-files --stage > "$TMPD/entries"
TAB=$(printf '\t')
while IFS="$TAB" read -r meta path; do
  mode=${meta%% *}; rest=${meta#* }; oid=${rest%% *}; stage=${rest##* }
  [ "$stage" = 0 ] || { echo 'FAIL: unresolved index entries'; exit 1; }
  case "$path" in \"*|*\\*) echo 'FAIL: quoted/escaped index paths unsupported'; exit 1 ;; esac
  case "$mode" in
    100644|100755)
      mkdir -p "$TMPD/index/$(dirname "$path")"
      git -C "$ROOT" cat-file blob "$oid" > "$TMPD/index/$path"
      ;;
    120000|160000) : ;; # Links/submodule contents are not regular staged evidence.
    *) echo "FAIL: unsupported index mode $mode"; exit 1 ;;
  esac
done < "$TMPD/entries"
SNAP="$TMPD/index"
for name in check-claim-discipline.sh check-ledger.sh; do
  [ -f "$SNAP/scripts/$name" ] && [ ! -L "$SNAP/scripts/$name" ] || {
    echo "FAIL: staged checker missing or symlink: scripts/$name" >&2; exit 1;
  }
done
CHECKER="$SNAP/scripts/check-claim-discipline.sh"
printf 'label\treadme_pattern\tcapability_key\texpected_substr\tproof_path\tenforce\tnotes\ncanary\tCANARY_OVERCLAIM_XYZ\t\t\tmissing-proof\tyes\tcanary\n' > "$TMPD/canary.tsv"
printf 'CANARY_OVERCLAIM_XYZ\n' > "$TMPD/canary.md"
if KIT_ROOT="$SNAP" sh "$CHECKER" "$TMPD/canary.tsv" "$TMPD/canary.md" >/dev/null 2>&1; then
  echo 'FAIL: claim checker admitted the missing-proof canary' >&2; exit 1
fi
(cd "$SNAP" && KIT_ROOT="$SNAP" sh scripts/check-claim-discipline.sh registries/claims.tsv README.md)
(cd "$SNAP" && sh scripts/check-ledger.sh docs/evidence/NEGATIVE_EVIDENCE.md)
# Drafting a planning packet is allowed; structure is advisory here, blocking in CI.
if [ -f "$SNAP/docs/planning/packet.md" ] && [ -f "$SNAP/scripts/check-readiness.sh" ]; then
  (cd "$SNAP" && sh scripts/check-readiness.sh docs/planning/packet.md) || {
    echo 'pre-commit: packet structurally incomplete (advisory); no execution authorization implied' >&2;
  }
fi
