#!/usr/bin/env bash
# ============================================================================
# yt-transcribe — repeatable YouTube/X transcription
#
# Strategy: captions first (exact text, fast); Whisper fallback ONLY when no
# captions exist, reusing the OpenSuperWhisper model already on this Mac.
# Accepts a URL (YouTube, X/Twitter, anything yt-dlp supports) OR a local
# media file (skips straight to Whisper; used by the watcher for reclip
# downloads).
#
# Usage:
#   yt-transcribe <url-or-file>       # transcript → media/transcripts/<id>/ (URL)
#                                     #             or <file>.txt sidecar  (file)
#   yt-transcribe <url> --lang de     # prefer German captions
#   yt-transcribe <url> --srt         # also produce an .srt (whisper path)
#   yt-transcribe <url> --force       # redo even if transcript exists
#
# X/Twitter: X has no public captions and now requires auth for most video
# extraction, so URLs on x.com/twitter.com go through gallery-dl (set
# YT_COOKIES=/path/to/cookies.txt for locked/NSFW/older tweets; exported
# cookies.txt format from a browser extension works for both yt-dlp and
# gallery-dl).
#
# Outputs (URL mode) in <share>/media/transcripts/<id>/:
#   <id>.txt            plain transcript (always)
#   <id>.vtt            raw captions (captions path)
#   <id>.srt            subtitles (whisper path, with --srt)
#   <id>.metadata.json  provenance: title, channel, source, date
#
# Dependencies (declared in dotfiles configuration.nix homebrew.brews):
#   yt-dlp, gallery-dl (X only), whisper-cli (whisper-cpp), ffmpeg (fallback only)
#   Whisper model: auto-detected from OpenSuperWhisper's model store,
#   or WHISPER_MODEL=/path/to/ggml-*.bin, or --model.
# Env overrides: YT_SHARE_ROOT (data share mount, default /Volumes/data),
#   YT_TRANSCRIBE_ROOT (transcript root), YT_MEDIA_DIR (reclip download dir),
#   YT_COOKIES (cookies.txt for yt-dlp/gallery-dl).
# Index: `yt-transcribe --list` prints id->title mapping; --index rewrites
#   INDEX.md next to the transcripts; both modes refresh it after each run.
# ============================================================================
set -euo pipefail

# --- locate the data share ---------------------------------------------------
# The tool lives in this repo (installed into the nix store by the dotfiles
# rebuild; stable symlink at ~/.local/bin/yt-transcribe). The Unraid share
# holds only data — media and transcripts.
SHARE_ROOT="${YT_SHARE_ROOT:-/Volumes/data}"
OUT_ROOT="${YT_TRANSCRIBE_ROOT:-$SHARE_ROOT/media/transcripts}"

# --- PATH: cover Homebrew on Apple Silicon / Intel (launchd PATH too) ------
for p in /opt/homebrew/bin /usr/local/bin; do
  [ -d "$p" ] && [[ ":$PATH:" != *":$p:"* ]] && PATH="$p:$PATH"
done

LANG_PREF="en"
KEEP_SRT=false
FORCE=false
DO_INDEX=false
DO_LIST=false
WHISPER_MODEL_ARG=""
INPUT=""
while [ $# -gt 0 ]; do
  case "$1" in
    --lang)     LANG_PREF="$2"; shift 2 ;;
    --srt)      KEEP_SRT=true; shift ;;
    --force)    FORCE=true; shift ;;
    --model)    WHISPER_MODEL_ARG="$2"; shift 2 ;;
    --index)    DO_INDEX=true; shift ;;
    --list)     DO_LIST=true; shift ;;
    -h|--help)  grep '^#   ' "$0" | sed 's/^#   //'; exit 0 ;;
    *)          INPUT="$1"; shift ;;
  esac
done
[ -n "$INPUT" ] || $DO_INDEX || $DO_LIST || { echo "usage: yt-transcribe <url-or-file> [--lang L] [--srt] [--force] [--model ggml.bin] [--index|--list]" >&2; exit 1; }

# --- transcript index (INDEX.md / --list) -----------------------------------
rebuild_index() {
  python3 - "$OUT_ROOT" "${YT_MEDIA_DIR:-$SHARE_ROOT/media/video}" <<'PY'
import json, os, sys, time
out_root, scan_dir = sys.argv[1], sys.argv[2]
rows = []
for dirpath, _, files in os.walk(out_root):
    for fn in files:
        if fn.endswith(".metadata.json"):
            try:
                d = json.load(open(os.path.join(dirpath, fn), encoding="utf-8"))
            except Exception:
                continue
            rows.append((d.get("transcribed_at") or "", d))
rows.sort(key=lambda r: r[0], reverse=True)
clean = lambda s: (s or "").replace("|", "/").replace("`", "/")
L = ["# Transcript Index", "",
     "URL transcripts live in `media/transcripts/<id>/` — the `<id>.txt` is the",
     "transcript, `<id>.metadata.json` has full provenance. Local files keep their",
     "`.txt` sidecar next to the media file.", "",
     "## URL transcripts", "", "| transcribed | id | title | channel | source |", "|---|---|---|---|---|"]
for ts, d in rows:
    L.append(f'| {ts} | `{clean(d.get("id"))}` | {clean(d.get("title"))} | {clean(d.get("channel"))} | {clean(d.get("source"))} |')
L += ["", "## Local media files (sidecar .txt in media/video)", "", "| file | modified |", "|---|---|"]
found = False
for dirpath, dirs, files in os.walk(scan_dir):
    dirs[:] = [d for d in dirs if not d.startswith(".")]
    for fn in sorted(files):
        if fn.endswith(".txt"):
            found = True
            p = os.path.join(dirpath, fn)
            mt = time.strftime("%Y-%m-%d", time.localtime(os.path.getmtime(p)))
            L.append(f"| `{clean(fn)}` | {mt} |")
if not found:
    L.append("| _(none yet — patched reclip or manual file-mode runs add one per download)_ | |")
print("\n".join(L))
PY
}
if $DO_INDEX || $DO_LIST; then
  mkdir -p "$OUT_ROOT"
  if $DO_LIST; then
    rebuild_index
  else
    rebuild_index > "$OUT_ROOT/INDEX.md"
    echo "== index rebuilt: $OUT_ROOT/INDEX.md"
  fi
  exit 0
fi

need() { command -v "$1" >/dev/null || { echo "MISSING DEP: $1 — install it first" >&2; exit 2; }; }

DL_ARGS=()
[ -n "${YT_COOKIES:-}" ] && DL_ARGS=(--cookies "$YT_COOKIES")

resolve_model() {
  local MODEL="${WHISPER_MODEL_ARG:-${WHISPER_MODEL:-}}"
  if [ -z "$MODEL" ]; then
    MODEL="$(find "$HOME/Library/Application Support/ru.starmel.OpenSuperWhisper/whisper-models" \
             -name 'ggml-*.bin' 2>/dev/null | head -1 || true)"
  fi
  printf '%s' "$MODEL"
}

# whisper_transcribe <wav> <out-stem> — writes <out-stem>.txt (and .srt w/ --srt)
whisper_transcribe() {
  local WAV="$1" STEM="$2" MODEL
  MODEL="$(resolve_model)"
  [ -n "$MODEL" ] && [ -f "$MODEL" ] || {
    echo "ERROR: no whisper model. Download one (e.g. ggml-large-v3-turbo.bin from huggingface.co/ggerganov/whisper.cpp)" >&2
    echo "       and pass --model or set WHISPER_MODEL." >&2; exit 4; }
  echo ">> model: $MODEL"
  local WARGS=(-m "$MODEL" -f "$WAV" -of "$STEM" -otxt)
  $KEEP_SRT && WARGS+=(-osrt)
  echo ">> transcribing with whisper-cli (this is the slow part)..."
  whisper-cli "${WARGS[@]}" 2>>"$(dirname "$STEM")/whisper.log"
  [ -s "$STEM.txt" ] || { echo "ERROR: whisper produced no text" >&2; exit 6; }
}

TMPD="$(mktemp -d)"
cleanup() { rm -rf "$TMPD"; }
trap cleanup EXIT

SOURCE=""
SOURCE_PREFIX=""
if [ -f "$INPUT" ]; then
  # ==========================================================================
  # FILE MODE — local media (reclip download, screen recording, anything)
  # ==========================================================================
  need ffmpeg; need whisper-cli
  SRC_FILE="$INPUT"
  STEM="$(basename "$SRC_FILE")"
  STEM="${STEM%.*}"
  OUT_DIR="$(cd "$(dirname "$SRC_FILE")" && pwd)"
  TXT="$OUT_DIR/$STEM.txt"
  if [ -s "$TXT" ] && ! $FORCE; then
    echo "== already transcribed: $TXT (use --force to redo)"
    exit 0
  fi
  echo ">> file mode: $SRC_FILE"
  echo ">> converting to 16 kHz mono wav..."
  ffmpeg -y -loglevel error -i "$SRC_FILE" -ac 1 -ar 16000 "$TMPD/in.wav"
  whisper_transcribe "$TMPD/in.wav" "$OUT_DIR/$STEM"
  SOURCE="whisper-local"
  rebuild_index > "$OUT_ROOT/INDEX.md" 2>/dev/null || true
  echo "== done: $TXT  (source: $SOURCE)"
  exit 0
fi

# ==========================================================================
# URL MODE
# ==========================================================================
need yt-dlp
URL="$INPUT"
IS_X=false
case "$URL" in
  *x.com/*|*twitter.com/*|*//t.co/*) IS_X=true ;;
esac

# --- metadata (yt-dlp; gallery-dl for X when yt-dlp can't) -------------------
VIDEO_ID=""; TITLE=""; CHANNEL=""
if META="$(yt-dlp --no-playlist --skip-download --no-warnings "${DL_ARGS[@]}" \
        --print "id=%(id)s" --print "title=%(title)s" --print "channel=%(channel|uploader)s" "$URL" 2>/dev/null)"; then
  VIDEO_ID="$(printf '%s\n' "$META" | sed -n 's/^id=//p')"
  TITLE="$(printf '%s\n' "$META" | sed -n 's/^title=//p')"
  CHANNEL="$(printf '%s\n' "$META" | sed -n 's/^channel=//p')"
fi

if $IS_X && [ -z "$VIDEO_ID" ]; then
  # X/Twitter via gallery-dl
  need gallery-dl
  echo ">> X URL — resolving via gallery-dl: $URL"
  VIDEO_ID="$(printf '%s' "$URL" | grep -oE 'status(es)?/[0-9]+' | grep -oE '[0-9]+' | head -1 || true)"
  if [ -z "$VIDEO_ID" ] && GJ="$(gallery-dl -j "$URL" 2>/dev/null | head -1)"; then
    VIDEO_ID="$(printf '%s' "$GJ" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('tweet_id',''))" 2>/dev/null || true)"
    TITLE="$(printf '%s' "$GJ" | python3 -c "import json,sys; d=json.load(sys.stdin); print((d.get('content') or '')[:200])" 2>/dev/null || true)"
    CHANNEL="$(printf '%s' "$GJ" | python3 -c "import json,sys; d=json.load(sys.stdin); a=d.get('author') or {}; print(a.get('nick') or a.get('name') or '')" 2>/dev/null || true)"
  fi
  [ -n "$VIDEO_ID" ] || { echo "ERROR: could not resolve a tweet id from: $URL" >&2; exit 3; }
fi
# Fill X title/channel from gallery-dl metadata when yt-dlp gave none
if $IS_X && { [ -z "$TITLE" ] || [ -z "$CHANNEL" ] || [ "$CHANNEL" = "uploader" ]; } && command -v gallery-dl >/dev/null; then
  GJ="$(gallery-dl -j "$URL" 2>/dev/null | head -1 || true)"
  if [ -n "$GJ" ]; then
    XMETA="$(printf '%s' "$GJ" | python3 -c '
import json, sys
def walk(o):
    if isinstance(o, dict):
        if "author" in o or "tweet_id" in o:
            yield o
        for v in o.values(): yield from walk(v)
    elif isinstance(o, list):
        for v in o: yield from walk(v)
items = list(walk(json.load(sys.stdin)))
d = items[-1] if items else {}
a = d.get("author") or {}
print(d.get("tweet_id") or "")
print((d.get("content") or "").replace("\n", " ")[:200])
print(a.get("nick") or a.get("name") or "")
' 2>/dev/null || true)"
    if [ -n "$XMETA" ]; then
      [ -z "$VIDEO_ID" ] && VIDEO_ID="$(printf '%s\n' "$XMETA" | sed -n '1p')"
      [ -z "$TITLE" ] && TITLE="$(printf '%s\n' "$XMETA" | sed -n '2p')"
      if [ -z "$CHANNEL" ] || [ "$CHANNEL" = "uploader" ]; then
        CHANNEL="$(printf '%s\n' "$XMETA" | sed -n '3p')"
      fi
    fi
  fi
  TITLE="${TITLE:-x.com post}"
  CHANNEL="${CHANNEL:-x.com}"
  OUT_DIR="$OUT_ROOT/$VIDEO_ID"
  mkdir -p "$OUT_DIR"
  TXT="$OUT_DIR/$VIDEO_ID.txt"
else
  [ -n "$VIDEO_ID" ] || { echo "ERROR: yt-dlp could not resolve the URL (private, geo-blocked, or unsupported?)" >&2; exit 3; }
  OUT_DIR="$OUT_ROOT/$VIDEO_ID"
  mkdir -p "$OUT_DIR"
  TXT="$OUT_DIR/$VIDEO_ID.txt"
fi

if [ -s "$TXT" ] && ! $FORCE; then
  echo "== already transcribed: $TXT (use --force to redo)"
  exit 0
fi

# --- path 1: captions -------------------------------------------------------
echo ">> trying captions ($LANG_PREF)..."
yt-dlp --no-playlist --skip-download --no-warnings "${DL_ARGS[@]}" \
       --write-subs --write-auto-subs \
       --sub-langs "$LANG_PREF" --sub-format "vtt" \
       -o "$OUT_DIR/%(id)s.%(ext)s" "$URL" 2>/dev/null || true
VTT="$(find "$OUT_DIR" -maxdepth 1 -name "$VIDEO_ID.$LANG_PREF.vtt" | head -1)"
if [ -z "$VTT" ]; then
  # exact code missing (e.g. video tagged en-US only) — broaden once, keep best, delete the rest
  yt-dlp --no-playlist --skip-download --no-warnings "${DL_ARGS[@]}" \
         --write-subs --write-auto-subs \
         --sub-langs "$LANG_PREF.*" --sub-format "vtt" \
         -o "$OUT_DIR/%(id)s.%(ext)s" "$URL" 2>/dev/null || true
  VTT="$(find "$OUT_DIR" -maxdepth 1 -name "$VIDEO_ID.$LANG_PREF-*.vtt" | sort | head -1)"
  find "$OUT_DIR" -maxdepth 1 -name "$VIDEO_ID.*.vtt" ! -path "$VTT" -delete 2>/dev/null || true
fi
if [ -n "$VTT" ]; then
  echo ">> captions found: $(basename "$VTT") -> converting"
  python3 - "$VTT" "$TXT" <<'PY'
import re, sys
src, dst = sys.argv[1], sys.argv[2]
out, prev = [], None
for raw in open(src, encoding="utf-8", errors="replace"):
    line = raw.strip()
    if (not line or "-->" in line or line.startswith(("WEBVTT", "Kind:", "Language:", "NOTE", "STYLE"))
            or re.match(r"^\d+$", line)):
        continue
    line = re.sub(r"<[^>]+>", "", line)          # strip inline tags
    if line and line != prev:
        out.append(line); prev = line
text = " ".join(out)
open(dst, "w", encoding="utf-8").write(text + "\n")
print(f"   {len(text.split())} words")
PY
  if $IS_X; then SOURCE="x-captions"; else SOURCE="youtube-captions"; fi
else
  # --- path 2: Whisper fallback --------------------------------------------
  echo ">> no captions — falling back to Whisper"
  need ffmpeg; need whisper-cli
  MEDIA_DIR="${YT_MEDIA_DIR:-$SHARE_ROOT/media/video}"   # e.g. reclip's downloads on the share
  echo ">> checking $MEDIA_DIR for an existing download..."
  LOCAL_MEDIA="$(find "$MEDIA_DIR" -maxdepth 4 -iname "*$VIDEO_ID*" \
                 \( -iname '*.mp4' -o -iname '*.mkv' -o -iname '*.webm' -o -iname '*.m4a' \
                    -o -iname '*.mp3' -o -iname '*.flac' -o -iname '*.mov' -o -iname '*.avi' -o -iname '*.wav' \) \
                 2>/dev/null | head -1 || true)"
  WAV="$TMPD/in.wav"
  if [ -n "$LOCAL_MEDIA" ]; then
    echo ">> reusing existing file: $LOCAL_MEDIA"
    ffmpeg -y -loglevel error -i "$LOCAL_MEDIA" -ac 1 -ar 16000 "$WAV"
  elif $IS_X && command -v gallery-dl >/dev/null; then
    echo ">> downloading X media via gallery-dl..."
    gallery-dl "${DL_ARGS[@]}" \
      --filter "extension not in ('jpg','jpeg','png','webp','gif')" \
      -o "filename={tweet_id}.{extension}" \
      -D "$TMPD" "$URL"
    XMEDIA="$(find "$TMPD" -maxdepth 1 -type f \( -iname '*.mp4' -o -iname '*.m4a' -o -iname '*.mov' -o -iname '*.webm' \) | sort | tail -1)"
    [ -n "$XMEDIA" ] || { echo "ERROR: gallery-dl found no video (private tweet? set YT_COOKIES=/path/to/cookies.txt)" >&2; exit 5; }
    ffmpeg -y -loglevel error -i "$XMEDIA" -ac 1 -ar 16000 "$WAV"
    SOURCE_PREFIX="gallery-dl"
  else
    echo ">> not found — downloading audio (16 kHz mono)..."
    yt-dlp --no-playlist --no-warnings "${DL_ARGS[@]}" -x --audio-format wav \
           --postprocessor-args "ffmpeg:-ac 1 -ar 16000" \
           -o "$TMPD/%(id)s.%(ext)s" "$URL"
  fi
  [ -f "$WAV" ] || { echo "ERROR: audio acquisition failed" >&2; exit 5; }
  whisper_transcribe "$WAV" "$OUT_DIR/$VIDEO_ID"
  SOURCE="${SOURCE_PREFIX:+$SOURCE_PREFIX+}whisper-local"
fi

# --- provenance --------------------------------------------------------------
TRANSCRIBED_AT="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
python3 - "$VIDEO_ID" "$TITLE" "$CHANNEL" "$URL" "$SOURCE" "$LANG_PREF" "$TRANSCRIBED_AT" \
  > "$OUT_DIR/$VIDEO_ID.metadata.json" <<'PY'
import json, sys
keys = ["id", "title", "channel", "url", "source", "lang_pref", "transcribed_at"]
print(json.dumps(dict(zip(keys, sys.argv[1:])), indent=2, ensure_ascii=False))
PY

echo "== done: $TXT  (source: $SOURCE)"
rebuild_index > "$OUT_ROOT/INDEX.md" 2>/dev/null || true
