#!/bin/bash
# Batch Carousel Generation
# 
# Purpose: Generate all carousels for a given date
# Usage: ./batch-generate-carousels.sh YYYY-MM-DD
# 
# This script finds all configs for the date and runs the 5-step pipeline

# Note: We don't use set -e so we can continue past validation failures

DATE=$1

if [ -z "$DATE" ]; then
  echo "❌ Usage: ./batch-generate-carousels.sh YYYY-MM-DD"
  exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONTENT_FACTORY_ROOT="$(dirname "$SCRIPT_DIR")"
CAROUSELS_DIR="$CONTENT_FACTORY_ROOT/media-lab/generation/carousels"
CONFIGS_DIR="$CAROUSELS_DIR/configs"

echo "📅 Generating carousels for: $DATE"
echo "📁 Configs directory: $CONFIGS_DIR"
echo ""

# Find all configs for the date
CONFIGS=($(ls "$CONFIGS_DIR/$DATE"-*.json 2>/dev/null || true))

if [ ${#CONFIGS[@]} -eq 0 ]; then
  echo "❌ No configs found for date: $DATE"
  echo "   Looking in: $CONFIGS_DIR/"
  exit 1
fi

echo "✅ Found ${#CONFIGS[@]} config(s)"
echo ""

# Array to store generated PDFs
GENERATED_PDFS=()

cd "$CAROUSELS_DIR"

# Process each config
for CONFIG in "${CONFIGS[@]}"; do
  CONFIG_NAME=$(basename "$CONFIG")
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  echo "🎨 Processing: $CONFIG_NAME"
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  
  # Step 0: Validate config against schema
  echo "🔍 Step 0/5: Validating config..."
  if ! node validate-config.js "configs/$CONFIG_NAME"; then
    echo "⚠️  Skipping $CONFIG_NAME (validation failed)"
    echo ""
    continue
  fi
  echo ""
  
  # Step 1: Build HTML
  echo "📝 Step 1/5: Building HTML slides..."
  node build-carousel.js "configs/$CONFIG_NAME"
  
  # Extract carousel title from config and create slug for directory name
  CAROUSEL_TITLE=$(node -e "const c=require('$CONFIG');console.log(c.carousel?.title||c.title||'carousel')")
  DIR_SLUG=$(echo "$CAROUSEL_TITLE" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]\+/-/g' | sed 's/^-\|-$//g' | cut -c1-60)
  OUTPUT_DIR="$DATE-$DIR_SLUG"
  
  # Step 2: Convert to PNG (pass directory name)
  echo "🖼️  Step 2/5: Converting to PNG..."
  node convert-html-slides-to-png.js "$OUTPUT_DIR"
  
  # Step 3: Assemble PDF (pass directory name)
  echo "📄 Step 3/5: Assembling PDF..."
  node assemble-png-to-pdf.js "$OUTPUT_DIR"
  
  # Step 4: Copy original config to output directory
  echo "📋 Step 4/5: Archiving config..."
  OUTPUT_PATH="$CONTENT_FACTORY_ROOT/media-lab/output/$OUTPUT_DIR"
  cp "$CONFIG" "$OUTPUT_PATH/"
  echo "   → Copied $CONFIG_NAME to output"
  
  # Find the generated PDF for Telegram
  PDF_PATH=$(find "$OUTPUT_PATH" -name "*.pdf" -type f | head -n 1)
  if [ -n "$PDF_PATH" ]; then
    GENERATED_PDFS+=("$PDF_PATH")
  fi
  
  echo "✅ Done: $CONFIG_NAME"
  echo ""
done

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🎉 All carousels generated for $DATE!"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Step 5: Send to Telegram (if configured)
if [ ${#GENERATED_PDFS[@]} -gt 0 ]; then
  if [ -n "$TELEGRAM_BOT_TOKEN" ] && [ -n "$TELEGRAM_CHAT_ID" ]; then
    echo "📤 Sending ${#GENERATED_PDFS[@]} PDF(s) to Telegram..."
    
    for PDF in "${GENERATED_PDFS[@]}"; do
      PDF_NAME=$(basename "$PDF")
      echo "   - Sending $PDF_NAME..."
      node "$CONTENT_FACTORY_ROOT/scripts/send-to-telegram.js" "$PDF" "📅 Batch generated: $DATE"
    done
    echo ""
    echo "✅ Telegram upload complete!"
    echo ""
  else
    echo "⚠️  Telegram credentials not set. Skipping upload."
    echo "   (Set TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID to enable)"
    echo ""
  fi
fi

echo "📁 Output location:"
echo "   $CONTENT_FACTORY_ROOT/media-lab/output/"
echo ""
echo "📋 Next steps:"
echo "   1. Review PDFs in output directories"
echo "   2. Send for approval via Telegram"
echo "   3. Schedule publishing via n8n"
