# subtitleburn.py
import tkinter as tk
from tkinter import filedialog, messagebox
import subprocess
import os

class SubtitleBurnerApp:
    def __init__(self, master):
        self.master = master
        master.title("FFmpeg Subtitle Burner")

        # Video file
        self.video_label = tk.Label(master, text="Video File (.mp4):")
        self.video_label.grid(row=0, column=0, sticky='e')
        self.video_entry = tk.Entry(master, width=50)
        self.video_entry.grid(row=0, column=1, padx=5, pady=5)
        self.video_button = tk.Button(master, text="Browse", command=self.browse_video)
        self.video_button.grid(row=0, column=2, padx=5)

        # Subtitle file
        self.subtitle_label = tk.Label(master, text="Subtitle File (.srt):")
        self.subtitle_label.grid(row=1, column=0, sticky='e')
        self.subtitle_entry = tk.Entry(master, width=50)
        self.subtitle_entry.grid(row=1, column=1, padx=5, pady=5)
        self.subtitle_button = tk.Button(master, text="Browse", command=self.browse_subtitle)
        self.subtitle_button.grid(row=1, column=2, padx=5)

        # Suffix entry
        self.suffix_label = tk.Label(master, text="Filename Suffix (e.g. _str):")
        self.suffix_label.grid(row=2, column=0, sticky='e')
        self.suffix_entry = tk.Entry(master, width=20)
        self.suffix_entry.grid(row=2, column=1, sticky='w', padx=5)

        # Run button
        self.run_button = tk.Button(master, text="Burn Subtitles", command=self.burn_subtitles)
        self.run_button.grid(row=3, column=1, pady=10)

        # Status message
        self.status_label = tk.Label(master, text="", fg="blue")
        self.status_label.grid(row=4, column=0, columnspan=3)

    def browse_video(self):
        path = filedialog.askopenfilename(filetypes=[("MP4 Video", "*.mp4")])
        if path:
            self.video_entry.delete(0, tk.END)
            self.video_entry.insert(0, path)

    def browse_subtitle(self):
        path = filedialog.askopenfilename(filetypes=[("Subtitle File", "*.srt")])
        if path:
            self.subtitle_entry.delete(0, tk.END)
            self.subtitle_entry.insert(0, path)

    def burn_subtitles(self):
        video_path = self.video_entry.get()
        subtitle_path = self.subtitle_entry.get()
        suffix = self.suffix_entry.get().strip()

        if not video_path or not os.path.isfile(video_path):
            messagebox.showerror("Error", "Please select a valid MP4 video file.")
            return
        if not subtitle_path or not os.path.isfile(subtitle_path):
            messagebox.showerror("Error", "Please select a valid subtitle file (.srt).")
            return
        if not suffix:
            messagebox.showerror("Error", "Please enter a suffix for the output filename.")
            return

        video_dir = os.path.dirname(video_path)
        video_name = os.path.basename(video_path)
        subtitle_file = os.path.basename(subtitle_path)

        base_name, ext = os.path.splitext(video_name)
        output_path = os.path.join(video_dir, f"{base_name}{suffix}{ext}")

        # Escape subtitle path for FFmpeg (relative to cwd)
        subtitle_ffmpeg_path = subtitle_file.replace("\\", "\\\\").replace(":", "\\:")

        # FFmpeg command (run from the video directory so relative paths work)
        cmd = [
            "ffmpeg",
            "-i", video_name,
            "-vf", f"subtitles={subtitle_ffmpeg_path}",
            "-c:a", "copy",
            output_path
        ]

        # Print for debugging
        print("Running FFmpeg command in:", video_dir)
        print(" ".join(cmd))

        self.status_label.config(text="Processing...")

        try:
            subprocess.run(cmd, cwd=video_dir, check=True)
            self.status_label.config(text="Success! Subtitled video created.")
            messagebox.showinfo("Done", f"Subtitled video saved as:\n{output_path}")
        except subprocess.CalledProcessError as e:
            self.status_label.config(text="FFmpeg failed.")
            messagebox.showerror("FFmpeg Error", f"FFmpeg failed:\n{e}")

# Run the GUI
if __name__ == "__main__":
    root = tk.Tk()
    app = SubtitleBurnerApp(root)
    root.mainloop()
