#!/usr/bin/env bash
# SessionStart hook for the intent-gate plugin.
# Injects the using-intent-gate discipline into every session so the agent
# knows WHEN to escalate to humans and WHERE the alignment playbook lives.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PLUGIN_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

using_intent_gate_content=$(cat "${PLUGIN_ROOT}/skills/using-intent-gate/SKILL.md" 2>&1 || echo "Error reading using-intent-gate skill")

# Escape string for JSON embedding using bash parameter substitution.
escape_for_json() {
    local s="$1"
    s="${s//\\/\\\\}"
    s="${s//\"/\\\"}"
    s="${s//$'\n'/\\n}"
    s="${s//$'\r'/\\r}"
    s="${s//$'\t'/\\t}"
    printf '%s' "$s"
}

using_intent_gate_escaped=$(escape_for_json "$using_intent_gate_content")

# Preflight: the MCP server is the enforcement half of this plugin. If the
# `intent-gate` command is not on PATH, skills still load but every mechanical
# gate (dispatch_question / resolve_question / lint_summary …) is dead —
# say so loudly in the injected context and tell the human how to fix it.
mcp_warning=""
if ! command -v intent-gate >/dev/null 2>&1; then
  mcp_warning="⚠️ INTENT-GATE MCP SERVER NOT RUNNING: command 'intent-gate' not found on PATH. Discipline skills are injected, but ALL mechanical gates are unavailable (no question persistence, no lint enforcement). Tell the human to run: pipx install intent-gate-mcp — then restart the session.\\n\\n"
fi

session_context="<EXTREMELY_IMPORTANT>\nYou have a human escalation gate (intent-gate MCP).\n\n${mcp_warning}**Below is the full content of your 'intent-gate:using-intent-gate' skill - your introduction to when and how to escalate decisions to humans. Read it before acting on anything it covers:**\n\n${using_intent_gate_escaped}\n</EXTREMELY_IMPORTANT>"

# Output context injection as JSON.
# Cursor hooks expect additional_context (snake_case).
# Claude Code hooks expect hookSpecificOutput.additionalContext (nested).
# Copilot CLI (v1.0.11+) and others expect additionalContext (top-level, SDK standard).
if [ -n "${CURSOR_PLUGIN_ROOT:-}" ]; then
  printf '{\n  "additional_context": "%s"\n}\n' "$session_context" | cat
elif [ -n "${CLAUDE_PLUGIN_ROOT:-}" ] && [ -z "${COPILOT_CLI:-}" ]; then
  printf '{\n  "hookSpecificOutput": {\n    "hookEventName": "SessionStart",\n    "additionalContext": "%s"\n  }\n}\n' "$session_context" | cat
else
  printf '{\n  "additionalContext": "%s"\n}\n' "$session_context" | cat
fi

exit 0
