#!/bin/bash
# NERDLETTER NUMBERS STATION — SUPER SIMPLE & RELIABLE
# Step-by-step mix so we can see exactly what’s happening

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

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

# 1. Voice track (slow letter-by-letter)
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 -s78 -k60 -a 210 -w voice.wav --punct="" 2>/dev/null
echo "✅ Voice track created ($(wc -c < voice.wav) bytes)"

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

# 3. Mix in TWO simple steps
echo "Mixing Poacher + Voice + Static..."

# Step 3a: Poacher + Static
ffmpeg -i poacher_intro.wav -i static.wav -filter_complex "[0:a][1:a]amix=inputs=2:duration=first:dropout_transition=3" -c:a pcm_s16le -y poacher_static.wav 2>/dev/null

# Step 3b: Add voice after Poacher ends
ffmpeg -i poacher_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

echo "✅ Final audio created ($(wc -c < final_audio.wav) bytes)"

# 4. Video
DUR=38
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

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

echo "✅ Done! → ${OUTFILE}"
echo "Check the length of final_audio.wav — it should be much longer than just the Poacher tune."
