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

import psycopg2
import json
from datetime import date, timedelta

DB = dict(host='127.0.0.1', port=5433, dbname='eventheodds_sports', user='eventheodds', password='eventheodds_dev_password')

conn = psycopg2.connect(**DB)
cur = conn.cursor()

# Get the 5 survey templates ordered by original week_start
cur.execute("SELECT title, questions, credit_reward FROM rm_surveys ORDER BY week_start ASC LIMIT 5")
templates = cur.fetchall()
print(f"Found {len(templates)} survey templates")

# Get latest week_start
cur.execute("SELECT MAX(week_start) FROM rm_surveys")
latest = cur.fetchone()[0]
print(f"Latest survey week: {latest}")

# Get total count for cycling
cur.execute("SELECT COUNT(*) FROM rm_surveys")
total = cur.fetchone()[0]

# Fill in surveys for the next 8 weeks from today
target = date.today() + timedelta(weeks=8)
current = latest
added = 0

while current < target:
    next_week = current + timedelta(days=7)

    # Check if exists
    cur.execute("SELECT 1 FROM rm_surveys WHERE week_start = %s", (next_week,))
    if cur.fetchone():
        current = next_week
        continue

    # Cycle through templates
    idx = (total + added) % len(templates)
    title, questions, reward = templates[idx]

    cur.execute(
        "INSERT INTO rm_surveys (title, questions, credit_reward, week_start) VALUES (%s, %s, %s, %s)",
        (title, json.dumps(questions), reward, next_week)
    )
    print(f"  Added: {title} for week {next_week}")
    added += 1
    current = next_week

conn.commit()
cur.close()
conn.close()
print(f"Done. Added {added} new survey weeks.")
