#!/usr/bin/env bash
# SessionStart hook for ks plugin — injects the ks space catalog
# (<ks-cli-reminder>) into the session so the agent can route shared-knowledge
# requests to ks. The ks SKILL.md itself is loaded on demand by the native
# skill mechanism and is intentionally NOT force-injected here.
#
# Also spawns ks-updater (heartbeat + auto-update) in the background on every run.
#
# Mode detection: the runtime environment is decided by an explicit flag baked
# in at install time, NOT by probing CLAUDE_PLUGIN_ROOT. The npm installer writes
# absolute hook paths (it never sets CLAUDE_PLUGIN_ROOT), so an env-var probe is
# unreliable. Default = Claude Code; the Hermes installer passes `--hermes` for
# its on_session_start / on_session_reset hooks (Hermes injects context via the
# separate hermes-context / pre_llm_call hook, so this entry point just acks).

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

if [ -f "${SCRIPT_DIR}/lib-ks-spaces.sh" ]; then
  # shellcheck source=/dev/null
  . "${SCRIPT_DIR}/lib-ks-spaces.sh"
fi
if [ -f "${SCRIPT_DIR}/lib-ks-updater.sh" ]; then
  # shellcheck source=/dev/null
  . "${SCRIPT_DIR}/lib-ks-updater.sh"
fi

# Default to Claude Code mode; switch to Hermes only when explicitly flagged.
mode="cc"
for arg in "$@"; do
  case "$arg" in
    --hermes) mode="hermes" ;;
  esac
done

spawn_updater

if [ "$mode" = "hermes" ]; then
  # Hermes on_session_start / on_session_reset: the <ks-cli-reminder> block is
  # injected by the hermes-context (pre_llm_call) hook, not here. Consume the
  # stdin payload Hermes pipes in and acknowledge with empty JSON.
  cat >/dev/null 2>&1 || true
  printf '{}\n'
  exit 0
fi

# Claude Code mode.
ks_reminder=""
if command -v ks_spaces_reminder >/dev/null 2>&1; then
  ks_reminder=$(ks_spaces_reminder 2>/dev/null || true)
fi

# Always-present permission guardrail, independent of space availability.
# Prepended before the (optional) <ks-cli-reminder> catalog so the policy is
# the first thing the agent reads.
ks_guardrail=""
if command -v ks_permission_policy >/dev/null 2>&1; then
  ks_guardrail=$(ks_permission_policy 2>/dev/null || true)
fi

if [ -n "$ks_guardrail" ] && [ -n "$ks_reminder" ]; then
  payload="${ks_guardrail}"$'\n\n'"${ks_reminder}"
elif [ -n "$ks_guardrail" ]; then
  payload="$ks_guardrail"
else
  payload="$ks_reminder"
fi

# Nothing to inject (helper not sourced) → stay silent.
if [ -z "$payload" ]; then
  exit 0
fi

# Emit the SessionStart JSON. Prefer jq — it escapes everything correctly,
# including C0 control bytes a stray ANSI sequence in `ks` output could carry
# (same approach as hermes-context's `jq -Rs`). Fall back to a minimal escaper
# only when jq is absent; in that case ks_spaces_reminder produced nothing
# (it needs jq), so $payload is just the static guardrail — clean text.
if command -v jq >/dev/null 2>&1; then
  printf '%s' "$payload" | jq -Rs \
    '{hookSpecificOutput: {hookEventName: "SessionStart", additionalContext: .}}'
else
  s="$payload"
  s="${s//\\/\\\\}"
  s="${s//\"/\\\"}"
  s="${s//$'\n'/\\n}"
  s="${s//$'\r'/\\r}"
  s="${s//$'\t'/\\t}"
  printf '{\n  "hookSpecificOutput": {\n    "hookEventName": "SessionStart",\n    "additionalContext": "%s"\n  }\n}\n' "$s"
fi

exit 0
