#!/bin/bash
# Daily Wallpaper Generation Job
# Lightweight, improveable, steerable
# Usage: bash daily-generation.sh [prompt_keyword]

set -e

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

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

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

# Function to generate single wallpaper
generate() {
    local prompt="$1"
    local prefix="$2"
    local model="${3:-@cf/black-forest-labs/flux-1-schnell}"

    log "Generating: $prefix"
    bash "$SCRIPT_DIR/../../shared/scripts/cf-generate-wp.sh" "$prompt" "$OUTPUT_DIR" "$prefix" 8 2>&1 | tee -a "$LOG_FILE"
}

# Check for Cloudflare limit before starting
log "Checking Cloudflare availability..."
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 daily limit reached. Skipping generation."
    log "Will retry tomorrow."

    # Send notification if configured
    if [ -n "$WEBHOOK_URL" ]; then
        curl -s -X POST "$WEBHOOK_URL" -d "content=Wallpaper generation skipped: Cloudflare daily limit reached"
    fi

    exit 0
fi

log "Cloudflare available. Starting daily generation..."

# Get prompt keyword from args or use default
KEYWORD="${1:-random}"

log "Daily Generation Job: $DATE"
log "Keyword: $KEYWORD"
log "Output: $OUTPUT_DIR"

# Daily prompts - light, improveable, steerable
case "$KEYWORD" in
    random|*)
        # Random selection from prompt themes
        THEMES=("geometry" "atmosphere" "surreal" "minimal" "glitch")
        SELECTED_THEME=${THEMES[$RANDOM % ${#THEMES[@]}]}

        log "Selected theme: $SELECTED_THEME"

        case "$SELECTED_THEME" in
            geometry)
                generate "Single impossible geometric form floating in void. Wireframe Klein bottle rendered with cyan and magenta neon glow. Mathematical precision, retro computing aesthetic. Against black void. CGA color palette: cyan, magenta, white, black. 1920x1080 widescreen masterpiece." "daily_geo_klein" "@cf/leonardo/lucid-origin"
                ;;
            atmosphere)
                generate "Empty atmospheric space at night. Solitary vending machine glowing in rain-soaked alley. Wet asphalt reflecting electric cyan and hot pink neon. Vapor rising from grates. No people, just mood. Blade Runner anime aesthetic, contemplative solitude, 1920x1080 widescreen masterpiece." "daily_atmos_vending" "@cf/leonardo/lucid-origin"
                ;;
            surreal)
                generate "Surreal object in domestic setting. Melting clock hanging on empty wall. Clock face dripping time like Salvador Dali. Room otherwise minimal. Dream logic, impossible physics. Matte black clock with cyan numerals. Against white wall. 1920x1080 widescreen masterpiece." "daily_surreal_clock" "@cf/leonardo/lucid-origin"
                ;;
            minimal)
                generate "Minimal silhouette against gradient sky. Dead tree with no leaves, just branches reaching upward. Sky gradient from electric cyan to deep magenta. Nature reduced to line drawing. Stark, graphic. High contrast. 1920x1080 widescreen masterpiece." "daily_min_tree" "@cf/leonardo/lucid-origin"
                ;;
            glitch)
                generate "Cyberpunk street with vertical pixel sorting glitch. Neon signs streaking downward in magenta and cyan columns. Reality sorted by brightness creating abstract patterns. Empty atmosphere, maximum digital corruption. CGA palette: magenta, cyan, white, black. Glitch art meets cyberpunk. 1920x1080 widescreen masterpiece." "daily_glitch_sort" "@cf/leonardo/lucid-origin"
                ;;
        esac
        ;;
esac

log "Daily generation complete!"

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

# Send notification if configured
if [ -n "$WEBHOOK_URL" ]; then
    curl -s -X POST "$WEBHOOK_URL" -d "content=Daily wallpaper generation complete: $GENERATED new wallpapers"
fi

log "Next run: Tomorrow"