#!/usr/bin/env bash
set -euo pipefail

PROJECT_DIR="/home/long/project/蚊子"
LOG_DIR="$PROJECT_DIR/logs"
SUP_LOG="$LOG_DIR/optimization_supervisor.log"
LOCK_FILE="/tmp/mosquito_optimization_supervisor.lock"
PRD_SCRIPT="$PROJECT_DIR/scripts/prd_review_cycle.sh"
E2E_KICK_SCRIPT="$PROJECT_DIR/scripts/e2e_kick.sh"
E2E_CONSISTENCY_SCRIPT="$PROJECT_DIR/scripts/check_e2e_consistency.sh"
DATA_CONTRACT_SCRIPT="$PROJECT_DIR/scripts/validate_test_contracts.sh"
PRD_REVIEW_DIR="$LOG_DIR/prd-review"
E2E_DIR="$LOG_DIR/e2e-automation"

mkdir -p "$LOG_DIR"

exec 9>"$LOCK_FILE"
if ! flock -n 9; then
  echo "[$(date '+%F %T')] skip: supervisor already running" >> "$SUP_LOG"
  exit 0
fi

log() { echo "[$(date '+%F %T')] $*" >> "$SUP_LOG"; }

now=$(date +%s)

if [ ! -x "$DATA_CONTRACT_SCRIPT" ]; then
  log "data-contract checker missing: $DATA_CONTRACT_SCRIPT"
else
  if SPRING_PROFILES_ACTIVE="${SPRING_PROFILES_ACTIVE:-e2e}" "$DATA_CONTRACT_SCRIPT" "$PROJECT_DIR" preflight >> "$SUP_LOG" 2>&1; then
    log "data-contract preflight PASS"
  else
    log "data-contract preflight FAIL; skip e2e kick this round"
    SKIP_E2E_KICK=1
  fi
fi

latest_prd_apply="$(ls -1t "$PRD_REVIEW_DIR"/claude_apply_*.md 2>/dev/null | head -n1 || true)"
if [ -n "$latest_prd_apply" ]; then
  prd_mtime=$(stat -c %Y "$latest_prd_apply" 2>/dev/null || echo 0)
  prd_age=$((now - prd_mtime))
  log "prd latest apply=$(basename "$latest_prd_apply") age=${prd_age}s"
  if [ "$prd_age" -gt 15000 ]; then
    log "prd stale (>15000s), triggering prd_review_cycle.sh"
    nohup "$PRD_SCRIPT" >> "$LOG_DIR/prd_review_cycle.cron.log" 2>&1 &
  fi
else
  log "prd apply report missing, triggering first prd_review_cycle.sh"
  nohup "$PRD_SCRIPT" >> "$LOG_DIR/prd_review_cycle.cron.log" 2>&1 &
fi

latest_e2e_report="$(ls -1t "$E2E_DIR"/report_*.md 2>/dev/null | head -n1 || true)"
if [ -n "$latest_e2e_report" ]; then
  e2e_mtime=$(stat -c %Y "$latest_e2e_report" 2>/dev/null || echo 0)
  e2e_age=$((now - e2e_mtime))
  log "e2e latest report=$(basename "$latest_e2e_report") age=${e2e_age}s"
  if [ "$e2e_age" -gt 15000 ]; then
    log "e2e stale (>15000s), triggering e2e_kick.sh"
    if [ "${SKIP_E2E_KICK:-0}" = "1" ]; then
      log "skip e2e kick due to failed data-contract preflight"
    else
      "$E2E_KICK_SCRIPT" || true
    fi
  fi
else
  log "e2e report missing, triggering e2e_kick.sh"
  if [ "${SKIP_E2E_KICK:-0}" = "1" ]; then
    log "skip e2e kick due to failed data-contract preflight"
  else
    "$E2E_KICK_SCRIPT" || true
  fi
fi

if [ -x "$E2E_CONSISTENCY_SCRIPT" ]; then
  CONSISTENCY_OUT="$E2E_DIR/consistency_latest.md"
  if "$E2E_CONSISTENCY_SCRIPT" "$CONSISTENCY_OUT"; then
    log "e2e consistency PASS: $CONSISTENCY_OUT"
  else
    log "e2e consistency FAIL: $CONSISTENCY_OUT"
  fi
else
  log "e2e consistency script missing: $E2E_CONSISTENCY_SCRIPT"
fi

log "supervisor done"
