#!/usr/bin/env bash
# SessionStart hook for the intent-gate plugin.
# Injects a compact router; full Skills and the playbook load only on demand.

set -euo pipefail

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

router_content=$(cat "${PLUGIN_ROOT}/hooks/session-context.md" 2>&1 || echo "Error reading intent-gate session context")

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

router_escaped=$(escape_for_json "$router_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. The compact router is available, 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="<INTENT_GATE_ROUTING>\nYou have a human escalation gate (intent-gate MCP).\n\n${mcp_warning}**Select Skills only for matching tasks; full Skill and playbook text stays on demand:**\n\n${router_escaped}\n</INTENT_GATE_ROUTING>"

# 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
