import os
import subprocess
import sys
import re

def convert_to_seconds(time_str):
    if re.match(r'\d{2}:\d{2}:\d{2}(\.\d+)?', time_str):
        parts = time_str.split(':')
        h, m = map(int, parts[:2])
        s = float(parts[2])
        return h * 3600 + m * 60 + s
    elif time_str.replace('.', '', 1).isdigit():
        return float(time_str)
    else:
        return None

def process_video(file, start, end):
    start_seconds = convert_to_seconds(start) if start else None
    end_seconds = convert_to_seconds(end) if end else None

    if start_seconds is not None and end_seconds is not None and not re.match(r'\d{2}:\d{2}:\d{2}(\.\d+)?', end):
        # If end time is a duration from start time
        end_seconds = start_seconds + end_seconds

    output_file = os.path.splitext(file)[0] + '_trimmed.mp4'
    command = ['./ffmpeg', '-i', file]

    if start_seconds is not None:
        command += ['-ss', str(start_seconds)]

    if end_seconds is not None:
        command += ['-to', str(end_seconds)]

    command += [
        '-c:v', 'libx264', '-crf', '5', '-preset', 'fast', '-pix_fmt', 'yuv420p10le', '-c:a', 'copy', output_file
    ]

    subprocess.run(command)
    print(f"Processed {file} -> {output_file}")

def main():
    if len(sys.argv) < 2:
        print("Please drag and drop video files onto this script.")
        return

    start_time = input("Enter the cut start time (in seconds or HH:MM:SS[.xx] format), or leave blank to start from the beginning: ")
    end_time = input("Enter the cut end time or duration (in seconds or HH:MM:SS[.xx] format), or leave blank to end at the video's end: ")

    for video_path in sys.argv[1:]:
        process_video(video_path, start_time, end_time)

if __name__ == "__main__":
    main()
