import os
import glob
import multiprocessing
import soundfile as sf
import librosa
import numpy as np
from tqdm import tqdm

SEARCH_DIR = os.getcwd()
TARGET_SR = 44100
TARGET_SUBTYPE = 'PCM_16'

def process_file(filepath):
    try:
        y, sr = sf.read(filepath)

        if y.ndim > 1:
            y = np.mean(y, axis=1)

        if sr != TARGET_SR:
            y = librosa.resample(y, orig_sr=sr, target_sr=TARGET_SR, res_type='kaiser_best')

        sf.write(filepath, y, TARGET_SR, subtype=TARGET_SUBTYPE)
        
        return None

    except Exception as e:
        return f"Error processing {filepath}: {str(e)}"

def main():
    print(f"Scanning '{SEARCH_DIR}' for .wav files...")
    files = glob.glob(os.path.join(SEARCH_DIR, "**", "*.wav"), recursive=True)

    if not files:
        print("No .wav files found.")
        return

    print(f"Found {len(files)} files. Starting processing on {multiprocessing.cpu_count()} cores...")

    with multiprocessing.Pool() as pool:
        results = list(tqdm(pool.imap_unordered(process_file, files), total=len(files)))

    errors = [res for res in results if res is not None]
    
    print("\nProcessing Complete.")
    if errors:
        print(f"{len(errors)} errors occurred:")
        for err in errors:
            print(err)
    else:
        print("All files processed successfully.")

if __name__ == "__main__":
    multiprocessing.freeze_support() 
    main()