import subprocess
import os
import sys

def get_ffmpeg_path():
    # Provera da li je ffmpeg.exe u istom folderu
    local_ffmpeg = os.path.join(os.getcwd(), "ffmpeg.exe")
    if os.path.exists(local_ffmpeg):
        return local_ffmpeg
    return "ffmpeg" # Ako nije, osloni se na sistemski PATH

def process_video(input_path):
    ffmpeg = get_ffmpeg_path()
    
    if not os.path.exists(input_path):
        print(f"Greška: Fajl {input_path} ne postoji u ovom folderu.")
        return

    # 1. MP4 Optimizacija (1080p, No Audio, Web optimized)
    mp4_output = "hero_1080p_optimized.mp4"
    mp4_cmd = [
        ffmpeg, '-y', '-i', input_path,
        '-vf', 'scale=-1:1080', # Smanji na 1080p
        '-vcodec', 'libx264',
        '-crf', '24',
        '-preset', 'veryslow',
        '-an', # Izbaci zvuk (rešava sync glitch)
        '-movflags', '+faststart',
        mp4_output
    ]

    # 2. WebM Optimizacija (VP9 je zakon za Hero sekcije)
    webm_output = "hero_1080p_optimized.webm"
    webm_cmd = [
        ffmpeg, '-y', '-i', input_path,
        '-vf', 'scale=-1:1080',
        '-c:v', 'libvpx-vp9',
        '-crf', '30', # VP9 CRF 30 je ekvivalent x264 24
        '-b:v', '0', 
        '-an',
        webm_output
    ]

    try:
        print("--- Pokrećem MP4 enkoding (H.264) ---")
        subprocess.run(mp4_cmd, check=True)
        
        print("\n--- Pokrećem WebM enkoding (VP9) ---")
        subprocess.run(webm_cmd, check=True)
        
        print("\n" + "="*40)
        print("USPEH! Fajlovi su spremni:")
        print(f"Original: {os.path.getsize(input_path)/(1024*1024):.2f} MB")
        print(f"MP4 (1080p): {os.path.getsize(mp4_output)/(1024*1024):.2f} MB")
        print(f"WebM (1080p): {os.path.getsize(webm_output)/(1024*1024):.2f} MB")
        print("="*40)

    except subprocess.CalledProcessError as e:
        print(f"Greška tokom rada FFmpeg-a: {e}")
    except Exception as e:
        print(f"Neočekivana greška: {e}")

if __name__ == "__main__":
    process_video("once-again.mp4")