import os
import uuid
import json
from werkzeug.utils import secure_filename
from flask import current_app

ALLOWED_VIDEO_EXTENSIONS = {'mp4', 'webm', 'mov', 'avi'}
MAX_VIDEO_SIZE = 500 * 1024 * 1024  # 500MB per video


def allowed_video_file(filename):
    """Check if file has allowed video extension."""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_VIDEO_EXTENSIONS


def get_video_upload_path(course_id):
    """Get upload directory path for a course."""
    return os.path.join(current_app.root_path, 'static', 'uploads', 'courses', 'videos', str(course_id))


def get_thumbnail_upload_path(course_id):
    """Get thumbnail directory path for a course."""
    return os.path.join(current_app.root_path, 'static', 'uploads', 'courses', 'thumbnails', str(course_id))


def process_uploaded_video(file, course_id, title=None, title_ar=None):
    """Process uploaded video: save, generate thumbnail info, return metadata."""
    if not file or not allowed_video_file(file.filename):
        raise ValueError("Invalid video file type")

    # Check file size
    file.seek(0, os.SEEK_END)
    file_size = file.tell()
    file.seek(0)
    if file_size > MAX_VIDEO_SIZE:
        raise ValueError(f"Video file too large (max {MAX_VIDEO_SIZE // (1024*1024)}MB)")

    # Generate unique filename
    ext = file.filename.rsplit('.', 1)[1].lower()
    unique_name = f"{uuid.uuid4().hex}.{ext}"

    # Create directories
    video_dir = get_video_upload_path(course_id)
    thumbnail_dir = get_thumbnail_upload_path(course_id)
    os.makedirs(video_dir, exist_ok=True)
    os.makedirs(thumbnail_dir, exist_ok=True)

    # Save video file
    video_path = os.path.join(video_dir, unique_name)
    file.save(video_path)

    # Generate paths for database (relative to static)
    video_db_path = f"uploads/courses/videos/{course_id}/{unique_name}"

    # Placeholder for thumbnail (will be generated by separate process)
    thumbnail_db_path = f"uploads/courses/thumbnails/{course_id}/{unique_name}.jpg"

    # Get file size for duration estimation (rough estimate: 1MB ≈ 5-10 seconds for 720p)
    # In production, use ffmpeg to get actual duration
    estimated_duration = max(60, file_size // (1024 * 1024) * 8)  # Conservative estimate

    return {
        "video_path": video_db_path,
        "thumbnail_path": thumbnail_db_path,
        "duration_seconds": estimated_duration,
        "original_filename": file.filename
    }


def generate_video_thumbnail(video_path, thumbnail_path):
    """Generate thumbnail from video using ffmpeg if available."""
    try:
        import subprocess
        # Try to use ffmpeg to generate thumbnail
        subprocess.run([
            'ffmpeg', '-i', video_path,
            '-ss', '00:00:01', '-vframes', '1',
            '-vf', 'scale=320:180',
            '-y', thumbnail_path
        ], check=True, capture_output=True)
        return True
    except (FileNotFoundError, subprocess.CalledProcessError):
        # Fallback: copy a default thumbnail
        default_thumb = os.path.join(current_app.root_path, 'static', 'img', 'video-placeholder.jpg')
        if os.path.exists(default_thumb):
            import shutil
            shutil.copy(default_thumb, thumbnail_path)
            return True
        return False


def get_video_duration(video_path):
    """Get video duration in seconds using ffprobe/ffmpeg."""
    try:
        import subprocess
        result = subprocess.run([
            'ffprobe', '-v', 'error',
            '-show_entries', 'format=duration',
            '-of', 'json', video_path
        ], check=True, capture_output=True, text=True)
        data = json.loads(result.stdout)
        return int(float(data['format']['duration']))
    except (FileNotFoundError, subprocess.CalledProcessError, KeyError, json.JSONDecodeError):
        return 0


def delete_video_files(course_id, filename):
    """Delete video and thumbnail files."""
    video_path = os.path.join(get_video_upload_path(course_id), filename)
    thumbnail_path = os.path.join(get_thumbnail_upload_path(course_id), f"{os.path.splitext(filename)[0]}.jpg")

    for path in [video_path, thumbnail_path]:
        if os.path.exists(path):
            os.remove(path)

    # Clean up empty directories
    try:
        os.rmdir(get_video_upload_path(course_id))
        os.rmdir(get_thumbnail_upload_path(course_id))
    except OSError:
        pass  # Directory not empty
