#!/bin/bash
set -euo pipefail

INPUT="$1"
BASENAME=$(basename "$INPUT" | sed 's/\.[^.]*$//')
OUTDIR_NAME="${BASENAME}-Transcode"
mkdir -p "$OUTDIR_NAME/sub-titles" "$OUTDIR_NAME/video/1080p" "$OUTDIR_NAME/video/720p" "$OUTDIR_NAME/audio"
OUTDIR=$(realpath "$OUTDIR_NAME")

# -------------------------------
# 0️⃣ Analyze Input
# -------------------------------
echo "[0/5] Analyzing Input..."
# Get exact FPS for GOP calculation
FPS=$(ffprobe -v 0 -select_streams v:0 -show_entries stream=r_frame_rate -of default=noprint_wrappers=1:nokey=1 "$INPUT" | bc -l)
GOP=$(printf "%.0f" $(echo "$FPS * 6" | bc -l)) # 6-second segments

ffprobe -v quiet -print_format json -show_format -show_streams "$INPUT" > "$OUTDIR/mediainfo.json"

# -------------------------------
# 1️⃣ Build Akamai/JW-Ready Master Playlist
# -------------------------------
echo "[1/5] Building Master Playlist..."
MASTER="$OUTDIR/playlist.m3u8"
# VERSION 4 is required for modern Subtitle/Audio handling
printf "#EXTM3U\n#EXT-X-VERSION:4\n\n" > "$MASTER"

# AUDIO GROUPING
AUDIO_DATA=$(jq -r '.streams[] | select(.codec_type=="audio") | @base64' "$OUTDIR/mediainfo.json")
count=0
for s in $AUDIO_DATA; do
    _jq() { echo "$s" | base64 --decode | jq -r "$1"; }
    LANG=$(_jq '.tags.language // "und"')
    TITLE=$(_jq '.tags.title // "Audio '$count'"')
    # Use a clean ID for the group
    printf "#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"aac_audio\",NAME=\"%s\",LANGUAGE=\"%s\",DEFAULT=%s,AUTOSELECT=YES,URI=\"audio/%s_%s/stream.m3u8\"\n" \
        "$TITLE" "$LANG" "$([ $count -eq 0 ] && echo "YES" || echo "NO")" "$count" "$LANG" >> "$MASTER"
    count=$((count+1))
done

# SUBTITLE GROUPING
SUB_DATA=$(jq -r '.streams[] | select(.codec_type=="subtitle") | @base64' "$OUTDIR/mediainfo.json")
HAS_SUBS=0
sub_idx=0
for s in $SUB_DATA; do
    _jq() { echo "$s" | base64 --decode | jq -r "$1"; }
    CODEC=$(_jq '.codec_name')
    # Only WebVTT is supported natively in HLS/JWPlayer
    if [[ "$CODEC" =~ (subrip|ass|ssa|mov_text|webvtt) ]]; then
        LANG=$(_jq '.tags.language // "und"')
        NAME=$(echo "$LANG" | tr '[:lower:]' '[:upper:]')
        printf "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"webvtt_subs\",NAME=\"%s\",LANGUAGE=\"%s\",DEFAULT=%s,AUTOSELECT=YES,FORCED=NO,URI=\"sub-titles/%s_%s.vtt\"\n" \
            "$NAME" "$LANG" "$([ $HAS_SUBS -eq 0 ] && echo "YES" || echo "NO")" "$sub_idx" "$LANG" >> "$MASTER"
        HAS_SUBS=$((HAS_SUBS+1))
    fi
    sub_idx=$((sub_idx+1))
done

printf "\n" >> "$MASTER"

# VIDEO VARIANTS (Linking Audio and Subtitle Groups)
for profile in "1080p:5000:1920x1080" "720p:2800:1280x720"; do
    RES=$(echo $profile | cut -d: -f1)
    BW=$(echo $profile | cut -d: -f2)
    DIM=$(echo $profile | cut -d: -f3)
    
    INF="#EXT-X-STREAM-INF:BANDWIDTH=$((BW*1000)),RESOLUTION=$DIM,CODECS=\"avc1.640029,mp4a.40.2\",AUDIO=\"aac_audio\""
    [ "$HAS_SUBS" -gt 0 ] && INF="$INF,SUBTITLES=\"webvtt_subs\""
    
    printf "%s\nvideo/%s/stream.m3u8\n" "$INF" "$RES" >> "$MASTER"
done

# -------------------------------
# 2️⃣ Extract Subtitles (Fixed for JW Player)
# -------------------------------
echo "[2/5] Extracting Subtitles..."
idx=0
while IFS=, read -r s_idx s_codec s_lang; do
    s_lang=${s_lang:-und}
    if [[ "$s_codec" =~ (subrip|ass|ssa|mov_text|webvtt) ]]; then
        # Ensure UTF-8 and clean WebVTT header
        ffmpeg -y -i "$INPUT" -map 0:"$s_idx" -f webvtt "$OUTDIR/sub-titles/${idx}_${s_lang}.vtt" -loglevel error
    fi
    idx=$((idx+1))
done < <(ffprobe -v error -select_streams s -show_entries stream=index,codec_name:stream_tags=language -of csv=p=0 "$INPUT")

# -------------------------------
# 3️⃣ Process Video (Akamai/HLS.js Aligned)
# -------------------------------
echo "[3/5] Processing Video..."
for profile in "1080p:5000:1080" "720p:2800:720"; do
    RES=$(echo $profile | cut -d: -f1)
    BW=$(echo $profile | cut -d: -f2)
    TARGET_H=$(echo $profile | cut -d: -f3)
    mkdir -p "$OUTDIR/video/$RES"

    # Strict GOP and IDR frames are mandatory for Akamai
    ffmpeg -y -hwaccel cuda -i "$INPUT" \
        -map 0:v:0 -c:v h264_nvenc \
        -profile:v high -level:v 4.1 -pix_fmt yuv420p \
        -b:v "${BW}k" -maxrate:v "${BW}k" -bufsize:v "${BW}k" \
        -rc cbr -g "$GOP" -keyint_min "$GOP" -sc_threshold 0 \
        -vf "scale=trunc(oh*a/2)*2:$TARGET_H" -an \
        -f hls -hls_time 6 -hls_playlist_type vod \
        -hls_flags independent_segments \
        -hls_segment_filename "$OUTDIR/video/$RES/file%d.ts" \
        "$OUTDIR/video/$RES/stream.m3u8" -loglevel error
done

# -------------------------------
# 4️⃣ Process Audio (Strictly Aligned)
# -------------------------------
echo "[4/5] Processing Audio..."
idx=0
for s in $AUDIO_DATA; do
    _jq() { echo "$s" | base64 --decode | jq -r "$1"; }
    A_LANG=$(_jq '.tags.language // "und"')
    A_IDX=$(_jq '.index')
    A_DIR="$OUTDIR/audio/${idx}_${A_LANG}"
    mkdir -p "$A_DIR"
    
    # Audio segments must have the same duration as video segments
    ffmpeg -y -i "$INPUT" -map 0:"$A_IDX" -c:a aac -b:a 128k -ar 48000 -vn \
        -f hls -hls_time 6 -hls_playlist_type vod \
        -hls_flags independent_segments \
        -hls_segment_filename "$A_DIR/file%d.ts" \
        "$A_DIR/stream.m3u8" -loglevel error
    idx=$((idx+1))
done

echo "[5/5] Success! Transcode complete and optimized for JW/Akamai."
