# subtitle_shift_dragdrop.py
import os
import json
import pysrt
import tkinter as tk
from tkinter import filedialog, messagebox
from tkinterdnd2 import DND_FILES, TkinterDnD

CONFIG_FILE = "subtitle_shift_config.json"

def load_config():
    if os.path.exists(CONFIG_FILE):
        try:
            with open(CONFIG_FILE, "r", encoding="utf-8") as f:
                return json.load(f)
        except:
            return {}
    return {}

def save_config(config):
    try:
        with open(CONFIG_FILE, "w", encoding="utf-8") as f:
            json.dump(config, f)
    except:
        pass

def shift_subtitles(file, offset, suffix):
    subs = pysrt.open(file)
    subs.shift(seconds=offset)
    base, ext = os.path.splitext(file)

    # Ensure suffix starts with underscore unless blank
    if suffix and not suffix.startswith("_"):
        suffix = "_" + suffix

    new_file = f"{base}{suffix}{ext}"

    # Check for overwrite
    if os.path.exists(new_file):
        answer = messagebox.askyesno(
            "File Exists",
            f"{os.path.basename(new_file)} already exists.\n\nDo you want to overwrite it?"
        )
        if not answer:
            return None  # cancel save

    subs.save(new_file, encoding="utf-8")
    return new_file

def browse_file():
    initial_dir = config.get("last_dir", os.getcwd())
    filepath = filedialog.askopenfilename(
        filetypes=[("Subtitle files", "*.srt")],
        title="Select Subtitle File",
        initialdir=initial_dir
    )
    if filepath:
        set_file(filepath)

def set_file(filepath):
    entry_file.delete(0, tk.END)
    entry_file.insert(0, filepath.strip("{}"))  # strip curly braces from drag&drop paths
    config["last_dir"] = os.path.dirname(filepath)
    save_config(config)

def do_shift():
    try:
        filepath = entry_file.get().strip()
        if not filepath:
            messagebox.showerror("Error", "Please select a subtitle file.")
            return

        offset = float(entry_offset.get().strip())
        suffix = entry_suffix.get().strip()

        new_file = shift_subtitles(filepath, offset, suffix)

        if new_file:  # only show success if saved
            # Save last values
            config["last_dir"] = os.path.dirname(filepath)
            config["last_shift"] = offset
            config["last_suffix"] = suffix
            save_config(config)

            messagebox.showinfo("Done", f"Shifted file saved:\n{new_file}")
    except Exception as e:
        messagebox.showerror("Error", str(e))

# Load saved config
config = load_config()

# GUI setup (with drag-and-drop)
root = TkinterDnD.Tk()
root.title("Subtitle Time Shifter")
root.geometry("480x220")

# File selection
tk.Label(root, text="Subtitle file (drag & drop or Browse):").pack(anchor="w", padx=10, pady=5)
frame_file = tk.Frame(root)
frame_file.pack(fill="x", padx=10)
entry_file = tk.Entry(frame_file)
entry_file.pack(side="left", fill="x", expand=True)
entry_file.drop_target_register(DND_FILES)
entry_file.dnd_bind("<<Drop>>", lambda e: set_file(e.data))
tk.Button(frame_file, text="Browse", command=browse_file).pack(side="left", padx=5)

# Shift amount
tk.Label(root, text="Shift (seconds, e.g. -1.5 or 2.25):").pack(anchor="w", padx=10, pady=5)
entry_offset = tk.Entry(root)
entry_offset.insert(0, str(config.get("last_shift", 1.0)))  # restore last shift or default
entry_offset.pack(fill="x", padx=10)

# Custom suffix
tk.Label(root, text="Output suffix (default: _shifted):").pack(anchor="w", padx=10, pady=5)
entry_suffix = tk.Entry(root)
entry_suffix.insert(0, config.get("last_suffix", "_shifted"))
entry_suffix.pack(fill="x", padx=10)

# Action button
tk.Button(root, text="Apply Shift", command=do_shift).pack(pady=10)

root.mainloop()