import os
import subprocess
from flask import Flask, render_template, request, send_file
from werkzeug.utils import secure_filename
from subprocess import PIPE
from app import app

UPLOAD_FOLDER = '/data/www/html/MLAudio/uploads'
CONVERTED_FOLDER = '/data/www/html/MLAudio/converted'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(CONVERTED_FOLDER, exist_ok=True)

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    app.logger.info('Sono in index')
    return render_template('index.html')

@app.route('/test', methods=['GET', 'POST'])
def test():
    app.logger.info('Sono in test')
    return "Sono in test"

@app.route('/upload', methods=['POST'])
def upload():
    if 'file_audio' not in request.files:
        return "Nessun file caricato", 400
    
    file = request.files['file_audio']
            
    if file.filename == '':
        return "Nessun file selezionato", 400

    if file:
        # 1. Salva il file originale in modo sicuro
        filename = secure_filename(file.filename)
        input_path = os.path.join(UPLOAD_FOLDER, filename)
        file.save(input_path)
        
        # 2. Definisci il percorso di output
        name_without_ext = os.path.splitext(filename)[0]
        output_filename = f"{name_without_ext}.wav"
        output_path = os.path.join(CONVERTED_FOLDER, output_filename)
        
        opt = '-af "loudnorm=I=-18:TP=-2:LRA=7"'
        # 3. Esegui FFmpeg
        comando = [
            'ffmpeg',
            '-i', input_path,
            '-y', # Sovrascrivi se esiste
            '-vn',
            '-map_metadata',
            '-1',
            '-fflags', '+bitexact', '-flags:a', '+bitexact',
            '-af', 'loudnorm=I=-18:TP=-2:LRA=7',
            '-ar', '8000',
            '-ac', '1',
            '-c:a', 'pcm_mulaw',
            output_path
        ]
        
        try:
            subprocess.run(comando, check=True, stdout=PIPE, stderr=PIPE)
            # 4. Invia il file convertito all'utente per il download
            return send_file(output_path, as_attachment=True)
        
        except subprocess.CalledProcessError as e:
            return f"Errore durante la conversione: {e.stderr.decode()}", 500
        finally:
            # Opzionale: pulizia dei file dopo l'invio (attenzione ai permessi)
            # os.remove(input_path) 
            pass

@app.route('/uploadp', methods=['POST'])
def uploadp():
    if 'file_audio' not in request.files:
        return "Nessun file caricato", 400
    
    file = request.files['file_audio']
            
    if file.filename == '':
        return "Nessun file selezionato", 400

    if file:
        # 1. Salva il file originale in modo sicuro
        filename = secure_filename(file.filename)
        input_path = os.path.join(UPLOAD_FOLDER, filename)
        file.save(input_path)
        
        # 2. Definisci il percorso di output
        name_without_ext = os.path.splitext(filename)[0]
        tempout = f"{name_without_ext}.tmp.wav"
        output_filename = f"{name_without_ext}.wav"
        output_path = os.path.join(CONVERTED_FOLDER, output_filename)
        tempout_path = os.path.join(CONVERTED_FOLDER, tempout)
        
        # 2.1 Trasforma il file in mono
        mono = [
            'ffmpeg',
            '-i', input_path,
            '-y', # Sovrascrivi se esiste
            '-ac', '1', # Sovrascrivi se esiste
            tempout_path
        ]
        
        # 3. Esegui FFmpeg
        comando = [
            'ffmpeg',
            '-i', tempout_path,
            '-y', # Sovrascrivi se esiste
            '-vn',
            '-map_metadata',
            '-1',
            '-fflags', '+bitexact', '-flags:a', '+bitexact',
            '-af', 'loudnorm=I=-18:TP=-2:LRA=7',
            '-af', 'adelay=2000',
            '-ar', '8000',
            '-ac', '1',
            '-c:a', 'pcm_mulaw',
            output_path
        ]
        
        try:
            subprocess.run(mono, check=True, stdout=PIPE, stderr=PIPE)
            subprocess.run(comando, check=True, stdout=PIPE, stderr=PIPE)
            # 4. Invia il file convertito all'utente per il download
            return send_file(output_path, as_attachment=True)
        
        except subprocess.CalledProcessError as e:
            return f"Errore durante la conversione: {e.stderr.decode()}", 500
        finally:
            # Opzionale: pulizia dei file dopo l'invio (attenzione ai permessi)
            # os.remove(input_path) 
            pass

if __name__ == '__main__':
    app.run(debug=True)