#!/usr/bin/env python
"""backup_selfies.py  — auto-back-up every Malin render to a Dropbox-synced folder.

Watches ComfyUI's output folder and copies each new Malin/Midori render into a Dropbox folder,
so Dropbox syncs it to the cloud automatically. Catches BOTH the pics Malin sends AND the ones
you render by hand in ComfyUI. Standalone — no change to malin.py, no redeploy.

Run it once in its own window and leave it open:
    py backup_selfies.py

Stop with Ctrl+C.
"""
import os, time, shutil, glob

# ───── CONFIG — verify these two paths, edit if yours differ ─────────────────────────────
WATCH_DIR = r"C:\ComfyUI\output"                      # where ComfyUI SAVES renders (check this!)
DEST_DIR  = r"C:\Users\jkhyb\Dropbox\Malin_pics"      # Dropbox-synced backup folder (auto-created)
PATTERNS  = ("Malin_*.png", "Midori_*.png", "*RealVisFace*.png")   # render prefixes to back up
POLL_SECS = 5
# ─────────────────────────────────────────────────────────────────────────────────────────


def find_renders():
    hits = []
    for pat in PATTERNS:
        hits += glob.glob(os.path.join(WATCH_DIR, pat))
        hits += glob.glob(os.path.join(WATCH_DIR, "**", pat), recursive=True)  # subfolders too
    return set(hits)


def main():
    if not os.path.isdir(WATCH_DIR):
        print(f"[backup] WATCH_DIR not found: {WATCH_DIR}")
        print("         Open this file and set WATCH_DIR to your real ComfyUI output folder.")
        return
    os.makedirs(DEST_DIR, exist_ok=True)
    already = set(os.listdir(DEST_DIR))           # don't re-copy what's already backed up
    print(f"[backup] watching {WATCH_DIR}")
    print(f"[backup]   ->     {DEST_DIR}")
    print("[backup] running. leave this window open. Ctrl+C to stop.")
    while True:
        try:
            for src in find_renders():
                name = os.path.basename(src)
                if name in already:
                    continue
                try:
                    shutil.copy2(src, os.path.join(DEST_DIR, name))
                    already.add(name)
                    print(f"[backup] {name}")
                except (PermissionError, FileNotFoundError):
                    pass   # still being written; grab it next poll
        except Exception as e:
            print(f"[backup] error: {e}")
        time.sleep(POLL_SECS)


if __name__ == "__main__":
    main()
