#!/usr/bin/env bash
#
# capture-resume.sh  -  one line at session start when a run was left unfinished.
#
# Runs from the SessionStart hook. Its whole job is to say what is pending and
# then get out of the way, so it is bound by three rules:
#
#   1. It never blocks. Exit 0 always, whatever it finds.
#   2. It never calls a model, and it never reads a transcript.
#   3. It prints at most a few lines. A session banner that scrolls is a banner
#      the user learns to skip, which costs more than it saves.
#
# It answers two questions:
#   - Is there a pipeline run that stopped before Phase 7? Name it and the resume
#     command, because that run's work is recoverable and its findings are not
#     yet in the durable stores until it flushes.
#   - Is the pipeline's own observation queue stale? (>= REVIEW_DAYS since the
#     last review, with at least one open observation.) Offer one line. The
#     user's own work is never made to wait on it.
#
# Usage: ./capture-resume.sh [--json]

set -uo pipefail

JSON=0
[ "${1:-}" = "--json" ] && JSON=1

LOGS="$HOME/.claude/logs/multi-agent"
PIPELINE_MEM="$HOME/.claude/memory/multi-agent/_pipeline"
REVIEW_DAYS=7

STALE_TASK=""
STALE_PHASE=""

if [ -d "$LOGS" ] && command -v jq >/dev/null 2>&1; then
  # Newest by mtime, not by name: task ids do not sort chronologically.
  NEWEST=$(find "$LOGS" -name agent-state.json -type f -maxdepth 4 -print0 2>/dev/null \
    | xargs -0 ls -t 2>/dev/null | head -1)
  if [ -n "$NEWEST" ] && [ -f "$NEWEST" ]; then
    P7=$(jq -r '[.phases[]? | select((.id // "") == "7") | .status] | first // ""' "$NEWEST" 2>/dev/null)
    STATUS=$(jq -r '.status // ""' "$NEWEST" 2>/dev/null)
    if [ "$P7" != "completed" ] && [ "$STATUS" != "completed" ]; then
      STALE_TASK=$(jq -r '.taskId // .jiraId // ""' "$NEWEST" 2>/dev/null)
      STALE_PHASE=$(jq -r '.currentPhase // "?"' "$NEWEST" 2>/dev/null)
    fi
  fi
fi

REVIEW_DUE=0
OPEN_OBS=0
if [ -d "$PIPELINE_MEM/observations" ]; then
  OPEN_OBS=$(grep -l '^status: open' "$PIPELINE_MEM/observations"/*.md 2>/dev/null | wc -l | tr -d ' ')
  LAST_REVIEW_FILE="$PIPELINE_MEM/last-review-date.txt"
  LAST=$(cat "$LAST_REVIEW_FILE" 2>/dev/null || echo "never")
  if [ "${OPEN_OBS:-0}" -gt 0 ]; then
    if [ "$LAST" = "never" ] || [ -z "$LAST" ]; then
      REVIEW_DUE=1
    else
      # Date arithmetic without GNU date: compare epoch seconds, and treat an
      # unparseable stamp as "due" rather than silently never reviewing again.
      LAST_EPOCH=$(date -j -f "%Y-%m-%d" "$LAST" +%s 2>/dev/null \
                || date -d "$LAST" +%s 2>/dev/null || echo "")
      if [ -z "$LAST_EPOCH" ]; then
        REVIEW_DUE=1
      else
        AGE_DAYS=$(( ( $(date +%s) - LAST_EPOCH ) / 86400 ))
        [ "$AGE_DAYS" -ge "$REVIEW_DAYS" ] && REVIEW_DUE=1
      fi
    fi
  fi
fi

if [ "$JSON" -eq 1 ]; then
  printf '{"staleTask":"%s","stalePhase":"%s","openObservations":%s,"reviewDue":%s}\n' \
    "$STALE_TASK" "$STALE_PHASE" "${OPEN_OBS:-0}" "$REVIEW_DUE"
  exit 0
fi

if [ -n "$STALE_TASK" ]; then
  printf 'multi-agent: %s stopped at Phase %s - `/multi-agent:resume` to continue, `/multi-agent:kill` to drop it.\n' \
    "$STALE_TASK" "$STALE_PHASE"
fi
if [ "$REVIEW_DUE" -eq 1 ]; then
  printf 'multi-agent: %s open pipeline observation(s), last review %s+ days ago - `/multi-agent:refactor backlog` when convenient.\n' \
    "$OPEN_OBS" "$REVIEW_DAYS"
fi
exit 0
