import os
import uuid
from flask import Flask, render_template, request, redirect, url_for, send_from_directory, flash
import ffmpeg  # ffmpeg-python library

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # Set a secure secret key in production

# Define folders for uploads and compressed videos
UPLOAD_FOLDER = 'uploads'
COMPRESSED_FOLDER = 'compressed'

os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(COMPRESSED_FOLDER, exist_ok=True)

@app.route('/')
def index():
    """Render the home page with the upload form."""
    return render_template('index.html')

@app.route('/upload', methods=['POST'])
def upload_video():
    """Handle video uploads and compress the video file."""
    if 'video' not in request.files:
        flash('No video file part')
        return redirect(request.url)
    
    file = request.files['video']
    if file.filename == '':
        flash('No video selected')
        return redirect(request.url)
    
    # Generate a unique filename preserving the extension
    ext = os.path.splitext(file.filename)[1]
    filename = f"{uuid.uuid4()}{ext}"
    input_filepath = os.path.join(UPLOAD_FOLDER, filename)
    file.save(input_filepath)
    
    # Set up output filename for the compressed version
    compressed_filename = f"compressed_{filename}"
    output_filepath = os.path.join(COMPRESSED_FOLDER, compressed_filename)
    
    try:
        # Using ffmpeg to compress the video
        # This example compresses the video using H.264 with a lower bitrate
        stream = ffmpeg.input(input_filepath)
        stream = ffmpeg.output(
            stream,
            output_filepath,
            vcodec='libx264',
            video_bitrate='500k',   # adjust this value as needed for quality vs. bandwidth
            preset='veryfast',
            acodec='aac'
        )
        ffmpeg.run(stream, capture_stdout=True, capture_stderr=True)
        flash('Video successfully uploaded and compressed!')
    except Exception as e:
        flash('Compression error: ' + str(e))
        return redirect(url_for('index'))
    
    return redirect(url_for('index'))

@app.route('/videos/<filename>')
def serve_video(filename):
    """Serve compressed video files from the designated folder."""
    return send_from_directory(COMPRESSED_FOLDER, filename)

if __name__ == '__main__':
    app.run(debug=True)