#!/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"

# This wrapper is the Claude plugin's, and a plugin is copied into Claude
# Code's own cache: no relative path from here reaches the Mirror tree. It
# runs the installed `mirror-hook` bin instead, and reads no tree .env.
REPO_ROOT=""

# 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
}

# Find the bin. MIRROR_BIN names the directory holding `mirror` and
# `mirror-hook` (`$(npm prefix -g)/bin`); then the PATH; then the global bin
# directories a GUI launch leaves off it.
#
# MIRROR_BIN is used only as an absolute path to a directory holding an
# executable `mirror-hook`, by MIRROR_NODE's rule and pattern (CR197): a
# relative one would resolve against the project the runtime spawned this hook
# from, and Node would run that project's file. Anything else is noted with its
# reason, in MIRROR_NODE's words, once a day, and the search goes on without it.
ENTRY=""
if [ -n "${MIRROR_BIN:-}" ]; then
  refused=""
  case "$MIRROR_BIN" in
    /*|\\*|[A-Za-z]:[\\/]*)
      if [ ! -e "$MIRROR_BIN" ]; then refused="missing"
      elif [ ! -d "$MIRROR_BIN" ]; then refused="not a directory"
      elif [ ! -f "$MIRROR_BIN/mirror-hook" ] || [ ! -x "$MIRROR_BIN/mirror-hook" ]; then refused="a directory without an executable mirror-hook"
      else ENTRY="$MIRROR_BIN/mirror-hook"
      fi
      ;;
    *) refused="relative" ;;
  esac
  if [ -n "$refused" ]; then
    note "MIRROR_BIN=${MIRROR_BIN//[$'\r\n']/} is $refused; searching the PATH and the usual places instead" daily
  fi
fi
[ -n "$ENTRY" ] || ENTRY="$(command -v mirror-hook 2>/dev/null || true)"
for candidate in "$HOME/.nvm/current/bin" /opt/homebrew/bin /usr/local/bin; do
  [ -n "$ENTRY" ] && break
  [ -x "$candidate/mirror-hook" ] && ENTRY="$candidate/mirror-hook"
done
# On Windows npm writes no symlink: the `mirror-hook` in its global prefix is
# a POSIX shell shim, and `node_modules/` sits beside it. Node cannot run the
# shim ("node exited 1" in hooks.log on every hook); the entry it wraps is the
# package's own bin, so that is the entry when it is there. A POSIX prefix
# keeps node_modules under lib/ and its bin is already the .js: no change.
shim_entry=""
[ -n "$ENTRY" ] && shim_entry="$(dirname "$ENTRY")/node_modules/mirror-mind/bin/mirror-hook.js"
[ -n "$shim_entry" ] && [ -f "$shim_entry" ] && ENTRY="$shim_entry"

if [ -z "$ENTRY" ]; then
  note "mirror-hook not found on PATH; hook skipped. Install mirror-mind (npm install -g mirror-mind) or set MIRROR_BIN to its bin directory."
  exit 0
fi

# 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
