#!/usr/bin/env python3
"""
Check video files for codec compatibility with ffpyplayer
"""
import os
import subprocess
import json

def check_video_codec(video_path):
    """Check video codec using ffprobe"""
    try:
        cmd = [
            'ffprobe',
            '-v', 'quiet',
            '-print_format', 'json',
            '-show_format',
            '-show_streams',
            video_path
        ]
        
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode != 0:
            return None, "ffprobe failed"
        
        data = json.loads(result.stdout)
        
        video_streams = [s for s in data.get('streams', []) if s.get('codec_type') == 'video']
        audio_streams = [s for s in data.get('streams', []) if s.get('codec_type') == 'audio']
        
        if not video_streams:
            return None, "No video stream found"
        
        video_stream = video_streams[0]
        
        info = {
            'codec': video_stream.get('codec_name', 'unknown'),
            'codec_long': video_stream.get('codec_long_name', 'unknown'),
            'width': video_stream.get('width', 0),
            'height': video_stream.get('height', 0),
            'fps': eval(video_stream.get('r_frame_rate', '0/1')),
            'duration': float(data.get('format', {}).get('duration', 0)),
            'bitrate': int(data.get('format', {}).get('bit_rate', 0)),
            'audio_codec': audio_streams[0].get('codec_name', 'none') if audio_streams else 'none',
            'size': int(data.get('format', {}).get('size', 0))
        }
        
        return info, None
        
    except FileNotFoundError:
        return None, "ffprobe not installed (run: sudo apt-get install ffmpeg)"
    except Exception as e:
        return None, str(e)

def main():
    base_dir = os.path.dirname(os.path.abspath(__file__))
    media_dir = os.path.join(base_dir, 'media')
    
    print("=" * 80)
    print("VIDEO CODEC COMPATIBILITY CHECKER")
    print("=" * 80)
    
    # Supported codecs by ffpyplayer
    supported_codecs = ['h264', 'h265', 'hevc', 'vp8', 'vp9', 'mpeg4']
    
    # Find video files
    video_extensions = ['.mp4', '.avi', '.mkv', '.mov', '.webm']
    video_files = []
    
    if os.path.exists(media_dir):
        for filename in os.listdir(media_dir):
            ext = os.path.splitext(filename)[1].lower()
            if ext in video_extensions:
                video_files.append(filename)
    
    if not video_files:
        print("\n✓ No video files found in media directory")
        return
    
    print(f"\nFound {len(video_files)} video file(s):\n")
    
    for filename in video_files:
        video_path = os.path.join(media_dir, filename)
        print(f"📹 {filename}")
        print(f"   Path: {video_path}")
        
        info, error = check_video_codec(video_path)
        
        if error:
            print(f"   ❌ ERROR: {error}")
            continue
        
        # Display video info
        print(f"   Video Codec: {info['codec']} ({info['codec_long']})")
        print(f"   Resolution: {info['width']}x{info['height']}")
        print(f"   Frame Rate: {info['fps']:.2f} fps")
        print(f"   Duration: {info['duration']:.1f}s")
        print(f"   Bitrate: {info['bitrate'] / 1000:.0f} kbps")
        print(f"   Audio Codec: {info['audio_codec']}")
        print(f"   File Size: {info['size'] / (1024*1024):.2f} MB")
        
        # Check compatibility
        if info['codec'] in supported_codecs:
            print(f"   ✅ COMPATIBLE - Codec '{info['codec']}' is supported by ffpyplayer")
        else:
            print(f"   ⚠️  WARNING - Codec '{info['codec']}' may not be supported")
            print(f"   Supported codecs: {', '.join(supported_codecs)}")
            print(f"   Consider re-encoding to H.264:")
            print(f"   ffmpeg -i \"{filename}\" -c:v libx264 -preset fast -crf 23 \"{os.path.splitext(filename)[0]}_h264.mp4\"")
        
        # Performance warnings
        if info['width'] > 1920 or info['height'] > 1080:
            print(f"   ⚠️  High resolution ({info['width']}x{info['height']}) may cause performance issues")
            print(f"   Consider downscaling to 1920x1080 or lower")
        
        if info['bitrate'] > 5000000:  # 5 Mbps
            print(f"   ⚠️  High bitrate ({info['bitrate'] / 1000000:.1f} Mbps) may cause playback issues")
            print(f"   Consider reducing bitrate to 2-4 Mbps")
        
        print()

if __name__ == '__main__':
    main()
