#!/bin/bash
# Check for stale worktrees across all products
# Usage: check-stale.sh [max-age-hours]

MAX_AGE_HOURS=${1:-24}
MAX_AGE_SECS=$((MAX_AGE_HOURS * 3600))
NOW=$(date +%s)

PRODUCTS_DIR="/home/aria/products"
STALE_FOUND=0

for STATE_FILE in "$PRODUCTS_DIR"/*/.worktree-state.json; do
  [ -f "$STATE_FILE" ] || continue
  
  SLUG=$(basename "$(dirname "$STATE_FILE")")
  
  # Find stale entries
  STALE=$(jq -r --argjson now "$NOW" --argjson max "$MAX_AGE_SECS" \
    '.active | to_entries[] | select(($now - (.value.started | fromdateiso8601)) > $max) | "\(.key)|\(.value.requester)|\(.value.requester_id)|\(.value.description)"' \
    "$STATE_FILE" 2>/dev/null)
  
  if [ -n "$STALE" ]; then
    echo "STALE_WORKTREES:$SLUG"
    echo "$STALE" | while IFS='|' read -r task_id requester requester_id desc; do
      echo "  $task_id: $desc (by $requester)"
    done
    STALE_FOUND=1
  fi
done

if [ "$STALE_FOUND" -eq 0 ]; then
  echo "No stale worktrees found"
fi
