#!/usr/bin/env bash
# State Class Registry pre-commit reminder.
#
# Reads contracts/state-classes.json from the inner .agent/ repository and
# reminds when syncable (tracked / derived) state is unstaged or untracked.
#
# This hook is relevant only when .agent/ is its own Git repository. Do not
# configure core.hooksPath from a plain .agent/ directory in a managed project:
# that would change the outer repository's hooks.
#
# It does NOT block the commit.
# To disable: git -C .agent commit --no-verify
# To uninstall: git -C .agent config --unset core.hooksPath

set -e

REGISTRY="contracts/state-classes.json"

if [ ! -f "$REGISTRY" ]; then
  echo "⚠️  state-sync reminder skipped: $REGISTRY is missing; run cortex-agent update."
  exit 0
fi

STATE_DIRS=()
STATE_FILES=()

while IFS=$'\t' read -r kind state_path; do
  [ -z "$kind" ] && continue
  if [ "$kind" = "directory" ]; then
    STATE_DIRS+=("$state_path")
  elif [ "$kind" = "file" ]; then
    STATE_FILES+=("$state_path")
  fi
done < <(
  node - "$REGISTRY" <<'NODE'
const fs = require("fs");
const file = process.argv[2];
try {
  const registry = JSON.parse(fs.readFileSync(file, "utf8"));
  for (const entry of registry.classes || []) {
    if (!["tracked", "derived"].includes(entry.sync_policy)) continue;
    process.stdout.write(entry.kind + "\t" + entry.path + "\n");
  }
} catch (error) {
  process.stderr.write("state-sync registry error: " + error.message + "\n");
  process.exit(2);
}
NODE
)

is_state_path() {
  local f="$1"
  for d in "${STATE_DIRS[@]}"; do
    if [ "$f" = "$d" ] || [[ "$f" == "$d/"* ]]; then
      return 0
    fi
  done
  for sf in "${STATE_FILES[@]}"; do
    if [ "$f" = "$sf" ]; then
      return 0
    fi
  done
  return 1
}

unstaged_state=()
while IFS= read -r line; do
  [ -z "$line" ] && continue
  rest="${line:3}"
  if [[ "$rest" == *" -> "* ]]; then
    file="${rest##* -> }"
  else
    file="$rest"
  fi
  xy="${line:0:2}"
  xy_staged_char="${xy:0:1}"
  if [ "$xy_staged_char" != " " ] && [ "$xy_staged_char" != "?" ]; then
    continue
  fi
  if is_state_path "$file"; then
    unstaged_state+=("$file")
  fi
done < <(git status --porcelain --untracked-files=all 2>/dev/null || true)

if [ "${#unstaged_state[@]}" -gt 0 ]; then
  echo ""
  echo "⚠️  state-sync reminder: ${#unstaged_state[@]} registry-managed state file(s) are unstaged / untracked:"
  for f in "${unstaged_state[@]}"; do
    echo "    $f"
  done
  echo ""
  echo "  Run `cortex-agent state-sync --add` to stage them,"
  echo "  or `--commit` / `--push` to finish in one shot."
  echo "  (This is a reminder, not a blocker — proceeding with commit.)"
  echo ""
fi

exit 0
