#!/bin/bash
set -euo pipefail

# Usage: tools/implement/status.sh [batch_id]
# Without argument: shows status for the active/latest batch

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
REGISTRY="$ROOT_DIR/.smbatcher/REGISTRY.md"

BATCH="${1:-}"

# Auto-detect batch if not provided
if [ -z "$BATCH" ]; then
  # Exit codes: 0=found, 1=no work, 2=error
  FIND_RESULT="$("$ROOT_DIR/tools/shared/find-next.sh" --registry "$REGISTRY" --mode active --format json)" || FIND_EXIT=$?
  FIND_EXIT=${FIND_EXIT:-0}

  if [ "$FIND_EXIT" -eq 2 ]; then
    echo "ERROR:auto_detect_failed:$FIND_RESULT"
    exit 2
  fi

  BATCH="$(echo "$FIND_RESULT" | "$ROOT_DIR/tools/run-python.sh" -c "import sys,json; d=json.load(sys.stdin); print(d.get('batch',''))")"

  if [ -z "$BATCH" ]; then
    echo "OK:no_active_batch:showing all entries"
    grep "|" "$REGISTRY" | head -20
    exit 0
  fi
fi

echo "=== Batch $BATCH Status ==="
grep "|" "$REGISTRY" | head -1  # header
grep "|" "$REGISTRY" | grep -E "[-]+\|" | head -1  # separator
grep "|" "$REGISTRY" | grep " $BATCH " || echo "No entries for batch $BATCH"
