##==================================================================
##
## Paste to Timeline Installer
##
## For Windows / macOS only - sorry Linux people.
##
## Instructions:
##
##   1. Ensure you have Python installed
##   2. Save this script as installer.py
##   3. Open Resolve
##   4. Open the console via Workspace -> Console
##   5. Drag installer.py onto the console
## 
## If successful, a new script will be added called paste-image.py.
##
## Running it will append an image copied to your clipboard to your
## timeline.
##
## Within Resolve, you can set create hotkey to run the script for
## ease of use.
## 
##==================================================================

import os

SCRIPT_CONTENT = """##====================================================================
##
##              Paste to Timeline for DaVinci Resolve
##                           optifx.dev
##
##                     This is a PAID script.
##                  The license fee is $10,000.
##
##                If you're using this unlicensed,
##                YOU'LL BE HEARING FROM MY LAWYER.
##
## Windows/macOS only.
## Requires the PIL Python package.
## Works on my machine.
## 
##====================================================================

import os
import uuid
from PIL import Image, ImageGrab


if __name__ == '__main__':
    project = resolve.GetProjectManager().GetCurrentProject()
    media_path = project.GetSetting("projectMediaLocation")
    
    if media_path is None or media_path == "":
        media_path = resolve.Fusion().MapPath("Fusion:/")
    
    pastes_dir = os.path.join(media_path, "pastes")
    if not os.path.exists(pastes_dir):
        os.mkdir(pastes_dir)
    
    tail = uuid.uuid4()
    img_path = os.path.join(pastes_dir, f"paste_{tail}.png")
    
    image = ImageGrab.grabclipboard()
    if not isinstance(image, Image.Image):
        print("No image found in clipboard.")
        exit()
    
    image.save(img_path, format="png")

    if not os.path.exists(img_path):
        exit()
    
    mp = resolve.GetProjectManager().GetCurrentProject().GetMediaPool()
    mp_items = mp.ImportMedia([img_path])
    
    if mp_items is None or len(mp_items) == 0:
        print("The image could not be imported (reason unknown).")
        exit()
    
    for mpi in mp_items:
        mp.AppendToTimeline(mpi)"""

# Everything below is hellishly ugly, but I didn't want people to
# have to manually install Pillow if they aren't familiar with
# pip/Python and I'm not sure of a simpler/more reliable way.

try:
    import PIL
except Exception as e:
    import subprocess
    subprocess.run(["pip", "install", "pillow"])

    try:
        import PIL
    except Exception as e:
        print("Unable to install Pillow. Cannot proceed.")
        exit()

scripts_dir = resolve.Fusion().MapPath("Scripts:/")

if not os.path.exists(scripts_dir):
    os.mkdir(scripts_dir)
edit_dir = os.path.join(scripts_dir, "Edit")

if not os.path.exists(edit_dir):
    os.mkdir(edit_dir)
script_path = os.path.join(edit_dir, "paste-image.py")

with open(script_path, "w") as f:
    f.write(SCRIPT_CONTENT)

print(f"Script saved as {script_path}")