#!/bin/bash
# NERDLETTER NUMBERS STATION — FINAL SEQUENCE EDITION
# Poacher tune → Voice announcement → Static throughout

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

echo "=== NERDLETTER SECRET TRANSMISSION #${EPISODE} ==="
echo "Building full sequence with Poacher intro first..."

# 1. Spaced letters for slow pronunciation
SPACED=$(echo "$MESSAGE" | sed 's/\([A-Z]\)/\1 /g' | sed 's/  / /g')

TEXT_TO_SPEAK="NERDLETTER SECRET MESSAGE ${EPISODE}. USE DAY BOOK PAGE ${PAGE}. ${SPACED}"

echo "$TEXT_TO_SPEAK" | \
espeak-ng -ven+f3 -s82 -k50 -a 200 -w voice.wav --punct="" 2>/dev/null

# 2. Ensure assets exist
if [ ! -f poacher_intro.wav ]; then
    echo "⚠️  poacher_intro.wav not found — please add a 10-15 second clip manually."
    echo "   (Download from The Conet Project and trim first 12 seconds)"
    exit 1
fi

if [ ! -f static.wav ]; then
    echo "Generating continuous shortwave static..."
    ffmpeg -f lavfi -i "anoisesrc=d=40:c=0.28" -af "highpass=f=2800,lowpass=f=8500,volume=0.22" -t 40 static.wav -y 2>/dev/null
fi

# 3. Create sequenced audio: Poacher → Voice (with static under everything)
ffmpeg -i poacher_intro.wav -i voice.wav -i static.wav \
-filter_complex "
[0:a]volume=0.75[poach];
[1:a]volume=1.05[voice];
[2:a]volume=0.28[stat];
[poach][stat]amix=duration=first[a1];
[a1][voice]acrossfade=d=1.2:o=1:c1=exp:c2=exp[a2];
[stat][a2]amix=duration=longest,volume=1.1[final]
" -c:a pcm_s16le -y final_audio.wav 2>/dev/null

# 4. Video (long enough for intro + voice)
ffmpeg -f lavfi -i color=black:s=1280x720:d=32 -c:v libx264 -t 32 -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

# Cleanup
rm -f voice.wav final_audio.wav temp_bg.mp4

echo "✅ Done! → ${OUTFILE}"
echo "Sequence: Poacher tune first → Voice → Static throughout"
