#!/bin/bash
# NERDLETTER NUMBERS STATION MP4 GENERATOR — ULTIMATE DRAMA EDITION
# Slow letter-by-letter + shortwave static + Lincolnshire Poacher intro

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

echo "=== NERDLETTER SECRET TRANSMISSION #${EPISODE} ==="
echo "Page ${PAGE} — Generating spoken MP4 with full drama..."

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

# === 2. Full text to speak (very slow & spooky) ===
TEXT_TO_SPEAK="NERDLETTER SECRET MESSAGE ${EPISODE}. USE DAY BOOK PAGE ${PAGE}. ${SPACED}"

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

# === 3. Download / prepare assets (run once) ===
if [ ! -f poacher_intro.wav ]; then
  echo "Downloading public-domain Lincolnshire Poacher intro (short 12-second clip)..."
  # Using a free direct link from The Conet Project style recording (public domain use)
  wget -q -O poacher_intro.wav "https://archive.org/download/The-Conet-Project/The%20Conet%20Project%20-%20Recordings%20of%20Shortwave%20Numbers%20Stations%20%281997%29%20%5B2013%20-%2015th%20Anniversary%20Bonus%20Disc%20Edition%5D%20%5BFLAC%5D/Disc%201/06%20-%20The%20Lincolnshire%20Poacher.flac" || \
  echo "Manual download needed — see note below"
fi

if [ ! -f static.wav ]; then
  echo "Generating shortwave static..."
  ffmpeg -f lavfi -i "anoisesrc=d=25:c=0.3" -af "highpass=f=3000,lowpass=f=8000" -t 25 static.wav -y 2>/dev/null
fi

# === 4. Mix audio: Poacher intro + static + voice ===
ffmpeg -i poacher_intro.wav -i static.wav -i voice_main.wav \
-filter_complex "[0:a]volume=0.65[a1];[1:a]volume=0.25[a2];[a1][a2]amix=inputs=2:duration=first[a3];[a3][2:a]amix=inputs=2:duration=first,volume=1.1" \
-c:a pcm_s16le -y final_audio.wav 2>/dev/null

# === 5. Video with retro text ===
ffmpeg -f lavfi -i color=black:s=1280x720:d=28 -c:v libx264 -t 28 -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_main.wav final_audio.wav temp_bg.mp4

echo "✅ Done! → ${OUTFILE}"
echo "Full cold-war numbers station experience achieved."
