import json
import os
import sys

# ==============================================================================
# Video Generator Skript
# ==============================================================================
# Dieses Skript liest die JSON-Playlist, die von videogen.php erstellt wurde,
# und zeigt, wie man die Videos zusammenfügt.
#
# VORAUSSETZUNG:
# pip install moviepy
# ==============================================================================

try:
    from moviepy.editor import VideoFileClip, concatenate_videoclips
    MOVIEPY_AVAILABLE = True
except ImportError:
    MOVIEPY_AVAILABLE = False
    print("WARNUNG: 'moviepy' ist nicht installiert. Es wird nur eine Simulation durchgeführt.")
    print("Installiere es mit: pip install moviepy")

def process_workflow(json_file_path, output_filename="final_video.mp4"):
    """
    Liest die JSON-Datei, lädt die Clips und erstellt das Video.
    """
    
    # 1. JSON Datei lesen
    try:
        with open(json_file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except FileNotFoundError:
        print(f"Fehler: Datei '{json_file_path}' nicht gefunden.")
        return

    if 'playlist' not in data:
        print("Fehler: Ungültiges JSON Format (keine 'playlist' gefunden).")
        return

    playlist = data['playlist']
    workflow_name = data.get('workflow_name', 'Unbekannt')
    
    print(f"\n=== Verarbeite Workflow: {workflow_name} ===")
    print(f"Anzahl der Clips: {len(playlist)}\n")

    clips = []
    
    # 2. Durch die Playlist iterieren
    for index, item in enumerate(playlist):
        seq_name = item['sequence']
        path = item['path'] # Relativer Pfad aus PHP (z.B. "uploads/video.mp4")
        
        # Pfad absolut machen, falls nötig (abhängig davon, wo dieses Skript liegt)
        # Hier gehen wir davon aus, dass das Skript im gleichen Ordner wie 'uploads' liegt.
        full_path = os.path.abspath(path)

        print(f"[{index+1}] Sequenz: '{seq_name}' -> Video: {os.path.basename(path)}")
        
        if not os.path.exists(full_path):
            print(f"    ACHTUNG: Datei nicht gefunden: {full_path}")
            continue

        if MOVIEPY_AVAILABLE:
            try:
                # Video laden
                clip = VideoFileClip(full_path)
                # clip = clip.resize(height=720) # Optional
                clips.append(clip)
            except Exception as e:
                print(f"    Fehler beim Laden des Clips: {e}")
        else:
            # Nur Simulation
            clips.append(full_path)

    # 3. Videos zusammenfügen (Rendern)
    if MOVIEPY_AVAILABLE and clips:
        print(f"\nStarte Rendering von {len(clips)} Clips...")
        try:
            final_clip = concatenate_videoclips(clips, method="compose")
            final_clip.write_videofile(output_filename, codec='libx264', audio_codec='aac')
            print(f"\nERFOLG: Video gespeichert unter '{output_filename}'")
        except Exception as e:
            print(f"\nFehler beim Rendern: {e}")
    elif not MOVIEPY_AVAILABLE:
        print("\nSimulation beendet. Pfade wurden erfolgreich geprüft.")
    else:
        print("\nKeine gültigen Clips gefunden.")

if __name__ == "__main__":
    # Beispielaufruf
    if len(sys.argv) > 1:
        json_input = sys.argv[1]
    else:
        json_input = "playlist.json" # Standardwert
        
    if os.path.exists(json_input):
        process_workflow(json_input)
    else:
        print(f"Bitte erstelle eine Playlist im Webinterface, lade sie als '{json_input}' herunter")
        print("oder ziehe die JSON-Datei auf dieses Skript.")