#!/usr/bin/env bash
# Mirror Mind hook wrapper — GENERATED by scripts/generate_hook_wrappers.sh.
# Edit the generator, never this file: every wrapper shares these bytes and
# differs only in the hook name and in how it finds the Mirror entry
# (CV22.DS10.TS5 decision D4; CV22.DS10.US3 decision D5).
set -uo pipefail
HOOK="claude:session-end"

# Resolve the tree from THIS FILE, never from the cwd: a runtime spawns hooks
# from whatever directory the session is in. The tree is a checkout or the
# installed package; the wrapper's depth to its root is the same in both.
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
REPO_ROOT="$(cd "$HERE/../.." && pwd -P)"

# A hook never fails the user's turn, and never fails in silence: when it
# cannot do its job it appends ONE line to <mirror home>/hooks.log and exits 0.
# The home is found the way the core finds it -- MIRROR_HOME, else
# MIRROR_USER -- from the environment when set there, else from the tree's
# .env when the wrapper is in a tree, else from the user's config file
# (~/.config/mirror/env), in the core's order (US3, D3). A GUI launch carries
# neither variable, and the first wrappers then wrote to a home nobody reads.
env_file_value() {
  [ -f "$2" ] || return 0
  sed -n -E "s/^[[:space:]]*(export[[:space:]]+)?$1[[:space:]]*=[[:space:]]*//p" "$2" \
    | tail -n 1 | tr -d "\"'\r"
}
env_value() {
  local value=""
  if [ -n "${!1+set}" ]; then printf '%s' "${!1}"; return; fi
  [ -z "$REPO_ROOT" ] || value="$(env_file_value "$1" "$REPO_ROOT/.env")"
  [ -n "$value" ] || value="$(env_file_value "$1" "${XDG_CONFIG_HOME:-$HOME/.config}/mirror/env")"
  printf '%s' "$value"
}
# `note <line> daily` writes at most once a day (UTC): for a setting to fix
# rather than a hook that failed, so the line stays inside diagnose's seven-day
# window while the setting stays wrong, without one per hook per turn (CR192).
# The log is read into a variable, not piped to `grep -q`: under pipefail, a
# reader that stops early can fail the pipeline and the line be written twice.
note() {
  local home user seen today
  home="$(env_value MIRROR_HOME)"
  user="$(env_value MIRROR_USER)"
  if [ -n "$home" ]; then
    home="${home/#\~/$HOME}"
  elif [ -n "$user" ]; then
    home="$HOME/.mirror-minds/$user"
    [ -d "$home" ] || [ ! -d "$HOME/.mirror/$user" ] || home="$HOME/.mirror/$user"
  else
    return 0
  fi
  if [ "${2:-}" = daily ]; then
    today="$(date -u +%Y-%m-%d)"
    seen="$(grep -F -- ": $1" "$home/hooks.log" 2>/dev/null)"
    case "$seen" in "$today"T*|*$'\n'"$today"T*) return 0 ;; esac
  fi
  mkdir -p "$home" 2>/dev/null \
    && printf '%s %s: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$HOOK" "$1" >> "$home/hooks.log" 2>/dev/null
}

ENTRY="$REPO_ROOT/bin/mirror-hook.js"

# Find Node. /usr/bin/python3 exists on every macOS; node usually lives under
# nvm or Homebrew and is NOT on the PATH of a GUI-launched runtime. The Python
# hooks could end in `|| true` because they always found their interpreter;
# the same silence here would hide a new failure — no logging, no inject, no
# close tail — that a user would meet weeks later as "Mirror stopped
# remembering". So an unresolvable Node is RECORDED, never swallowed. The
# directory the entry was found in is searched first: an npm global bin holds
# the `node` that installed the package beside `mirror-hook`, while a system
# `/usr/local/bin/node` can be years older (CI's Ubuntu runner has one).
#
# MIRROR_NODE is used only as an absolute path to an executable file, as every
# reader uses it (CR192): a relative one would resolve against the project the
# runtime spawned this hook from. Anything else is noted with its reason, in
# the Pi extension's words, once a day, and the search goes on without it.
# "Absolute" is the MCP locator's pattern too, and it classifies exactly as
# path.win32.isAbsolute: under Git Bash the Windows installer writes a
# drive-letter path, C:\Users\...\AppData\Local\Programs\MirrorMind\node\node.exe
# (PR #47).
NODE=""
if [ -n "${MIRROR_NODE:-}" ]; then
  refused=""
  case "$MIRROR_NODE" in
    /*|\\*|[A-Za-z]:[\\/]*)
      if [ -d "$MIRROR_NODE" ]; then refused="a directory"
      elif [ ! -e "$MIRROR_NODE" ]; then refused="missing"
      elif [ ! -f "$MIRROR_NODE" ] || [ ! -x "$MIRROR_NODE" ]; then refused="not executable"
      else NODE="$MIRROR_NODE"
      fi
      ;;
    *) refused="relative" ;;
  esac
  if [ -n "$refused" ]; then
    note "MIRROR_NODE=${MIRROR_NODE//[$'\r\n']/} is $refused; searching the PATH and the usual places instead" daily
  fi
fi
[ -n "$NODE" ] || NODE="$(command -v node 2>/dev/null || true)"
for candidate in "$(dirname "$ENTRY")/node" "$HOME/.nvm/current/bin/node" /opt/homebrew/bin/node /usr/local/bin/node; do
  [ -n "$NODE" ] && break
  [ -x "$candidate" ] && NODE="$candidate"
done

if [ -z "$NODE" ]; then
  note "node not found on PATH; hook skipped. Set MIRROR_NODE."
  exit 0
fi

# Not `exec`: the entry exits 0 whatever happens inside it, so a non-zero exit
# means Node itself could not run the hook -- too old for the loader shim, or
# it crashed. That used to vanish into a stderr no runtime shows (TS5 handoff
# review, finding N1). No flags: the entry reads configuration and silences
# its own warnings (US3, D3).
"$NODE" "$ENTRY" "$HOOK" "$@"
status=$?
if [ "$status" -ne 0 ]; then
  note "node exited $status before the hook finished ($NODE, $("$NODE" --version 2>/dev/null || echo 'version unknown')); Mirror needs Node 24 or later. Set MIRROR_NODE."
fi
exit 0
