#!/usr/bin/env bash
# Descarcă un video (Facebook, YouTube etc.), extrage audio, transcrie cu Whisper.
# Usage: ./transcribe_video.sh <URL> [language]
# Exemple:
#   ./transcribe_video.sh "https://www.facebook.com/share/v/1EdPt3q2sq/"
#   ./transcribe_video.sh "https://youtu.be/xyz" ro

set -euo pipefail

URL="${1:-}"
LANG="${2:-en}"
WORKDIR="/tmp/transcribe_$$"

if [[ -z "$URL" ]]; then
  echo "Usage: $0 <URL> [language (default: en)]"
  exit 1
fi

export PATH="/home/moltbot/bin:$PATH"

mkdir -p "$WORKDIR"
trap 'rm -rf "$WORKDIR"' EXIT

echo "→ Descarc video..."
yt-dlp "$URL" -o "$WORKDIR/video.%(ext)s" --no-playlist -q

VIDEO_FILE=$(ls "$WORKDIR"/video.* 2>/dev/null | head -1)
if [[ -z "$VIDEO_FILE" ]]; then
  echo "Eroare: descărcarea a eșuat."
  exit 1
fi

echo "→ Extrag audio..."
ffmpeg -i "$VIDEO_FILE" -vn -acodec pcm_s16le -ar 16000 -ac 1 "$WORKDIR/audio.wav" -y -loglevel error

echo "→ Transcriu cu Whisper (model: small, limbă: $LANG)..."
python3 -c "
import whisper
model = whisper.load_model('small')
result = model.transcribe('$WORKDIR/audio.wav', language='$LANG')
print(result['text'])
" 2>/dev/null

echo ""
echo "✓ Gata."
