import uuid
from flask import Flask, request, jsonify
import os

app = Flask(__name__)

UPLOAD_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uploads')
ALLOWED_EXTENSIONS = {'mp4', 'avi', 'mov'}

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload-media', methods=['POST'])
def upload_media():
    print("Receiving file... Please wait...")
    try:
        if 'Content-Type' not in request.headers or 'video/mp4' not in request.headers.get('Content-Type'):
            return jsonify({'error': 'File format not allowed'}), 400

        file_data = request.data
        if not file_data:
            return jsonify({'error': 'No file provided in the request'}), 400

        name = uuid.uuid4()
        filename = str(name)+'.mp4'  # Assign a desired file name
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        with open(filepath, 'wb') as f:
            f.write(file_data)

        if os.path.exists(filepath):
            return jsonify({'message': 'File uploaded successfully'}), 200
        else:
            return jsonify({'error': 'Error saving file on server'}), 500
        
    except Exception as e:
        print(f"Error processing request: {e}")  # Print error in console
        return jsonify({'error': 'Internal server error: ' + str(e)}), 500

if __name__ == '__main__':
    if not os.path.exists(UPLOAD_FOLDER):
        os.makedirs(UPLOAD_FOLDER)
    app.run(host='0.0.0.0')