#!/bin/bash
# Daily pipeline: replayer (postmortem) → autofix (fix eligible issues)
#
# Usage:
#   tools/daily.sh                  # Full pipeline: replayer + autofix
#   tools/daily.sh --replayer-only  # Only run replayer (postmortem + triage)
#   tools/daily.sh --autofix-only   # Only run autofix (fix eligible issues)
#
# Prerequisites:
#   - claude CLI authenticated (~/.claude)
#   - tools/replayer/.github_token exists
#   - Backend running (for replayer workspace API access)

set -euo pipefail

REPO_ROOT="$(git -C "$(dirname "$0")" rev-parse --show-toplevel)"
cd "$REPO_ROOT"

LOG_DIR="${REPO_ROOT}/.worktree"
DATE=$(date +%Y-%m-%d)
LOGFILE="${LOG_DIR}/daily-${DATE}.log"

mkdir -p "$LOG_DIR"

log()  { echo "[$(date +%H:%M:%S)] $*" | tee -a "$LOGFILE"; }
err()  { echo "[$(date +%H:%M:%S)] ERROR: $*" | tee -a "$LOGFILE" >&2; }

# --- Parse args ---
RUN_REPLAYER=true
RUN_AUTOFIX=true

case "${1:-}" in
  --replayer-only) RUN_AUTOFIX=false ;;
  --autofix-only)  RUN_REPLAYER=false ;;
  --help|-h)
    echo "Usage: $0 [--replayer-only | --autofix-only]"
    exit 0
    ;;
esac

# --- Preflight ---
if ! command -v claude &>/dev/null; then
  err "claude CLI not found in PATH"
  exit 1
fi

if [ ! -f "${REPO_ROOT}/tools/replayer/.github_token" ]; then
  err "GitHub token not found at tools/replayer/.github_token"
  exit 1
fi

log "=== Daily pipeline started (${DATE}) ==="
log "Log: ${LOGFILE}"

# --- Step 1: Sync ---
log "--- Step 1: git pull ---"
git pull --rebase origin main 2>&1 | tee -a "$LOGFILE" || {
  err "git pull failed, continuing with current state"
}

# --- Step 2: Replayer ---
if [ "$RUN_REPLAYER" = true ]; then
  log "--- Step 2: Replayer ---"

  claude -p "Run replayer skill per tools/replayer/SKILL.md. Execute Phase 0-8." \
    2>&1 | tee -a "$LOGFILE"

  log "Replayer session finished (exit=$?)"
else
  log "--- Step 2: Skipped (--autofix-only) ---"
fi

# --- Step 3: Autofix ---
if [ "$RUN_AUTOFIX" = true ]; then
  log "--- Step 3: Autofix ---"

  claude -p "Run autofix skill per tools/autofix/SKILL.md. Fix all eligible issues.
Use a single branch fix/daily-${DATE} for all fixes. Commit each issue separately
(fix(ISS-NNNN): title), but create only ONE PR at the end covering all fixes.
Skip issues that affect acp.py (high blast radius).
If no eligible issues, exit cleanly." \
    2>&1 | tee -a "$LOGFILE"

  log "Autofix session finished (exit=$?)"
else
  log "--- Step 3: Skipped (--replayer-only) ---"
fi

# --- Done ---
log ""
log "=== Daily pipeline finished (${DATE}) ==="
log "Full log: ${LOGFILE}"
