#!/bin/bash
# session-start.sh — Fetches recent conversation history on startup
# Output goes to Claude Code as SessionStart hook context
# This gives the conductor continuity across restarts

PORT="${ONE_CHANNEL_PORT:-7100}"
SECRET="${ONE_CHANNEL_SECRET}"
BASE="http://127.0.0.1:${PORT}"
MAX_CONVERSATIONS=5
MAX_MESSAGES_PER_CONVERSATION=20

# Fetch recent conversations from the channel server
# Retry a few times — the channel server (MCP) may still be starting up
conversations=""
for i in 1 2 3 4 5; do
  conversations=$(curl -s -f \
    -H "Authorization: Bearer ${SECRET}" \
    "${BASE}/conversations" 2>/dev/null)
  if [ $? -eq 0 ] && [ -n "$conversations" ]; then
    break
  fi
  sleep 1
done

if [ -z "$conversations" ]; then
  echo "No conversation history available (channel server may not be ready)."
  exit 0
fi

# Extract recent conversations with their messages
result=$(echo "$conversations" | jq -r --argjson max_c "$MAX_CONVERSATIONS" --argjson max_m "$MAX_MESSAGES_PER_CONVERSATION" '
  .conversations
  | sort_by(-.updated_at)
  | .[:$max_c]
  | map(
    "## Conversation: \(.id)\n" +
    "Updated: \(.updated_at / 1000 | strftime("%Y-%m-%d %H:%M:%S UTC"))\n" +
    (.messages | .[-$max_m:] | map(
      if .role == "user" then
        "**User" + (if .user_email then " (\(.user_email))" else "" end) + "**: \(.text)"
      else
        "**Assistant**: \(.text)"
      end
    ) | join("\n")) +
    "\n"
  )
  | join("\n---\n\n")
')

if [ -z "$result" ] || [ "$result" = "null" ]; then
  echo "No recent conversations found."
  exit 0
fi

cat <<EOF
# Recent Conversation History

You are resuming after a restart. Below are your most recent conversations.
Use this context to pick up where you left off if a user continues a previous thread.

${result}

EOF
