#!/usr/bin/env bash
# SessionStart hook for qiushi-skill plugin
# 在每次会话开始时注入"武装思想"入口 skill

set -euo pipefail

# 确定插件根目录
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PLUGIN_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
SKILL_PATH="${PLUGIN_ROOT}/skills/arming-thought/SKILL.md"

# 读取武装思想 skill 内容
if [ ! -f "${SKILL_PATH}" ]; then
  echo "Error: missing skill file at ${SKILL_PATH}" >&2
  exit 1
fi

arming_thought_content=$(cat "${SKILL_PATH}")

# JSON 转义函数
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"
}

arming_thought_escaped=$(escape_for_json "$arming_thought_content")
session_context="<QIUSHI_SKILL>\n已加载 qiushi:arming-thought。请先遵守用户指令、项目约束和宿主平台规则，再在明确适用时把这份方法论作为补充的路由与校验框架。\n\n${arming_thought_escaped}\n\n</QIUSHI_SKILL>"

# 平台适配输出
# Cursor hooks 使用 additional_context
# Claude Code hooks 使用 hookSpecificOutput.additionalContext
# 使用 printf 而非 heredoc 以避免 bash 5.3+ 的大内容变量展开挂起问题
if [ -n "${CURSOR_PLUGIN_ROOT:-}" ]; then
  printf '{\n  "additional_context": "%s"\n}\n' "$session_context"
elif [ -n "${CLAUDE_PLUGIN_ROOT:-}" ]; then
  printf '{\n  "hookSpecificOutput": {\n    "hookEventName": "SessionStart",\n    "additionalContext": "%s"\n  }\n}\n' "$session_context"
else
  printf '{\n  "additional_context": "%s"\n}\n' "$session_context"
fi

exit 0
