#!/usr/bin/env bash
# transcribe.sh — transcribe hub recordings with LOCAL Whisper (free, GPU-accelerated)
# and drop the text into BILLO OS so the script miner / Chameleon Protocol picks it up.
#
# This is BILLO OS "Layer 6 — Content Capture" → Whisper transcription pipeline.
#
# Usage:
#   ./transcribe.sh recordings/show.wav          # one file
#   ./transcribe.sh recordings/                  # every wav/mp3/m4a/aiff/flac in a dir
#
# Outputs: <file>.txt + <file>.srt next to the source, plus a copy of the .txt in
# ~/BillySorrells/transcripts/  (set BILLO_TRANSCRIPTS to change that).
set -euo pipefail

MODEL="${WHISPER_MODEL:-$HOME/.cache/whisper-cpp/ggml-large-v3-turbo-q5_0.bin}"
OUT_DIR="${BILLO_TRANSCRIPTS:-$HOME/BillySorrells/transcripts}"
WHISPER="${WHISPER_CLI:-$(command -v whisper-cli || true)}"
LANG="${WHISPER_LANG:-en}"

[ -n "$WHISPER" ] || { echo "whisper-cli not found" >&2; exit 1; }
[ -f "$MODEL" ] || { echo "whisper model not found at $MODEL" >&2; exit 1; }
mkdir -p "$OUT_DIR"

transcribe_one() {
  local f="$1"
  local stem; stem="$(basename "${f%.*}")"
  echo "▶ $f"
  # -mc 0 avoids the whisper.cpp repeat-loop; no VAD model (silero returns zero segments)
  "$WHISPER" -m "$MODEL" -f "$f" -otxt -osrt -mc 0 -l "$LANG" >/dev/null 2>&1 || true
  if [ -f "${f}.txt" ]; then
    cp "${f}.txt" "$OUT_DIR/${stem}.txt"
    echo "   ✓ transcript -> $OUT_DIR/${stem}.txt"
  else
    echo "   ⚠ no transcript produced (silence?)"
  fi
}

if [ "$#" -eq 0 ]; then
  echo "usage: $0 <audio_file_or_dir> [...]"; exit 1
fi

for arg in "$@"; do
  if [ -d "$arg" ]; then
    while IFS= read -r -d '' f; do transcribe_one "$f"; done \
      < <(find "$arg" -type f \( -iname '*.wav' -o -iname '*.mp3' -o -iname '*.m4a' -o -iname '*.aiff' -o -iname '*.flac' \) -print0)
  elif [ -f "$arg" ]; then
    transcribe_one "$arg"
  else
    echo "skip (not found): $arg"
  fi
done
