#!/usr/bin/env bash
# SessionStart hook for sumo-qa plugin.
#
# Injects the `using-sumo-qa` skill into every conversation so the host LLM
# reliably runs sumo-qa's senior-QA workflow (qa-deciding-approach →
# qa-preparing-for-work / qa-implementing-with-tdd / qa-reviewing-before-merge
# / etc.) rather than free-styling generic testing advice.

set -euo pipefail

# Determine plugin root directory
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PLUGIN_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

# Read using-sumo-qa content
using_sumo_qa_content=$(cat "${PLUGIN_ROOT}/skills/using-sumo-qa/SKILL.md" 2>&1 || echo "Error reading using-sumo-qa skill")

# Escape string for JSON embedding using bash parameter substitution.
# Each ${s//old/new} is a single C-level pass - orders of magnitude
# faster than the character-by-character loop this replaces.
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_sumo_qa_escaped=$(escape_for_json "$using_sumo_qa_content")

# Note: the Sumo-sensei persona is OFF by default. The user can ask for it
# mid-conversation ('turn on the sumo persona', 'enable sumo-sensei', etc.)
# and the agent will load docs/PERSONA.md and adopt the voice for the rest
# of the session. See docs/PERSONA.md + skills/using-sumo-qa/SKILL.md.

session_context="<EXTREMELY_IMPORTANT>\nYou have sumo-qa: a senior-QA skills library + MCP server.\n\n**Below is the full content of your 'sumo-qa:using-sumo-qa' skill - your entry router for every QA-shaped task. For all other sumo-qa skills, use the 'Skill' tool:**\n\n${using_sumo_qa_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).
# Claude Code reads BOTH additional_context and hookSpecificOutput without
# deduplication, so we must emit only the field the current platform consumes.
#
# Uses printf instead of heredoc to work around bash 5.3+ heredoc hang.
if [ -n "${CURSOR_PLUGIN_ROOT:-}" ]; then
  # Cursor sets CURSOR_PLUGIN_ROOT (may also set CLAUDE_PLUGIN_ROOT)
  printf '{\n  "additional_context": "%s"\n}\n' "$session_context"
elif [ -n "${CLAUDE_PLUGIN_ROOT:-}" ] && [ -z "${COPILOT_CLI:-}" ]; then
  # Claude Code sets CLAUDE_PLUGIN_ROOT without COPILOT_CLI
  printf '{\n  "hookSpecificOutput": {\n    "hookEventName": "SessionStart",\n    "additionalContext": "%s"\n  }\n}\n' "$session_context"
else
  # Copilot CLI (sets COPILOT_CLI=1) or unknown platform — SDK standard format
  printf '{\n  "additionalContext": "%s"\n}\n' "$session_context"
fi

exit 0
