#!/usr/bin/env bash
# ============================================================================
# yt-transcribe-watcher — watch the reclip download dir and transcribe new
# files automatically. Runs every 5 min via launchd (nix-darwin
# launchd.user.agents."yt-transcribe-watcher") or by hand: `yt-transcribe-watcher`
# (installed on PATH / ~/.local/bin by the dotfiles rebuild).
#
# For each media file in media/video without a sidecar .txt:
#   - skips files still being written (mtime < 120 s ago)
#   - marks work with <stem>.transcribing so overlapping runs can't double up
#   - calls yt-transcribe in file mode (ffmpeg -> whisper-cli, model reused
#     from OpenSuperWhisper)
# Files downloaded by reclip carry no captions, so this is always Whisper.
# Env: YT_MEDIA_DIR (scan dir), YT_DRY_RUN=1 (log-only pass), YT_COOKIES,
#      WHISPER_MODEL — all passed through to yt-transcribe.
# ============================================================================
set -uo pipefail

SHARE_ROOT="${YT_SHARE_ROOT:-/Volumes/data}"
SCAN_DIR="${YT_MEDIA_DIR:-$SHARE_ROOT/media/video}"
MAIN="$(dirname "${BASH_SOURCE[0]}")/yt-transcribe"
STATE_DIR="$HOME/.local/state/yt-transcribe"
LOG="$STATE_DIR/watcher.log"
mkdir -p "$STATE_DIR"

[ -d "$SCAN_DIR" ] || exit 0            # share not mounted — silent, retry next tick
[ -x "$MAIN" ] || { echo "missing $MAIN" >&2; exit 1; }

log() {
  printf '[%s] %s\n' "$(date '+%F %T')" "$*" >> "$LOG" 2>/dev/null || true
  # keep the log bounded
  if [ -f "$LOG" ] && [ "$(stat -f %z "$LOG" 2>/dev/null || echo 0)" -gt 512000 ]; then
    tail -c 256000 "$LOG" > "$LOG.tmp" 2>/dev/null && mv "$LOG.tmp" "$LOG" 2>/dev/null || true
  fi
}

shopt -s nullglob
COUNT=0
while IFS= read -r -d '' f; do
  STEM="${f%.*}"
  TXT="$STEM.txt"
  MARKER="$STEM.transcribing"
  [ -s "$TXT" ] && continue
  NOW="$(date +%s)"
  if [ -e "$MARKER" ]; then
    MM="$(stat -f %m "$MARKER" 2>/dev/null || stat -c %Y "$MARKER" 2>/dev/null || echo 0)"
    if [ $((NOW - MM)) -gt 10800 ]; then
      log "stale marker purged (crashed run): $(basename "$MARKER")"
      rm -f "$MARKER"
    else
      continue
    fi
  fi
  MTIME="$(stat -f %m "$f" 2>/dev/null || stat -c %Y "$f" 2>/dev/null || echo 0)"
  if [ $((NOW - MTIME)) -lt 120 ]; then
    log "skip (still downloading): $(basename "$f")"
    continue
  fi
  if [ "${YT_DRY_RUN:-0}" = "1" ]; then
    log "DRY-RUN would transcribe: $f"
    continue
  fi
  touch "$MARKER" 2>/dev/null || continue
  COUNT=$((COUNT + 1))
  log "transcribing: $f"
  if "$MAIN" "$f" >>"$LOG" 2>&1; then
    log "ok: $TXT"
    "$MAIN" --index >/dev/null 2>&1 || true
  else
    log "FAILED: $f"
  fi
  rm -f "$MARKER"
done < <(find "$SCAN_DIR" -maxdepth 3 -type f \
         \( -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' -o -iname '*.ts' \) \
         -print0 2>/dev/null)

[ "$COUNT" -gt 0 ] && log "done: $COUNT file(s) transcribed"
exit 0
