from moviepy.editor import VideoFileClip, concatenate_videoclips
import os, cv2

def add_intro_to_video(input_video, intro_video='intro.mp4', output_video='output.mp4'):
    clip_main = VideoFileClip(input_video)
    
    clip_intro = VideoFileClip(intro_video).resize(clip_main.size).set_fps(clip_main.fps)
    
    if clip_main.audio is not None and clip_intro.audio is None:
        from moviepy.editor import AudioArrayClip
        silent_audio = AudioArrayClip([[0] * int(clip_intro.duration * clip_main.audio.fps)], fps=clip_main.audio.fps)
        clip_intro = clip_intro.set_audio(silent_audio)
    
    final_clip = concatenate_videoclips([clip_intro, clip_main])
    
    final_clip.write_videofile(output_video, codec='libx264')

def get_duration(input_file):
    if not os.path.isfile(input_file):
        print('Input file does not exist')
        return 0

    try:
        video = cv2.VideoCapture(input_file)
        frames = video.get(cv2.CAP_PROP_FRAME_COUNT)
        fps = video.get(cv2.CAP_PROP_FPS)
        duration = frames / fps
        video.release()

        return int(duration)
    except Exception as e:
        print(e)
        return 0

def generate_thumbnails(input_file, filename):
    output_folder = 'temp/'
    if not os.path.isfile(input_file):
        raise ValueError('Input file does not exist')
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    posterPath = os.path.join(output_folder, f'{filename}.jpg')
    previewPath = os.path.join(output_folder, f'{filename}.mp4')
    
    clip = VideoFileClip(input_file)
    duration = clip.duration

    interval = duration / 11.0

    start_time_first_clip = 0 * interval
    try:
        clip.save_frame(posterPath, t=start_time_first_clip)
    except:
        pass
    
    clips = []
    for i in range(10):
        start_time = i * interval
        end_time = start_time + 1
        clips.append(clip.subclip(start_time, end_time))
    
    final_clip = concatenate_videoclips(clips).resize(newsize=(384, 216)).without_audio()
    final_clip.write_videofile(previewPath, fps=24, codec="libx264")

    for subclip in clips:
        subclip.close()

    clip.close()
    final_clip.close()
    
    return posterPath, previewPath

def split_video(file_path, segment_size_gb=8):
    import subprocess
    
    # Convert GB to bytes
    segment_size_bytes = segment_size_gb * 1024 * 1024 * 1024
    
    # Get the total size of the video file
    total_size_bytes = os.path.getsize(file_path)
    
    # Calculate the number of segments needed
    num_segments = total_size_bytes // segment_size_bytes + 1

    # Get the duration of the video file
    duration = get_duration(file_path)
    
    # Calculate the duration of each segment
    segment_duration = duration / num_segments
    
    # Generate output file pattern
    file_name, file_extension = os.path.splitext(file_path)
    output_pattern = f"{file_name}_segment_%03d{file_extension}"
    
    # Run FFmpeg command to split the video
    command = [
        "ffmpeg", "-i", file_path, "-c", "copy", "-map", "0", 
        "-segment_time", str(segment_duration), "-f", "segment", output_pattern
    ]
    subprocess.run(command)