"""
UvoClips AI — DaVinci Resolve Import Script
==========================================
Run this script from inside DaVinci Resolve:
  Workspace > Scripts > Run Script... > select this file

Requirements:
  - DaVinci Resolve 18+ (provides the DaVinciResolveScript module)
  - Python 3.6+
  - A manifest.json file exported from the UvoClips AI web app
"""

import json
import sys
import os

# Use tkinter for the file dialog (stdlib — no pip install needed)
try:
    import tkinter as tk
    from tkinter import filedialog, messagebox
except ImportError:
    print("ERROR: tkinter is not available. Please use Python 3 with tkinter support.")
    sys.exit(1)

# Suppress the Tk root window
root = tk.Tk()
root.withdraw()
root.attributes("-topmost", True)


def show_error(msg: str):
    messagebox.showerror("UvoClips AI", msg)


def show_info(msg: str):
    messagebox.showinfo("UvoClips AI", msg)


def load_manifest() -> dict:
    path = filedialog.askopenfilename(
        title="Select PodClip manifest.json",
        filetypes=[("JSON files", "*.json"), ("All files", "*.*")],
    )
    if not path:
        sys.exit(0)  # User cancelled

    if not os.path.isfile(path):
        show_error(f"File not found: {path}")
        sys.exit(1)

    with open(path, "r", encoding="utf-8") as f:
        try:
            data = json.load(f)
        except json.JSONDecodeError as e:
            show_error(f"Invalid JSON in manifest: {e}")
            sys.exit(1)

    if "clips" not in data or not isinstance(data["clips"], list):
        show_error("manifest.json is missing a 'clips' array.")
        sys.exit(1)

    return data


def connect_resolve():
    """Connect to the running DaVinci Resolve instance."""
    try:
        import DaVinciResolveScript as dvr_script  # type: ignore  # provided by Resolve
    except ImportError:
        show_error(
            "Could not import DaVinciResolveScript.\n\n"
            "Make sure you are running this script from within DaVinci Resolve "
            "(Workspace > Scripts > Run Script...)."
        )
        sys.exit(1)

    resolve = dvr_script.scriptapp("Resolve")
    if resolve is None:
        show_error("Could not connect to DaVinci Resolve. Is Resolve open?")
        sys.exit(1)
    return resolve


def main():
    manifest = load_manifest()

    fps = manifest.get("project_framerate", 24)
    clips = manifest["clips"]

    if not clips:
        show_error("No clips found in manifest.json.")
        sys.exit(1)

    resolve = connect_resolve()
    project_manager = resolve.GetProjectManager()
    project = project_manager.GetCurrentProject()

    if project is None:
        show_error("No project is currently open in DaVinci Resolve.")
        sys.exit(1)

    added = 0
    errors = []

    for clip in clips:
        clip_name = clip.get("clip_name", f"clip_{added + 1}")
        start_frame = clip.get("start_frame")
        end_frame = clip.get("end_frame")

        if start_frame is None or end_frame is None:
            errors.append(f"  • {clip_name}: missing start_frame or end_frame, skipped.")
            continue

        if start_frame >= end_frame:
            errors.append(f"  • {clip_name}: start_frame >= end_frame, skipped.")
            continue

        render_settings = {
            "MarkIn": int(start_frame),
            "MarkOut": int(end_frame),
            "CustomName": clip_name,
        }

        success = project.SetRenderSettings(render_settings)
        if not success:
            errors.append(f"  • {clip_name}: SetRenderSettings failed, skipped.")
            continue

        job_id = project.AddRenderJob()
        if not job_id:
            errors.append(f"  • {clip_name}: AddRenderJob failed, skipped.")
            continue

        added += 1

    # Summary
    summary = f"Added {added} of {len(clips)} clips to the Render Queue."
    if errors:
        summary += "\n\nWarnings:\n" + "\n".join(errors)
        show_info(summary)
    else:
        show_info(summary)


if __name__ == "__main__":
    main()
