#!/bin/bash

# Check if ffprobe is installed
if ! command -v ffprobe &> /dev/null; then
    echo "ffprobe is not installed. Please install ffmpeg."
    exit 1
fi

# Initialize JSON array
json_array=""

# Loop through directories
for dir in */; do
    if [ -d "$dir" ]; then
        # Remove trailing slash
        name="${dir%/}"

        # Generate slug
        # 1. Lowercase
        # 2. Replace Umlauts (ä->a, ö->o, ü->u, ß->ss)
        # 3. Replace non-alphanumeric chars with hyphens
        # 4. Remove leading/trailing hyphens
        slug=$(echo "$name" | tr '[:upper:]' '[:lower:]' | sed 's/ä/a/g;s/ö/o/g;s/ü/u/g;s/ß/ss/g' | sed -E 's/[^a-z0-9]+/-/g' | sed -E 's/^-+|-+$//g')

        # Check if video.mkv exists
        if [ -f "$dir/video.mkv" ]; then
            # Get duration using ffprobe
            duration=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$dir/video.mkv")
            # Convert to integer (floor)
            duration=${duration%.*}

            # Build JSON object
            obj="{\"name\":\"$name\",\"slug\":\"$slug\",\"streamUrl\":\"$name/video.m3u8\",\"fileUrl\":\"$name/video.mkv\",\"posterUrl\":\"$name/poster.jpg\",\"duration\":$duration}"

            # Add to array
            if [ -z "$json_array" ]; then
                json_array="$obj"
            else
                json_array="$json_array,$obj"
            fi
        else
            echo "Warning: $dir/video.mkv not found. Skipping."
        fi
    fi
done

# Write to videos.json
echo "{\"videos\":[$json_array]}" > index.json

echo "index.json generated successfully."
