from pydub import AudioSegment
import os

def convert_to_wav(input_file_path, output_file_path):
    """
    Converts an audio file to WAV format (8bit, 22050Hz).

    Parameters:
    - input_file_path: str, path to the input audio file
    - output_file_path: str, path where the output WAV file will be saved
    """
    try:
        # Load the audio file
        audio = AudioSegment.from_file(input_file_path)
        # Convert to mono, 22050Hz, 16bit
        audio = audio.set_frame_rate(22050).set_sample_width(2)
        # Export the audio file as WAV
        audio.export(output_file_path, format='wav')
        return True
    except Exception as e:
        print(f"Error converting file {input_file_path}: {e}")
        return False

def convert_to_mp3(input_file_path, output_file_path):
    """
    Converts an audio file to MP3 format (44.1kHz, 128kbps).

    Parameters:
    - input_file_path: str, path to the input audio file
    - output_file_path: str, path where the output MP3 file will be saved
    """
    try:
        # Load the audio file
        audio = AudioSegment.from_file(input_file_path)
        # Convert to mono, 44100Hz
        audio = audio.set_frame_rate(44100)
        # Export the audio file as MP3 with 128k bitrate
        audio.export(output_file_path, format='mp3', bitrate='128k')
        return True
    except Exception as e:
        print(f"Error converting file {input_file_path} to mp3: {e}")
        return False

def allowed_file(filename):
    """
    Checks if the uploaded file is an allowed audio format.

    Parameters:
    - filename: str, name of the file to check

    Returns:
    - bool: True if the file is allowed, False otherwise
    """
    ALLOWED_EXTENSIONS = {'mp3', 'ogg', 'flac', 'wav', 'aac'}
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def process_audio_file(uploaded_file):
    """
    Processes the uploaded audio file and converts it to WAV format.

    Parameters:
    - uploaded_file: FileStorage, the uploaded audio file

    Returns:
    - str: path to the converted WAV file
    """
    if uploaded_file and allowed_file(uploaded_file.filename):
        input_file_path = os.path.join('uploads', uploaded_file.filename)
        output_file_path = os.path.splitext(input_file_path)[0] + '.wav'
        
        # Save the uploaded file
        uploaded_file.save(input_file_path)
        
        # Convert to WAV
        if convert_to_wav(input_file_path, output_file_path):
            return output_file_path
    return None

def process_audio_file_to_mp3(uploaded_file):
    """
    Processes the uploaded audio file and converts it to MP3 format.

    Parameters:
    - uploaded_file: FileStorage, the uploaded audio file

    Returns:
    - str: path to the converted MP3 file
    """
    if uploaded_file and allowed_file(uploaded_file.filename):
        input_file_path = os.path.join('uploads', uploaded_file.filename)
        output_file_path = os.path.splitext(input_file_path)[0] + '.mp3'
        
        # Save the uploaded file
        uploaded_file.save(input_file_path)
        
        # Convert to MP3
        if convert_to_mp3(input_file_path, output_file_path):
            return output_file_path
    return None