#!/usr/bin/env bash
# mosaic-context-loader.sh — SessionStart hook for Claude Code
# Injects mandatory Mosaic config files into agent context at session init.
# Stdout from this script is added to Claude's context before processing.
set -euo pipefail

MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"

# Mandatory load order (per AGENTS.md contract)
MANDATORY_FILES=(
  "$MOSAIC_HOME/SOUL.md"
  "$MOSAIC_HOME/USER.md"
  "$MOSAIC_HOME/STANDARDS.md"
  "$MOSAIC_HOME/AGENTS.md"
  "$MOSAIC_HOME/TOOLS.md"
)

# E2E delivery guide (canonical uppercase path)
E2E_DELIVERY=""
for candidate in \
  "$MOSAIC_HOME/guides/E2E-DELIVERY.md"; do
  if [[ -f "$candidate" ]]; then
    E2E_DELIVERY="$candidate"
    break
  fi
done

# Runtime-specific reference
RUNTIME_FILE="$MOSAIC_HOME/runtime/claude/RUNTIME.md"

# Project-local AGENTS.md (cwd at session start)
PROJECT_AGENTS=""
if [[ -f "./AGENTS.md" ]]; then
  PROJECT_AGENTS="./AGENTS.md"
fi

emit_file() {
  local filepath="$1"
  local label="${2:-$(basename "$filepath")}"
  if [[ -f "$filepath" ]]; then
    echo "=== MOSAIC: $label ==="
    cat "$filepath"
    echo ""
  fi
}

echo "=== MOSAIC CONTEXT INJECTION (SessionStart) ==="
echo ""

for f in "${MANDATORY_FILES[@]}"; do
  emit_file "$f"
done

if [[ -n "$E2E_DELIVERY" ]]; then
  emit_file "$E2E_DELIVERY" "E2E-DELIVERY.md"
fi

if [[ -n "$PROJECT_AGENTS" ]]; then
  emit_file "$PROJECT_AGENTS" "Project AGENTS.md ($(pwd))"
fi

emit_file "$RUNTIME_FILE" "Claude RUNTIME.md"

echo "=== END MOSAIC CONTEXT INJECTION ==="
