#!/bin/bash
# PostToolUse hook: validates aiwiki/** markdown writes against their declared
# schemas. Reads the file path from hook input, invokes the lint script if the
# write targets a typed wiki page, surfaces findings to stderr.
#
# Cannot block the write (it already happened); informs the AI/user via stderr
# so the next edit corrects the issue. Returns continue:true unconditionally.
#
# Skipped for: non-markdown files, files outside aiwiki/, schema files
# themselves (they describe other pages), and fresh projects before aiwiki/
# is scaffolded by /setup.

set -uo pipefail

INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name // ""')

# Only Edit, Write, and MultiEdit can modify files. MultiEdit shares Edit's
# top-level file_path shape (one file, multiple edits) — the edit deltas live
# in tool_input.edits[*] but we only need the path here (the linter re-reads
# the file from disk, so it sees the final post-write content regardless of
# whether the change was one Edit or many).
case "$TOOL_NAME" in
  Edit|Write|MultiEdit) ;;
  *)
    echo '{"continue":true}'
    exit 0
    ;;
esac

FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // ""')

# Only check aiwiki/ writes
case "$FILE_PATH" in
  *aiwiki/*) ;;
  *) echo '{"continue":true}'; exit 0 ;;
esac

# Skip non-markdown files
case "$FILE_PATH" in
  *.md) ;;
  *) echo '{"continue":true}'; exit 0 ;;
esac

# Skip schema files themselves (they describe other pages; aren't validated against schemas)
case "$FILE_PATH" in
  *aiwiki/schemas/*) echo '{"continue":true}'; exit 0 ;;
esac

# Skip aiwiki/proposed/ writes during dream output; dream's lint runs separately at completion
case "$FILE_PATH" in
  *aiwiki/proposed/*) echo '{"continue":true}'; exit 0 ;;
esac

# Skip the wiki's own meta files (CLAUDE.md, INDEX.md, projectbrief.md)
case "$(basename "$FILE_PATH")" in
  CLAUDE.md|INDEX.md|projectbrief.md) echo '{"continue":true}'; exit 0 ;;
esac

# Locate inputs
PROJECT_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
SCHEMAS_DIR="$PROJECT_ROOT/aiwiki/schemas"
SCRIPT_PATH="$PROJECT_ROOT/.claude/skills/support-wiki-lint/scripts/lint.mjs"

# Skip if scaffolded path missing (fresh project before /setup, or installation gap)
if [ ! -d "$SCHEMAS_DIR" ] || [ ! -f "$SCRIPT_PATH" ]; then
  echo '{"continue":true}'
  exit 0
fi

# Resolve the file path relative to repo root for the script
case "$FILE_PATH" in
  /*) REL_PATH="${FILE_PATH#$PROJECT_ROOT/}" ;;
  *) REL_PATH="$FILE_PATH" ;;
esac

# Run lint (don't let non-zero exit kill us — we surface findings, not block)
LINT_OUTPUT=$(node "$SCRIPT_PATH" --file "$REL_PATH" --schemas "$SCHEMAS_DIR" --root "$PROJECT_ROOT" 2>&1)
LINT_EXIT=$?

if [ $LINT_EXIT -ne 0 ]; then
  echo "wiki-lint findings on $REL_PATH:" >&2
  echo "$LINT_OUTPUT" >&2
fi

echo '{"continue":true}'
exit 0
