"""
wivexx_projects.py — saved reel/video projects (the reel builder's save-load).
═══════════════════════════════════════════════════════════════════════════════
A project is just the reel builder's state (clips + trims/speed/mute/motion,
overlays, music, transition, format) serialised to JSON. Clips reference the
source files by absolute path, so a project is small metadata — re-open it later
to keep editing, then build. Stored as one JSON file in the project tree (the
live app can always read/write there, unlike %LOCALAPPDATA%).

    list_projects() -> [{id, name, ts, clips, overlays}]
    save_project(name, data, pid=None) -> (id, name)
    load_project(id) -> data | None
    delete_project(id) -> bool
"""
from __future__ import annotations

import json
import os
import time
import uuid

_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "wivexx_video_projects.json")


def _load_all() -> dict:
    try:
        with open(_FILE, encoding="utf-8") as fh:
            d = json.load(fh)
            if isinstance(d, dict) and isinstance(d.get("projects"), list):
                return d
    except Exception:
        pass
    return {"projects": []}


def _save_all(d: dict) -> None:
    tmp = _FILE + ".tmp"
    with open(tmp, "w", encoding="utf-8") as fh:
        json.dump(d, fh, indent=2)
    os.replace(tmp, _FILE)


def list_projects() -> list:
    out = []
    for p in _load_all().get("projects", []):
        data = p.get("data") or {}
        out.append({"id": p.get("id"), "name": p.get("name", ""), "ts": p.get("ts", 0),
                    "clips": len(data.get("clips") or []),
                    "overlays": len(data.get("overlays") or [])})
    out.sort(key=lambda x: x.get("ts", 0), reverse=True)
    return out


def save_project(name: str, data: dict, pid: str = None):
    d = _load_all()
    projs = d.setdefault("projects", [])
    name = (name or "Untitled reel").strip()[:80] or "Untitled reel"
    if pid:
        for p in projs:
            if p.get("id") == pid:
                p["name"], p["data"], p["ts"] = name, (data or {}), time.time()
                _save_all(d)
                return pid, name
    pid = uuid.uuid4().hex[:12]
    projs.append({"id": pid, "name": name, "ts": time.time(), "data": (data or {})})
    _save_all(d)
    return pid, name


def load_project(pid: str):
    for p in _load_all().get("projects", []):
        if p.get("id") == pid:
            return p.get("data")
    return None


def delete_project(pid: str) -> bool:
    d = _load_all()
    before = len(d.get("projects", []))
    d["projects"] = [p for p in d.get("projects", []) if p.get("id") != pid]
    _save_all(d)
    return len(d["projects"]) < before
