#!/bin/sh
# Pre-commit guardrails:
#   1. Reject SQLite WAL/SHM files (data corruption risk).
#   2. Block commits when core CLEO files are gitignored (data integrity).
#
# Installation: Automatically installed via `cleo init`

set -e

# ── 1. WAL/SHM/journal files ──────────────────────────────────────────
BAD_FILES=$(git diff --cached --name-only | grep -E '\.(db-wal|db-shm|db-journal)$' || true)

if [ -n "$BAD_FILES" ]; then
  echo "ERROR: Refusing to commit SQLite WAL/SHM/journal files:"
  echo "$BAD_FILES"
  echo ""
  echo "These are runtime files that must never be tracked in git."
  echo "To fix: git rm --cached <file>"
  exit 1
fi

# ── 2. Core file gitignore protection ─────────────────────────────────
# Per ADR-013 §9 (T5158 — 2026-04-07): tasks.db, brain.db, config.json,
# and project-info.json are NOT tracked in git (regenerated by cleo init,
# backed up via VACUUM INTO snapshots). DO NOT include those four files
# in PROTECTED_FILES — that would re-open the T5158 data-loss vector.
PROTECTED_FILES=".cleo/.gitignore .cleo/project-context.json"
IGNORED_CORE=""

for f in $PROTECTED_FILES; do
  if [ -f "$f" ] && git check-ignore -q "$f" 2>/dev/null; then
    IGNORED_CORE="$IGNORED_CORE $f"
  fi
done

if [ -n "$IGNORED_CORE" ]; then
  echo "ERROR: Critical CLEO files are being ignored by .gitignore:"
  echo "$IGNORED_CORE"
  echo ""
  echo "These files MUST be tracked by git for CLEO data integrity."
  echo "Check .gitignore and .cleo/.gitignore for rules ignoring these files."
  echo "To fix: remove the ignore rule, then: git add <file>"
  exit 1
fi

# ── 3. Block staging of T5158/ADR-013 §9 data-safety files ────────────
# tasks.db / brain.db / config.json / project-info.json must NEVER be
# staged — risks data loss on branch switch (SQLite WAL/JSON sync).
DATA_SAFETY_STAGED=$(git diff --cached --name-only | grep -E '^\.cleo/(tasks\.db|brain\.db|config\.json|project-info\.json)$' || true)

if [ -n "$DATA_SAFETY_STAGED" ]; then
  echo "ERROR: Refusing to commit T5158/ADR-013 §9 data-safety files:"
  echo "$DATA_SAFETY_STAGED"
  echo ""
  echo "These files are runtime state that must never be tracked in git."
  echo "Commiting them re-opens the T5158 data-loss vector (SQLite WAL/"
  echo "JSON sync gets corrupted on branch switch)."
  echo "To fix: git rm --cached <file>"
  exit 1
fi
