#!/usr/bin/env bash
# SessionStart hook: 把 friday 入口技能全文注入会话上下文。
#
# 平台输出格式（参照 obra/superpowers 的判别逻辑）：
# - Cursor（CURSOR_PLUGIN_ROOT）          → {"additional_context": "..."}
# - Claude Code（CLAUDE_PLUGIN_ROOT）     → {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": "..."}}
# - 其他（Copilot CLI 等 SDK 标准）       → {"additionalContext": "..."}
#
# 用 printf 而非 heredoc，规避 bash 5.3+ 的 heredoc 挂起问题
# （见 https://github.com/obra/superpowers/issues/571）。

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_ROOT="${CURSOR_PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-$(dirname "$SCRIPT_DIR")}}"
SKILL_FILE="$PLUGIN_ROOT/skills/friday/SKILL.md"

if [ ! -f "$SKILL_FILE" ]; then
  # 找不到入口技能时静默退出，不阻塞会话启动
  printf '{}\n'
  exit 0
fi

skill_content="$(cat "$SKILL_FILE")"

session_context="<friday-skill>
You have Friday AI skills. The following is the full content of the 'friday' skill — your entry point for driving Friday AI. For all other friday-* skills, read them on demand per the routing table.

主动触发提醒（两类场景都不要等用户点名）：
1. 本地分支项目上下文：用户问「开发到哪一步了 / 继续开发 / 现在有什么问题 / PRD·feature list·技术方案」，或任何仓库编码任务开工——先用当前 git 分支名调 lookup_project_by_branch 召回项目上下文（详见 friday-dev 技能）。
2. 跨仓库追接口（前后端打通）：前端拿到接口要看后端实现、后端改接口要看前端哪里调用、或代码检索命中接口调用/路由定义/请求 URL 且指向另一侧仓库。
先过下面的「决策门」，命中即按路由表行动。

${skill_content}
</friday-skill>"

# JSON 字符串转义（反斜杠必须最先处理）
escaped="${session_context//\\/\\\\}"
escaped="${escaped//\"/\\\"}"
escaped="${escaped//$'\t'/\\t}"
escaped="${escaped//$'\r'/\\r}"
escaped="${escaped//$'\n'/\\n}"

if [ -n "${CURSOR_PLUGIN_ROOT:-}" ]; then
  printf '{\n  "additional_context": "%s"\n}\n' "$escaped"
elif [ -n "${CLAUDE_PLUGIN_ROOT:-}" ] && [ -z "${COPILOT_CLI:-}" ]; then
  printf '{\n  "hookSpecificOutput": {\n    "hookEventName": "SessionStart",\n    "additionalContext": "%s"\n  }\n}\n' "$escaped"
else
  printf '{\n  "additionalContext": "%s"\n}\n' "$escaped"
fi
