#!/usr/bin/env bash
set -euo pipefail

if [[ $# -ne 1 ]]; then
  echo "Usage: $(basename "$0") <remote media directory>" >&2
  exit 1
fi

: "${WHISPER_ASR_HOST:?Set WHISPER_ASR_HOST to the SSH host running whisper-asr-webservice}"
: "${WHISPER_ASR_USER:?Set WHISPER_ASR_USER to the SSH user}"

WHISPER_ASR_SSH_PORT="${WHISPER_ASR_SSH_PORT:-22}"
WHISPER_ASR_SSH_KEY="${WHISPER_ASR_SSH_KEY:-}"
WHISPER_ASR_HTTP_PORT="${WHISPER_ASR_HTTP_PORT:-9000}"
WHISPER_LANGUAGE="${WHISPER_LANGUAGE:-en}"
REMOTE_ROOT="$1"

ssh_options=(-p "$WHISPER_ASR_SSH_PORT")
if [[ -n "$WHISPER_ASR_SSH_KEY" ]]; then
  ssh_options+=(-i "$WHISPER_ASR_SSH_KEY")
fi
remote="${WHISPER_ASR_USER}@${WHISPER_ASR_HOST}"
printf -v remote_root_q '%q' "$REMOTE_ROOT"
printf -v language_q '%q' "$WHISPER_LANGUAGE"
printf -v http_port_q '%q' "$WHISPER_ASR_HTTP_PORT"

echo "Checking the remote media directory and Whisper service..."
if ! ssh "${ssh_options[@]}" "$remote" "test -d $remote_root_q"; then
  echo "Remote directory does not exist: $REMOTE_ROOT" >&2
  exit 1
fi

if ! ssh "${ssh_options[@]}" "$remote" \
  "curl -fsS --connect-timeout 5 http://localhost:${WHISPER_ASR_HTTP_PORT}/docs" \
  >/dev/null; then
  echo "whisper-asr-webservice is not reachable on the remote host." >&2
  exit 1
fi

ssh "${ssh_options[@]}" "$remote" \
  "bash -s -- $remote_root_q $language_q $http_port_q" <<'REMOTE_SCRIPT'
set -euo pipefail

root="$1"
language="$2"
http_port="$3"
asr_url="http://localhost:${http_port}/asr?task=transcribe&language=${language}&output=srt"

find_media() {
  find "$root" -type f \
    \( -iname '*.mp4' -o -iname '*.m4v' -o -iname '*.mov' -o -iname '*.mkv' \) \
    -print0 | sort -z
}

total=0
while IFS= read -r -d '' unused_path; do
  total=$((total + 1))
done < <(find_media)

processed=0
skipped=0
failed=0
index=0

echo "Directory: $root"
echo "Media files: $total"

while IFS= read -r -d '' media_path; do
  index=$((index + 1))
  directory="$(dirname "$media_path")"
  filename="$(basename "$media_path")"
  srt_path="${directory}/${filename%.*}.srt"
  temporary_path="${srt_path}.tmp"

  echo "[$index/$total] $filename"
  if [[ -f "$srt_path" ]]; then
    echo "  skipped: SRT already exists"
    skipped=$((skipped + 1))
    continue
  fi

  http_code="$({
    curl -sS --connect-timeout 10 \
      -F "audio_file=@${media_path}" \
      "$asr_url" -o "$temporary_path" -w '%{http_code}'
  } || printf '000')"

  if [[ "$http_code" == "200" && -s "$temporary_path" ]]; then
    mv "$temporary_path" "$srt_path"
    processed=$((processed + 1))
    echo "  saved: $srt_path"
  else
    rm -f "$temporary_path"
    failed=$((failed + 1))
    echo "  failed: HTTP $http_code" >&2
  fi
done < <(find_media)

echo "Processed: $processed"
echo "Skipped: $skipped"
echo "Failed: $failed"
REMOTE_SCRIPT
