import os
from moviepy import *

def create_video(image_folder, audio_folder, output_video):
    # Get sorted lists of images and audio files
    images = []
    audio_files = []
    for i in range(len([name for name in os.listdir('./images')])):
        images.append(f"./images/{i}.png")
        audio_files.append(f"./audios/{i}.wav")

    clips = []

    for img, audio in zip(images, audio_files):
        # Create an ImageClip
        img_path = os.path.join(image_folder, img)
        image_clip = ImageClip(img_path)

        # Create an AudioFileClip
        audio_path = os.path.join(audio_folder, audio)
        audio_clip = AudioFileClip(audio_path)
        audio_clip = CompositeAudioClip([audio_clip])

        # Set the duration of the image clip to the duration of the audio clip
        image_clip = image_clip.with_duration(audio_clip.duration)

        # Set the audio of the image clip
        image_clip.audio = audio_clip

        # Append the image clip to the list of clips
        clips.append(image_clip)

    # Concatenate all the clips into a single video
    final_video = concatenate_videoclips(clips, method="compose")

    # Write the result to a file
    final_video.write_videofile(output_video, codec='libx264', audio_codec='aac', fps=24)

"""
import os
from moviepy import *

def create_video_from_images_and_audio(image_folder, audio_folder, output_video):
    video_files = []
    audio_files = []
    for i in range(len([name for name in os.listdir('./images')])):
        video_files.append(f"./videos/{i}.mp4")
        audio_files.append(f"./audios/{i}.wav")


    audio_clip = AudioFileClip(audio_file)
    audio_duration = audio_clip.duration

    clips = []

    for video, audio in zip(video_files, audio_files):
        video_clip = VideoFileClip(video_path)
        audio_clip = AudioFileClip(audio_path)
        if video_clip.duration < audio_clip.duration:
            loops_needed = int(audio_clip.duration // video_clip.duration) + 1
            video_clip = video_clip.loop(loops=loops_needed)
        video_clip = video_clip.subclip(0, audio_clip.duration)
        video_clip = video_clip.set_audio(audio_clip)
        clips.append(video_clip)

    final_video = concatenate_videoclips(clips, method="compose")
    final_video.write_videofile(output_video, codec='libx264', audio_codec='aac', fps=24)
"""
