#!/bin/bash
# NERDLETTER NUMBERS STATION — FIXED LETTER-BY-LETTER + PAUSES

MESSAGE="$1"
PAGE="$2"
EPISODE="${3:-01}"
OUTFILE="nerdletter_secret_${EPISODE}_page${PAGE}.mp4"

echo "=== NERDLETTER SECRET TRANSMISSION #${EPISODE} ==="

# 1. Intro voice
INTRO="NERDLETTER SECRET MESSAGE ${EPISODE}. USE DAY BOOK PAGE ${PAGE}."
echo "$INTRO" | espeak-ng -ven+f3 -s80 -k50 -a 200 -w intro.wav --punct="" 2>/dev/null

# 2. Build full groups voice letter-by-letter with pauses
> groups_voice.wav   # start fresh

for group in $MESSAGE; do
    echo "Processing group: $group"
    for ((i=0; i<${#group}; i++)); do
        letter="${group:$i:1}"
        echo "$letter" | espeak-ng -ven+f3 -s74 -k65 -a 210 -w temp.wav 2>/dev/null
        cat temp.wav >> groups_voice.wav
        rm temp.wav
    done
    # 1 second pause after each group
    ffmpeg -f lavfi -i "anullsrc=r=22050" -t 1.05 silence.wav -y 2>/dev/null
    cat silence.wav >> groups_voice.wav
    rm silence.wav
done

# Combine intro + groups
ffmpeg -i intro.wav -i groups_voice.wav -filter_complex "[0:a][1:a]concat=n=2:v=0:a=1" -c:a pcm_s16le -y voice.wav 2>/dev/null

echo "✅ Full voice track built (letter-by-letter with pauses)"

# 3. Static (if missing)
if [ ! -f static.wav ]; then
    ffmpeg -f lavfi -i "anoisesrc=d=50:c=0.22" -af "highpass=f=2500,lowpass=f=9000,volume=0.22" -t 50 static.wav -y 2>/dev/null
fi

# 4. Final mix: Poacher tune → Voice, static under everything
ffmpeg -i poacher_intro.wav -i static.wav -filter_complex "[0:a][1:a]amix=inputs=2:duration=first" -c:a pcm_s16le -y tune_static.wav 2>/dev/null

ffmpeg -i tune_static.wav -i voice.wav -filter_complex "[0:a][1:a]concat=n=2:v=0:a=1" -c:a pcm_s16le -y final_audio.wav 2>/dev/null

# 5. Video
DUR=48
ffmpeg -f lavfi -i color=black:s=1280x720:d=$DUR -c:v libx264 -t $DUR -pix_fmt yuv420p temp_bg.mp4 -y

ffmpeg -i temp_bg.mp4 -i final_audio.wav \
-vf "drawtext=font='Courier':fontsize=50:fontcolor=green@0.95:text='NERDLETTER SECRET TRANSMISSION #${EPISODE}':x=(w-text_w)/2:y=80, \
drawtext=font='Courier':fontsize=36:fontcolor=green@0.85:text='USE DAY BOOK PAGE ${PAGE}':x=(w-text_w)/2:y=170, \
drawtext=font='Courier':fontsize=44:fontcolor=lime@0.95:text='${MESSAGE}':x=(w-text_w)/2:y=270:box=1:boxcolor=black@0.75:boxborderw=15, \
drawtext=font='Courier':fontsize=30:fontcolor=green@0.75:text='DESTROY PAGE AFTER USE — SUBSCRIBERS ONLY':x=(w-text_w)/2:y=640" \
-c:v libx264 -c:a aac -shortest "$OUTFILE" -y

rm -f intro.wav groups_voice.wav tune_static.wav temp_bg.mp4
echo "✅ DONE! → ${OUTFILE}"
