#!/usr/bin/env python3
"""
Audio conversion script to convert audio files to u8 22100 Hz format
"""

from pydub import AudioSegment
import os
import sys
import argparse

def convert_audio(input_path, output_path=None):
    """Convert audio file to u8 format at 22100 Hz"""
    
    # Generate output path if not provided
    if output_path is None:
        base_name = os.path.splitext(input_path)[0]
        output_path = f"{base_name}_converted.wav"
    
    if not os.path.exists(input_path):
        print(f"Error: {input_path} not found!")
        return
    
    try:
        # Load the audio file
        print(f"Loading {input_path}...")
        audio = AudioSegment.from_wav(input_path)
        
        # Print current format info
        print(f"Original format:")
        print(f"  Sample rate: {audio.frame_rate} Hz")
        print(f"  Channels: {audio.channels}")
        print(f"  Sample width: {audio.sample_width} bytes ({audio.sample_width * 8} bits)")
        print(f"  Duration: {len(audio)} ms")
        
        # Convert to mono if stereo
        if audio.channels > 1:
            print("Converting to mono...")
            audio = audio.set_channels(1)
        
        # Convert to 22100 Hz sample rate
        print("Converting sample rate to 22100 Hz...")
        audio = audio.set_frame_rate(22100)
        
        # Convert to 8-bit unsigned (u8)
        print("Converting to 8-bit unsigned format...")
        audio = audio.set_sample_width(1)  # 1 byte = 8 bits
        
        # Export the converted audio
        print(f"Saving to {output_path}...")
        audio.export(output_path, format="wav")
        
        # Print new format info
        converted_audio = AudioSegment.from_wav(output_path)
        print(f"\nConverted format:")
        print(f"  Sample rate: {converted_audio.frame_rate} Hz")
        print(f"  Channels: {converted_audio.channels}")
        print(f"  Sample width: {converted_audio.sample_width} bytes ({converted_audio.sample_width * 8} bits)")
        print(f"  Duration: {len(converted_audio)} ms")
        
        print(f"\nConversion complete! Output saved as: {output_path}")
        
        # Optionally replace the original file
        replace = input("\nReplace original mine.wav with converted version? (y/n): ").lower()
        if replace == 'y':
            import shutil
            # Backup original
            backup_path = "sound/mine_original.wav"
            shutil.copy2(input_path, backup_path)
            print(f"Original file backed up as: {backup_path}")
            
            # Replace original
            shutil.copy2(output_path, input_path)
            os.remove(output_path)
            print(f"Original file replaced with converted version.")
        
    except Exception as e:
        print(f"Error during conversion: {e}")

def main():
    """Main function to handle command line arguments"""
    parser = argparse.ArgumentParser(description='Convert audio files to u8 22100 Hz format')
    parser.add_argument('input_file', help='Input audio file path')
    parser.add_argument('-o', '--output', help='Output file path (optional)')
    
    args = parser.parse_args()
    
    convert_audio(args.input_file, args.output)

if __name__ == "__main__":
    main()
