from pydub import AudioSegment, generators
import os
import random

# Input WAV file converted manually from MP3
input_filename = "Je_Suis_Malade.wav"
output_filename = "Je_Suis_Malade_Battle_Remix.wav"

# Load the WAV file
track = AudioSegment.from_wav(input_filename)

# Ensure it's about 140 seconds (if needed, loop or cut)
if len(track) < 140000:
    times = int(140000 / len(track)) + 1
    track = track * times
track = track[:140000]

# Create a fluctuating bassline
bassline = AudioSegment.silent(duration=len(track))
for i in range(0, len(track), 500):  # Every 0.5 second
    freq = random.choice([60, 63, 66, 70])  # Slight frequency changes
    segment = generators.Sine(freq).to_audio_segment(duration=500).apply_gain(-10)
    bassline = bassline.overlay(segment, position=i)

# Create a basic drum kit beat
kick = generators.Sine(100).to_audio_segment(duration=50).apply_gain(-5)  # Simulate kick drum
snare = generators.Sine(2000).to_audio_segment(duration=30).apply_gain(-10)  # Simulate snare hit
hihat = generators.Sine(8000).to_audio_segment(duration=20).apply_gain(-15)  # Simulate hihat

# Build a simple drum loop
drums = AudioSegment.silent(duration=len(track))
for i in range(0, len(track), 500):  # Kick every 0.5 second
    drums = drums.overlay(kick, position=i)
for i in range(250, len(track), 1000):  # Snare every second, off-beat
    drums = drums.overlay(snare, position=i)
for i in range(0, len(track), 125):  # Hi-hat every 0.125 second
    drums = drums.overlay(hihat, position=i)

# Add special effects (random short high-frequency sweeps)
fx = AudioSegment.silent(duration=len(track))
for i in range(0, len(track), 7000):  # Every ~7 seconds
    sweep = generators.Sine(random.randint(6000, 12000)).to_audio_segment(duration=500).apply_gain(-10)
    fx = fx.overlay(sweep, position=i)

# Mix everything together
mixed = track.overlay(bassline).overlay(drums).overlay(fx)

# Light compression (not aggressive)
compressed = mixed.compress_dynamic_range(threshold=-20.0, ratio=2.0)

# Export as WAV
compressed.export(output_filename, format="wav")

compressed.export("Je_Suis_Malade_Battle_Remix.mp3", format="mp3", bitrate="320k")


print("\n✅ Successfully created enhanced Je_Suis_Malade_Battle_Remix.wav with bass fluctuations, drum kit, and special FX!")