#!/bin/bash
# WitWiki hooks: read the wiki before asking or searching, write to it after work.
#
#   witwiki-hooks.sh remind       UserPromptSubmit  one line of context on every prompt
#   witwiki-hooks.sh check-first  PreToolUse        AskUserQuestion | WebSearch | WebFetch
#   witwiki-hooks.sh record       Stop              nudge to record what changed
#
# Every mode fails open: a missing jq, an unreadable transcript or an unexpected
# payload exits 0 with no output, so a broken hook never blocks a session.

set -u

MODE="${1:-}"
STATE_DIR="${WITWIKI_HOOK_STATE_DIR:-${TMPDIR:-/tmp}/witwiki-hooks}"

if [ "$MODE" = "remind" ]; then
  cat <<'MSG'
WitWiki is this project's knowledge base. Before asking the user for information, and whenever you search for an answer, search it as well: mcp__witwiki__wiki_getBrief({task}) or mcp__witwiki__wiki_listPages({q}). After work that changes what is true about the project, record it: wiki_patchPage for an existing page, wiki_updatePage only for a new one, then wiki_appendLog.
MSG
  exit 0
fi

command -v jq >/dev/null 2>&1 || exit 0

INPUT="$(cat)"
SESSION="$(jq -r '.session_id // empty' <<<"$INPUT" 2>/dev/null)"
TRANSCRIPT="$(jq -r '.transcript_path // empty' <<<"$INPUT" 2>/dev/null)"
ROOT="${CLAUDE_PROJECT_DIR:-$(jq -r '.cwd // empty' <<<"$INPUT" 2>/dev/null)}"

[ -n "$SESSION" ] && [ -r "$TRANSCRIPT" ] && [ -n "$ROOT" ] || exit 0
mkdir -p "$STATE_DIR" 2>/dev/null || exit 0

# One letter per transcript event, in order:
#   P  a prompt from the user (a new turn)
#   R  a wiki read    W  a wiki write    E  an edit to a file inside the project
EVENTS="$(jq -r --arg root "$ROOT" '
  if .isSidechain == true then empty
  elif .type == "user" and .isMeta != true then
    (.message.content) as $c
    | if ($c | type) == "string" then "P"
      elif ($c | type) == "array" and ($c | any(.type == "tool_result") | not) then "P"
      else empty end
  elif .type == "assistant" then
    .message.content[]? | select(.type == "tool_use")
    | if (.name | test("witwiki.*__wiki_(getBrief|listPages|getPage|getIndex|getLog)$"; "i")) then "R"
      elif (.name | test("witwiki.*__wiki_(patchPage|updatePage|appendLog|updateIndex)$"; "i")) then "W"
      elif (.name | test("^(Edit|Write|NotebookEdit)$"))
           and ((.input.file_path // .input.notebook_path // "") | startswith($root + "/")) then "E"
      else empty end
  else empty end
' "$TRANSCRIPT" 2>/dev/null)" || exit 0

# turn: prompts so far.  consulted: a wiki call since the last prompt.
# pending: project edits since the last wiki write.  total: project edits this session.
read -r TURN CONSULTED PENDING TOTAL <<<"$(awk '
  /^P/ { turn++; consulted = 0 }
  /^R/ { consulted = 1 }
  /^W/ { consulted = 1; pending = 0 }
  /^E/ { pending++; total++ }
  END  { print turn + 0, consulted + 0, pending + 0, total + 0 }
' <<<"$EVENTS")"

case "$MODE" in
  check-first)
    [ "$CONSULTED" = "1" ] && exit 0
    TOOL="$(jq -r '.tool_name // empty' <<<"$INPUT")"
    if [ "$TOOL" = "AskUserQuestion" ]; then KIND=ask; else KIND=web; fi
    MARK="$STATE_DIR/$SESSION.$KIND"

    # Once per turn. A retry goes through, so a question the wiki cannot answer
    # (a confirmation, a preference) or a disconnected wiki server never deadlocks.
    [ "$(cat "$MARK" 2>/dev/null)" = "$TURN" ] && exit 0
    echo "$TURN" >"$MARK"

    if [ "$KIND" = "ask" ]; then
      jq -n '{hookSpecificOutput: {
        hookEventName: "PreToolUse",
        permissionDecision: "deny",
        permissionDecisionReason: "WitWiki has not been checked this turn. Search it before asking the user: mcp__witwiki__wiki_getBrief({task}) or mcp__witwiki__wiki_listPages({q}). If the wiki cannot answer this (a confirmation, a preference, or the wiki tools are unavailable), ask again and the question will go through."
      }}'
    else
      jq -n '{hookSpecificOutput: {
        hookEventName: "PreToolUse",
        additionalContext: "WitWiki has not been searched this turn. Treat it as one of your sources for this answer: mcp__witwiki__wiki_listPages({q}) or mcp__witwiki__wiki_getBrief({task})."
      }}'
    fi
    ;;

  record)
    [ "$(jq -r '.stop_hook_active // false' <<<"$INPUT")" = "true" ] && exit 0
    [ "$PENDING" -gt 0 ] || exit 0
    MARK="$STATE_DIR/$SESSION.rec"

    # Once per batch of edits: if nothing has been edited since the last nudge,
    # Claude already decided there was nothing to record.
    [ "$(cat "$MARK" 2>/dev/null)" = "$TOTAL" ] && exit 0
    echo "$TOTAL" >"$MARK"

    jq -n --arg n "$PENDING" '{
      decision: "block",
      reason: ("This session edited " + $n + " project file(s) since the last WitWiki write. If that changed something a future session should know (a decision, a behaviour, a status), record it now: mcp__witwiki__wiki_listPages({q}) to find the page, then wiki_patchPage (wiki_updatePage only for a new page) and wiki_appendLog. If nothing here is worth keeping, say so in one line and stop.")
    }'
    ;;
esac

exit 0
