#!/usr/bin/env bash

shopt -s nullglob

rename_tracks() {
    local f="$1"
    local i

    # Video tracks
    i=1
    while mkvpropedit "$f" \
        --edit "track:v${i}" \
        --set name="Animex" >/dev/null 2>&1; do

        echo "✅ $f -> track:v${i} name=Animex"
        ((i++))
    done

    # Audio tracks
    i=1
    while mkvpropedit "$f" \
        --edit "track:a${i}" \
        --set name="Animex" >/dev/null 2>&1; do

        echo "✅ $f -> track:a${i} name=Animex"
        ((i++))
    done

    # Existing subtitle tracks
    i=1
    while mkvpropedit "$f" \
        --edit "track:s${i}" \
        --set name="Animex" \
        --set language=qad >/dev/null 2>&1; do

        echo "✅ $f -> track:s${i} name=Animex language=qad"
        ((i++))
    done
}

echo "🔧 Renaming existing tracks in all MKV files..."

for f in *.mkv; do
    rename_tracks "$f"
done

echo "🎬 Starting mkvmerge process..."

for file in *d.mkv; do
    filename=$(basename -- "$file")
    base="${filename%.mkv}"

    # Resolution
    resolution=$(grep -oP '\[(?:[0-9]+p|4k)\]' <<< "$base" |
        head -n1 |
        tr -d '[]')

    if [[ -z "$resolution" ]]; then
        echo "❌ Resolution not found in: $file"
        continue
    fi

    # Codec
    if [[ "$base" == *"[x265]"* ]]; then
        codec="[x265]"
    else
        codec=""
    fi

    # Remove resolution, codec and final d from filename
    clean_name="$base"
    clean_name=$(sed -E 's/[[:space:]]*\[([0-9]+p|4k)\]//g' <<< "$clean_name")
    clean_name=$(sed -E 's/[[:space:]]*\[x265\]//g' <<< "$clean_name")
    clean_name=$(sed -E 's/d$//' <<< "$clean_name")
    clean_name=$(sed -E 's/[[:space:]]+$//' <<< "$clean_name")

    # Detect episode number only when it is at the end
    if [[ "$clean_name" =~ ^(.+)[[:space:]]-[[:space:]]([0-9]+)$ ]]; then
        title="${BASH_REMATCH[1]}"
        ep="${BASH_REMATCH[2]}"

        subtitle_base="$title - $ep"
        output="$title - $ep.[SS][${resolution}]${codec}[MixFlixTop].mkv"
    else
        # Movie or special without episode number
        title="$clean_name"
        subtitle_base="$title"
        output="$title.[SS][${resolution}]${codec}[MixFlixTop].mkv"
    fi

    ass_subfile="$subtitle_base.ass"
    srt_subfile="$subtitle_base.srt"

    if [[ -f "$ass_subfile" ]]; then
        subfile="$ass_subfile"
        subtitle_format="ASS"
    elif [[ -f "$srt_subfile" ]]; then
        subfile="$srt_subfile"
        subtitle_format="SRT"
    else
        echo "❌ ASS/SRT subtitle not found for: $file"
        echo "   Expected: $ass_subfile"
        echo "   Or:       $srt_subfile"
        continue
    fi

    # Never overwrite an already existing completed output
    if [[ -e "$output" ]]; then
        echo "⚠️ Output already exists; skipped to prevent overwrite:"
        echo "   $output"
        continue
    fi

    # Create output under a temporary name first
    temp_output="${output}.partial"

    # Remove only an abandoned temporary output, never the input
    if [[ -e "$temp_output" ]]; then
        echo "🧹 Removing old partial output: $temp_output"
        rm -f -- "$temp_output"

        if [[ -e "$temp_output" ]]; then
            echo "❌ Could not remove old partial output."
            echo "   Input will NOT be deleted: $file"
            continue
        fi
    fi

    echo "────────────────────────────────────────"
    echo "🎞 Input:    $file"
    echo "📝 Subtitle: $subfile ($subtitle_format)"
    echo "📦 Output:   $output"

    mkvmerge -o "$temp_output" \
        "$file" \
        --default-track 0:yes \
        --forced-track 0:yes \
        --track-name "0:Animex" \
        --language 0:fa \
        "$subfile"

    mkvmerge_status=$?

    # mkvmerge:
    # 0 = successful
    # 1 = successful with warnings
    # 2+ = failed
    if (( mkvmerge_status > 1 )); then
        echo "❌ mkvmerge failed for: $file"
        echo "   Exit code: $mkvmerge_status"
        echo "   Input file was NOT deleted."

        rm -f -- "$temp_output"
        continue
    fi

    # Confirm that a non-empty temporary output actually exists
    if [[ ! -s "$temp_output" ]]; then
        echo "❌ Temporary output is missing or empty."
        echo "   Input file was NOT deleted: $file"

        rm -f -- "$temp_output"
        continue
    fi

    # Rename temporary output to final output
    if ! mv -- "$temp_output" "$output"; then
        echo "❌ Could not finalize output: $output"
        echo "   Input file was NOT deleted: $file"

        rm -f -- "$temp_output"
        continue
    fi

    # Double-check final output before deleting the original
    if [[ ! -s "$output" ]]; then
        echo "❌ Final output is missing or empty."
        echo "   Input file was NOT deleted: $file"

        rm -f -- "$output"
        continue
    fi

    # Delete input only after successful output creation
    if rm -- "$file"; then
        if (( mkvmerge_status == 1 )); then
            echo "⚠️ Done with warnings: $output"
            echo "🗑 Deleted input: $file"
        else
            echo "✅ Done: $output"
            echo "🗑 Deleted input: $file"
        fi
    else
        echo "⚠️ Output created successfully, but input could not be deleted:"
        echo "   $file"
    fi
done

echo "────────────────────────────────────────"
echo "🏁 All matching files processed."