#!/bin/bash
# SubagentStop — log completion + return additionalContext for orchestrator.
# Orchestrator decides whether to send iMessage (no direct API calls here).
set -u

INPUT=$(cat)
AGENT_ID=$(echo "$INPUT" | jq -r '.agent_id // "unknown"')
AGENT_TYPE=$(echo "$INPUT" | jq -r '.agent_type // "unknown"')
LAST_MSG=$(echo "$INPUT" | jq -r '.last_assistant_message // ""' | head -c 2000)
TS=$(date -u +%Y-%m-%dT%H:%M:%SZ)

# Log to agent results — match server.ts HARNESS_DIR resolution so hosts
# don't trample one another's state.
HARNESS_DIR="${SENDBLUE_HARNESS_DIR:-${SENDBLUE_STATE_DIR:-$HOME/.claude/channels/sendblue}/harness}"
RESULTS_FILE="$HARNESS_DIR/agent-results.jsonl"
mkdir -p "$(dirname "$RESULTS_FILE")"
jq -n --arg id "$AGENT_ID" --arg type "$AGENT_TYPE" --arg msg "$LAST_MSG" --arg ts "$TS" \
  '{ts:$ts, agent_id:$id, agent_type:$type, summary:$msg}' >> "$RESULTS_FILE"

# Parse structured completion report if present
STATUS=$(echo "$LAST_MSG" | grep -oP '(?<=\*\*Status:\*\* )\S+' || echo "unknown")
BRANCH=$(echo "$LAST_MSG" | grep -oP '(?<=\*\*Branch:\*\* )\S+' || echo "none")
MSG_REC=$(echo "$LAST_MSG" | grep -oP '(?<=\*\*Message recommendation:\*\* )\S+' || echo "SKIP")
MSG_DRAFT=$(echo "$LAST_MSG" | grep -oP '(?<=\*\*Message draft:\*\* ).*' || echo "")

# Return additionalContext so orchestrator sees the result inline
SUMMARY=$(echo "$LAST_MSG" | head -c 500)
jq -n \
  --arg agent_id "$AGENT_ID" \
  --arg agent_type "$AGENT_TYPE" \
  --arg status "$STATUS" \
  --arg branch "$BRANCH" \
  --arg msg_rec "$MSG_REC" \
  --arg msg_draft "$MSG_DRAFT" \
  --arg summary "$SUMMARY" \
  '{additionalContext: ("Agent \(.agent_type) (\(.agent_id)) completed.\nStatus: \(.status) | Branch: \(.branch)\nMessage: \(.msg_rec) \(.msg_draft)\nSummary: \(.summary)")}'
