import os
from tkinter import Tk, filedialog, simpledialog, messagebox
from moviepy.video.io.VideoFileClip import VideoFileClip
from datetime import datetime, timedelta

def format_srt_time(seconds):
    """Format time for SRT: hh:mm:ss,SSS"""
    hrs = int(seconds // 3600)
    mins = int((seconds % 3600) // 60)
    secs = int(seconds % 60)
    millis = int((seconds - int(seconds)) * 1000)
    return f"{hrs:02}:{mins:02}:{secs:02},{millis:03}"

def generate_srt(video_path, interval, ref_video_seconds, ref_real_time):
    clip = VideoFileClip(video_path)
    duration = clip.duration

    srt_lines = []
    count = 1
    current = 0

    # Calculate time difference between 0 sec in video and real-world clock
    delta = timedelta(
        hours=ref_real_time.hour,
        minutes=ref_real_time.minute,
        seconds=ref_real_time.second
    ) - timedelta(seconds=ref_video_seconds)

    while current < duration:
        start_time = format_srt_time(current)
        end_time = format_srt_time(min(current + interval, duration))

        # Real-world time at "current" second
        real_world_time = timedelta(seconds=current) + delta
        hours = int(real_world_time.total_seconds() // 3600) % 24
        minutes = int((real_world_time.total_seconds() % 3600) // 60)
        seconds = int(real_world_time.total_seconds() % 60)

        subtitle_text = f"{hours:02}:{minutes:02}:{seconds:02}"

        srt_lines.append(f"{count}")
        srt_lines.append(f"{start_time} --> {end_time}")
        srt_lines.append(subtitle_text)
        srt_lines.append("")
        count += 1
        current += interval

    srt_output_path = os.path.splitext(video_path)[0] + "_timeofday.srt"
    with open(srt_output_path, 'w', encoding='utf-8') as f:
        f.write('\n'.join(srt_lines))

    messagebox.showinfo("Done", f"SRT file saved as:\n{srt_output_path}")

def main():
    root = Tk()
    root.withdraw()

    video_path = filedialog.askopenfilename(title="Select MP4 video", filetypes=[("MP4 files", "*.mp4")])
    if not video_path:
        return

    try:
        interval = simpledialog.askinteger("Interval", "Enter subtitle interval (in seconds):", minvalue=1)
        ref_video_seconds = simpledialog.askfloat("Reference video time", "Enter reference time in video (seconds):")
        ref_real_time_str = simpledialog.askstring("Real-world time", "Enter real-world start time (HH:MM:SS):")

        ref_real_time = datetime.strptime(ref_real_time_str, "%H:%M:%S")

        generate_srt(video_path, interval, ref_video_seconds, ref_real_time)

    except Exception as e:
        messagebox.showerror("Error", str(e))

if __name__ == "__main__":
    main()
