#!/bin/bash
set -euo pipefail

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

echo "========================================"
echo "Processing: $INPUT"
echo "Output: $OUTDIR"
echo "========================================"

mkdir -p "$OUTDIR/video"
mkdir -p "$OUTDIR/audio"
mkdir -p "$OUTDIR/sub-titles"

# -------------------------------
# 1️⃣ Generate mediainfo.json
# -------------------------------
echo "[0/5] Generating mediainfo.json"
ffprobe -v quiet -print_format json -show_format -show_streams "$INPUT" > "$OUTDIR/mediainfo.json"

# -------------------------------
# 2️⃣ Extract subtitles
# -------------------------------
echo "[1/5] Extracting subtitles"
SUBS=$(jq -r '.streams[] | select(.codec_type=="subtitle") | @base64' "$OUTDIR/mediainfo.json")
IDX=0
for s in $SUBS; do
    _jq() { echo "$s" | base64 --decode | jq -r "$1"; }
    CODEC=$(_jq '.codec_name')
    LANG=$(_jq '.tags.language // "und"')
    
    # Set proper filename extension
    if [[ "$CODEC" == "subrip" || "$CODEC" == "ass" || "$CODEC" == "ssa" ]]; then
        EXT="srt"
    else
        EXT="sub"  # image-based (dvd, hdmv)
    fi
    
    FNAME="$OUTDIR/sub-titles/${IDX}_${LANG}.${EXT}"
    
    ffmpeg -y -i "$INPUT" -map 0:$(_jq '.index') "$FNAME"
    echo "  Extracted $FNAME"
    
    IDX=$((IDX+1))
done

# -------------------------------
# 3️⃣ Encode video streams (GPU)
# -------------------------------
echo "[2/5] Encoding video streams"

VIDEO_STREAMS=$(jq -r '.streams[] | select(.codec_type=="video") | @base64' "$OUTDIR/mediainfo.json")
IDX=0
for v in $VIDEO_STREAMS; do
    _jq() { echo "$v" | base64 --decode | jq -r "$1"; }
    # You can add multiple resolutions if needed
    RES="1080p"
    BITRATE="2000k"
    mkdir -p "$OUTDIR/video/$RES"
    
    WIDTH=1920
    HEIGHT=1080
    
    ffmpeg -y -hwaccel cuda -i "$INPUT" \
        -map 0:v:$(_jq '.index') -c:v h264_nvenc -b:v "$BITRATE" \
        -vf "scale=$WIDTH:$HEIGHT,setsar=1" -pix_fmt yuv420p \
        -hls_time 600 -hls_list_size 0 -hls_flags append_list+independent_segments \
        "$OUTDIR/video/$RES/stream.m3u8"
    
    echo "  $RES @ $BITRATE encoded"
    IDX=$((IDX+1))
done

# -------------------------------
# 4️⃣ Encode audio streams
# -------------------------------
echo "[3/5] Encoding audio streams"
AUDIO_STREAMS=$(jq -r '.streams[] | select(.codec_type=="audio") | @base64' "$OUTDIR/mediainfo.json")
IDX=0
for a in $AUDIO_STREAMS; do
    _jq() { echo "$a" | base64 --decode | jq -r "$1"; }
    LANG=$(_jq '.tags.language // "und"')
    FNAME="$OUTDIR/audio/${IDX}_${LANG}.aac"
    mkdir -p "$(dirname "$FNAME")"
    ffmpeg -y -i "$INPUT" -map 0:$(_jq '.index') -c:a aac -b:a 128k -hls_time 600 -hls_list_size 0 -hls_flags append_list "$OUTDIR/audio/${IDX}_${LANG}.m3u8"
    echo "  $FNAME HLS playlist generated"
    IDX=$((IDX+1))
done

# -------------------------------
# 5️⃣ Master playlist
# -------------------------------
echo "[4/5] Creating master playlist"
MASTER="$OUTDIR/playlist.m3u8"
rm -f "$MASTER"

echo "#EXTM3U" >> "$MASTER"

# Map video playlists
VIDEO_HLS=$(find "$OUTDIR/video" -name "*.m3u8" | sort)
for v in $VIDEO_HLS; do
    # Use BANDWIDTH estimate (simple)
    BITRATE=2000000
    RES=$(basename $(dirname "$v"))
    echo "#EXT-X-STREAM-INF:BANDWIDTH=$BITRATE,RESOLUTION=${RES%p}x$(( ${RES%p} * 9 / 16 ))" >> "$MASTER"
    echo "video/$RES/stream.m3u8" >> "$MASTER"
done

# Map audio playlists
AUDIO_HLS=$(find "$OUTDIR/audio" -name "*.m3u8" | sort)
for a in $AUDIO_HLS; do
    LANG=$(basename "$a" | cut -d_ -f2 | cut -d. -f1)
    echo "#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"audio\",NAME=\"$LANG\",DEFAULT=YES,AUTOSELECT=YES,URI=\"$a\"" >> "$MASTER"
done

# Map subtitle tracks
SUB_HLS=$(find "$OUTDIR/sub-titles" -name "*.srt" -o -name "*.sub" | sort)
for s in $SUB_HLS; do
    NAME=$(basename "$s")
    TYPE="SUBTITLES"
    echo "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"$NAME\",DEFAULT=NO,AUTOSELECT=YES,LANGUAGE=\"$NAME\",URI=\"$s\"" >> "$MASTER"
done

echo "[5/5] Conversion complete for $INPUT"
echo "Master playlist: $MASTER"
echo "========================================"
