#!/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..."
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)) # 6s Segments for VOD stability

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

# -------------------------------
# 1️⃣ Master Playlist (HLS Version 6/7)
# -------------------------------
echo "[1/5] Building Master Playlist..."
MASTER="$OUTDIR/playlist.m3u8"
printf "#EXTM3U\n#EXT-X-VERSION:6\n#EXT-X-INDEPENDENT-SEGMENTS\n\n" > "$MASTER"

# AUDIO GROUP
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 // "English"')
    printf "#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"audio\",NAME=\"%s\",LANGUAGE=\"%s\",AUTOSELECT=YES,DEFAULT=%s,URI=\"audio/%s_%s/stream.m3u8\"\n" \
        "$TITLE" "$LANG" "$([ $count -eq 0 ] && echo "YES" || echo "NO")" "$count" "$LANG" >> "$MASTER"
    count=$((count+1))
done

# VIDEO RENDITIONS (Using Version 6 syntax like your example)
for profile in "1080p:6000:1920x1080" "720p:3000:1280x720"; do
    RES=$(echo $profile | cut -d: -f1)
    BW=$(echo $profile | cut -d: -f2)
    DIM=$(echo $profile | cut -d: -f3)
    printf "#EXT-X-STREAM-INF:BANDWIDTH=$((BW*1000)),CODECS=\"avc1.64002a,mp4a.40.2\",RESOLUTION=$DIM,AUDIO=\"audio\"\n" >> "$MASTER"
    printf "video/%s/stream.m3u8\n" "$RES" >> "$MASTER"
done

# -------------------------------
# 2️⃣ Extract Subtitles (WebVTT)
# -------------------------------
echo "[2/5] Extracting Subtitles..."
idx=0
while IFS=, read -r s_idx s_codec s_lang; do
    s_lang=${s_lang:-und}
    ffmpeg -y -i "$INPUT" -map 0:"$s_idx" -f webvtt "$OUTDIR/sub-titles/${idx}_${s_lang}.vtt" -loglevel error
    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 (Fragmented MP4 / HLS v7)
# -------------------------------
echo "[3/5] Processing Video (fMP4)..."
for profile in "1080p:6000:1080" "720p:3000: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"

    # Use hls_segment_type fmp4 for the modern version 7 behavior
    ffmpeg -y -hwaccel cuda -i "$INPUT" \
        -map 0:v:0 -c:v h264_nvenc \
        -profile:v high -level:v 4.2 -pix_fmt yuv420p \
        -b:v "${BW}k" -maxrate:v "${BW}k" -bufsize:v "$((BW*2))k" \
        -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_segment_type fmp4 \
        -hls_flags independent_segments \
        -hls_segment_filename "$OUTDIR/video/$RES/v_%d.m4s" \
        -hls_fmp4_init_filename "init.mp4" \
        "$OUTDIR/video/$RES/stream.m3u8" -loglevel error
done

# -------------------------------
# 4️⃣ Process Audio (Fragmented MP4)
# -------------------------------
echo "[4/5] Processing Audio (fMP4)..."
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"
    
    ffmpeg -y -i "$INPUT" -map 0:"$A_IDX" -c:a aac -b:a 160k -ar 48000 -vn \
        -f hls -hls_time 6 -hls_playlist_type vod \
        -hls_segment_type fmp4 \
        -hls_flags independent_segments \
        -hls_segment_filename "$A_DIR/a_%d.m4s" \
        -hls_fmp4_init_filename "init.mp4" \
        "$A_DIR/stream.m3u8" -loglevel error
    idx=$((idx+1))
done

echo "[5/5] Success! fMP4 HLS Version 7 generated."
