#!/usr/bin/env bash
# rotate-surveys.sh — ensures there's always a survey available for the next 8 weeks
# Cycles through the 5 survey templates (week 1-5) repeating indefinitely
# Run weekly via cron: 0 0 * * 1 /var/www/html/rainmaker/backend/scripts/rotate-surveys.sh

set -euo pipefail
export PGPASSWORD=eventheodds_dev_password
DB_ARGS="-h 127.0.0.1 -p 5433 -U eventheodds -d eventheodds_sports -t -A"

# Get the latest week_start in the DB
LATEST=$(psql $DB_ARGS -c "SELECT MAX(week_start) FROM rm_surveys;" | tr -d '[:space:]')
echo "Latest survey week_start: $LATEST"

# Get the 5 survey templates (questions JSON) ordered by original week_start
readarray -t TEMPLATES < <(psql $DB_ARGS -c "
  SELECT row_to_json(t) FROM (
    SELECT title, questions::text, credit_reward
    FROM rm_surveys
    ORDER BY week_start ASC
    LIMIT 5
  ) t;
")

echo "Found ${#TEMPLATES[@]} survey templates"

# Ensure we have surveys for the next 8 weeks from today
TARGET_DATE=$(date -d "+8 weeks" +%Y-%m-%d)
CURRENT_DATE="$LATEST"
ADDED=0

while [[ "$CURRENT_DATE" < "$TARGET_DATE" ]]; do
  # Next Monday after current_date
  NEXT_MONDAY=$(date -d "$CURRENT_DATE + 7 days" +%Y-%m-%d)

  # Check if this week already exists
  EXISTS=$(psql $DB_ARGS -c "SELECT COUNT(*) FROM rm_surveys WHERE week_start = '$NEXT_MONDAY';")
  if [[ "$EXISTS" -gt 0 ]]; then
    CURRENT_DATE="$NEXT_MONDAY"
    continue
  fi

  # Determine which template to use (cycle 0-4)
  # Count total surveys, mod 5
  TOTAL=$(psql $DB_ARGS -c "SELECT COUNT(*) FROM rm_surveys;")
  IDX=$((TOTAL % 5))
  TEMPLATE="${TEMPLATES[$IDX]}"

  TITLE=$(echo "$TEMPLATE" | python3 -c "import sys,json; print(json.load(sys.stdin)['title'])")
  QUESTIONS=$(echo "$TEMPLATE" | python3 -c "import sys,json; print(json.dumps(json.load(sys.stdin)['questions']))")
  REWARD=$(echo "$TEMPLATE" | python3 -c "import sys,json; print(json.load(sys.stdin)['credit_reward'])")

  psql $DB_ARGS -c "
    INSERT INTO rm_surveys (title, questions, credit_reward, week_start)
    VALUES ('$TITLE', '$QUESTIONS'::jsonb, $REWARD, '$NEXT_MONDAY');
  " > /dev/null

  echo "Added: $TITLE for week $NEXT_MONDAY"
  ADDED=$((ADDED + 1))
  CURRENT_DATE="$NEXT_MONDAY"
done

echo "Done. Added $ADDED new survey weeks."
