#!/bin/bash

# --- Konfiguration ---
API_URL="127.0.0.1:1608"
PLAYLIST_FILE="/home/alex/Videos/Metadaten/playlist.txt"
SLEEP_INTERVAL=3
# Zeitzone (Winter: GMT-1, Sommer: GMT-2)
TIMEZONE="GMT-2"

echo "Kombiniertes Metadaten-Skript gestartet..."

while true; do
    # 1. API-Daten einmalig abrufen
    # Wir nutzen curl -s fÃ¼r bessere StabilitÃ¤t
    response=$(curl -s "$API_URL")

    if [ -n "$response" ]; then
        # 2. Daten mit jq extrahieren
        title=$(echo "$response" | jq -r ".title // \"Unbekannter Titel\"")
        duration=$(echo "$response" | jq -r ".duration // 0")
        progress=$(echo "$response" | jq -r ".progress // 0")
        url=$(echo "$response" | jq -r ".album // \"\"")

        # 3. Berechnungen
        current_time_ms=$(date +%s%3N)
        remaining_ms=$((duration - progress))
        finish_timestamp_ms=$((current_time_ms + remaining_ms))
        
        # Formatierung der Endzeit (hh:mm)
        finish_time_formatted=$(TZ="$TIMEZONE" date -d "@$(($finish_timestamp_ms/1000))" '+%H:%M')
        
        # Aktueller Video-Timestamp fÃ¼r Twitch-Link
        video_seconds=$((progress / 1000))

        # 4. Playlist/Next Video Info (nur wenn Datei existiert)
        if [ -f "$PLAYLIST_FILE" ]; then
            line=$(head -n 1 "$PLAYLIST_FILE")
            next_name=$(echo "$line" | cut -d, -f1 | sed 's/\\,/\\\\,/g')
            next_duration_raw=$(echo "$line" | cut -d',' -f2 | sed 's/{\|}//g' | tr -d '\r')
            
            if [ -n "$next_duration_raw" ]; then
                next_min=$((next_duration_raw / 60000))
                next_sec=$((next_duration_raw / 1000 % 60))
                next_duration_formatted="${next_min} Min ${next_sec} Sek"
            fi
        fi

        # 5. Alle Dateien schreiben
        # Current Info
        echo "$title" > current.txt
        echo "$url?t=$video_seconds" > timestamp.txt
        
        # Next Info
        echo "$next_name" > next.txt
        echo "$next_duration_formatted" > duration.txt
        echo "$finish_time_formatted" > start_at.txt

        # 6. Konsolen-Ausgabe (Debugging)
        echo "-------------------------------------------"
        echo "AKTUELL: $title"
        echo "LINK:    $url?t=$video_seconds"
        echo "ENDE UM: $finish_time_formatted Uhr"
        echo "NÃCHSTES: $next_name ($next_duration_formatted)"
        
    else
        echo "WARNUNG: Konnte keine Daten von Tuna API empfangen."
    fi

    sleep "$SLEEP_INTERVAL"
done
