#!/bin/bash
set -euo pipefail

if [ -z "${1:-}" ]; then
    echo "Usage: $0 input_file.mkv"
    exit 1
fi

INPUT="$1"
BASENAME=$(basename "$INPUT" | sed 's/\.[^.]*$//')
OUTDIR="${BASENAME}-Transcode"
TEMPDIR="temp_raw_${BASENAME}"

# Create Directory Structure
mkdir -p "$OUTDIR/video/1080p" "$OUTDIR/video/720p" "$OUTDIR/audio" "$OUTDIR/sub-titles" "$TEMPDIR"

# -------------------------------
# 1️⃣ Encode Video (Multi-Resolution)
# -------------------------------
echo "[1/4] Encoding Video (1080p & 720p)..."
# 1080p
ffmpeg -y -hwaccel cuda -i "$INPUT" -map 0:v:0 -c:v h264_nvenc -preset p4 -b:v 6000k \
    -g 144 -keyint_min 144 -sc_threshold 0 -vf "scale=1920:1080" -an \
    -movflags +faststart "$TEMPDIR/v1080.mp4" -loglevel error

# 720p
ffmpeg -y -hwaccel cuda -i "$INPUT" -map 0:v:0 -c:v h264_nvenc -preset p4 -b:v 3000k \
    -g 144 -keyint_min 144 -sc_threshold 0 -vf "scale=1280:720" -an \
    -movflags +faststart "$TEMPDIR/v720.mp4" -loglevel error

# -------------------------------
# 2️⃣ Encode ALL Audio Tracks
# -------------------------------
echo "[2/4] Processing all Audio tracks..."
AUDIO_INPUTS=""
# Get index, language, and title for audio
while IFS=, read -r a_idx a_lang a_title; do
    a_lang=${a_lang:-und}
    a_title=${a_title:-Stream}
    
    # Create unique filename using index
    A_FILE="audio_${a_idx}_${a_lang}.mp4"
    A_PLAYLIST="audio_${a_idx}_${a_lang}.m3u8"
    
    echo "  -> Encoding Audio Track $a_idx ($a_lang)..."
    ffmpeg -y -i "$INPUT" -map 0:"$a_idx" -c:a aac -b:a 128k -ar 48000 -vn \
        -movflags +faststart "$TEMPDIR/$A_FILE" -loglevel error
    
    # Add to Shaka command
    AUDIO_INPUTS+="in=$TEMPDIR/$A_FILE,stream=audio,output=$OUTDIR/audio/$A_FILE,playlist_name=audio/$A_PLAYLIST,hls_group_id=audio,hls_name=${a_lang^^}_${a_idx} "
done <<< "$(ffprobe -v error -select_streams a -show_entries stream=index:stream_tags=language,title -of csv=p=0 "$INPUT")"

# -------------------------------
# 3️⃣ Process ALL Subtitle Tracks
# -------------------------------
echo "[3/4] Processing all Subtitle tracks..."
SUB_INPUTS=""
while IFS=, read -r s_idx s_lang; do
    s_lang=${s_lang:-und}
    
    # Extract to VTT
    ffmpeg -y -i "$INPUT" -map 0:"$s_idx" "$TEMPDIR/sub_${s_idx}.vtt" -loglevel error
    
    # Create unique filename using index
    S_FILE="${s_idx}_${s_lang}.mp4"
    S_PLAYLIST="${s_idx}_${s_lang}.m3u8"
    
    # Add to Shaka command
    SUB_INPUTS+="in=$TEMPDIR/sub_${s_idx}.vtt,stream=text,output=$OUTDIR/sub-titles/$S_FILE,playlist_name=sub-titles/$S_PLAYLIST,hls_group_id=subs,hls_name=${s_lang^^}_${s_idx} "
done <<< "$(ffprobe -v error -select_streams s -show_entries stream=index:stream_tags=language -of csv=p=0 "$INPUT")"

# -------------------------------
# 4️⃣ Package with Shaka
# -------------------------------
echo "[4/4] Packaging with Shaka (Byte-Range)..."

packager \
  in="$TEMPDIR/v1080.mp4",stream=video,output="$OUTDIR/video/1080p/stream.mp4",playlist_name="video/1080p/stream.m3u8" \
  in="$TEMPDIR/v720.mp4",stream=video,output="$OUTDIR/video/720p/stream.mp4",playlist_name="video/720p/stream.m3u8" \
  $AUDIO_INPUTS \
  $SUB_INPUTS \
  --hls_master_playlist_output "$OUTDIR/playlist.m3u8" \
  --hls_playlist_type VOD \
  --segment_duration 6 \
  --segment_sap_aligned

rm -rf "$TEMPDIR"
echo "Done! All streams packaged successfully."
