import sys
import os
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QMessageBox
from PyQt5.QtCore import Qt
from pydub import AudioSegment

class DragDropWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Audio Converter")
        self.setGeometry(100, 100, 500, 300)
        self.setAcceptDrops(True)
        # A text edit area to display instructions and logs.
        self.textEdit = QTextEdit(self)
        self.textEdit.setReadOnly(True)
        self.textEdit.setText("Drag and drop audio files here.\n\n"
                              "Accepted formats: wav, mp3, ogg, flag, etc.\n\n"
                              "Files will be converted to WAV (22050 Hz, 16-bit, mono).")
        self.setCentralWidget(self.textEdit)

    def dragEnterEvent(self, event):
        # Accept the drag event if it contains URLs (files).
        if event.mimeData().hasUrls():
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        # When files are dropped, process each one.
        urls = event.mimeData().urls()
        if urls:
            for url in urls:
                file_path = url.toLocalFile()
                if os.path.isfile(file_path):
                    self.process_file(file_path)

    def process_file(self, file_path):
        try:
            self.textEdit.append(f"Processing: {file_path}")
            # Load the audio file with pydub. pydub will call ffmpeg in the background.
            audio = AudioSegment.from_file(file_path)
            # Convert audio: set sample rate, channels, and sample width (16-bit -> 2 bytes).
            audio = audio.set_frame_rate(22050).set_channels(1).set_sample_width(2)
            
            # Determine the output filename.
            directory, filename = os.path.split(file_path)
            base, ext = os.path.splitext(filename)
            # If the file is already a WAV, append '_c'
            if ext.lower() == ".wav":
                new_filename = f"{base}_c.wav"
            else:
                new_filename = f"{base}.wav"
            new_file_path = os.path.join(directory, new_filename)
            
            # Export the converted audio as WAV.
            audio.export(new_file_path, format="wav")
            self.textEdit.append(f"Saved: {new_file_path}\n")
        except Exception as e:
            self.textEdit.append(f"Error processing {file_path}: {e}")
            QMessageBox.critical(self, "Error", f"Error processing {file_path}:\n{e}")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = DragDropWindow()
    window.show()
    sys.exit(app.exec_())
