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

# -------------------------------
# 1️⃣ Master Playlist Generation
# -------------------------------
echo "[1/5] Building Master Playlist..."
MASTER="$OUTDIR/playlist.m3u8"
printf "#EXTM3U\n#EXT-X-VERSION:3\n\n" > "$MASTER"

# AUDIO
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 Track '$count'"')
    printf "#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"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

# SUBTITLES
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')
    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=\"subs\",NAME=\"%s (%s)\",LANGUAGE=\"%s\",DEFAULT=%s,AUTOSELECT=YES,FORCED=NO,URI=\"sub-titles/%s_%s.vtt\"\n" \
            "$NAME" "$sub_idx" "$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
for profile in "1080p:4500" "720p:2500"; do
    RES=${profile%%:*}
    BW=${profile##*:}
    V_RES="$([ "$RES" == "1080p" ] && echo "1920x1080" || echo "1280x720")"
    INF="#EXT-X-STREAM-INF:BANDWIDTH=$((BW*1024)),RESOLUTION=$V_RES,CODECS=\"avc1.640029,mp4a.40.2\",AUDIO=\"audio\""
    [ "$HAS_SUBS" -gt 0 ] && INF="$INF,SUBTITLES=\"subs\""
    printf "%s\nvideo/%s/stream.m3u8\n" "$INF" "$RES" >> "$MASTER"
done

# -------------------------------
# 2️⃣ Extract Subtitles
# -------------------------------
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
        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 (Fix: hls_playlist_type vod)
# -------------------------------
echo "[3/5] Processing Video..."
for profile in "1080p:4500" "720p:2500"; do
    RES=${profile%%:*}
    TARGET_BW=${profile##*:}
    TARGET_H="$([ "$RES" == "1080p" ] && echo 1080 || echo 720)"
    mkdir -p "$OUTDIR/video/$RES"

    echo "  Encoding $RES (H.264 High 4.1 via NVENC)..."
    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 "${TARGET_BW}k" -maxrate:v "${TARGET_BW}k" -bufsize:v "$((TARGET_BW*2))k" \
        -g 60 -keyint_min 60 -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
# -------------------------------
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"
    
    ffmpeg -y -i "$INPUT" -map 0:"$A_IDX" -c:a aac -b:a 160k -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! Fixed VOD parameter and forced H.264 High 4.1."
