#!/usr/bin/env bash

set -euo pipefail

srt=false
if [[ ${1:-} == --srt ]]; then
    srt=true
    shift
fi
if [[ $# == 1 && ($1 == -h || $1 == --help) ]]; then
    echo "Usage: ${0##*/} [--srt] AUDIO_FILE"
    echo 'Transcribe audio using OPENROUTER_API_KEY; print the text to stdout.'
    echo '  --srt  Print SRT subtitles in short cues using word timestamps instead.'
    exit 0
fi
if [[ $# != 1 ]]; then
    echo "Usage: ${0##*/} [--srt] AUDIO_FILE" >&2
    exit 1
fi
if [[ ! -f $1 || ! -r $1 ]]; then
    echo "Cannot read audio file: $1" >&2
    exit 1
fi
export OPENROUTER_API_KEY
OPENROUTER_API_KEY="$(op read "op://API Keys/openrouter-mai-transcribe-2/credential")"
: "${OPENROUTER_API_KEY:?Set OPENROUTER_API_KEY first}"
dependencies=(ffmpeg curl jq base64 mktemp)
if "$srt"; then
    dependencies+=(python3)
fi
for tool in "${dependencies[@]}"; do
    command -v "$tool" >/dev/null || {
        echo "Missing dependency: $tool" >&2
        exit 1
    }
done

tmp=$(mktemp -d)
trap 'rm -rf -- "$tmp"' EXIT
trap 'exit 130' INT
trap 'exit 143' TERM

# Normalize any FFmpeg-readable audio (or the first audio track in a video).
ffmpeg -nostdin -hide_banner -loglevel error -i "$(realpath -- "$1")" \
    -map 0:a:0 -ac 1 -ar 16000 -c:a libmp3lame -b:a 64k "$tmp/audio.mp3"

# Keep large audio payloads out of shell arguments (which have a size limit).
base64 <"$tmp/audio.mp3" | tr -d '\n\r' >"$tmp/audio.b64"
jq -n --rawfile data "$tmp/audio.b64" --argjson srt "$srt" \
    '{model: "microsoft/mai-transcribe-2", input_audio: {data: $data, format: "mp3"}}
     + (if $srt then {response_format: "verbose_json", timestamp_granularities: ["segment", "word"]}
        else {} end)' \
    >"$tmp/request.json"

curl --silent --show-error --fail-with-body \
    https://openrouter.ai/api/v1/audio/transcriptions \
    -H "Authorization: Bearer $OPENROUTER_API_KEY" \
    -H 'Content-Type: application/json' \
    --data-binary @"$tmp/request.json" -o "$tmp/response.json" || {
    cat "$tmp/response.json" >&2
    exit 1
}
if "$srt"; then
    python3 "$(dirname -- "$(realpath -- "$0")")/subtitles.py" "$tmp/response.json"
else
    jq -r 'if (.text | type) == "string" then .text
       else error("Transcription failed: " + (.error.message // tojson)) end' \
        "$tmp/response.json"
fi
