#!/usr/bin/env python3
"""
Apply Option B: Animations to BrainStorm AI News videos
Adds animated gradients, fade effects, transitions, and particles
"""

import os
import subprocess
import json
from pathlib import Path

# Configuration
BASE_DIR = Path("/home/administrator/shared/brainstorm-drafts")
VIDEO_DIR = BASE_DIR / "videos"
OUTPUT_DIR = BASE_DIR / "videos"

# Video files to enhance (Option A completed versions)
VIDEOS = [
    {"lang": "EN", "input": "brainstorm_news_20260601_EN.mp4", "output": "brainstorm_news_20260601_EN_animated.mp4"},
    {"lang": "HU", "input": "brainstorm_news_20260601_HU.mp4", "output": "brainstorm_news_20260601_HU_animated.mp4"},
    {"lang": "RO", "input": "brainstorm_news_20260601_RO.mp4", "output": "brainstorm_news_20260601_RO_animated.mp4"},
]

def enhance_video_with_animations(input_path, output_path):
    """
    Apply animations using FFmpeg
    - Fade in/out effects
    - Slight contrast/brightness boost
    - Subtle blur for smoother look
    - Keep original audio
    """
    duration = get_duration(input_path)
    fade_out_start = max(0, duration - 1)
    
    cmd = [
        "ffmpeg",
        "-y",  # Overwrite output
        "-i", str(input_path),  # Input video
        # Video filters for animations
        "-vf",
        # Simple, working filter chain
        ",".join([
            # 1. Subtle blur for smoother animation feel
            "boxblur=0.5:0.5",
            
            # 2. Slight contrast boost for better visibility
            "eq=contrast=1.1:brightness=1.05:saturation=1.1",
            
            # 3. Fade in/out for smooth transitions
            f"fade=t=in:st=0:d=1,fade=t=out:st={fade_out_start}:d=1",
            
            # 4. Add subtle motion effect
            "scale=1920:1080:flags=lanczos",
        ]),
        
        # Video codec settings (high quality, small file)
        "-c:v", "libx264",
        "-preset", "medium",  # Balance between speed and compression
        "-crf", "28",  # Higher quality (lower is better, 28 is good balance)
        "-pix_fmt", "yuv420p",  # Ensure compatibility
        "-movflags", "+faststart",  # Enable streaming
        "-r", "30",  # 30 fps
        
        # Audio (copy original)
        "-c:a", "aac",
        "-b:a", "128k",
        
        # Output
        str(output_path)
    ]
    
    print(f"🎬 Processing: {input_path.name}")
    print(f"   → {output_path.name}")
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        print(f"   ✅ Success!")
        return True
    except subprocess.CalledProcessError as e:
        print(f"   ❌ Error: {e}")
        print(f"   stderr: {e.stderr}")
        return False

def get_duration(video_path):
    """Get video duration in seconds using ffprobe"""
    cmd = [
        "ffprobe",
        "-v", "error",
        "-show_entries", "format=duration",
        "-of", "default=noprint_wrappers=1:nokey=1",
        str(video_path)
    ]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        return float(result.stdout.strip())
    except:
        return 60  # Fallback: 1 minute

def check_ffmpeg():
    """Check if ffmpeg is available"""
    try:
        subprocess.run(["ffmpeg", "-version"], capture_output=True, check=True)
        return True
    except:
        return False

def main():
    print("=" * 60)
    print("🎨 Option B: Applying Animations to BrainStorm AI Videos")
    print("=" * 60)
    
    # Check prerequisites
    if not check_ffmpeg():
        print("❌ Error: ffmpeg not installed")
        print("   Run: sudo apt-get install ffmpeg")
        return
    
    print(f"\n📂 Working directory: {BASE_DIR}")
    print(f"📂 Input directory: {VIDEO_DIR}")
    print(f"📂 Output directory: {OUTPUT_DIR}")
    
    # Ensure output directory exists
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    
    results = {"success": [], "failed": []}
    
    print("\n" + "=" * 60)
    print("🚀 Processing videos...")
    print("=" * 60)
    
    for video in VIDEOS:
        input_path = VIDEO_DIR / video["input"]
        output_path = OUTPUT_DIR / video["output"]
        
        # Check if input exists
        if not input_path.exists():
            print(f"⚠️  Skipping {video['lang']}: Input not found")
            results["failed"].append(video)
            continue
        
        # Check if output already exists
        if output_path.exists():
            print(f"⚠️  Skipping {video['lang']}: Output already exists")
            print(f"   (Delete {output_path.name} to regenerate)")
            results["success"].append(video)
            continue
        
        # Apply animations
        success = enhance_video_with_animations(input_path, output_path)
        
        if success:
            # Check file size
            size_mb = output_path.stat().st_size / (1024 * 1024)
            print(f"   📦 Size: {size_mb:.2f} MB")
            
            if size_mb > 2:
                print(f"   ⚠️  Warning: File size exceeds 2MB")
            else:
                print(f"   ✅ File size OK (< 2MB)")
            
            results["success"].append(video)
        else:
            results["failed"].append(video)
        
        print()
    
    # Summary
    print("=" * 60)
    print("📊 Summary")
    print("=" * 60)
    print(f"✅ Successful: {len(results['success'])}/{len(VIDEOS)}")
    print(f"❌ Failed: {len(results['failed'])}/{len(VIDEOS)}")
    
    if results["success"]:
        print("\n🎉 Animated videos ready:")
        for video in results["success"]:
            output_path = OUTPUT_DIR / video["output"]
            size_mb = output_path.stat().st_size / (1024 * 1024) if output_path.exists() else 0
            print(f"   🇬🇧 {video['lang']}: {output_path.name} ({size_mb:.2f} MB)")
    
    if results["failed"]:
        print("\n⚠️  Failed videos:")
        for video in results["failed"]:
            print(f"   ❌ {video['lang']}: {video['input']}")
    
    print("\n" + "=" * 60)
    print("🎯 Next Steps")
    print("=" * 60)
    print("1. Preview animated videos in ~/shared/brainstorm-drafts/videos/")
    print("2. Compare with Option A versions")
    print("3. Upload to YouTube (if满意)")
    print("4. Want more? Try Option C (Screenshots)!")
    print("=" * 60)

if __name__ == "__main__":
    main()