#!/bin/bash
# NERDLETTER NUMBERS STATION — FINAL PERFECT VERSION

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

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

# 1. Create voice with 1-second pauses between groups
SPACED_GROUPS=$(echo "$MESSAGE" | sed 's/\([A-Z]\{5\}\)/\1 /g' | sed 's/  / /g')
TEXT_TO_SPEAK="NERDLETTER SECRET MESSAGE ${EPISODE}. USE DAY BOOK PAGE ${PAGE}. <break time=\"800ms\"/> ${SPACED_GROUPS// / <break time=\"1000ms\"/> }"

echo "$TEXT_TO_SPEAK" | espeak-ng -ven+f3 -s76 -k55 -a 205 -w voice.wav --punct="" --ssml 2>/dev/null

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

# 3. Mix with gentle overlap
ffmpeg -i poacher_intro.wav -i voice.wav -i static.wav \
-filter_complex "
[0:a]volume=0.68,atrim=0:14[a0];           # tune ~14 seconds
[1:a]volume=1.12[a1];
[2:a]volume=0.23[stat];
[a0][stat]amix=duration=first[a_tune];
[a1][stat]amix=duration=first[a_voice];
[a_tune][a_voice]acrossfade=d=2.5:o=1[cross];
[cross][stat]amix=duration=longest[out]
" -map "[out]" -c:a pcm_s16le -y final_audio.wav 2>/dev/null

# 4. Video
DUR=42
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 voice.wav temp_bg.mp4
echo "✅ Done! → ${OUTFILE}"
