#!/bin/bash
set -e

CHAPTERS_DIR="../chapters"
OUTPUT_DIR="."
TEXT_EXTRACTOR="./extract_text.py"
VOICE="Alex"
QUALITY=3

for i in $(seq -w 1 18); do
    CHAPTER_FILE="$CHAPTERS_DIR/chapter-$i.md"
    if [[ ! -f "$CHAPTER_FILE" ]]; then
        echo "Chapter file not found: $CHAPTER_FILE"
        continue
    fi
    
    echo "Processing chapter $i..."
    TEXT_FILE="ch${i}-text.txt"
    AIFF_FILE="ch${i}-sample.aiff"
    WAV_FILE="ch${i}-sample.wav"
    OGG_FILE="ch${i}-sample.ogg"
    
    # Extract text
    python3 "$TEXT_EXTRACTOR" "$CHAPTER_FILE" "$TEXT_FILE"
    
    # Generate speech
    say -v "$VOICE" -o "$AIFF_FILE" -f "$TEXT_FILE"
    
    # Convert AIFF to WAV
    ffmpeg -i "$AIFF_FILE" -c:a pcm_s16le -ar 22050 -ac 1 "$WAV_FILE" -y 2>/dev/null
    
    # Convert WAV to OGG
    oggenc "$WAV_FILE" -o "$OGG_FILE" -q "$QUALITY" 2>&1 | grep -E "Done encoding|ERROR"
    
    # Clean up intermediate files
    rm -f "$TEXT_FILE" "$AIFF_FILE" "$WAV_FILE"
    
    echo "  -> $OGG_FILE"
done

echo "All chapters processed."