#!/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 "--- ANALYZING INPUT ---"
ffprobe -v quiet -print_format json -show_format -show_streams "$INPUT" > "$OUTDIR/mediainfo.json"

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))

# 1️⃣ Build Master Playlist
echo "--- BUILDING MASTER PLAYLIST ---"
MASTER="$OUTDIR/playlist.m3u8"
printf "#EXTM3U\n#EXT-X-VERSION:3\n\n" > "$MASTER"

# Subtitles Group
SUB_DATA=$(jq -r '.streams[] | select(.codec_type=="subtitle") | select(.codec_name | test("subrip|ass|webvtt|mov_text")) | @base64' "$OUTDIR/mediainfo.json")
s_count=0
for s in $SUB_DATA; do
    _jq() { echo "$s" | base64 --decode | jq -r "$1"; }
    S_IDX=$(_jq '.index')
    S_LANG=$(_jq '.tags.language // "und"')
    printf "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"%s\",LANGUAGE=\"%s\",AUTOSELECT=YES,DEFAULT=%s,URI=\"sub-titles/%s_%s.vtt\"\n" \
        "${S_LANG^^}_$S_IDX" "$S_LANG" "$([ $s_count -eq 0 ] && echo "YES" || echo "NO")" "$S_IDX" "$S_LANG" >> "$MASTER"
    s_count=$((s_count+1))
done

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

# Video Variants
printf "#EXT-X-STREAM-INF:BANDWIDTH=3200000,RESOLUTION=1920x1080,CODECS=\"avc1.64002a,mp4a.40.2\",AUDIO=\"audio\",SUBTITLES=\"subs\"\nvideo/1080p/stream.m3u8\n" >> "$MASTER"
printf "#EXT-X-STREAM-INF:BANDWIDTH=1700000,RESOLUTION=1280x720,CODECS=\"avc1.64002a,mp4a.40.2\",AUDIO=\"audio\",SUBTITLES=\"subs\"\nvideo/720p/stream.m3u8\n" >> "$MASTER"

# 2️⃣ Subtitles
echo "--- EXTRACTING SUBTITLES ---"
for s in $SUB_DATA; do
    _jq() { echo "$s" | base64 --decode | jq -r "$1"; }
    S_IDX=$(_jq '.index')
    S_LANG=$(_jq '.tags.language // "und"')
    echo "Processing Subtitle Track Index: $S_IDX ($S_LANG)"
    ffmpeg -y -i "$INPUT" -map 0:"$S_IDX" "$OUTDIR/sub-titles/${S_IDX}_${S_LANG}.vtt" -loglevel error
done

# 3️⃣ Video (NVIDIA NVENC)
echo "--- TRANSCODING VIDEO (NVIDIA GPU) ---"
echo "Processing Main Video Track (1080p @ 3000k)"
ffmpeg -y -hwaccel cuda -i "$INPUT" -map 0:v:0 -c:v h264_nvenc -b:v 3000k -g "$GOP" -f hls -hls_time 6 -hls_playlist_type vod -hls_segment_type fmp4 -hls_segment_filename "$OUTDIR/video/1080p/v_%d.m4s" "$OUTDIR/video/1080p/stream.m3u8" -loglevel error

echo "Processing Main Video Track (720p @ 1500k)"
ffmpeg -y -hwaccel cuda -i "$INPUT" -map 0:v:0 -c:v h264_nvenc -b:v 1500k -g "$GOP" -f hls -hls_time 6 -hls_playlist_type vod -hls_segment_type fmp4 -hls_segment_filename "$OUTDIR/video/720p/v_%d.m4s" "$OUTDIR/video/720p/stream.m3u8" -loglevel error

# 4️⃣ Audio (CPU AAC)
echo "--- TRANSCODING AUDIO (CPU) ---"
for s in $AUDIO_DATA; do
    _jq() { echo "$s" | base64 --decode | jq -r "$1"; }
    A_IDX=$(_jq '.index')
    A_LANG=$(_jq '.tags.language // "und"')
    A_TITLE=$(_jq '.tags.title // "Audio"')
    echo "Processing Audio Track Index: $A_IDX ($A_LANG) [$A_TITLE] @ 128k"
    
    mkdir -p "$OUTDIR/audio/${A_IDX}_${A_LANG}"
    ffmpeg -y -i "$INPUT" -map 0:"$A_IDX" -c:a aac -b:a 128k -f hls -hls_time 6 -hls_playlist_type vod -hls_segment_type fmp4 -hls_segment_filename "$OUTDIR/audio/${A_IDX}_${A_LANG}/a_%d.m4s" "$OUTDIR/audio/${A_IDX}_${A_LANG}/stream.m3u8" -loglevel error
done

echo "--- SUCCESS: TRANSCODE COMPLETE ---"
