#!/bin/bash
# Auto Daily Generator with Review Prompts
# Set up cron to run this daily

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
OUTPUT_DIR="$SCRIPT_DIR/../renders/daily-$(date +%Y%m%d)"
LOG_FILE="$SCRIPT_DIR/../logs/daily-$(date +%Y%m%d).log"

mkdir -p "$OUTPUT_DIR"
mkdir -p "$(dirname "$LOG_FILE")"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# Check Cloudflare availability
log "Checking Cloudflare..."
TEST_OUTPUT=$(bash "$SCRIPT_DIR/../../shared/scripts/cf-generate-wp.sh "test" "/tmp/test" "test" 4 2>&1 || true)

if echo "$TEST_OUTPUT" | grep -q "429"; then
    log "Cloudflare limit reached - skipping"
    exit 0
fi

log "Cloudflare available - starting generation"

# Today's theme rotation (7 themes cycling)
DAY_OF_WEEK=$(date +%u)
THEMES=("glitch" "palettes" "selective" "geometry" "bedroom" "chaos" "classics")
THEME_INDEX=$((($DAY_OF_WEEK - 1) % 7))
TODAY_THEME="${THEMES[$THEME_INDEX]}"

log "Theme: $TODAY_THEME"

case "$TODAY_THEME" in
    glitch)
        log "Generating: Glitch aesthetics"
        bash "$SCRIPT_DIR/showcase-glitch.sh"
        ;;
    palettes)
        log "Generating: Color palettes"
        bash "$SCRIPT_DIR/showcase-palettes.sh"
        ;;
    selective)
        log "Generating: B/W selective color"
        bash "$SCRIPT_DIR/showcase-selective-color.sh"
        ;;
    geometry)
        log "Generating: Impossible geometry"
        bash "$SCRIPT_DIR/showcase-mecha-geo.sh"
        ;;
    bedroom)
        log "Generating: Bedroom POVs"
        bash "$SCRIPT_DIR/showcase-bedroom-views.sh"
        ;;
    chaos)
        log "Generating: Chaos surrealism"
        bash "$SCRIPT_DIR/showcase-chaos.sh"
        ;;
    classics)
        log "Generating: ComfyUI classics"
        bash "$SCRIPT_DIR/comfyui-classics.sh"
        ;;
    *)
        # Random single from daily-generation.sh
        log "Generating: Random theme"
        bash "$SCRIPT_DIR/daily-generation.sh"
        ;;
esac

GENERATED=$(find "$OUTPUT_DIR" -type f \( -name "*.jpg" -o -name "*.png" \) 2>/dev/null | wc -l)
log "Generated: $GENERATED wallpapers"

log "Daily generation complete!"
log "Remember to review at: http://localhost:8765"