#!/usr/bin/env bash

set -euo pipefail

# ------------------------------------------------------------
# reel-srt
#
# Generate Facebook-ready subtitles from a video using Whisper.
#
# Usage:
#   reel-srt video.mp4
#   reel-srt video.mp4 ~/Videos/Captions
# ------------------------------------------------------------

WHISPER_VENV="$HOME/whisper-srt"

MODEL="turbo"
LANGUAGE="en"
LOCALE="en_GB"

if [[ $# -lt 1 ]]; then
    echo "Usage: reel-srt <video-file> [output-directory]"
    exit 1
fi

INPUT="$1"

if [[ ! -f "$INPUT" ]]; then
    echo "Error: File not found:"
    echo "$INPUT"
    exit 1
fi

# Default output directory is the same directory as the video.
INPUT_DIR="$(cd "$(dirname "$INPUT")" && pwd)"
OUTPUT_DIR="${2:-$INPUT_DIR}"

mkdir -p "$OUTPUT_DIR"

FILENAME="$(basename "$INPUT")"
BASENAME="${FILENAME%.*}"

TEMP_SRT="$OUTPUT_DIR/$BASENAME.srt"
FINAL_SRT="$OUTPUT_DIR/$BASENAME.$LOCALE.srt"
US_SRT="$OUTPUT_DIR/$BASENAME.en_US.srt"

if [[ ! -f "$WHISPER_VENV/bin/activate" ]]; then
    echo "Error: Whisper virtual environment not found:"
    echo "$WHISPER_VENV"
    exit 1
fi

echo
echo "========================================"
echo " Reel SRT Generator"
echo "========================================"
echo "Input : $INPUT"
echo "Model : $MODEL"
echo "Output: $FINAL_SRT"
echo "========================================"
echo

source "$WHISPER_VENV/bin/activate"

whisper "$INPUT" \
    --model "$MODEL" \
    --language "$LANGUAGE" \
    --task transcribe \
    --output_format srt \
    --output_dir "$OUTPUT_DIR"

if [[ -f "$TEMP_SRT" ]]; then
    mv -f "$TEMP_SRT" "$FINAL_SRT"
else
    echo
    echo "Error: Whisper completed but the SRT file was not found:"
    echo "$TEMP_SRT"
    exit 1
fi

# Create a US English caption filename pointing to the
# British English master file.
ln -sf "$(basename "$FINAL_SRT")" "$US_SRT"

echo
echo "========================================"
echo " Done!"
echo "========================================"
echo
echo "British English: $FINAL_SRT"
echo "US English     : $US_SRT"
echo

# Automatically open the master subtitle file in Geany.
if command -v geany >/dev/null 2>&1; then
    geany "$FINAL_SRT" >/dev/null 2>&1 &
else
    echo "Note: Geany was not found."
fi
