import os
from typing import List
from models import Video
import ffmpeg
from PIL import Image

def generate_thumbnail(video_path: str, thumbnail_path: str):
    """
    Generates a thumbnail from a video file.
    """
    try:
        # Extract a frame at 1 second mark
        (
            ffmpeg
            .input(video_path)
            .output(thumbnail_path, vframes=1)
            .overwrite_output()
            .run(capture_stdout=True, capture_stderr=True)
        )
    except ffmpeg.Error as e:
        print(f"Error generating thumbnail for {video_path}: {e.stderr.decode()}")
        # Fallback to a default thumbnail or handle error
        # For now, we'll just let it fail and the frontend will use a placeholder
    except Exception as e:
        print(f"An unexpected error occurred: {e}")


def scan_video_directory(directory_path: str) -> List[dict]:
    """
    Scan a directory for video files and return a list of video information.
    """
    video_extensions = {'.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.m4v'}
    videos = []
    
    if not os.path.exists(directory_path):
        raise FileNotFoundError(f"Directory {directory_path} does not exist")
    
    # Create a directory for thumbnails if it doesn't exist
    thumbnails_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "thumbnails")
    os.makedirs(thumbnails_dir, exist_ok=True)

    for root, dirs, files in os.walk(directory_path):
        for file in files:
            if os.path.splitext(file)[1].lower() in video_extensions:
                full_path = os.path.join(root, file)
                stat = os.stat(full_path)
                
                # Generate thumbnail path
                thumbnail_filename = f"{os.path.splitext(file)[0]}.jpg"
                thumbnail_path = os.path.join(thumbnails_dir, thumbnail_filename)

                # Generate thumbnail
                generate_thumbnail(full_path, thumbnail_path)

                video_info = {
                    "title": os.path.splitext(file)[0],
                    "path": full_path,
                    "size": stat.st_size,
                    "thumbnail_path": thumbnail_path if os.path.exists(thumbnail_path) else None,
                }
                videos.append(video_info)
    
    return videos
