#!/bin/bash
# Hook: SessionStart — inject core Claude behavioral rules
# Triggered when a new session starts
#
# Reads core prompt files and injects them as additionalContext.
# Uses the extension directory to resolve prompt paths reliably.

set -e

# Resolve prompts dir relative to this hook's location
HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROMPTS_DIR="$HOOK_DIR/prompts/core"

# If not found next to hook, check extension directory
if [ ! -d "$PROMPTS_DIR" ]; then
    EXTENSION_DIR="$(cd "$HOOK_DIR/.." && pwd)"
    PROMPTS_DIR="$EXTENSION_DIR/prompts/core"
fi

if [ ! -d "$PROMPTS_DIR" ]; then
    echo '{"type": "no-op"}'
    exit 0
fi

# Read all core prompts into a single context
CONTEXT=""
for file in "$PROMPTS_DIR"/*.md; do
    if [ -f "$file" ]; then
        CONTEXT="${CONTEXT}$(basename "$file"):
$(cat "$file")

"
    fi
done

if [ -z "$CONTEXT" ]; then
    echo '{"type": "no-op"}'
    exit 0
fi

# Truncate if too large (context limits) — stay under safe character boundary
MAX_LENGTH=8000
if [ ${#CONTEXT} -gt $MAX_LENGTH ]; then
    CONTEXT="${CONTEXT:0:$MAX_LENGTH}"
fi

# Output as additionalContext (use jq to properly escape JSON)
printf '{"type": "additionalContext", "context": %s}\n' "$(printf '%s' "$CONTEXT" | jq -Rs .)"
