#!/usr/bin/env bash
# on-file-changed: FileChanged hook handler for MindrianOS
# Detects external modifications to room files and re-runs the post-write
# cascade (classify, KuzuDB index, HSI compute, state recompute).
# Must complete in under 3 seconds.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PLUGIN_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

# The changed file path comes from the hook event
FILE_PATH="${1:-${TOOL_INPUT_PATH:-}}"

if [ -z "$FILE_PATH" ]; then
  # 95-04: silent on diagnostic paths. FileChanged allows
  # {continue, stopReason, suppressOutput, systemMessage}; `status` is
  # not in the set. No message needed for diagnostic exits.
  # silent: no file path
  exit 0
fi

# Resolve active room
WORK_DIR="${PWD}"
ACTIVE_ROOM=$("${SCRIPT_DIR}/resolve-room" "$WORK_DIR" 2>/dev/null) || ACTIVE_ROOM=""

if [ -z "$ACTIVE_ROOM" ]; then
  # silent: no active room
  exit 0
fi

# Only process files within the active room
case "$FILE_PATH" in
  "${ACTIVE_ROOM}"/*) ;; # File is in active room -- proceed
  *) exit 0 ;; # silent: outside room
esac

# Skip STATE.md and ROOM.md (infrastructure files, not artifacts)
basename_file=$(basename "$FILE_PATH")
if [[ "$basename_file" == "STATE.md" ]] || [[ "$basename_file" == "ROOM.md" ]] || [[ "$basename_file" == "TEAM-STATE.md" ]] || [[ "$basename_file" == "MEETINGS-INTELLIGENCE.md" ]]; then
  # silent: skipped infra
  exit 0
fi

# Skip hidden files and directories
case "$FILE_PATH" in
  */.*) exit 0 ;; # silent: skipped hidden
esac

# Phase 144.1-06 RETRO-03 (audit item 65): fire SENS-06 through the navigation
# chokepoint and emit a memory_event the engine can observe BEFORE delegating to
# post-write. on-file-changed "inherits the post-write fix": the cascade below
# routes through file-evidence-readback inside post-write (cross-relationship-scan
# + artifact_filed), and this fire is the sensor-side firing the engine reads.
# The reach is context_block / SENS-06 / cross-relationship-scan / push_forward.
# LOCAL only (Canon Part 8): the fire carries a sha256 of the relative file path
# plus generic handles, never the file body. Backgrounded + soft-fail so the hook
# return is never serialized on the chokepoint write; never blocks the cascade.
REL_FILE_PATH="${FILE_PATH#${ACTIVE_ROOM}/}"
( node "${SCRIPT_DIR}/fire-sensor-event.cjs" "$ACTIVE_ROOM" \
    "context_block" "SENS-06" "cross-relationship-scan" "push_forward" \
    "$REL_FILE_PATH" >/dev/null 2>&1 || true ) &

# Delegate to post-write for the full cascade. post-write routes the cascade
# through file-evidence-readback (fileEvidenceWithReadback) and emits the
# artifact_filed memory_event -- the post-write fix on-file-changed inherits.
# post-write also handles: classify, graph index, HSI compute, presentation regen.
exec bash "${SCRIPT_DIR}/post-write" "$FILE_PATH"
