#!/usr/bin/env python3
"""Render a .blend with EEVEE on api.mdstudios.dev (v2) with live progress, and save one MP4.

  export MDS_API_KEY=mds_live_...
  python3 render_mds.py scene.blend --start 1 --end 600 --mode preview --out preview.mp4
  python3 render_mds.py scene.blend --start 1 --end 600 --mode final   --out final.mp4 --label "GALLINA" --name C1

Videos: every render belongs to a video. The API gives each video a unique id (vid_…); its label is the video's name
and may repeat. The first time a --label is used in a folder this script creates the video and remembers its id in
.mds_videos.json next to the .blend, so the sample, previews and finals of that label land in the same video.
--video vid_… picks one explicitly; --new-video starts a new video with the same label.

Modes: preview = 25 % resolution, 1 sample (fast, cheap) · final = 100 %, 16 samples.

Sample first: the API only renders a preview or final of a .blend after its sample was approved. For a new .blend
this script first renders a sample (about 8 frames spread over --start..--end, 25 %, 1 sample, a few cents), saves it
as <out>_muestra.mp4 (each frame held 1 s), prints its path and asks "¿Está bien la muestra? (s/n)". "s" approves
that .blend and goes on with the requested render; anything else stops so the .blend can be fixed and sent again
(a changed .blend is a new one and gets its own sample). Check missing textures (magenta), missing fonts (boxes),
lights and framing. Without a terminal (an AI assistant driving this script):
  python3 render_mds.py scene.blend --start 1 --end 600 --mode preview --out preview.mp4 --sample-only
  (look at preview_muestra.mp4, then)
  python3 render_mds.py scene.blend --start 1 --end 600 --mode preview --out preview.mp4 --approve
The .blend is uploaded once; the API splits the range into parts, renders several at once and retries failed parts.
This script shows the progress (frames, parts, ETA, cost so far), downloads each part as soon as it is done
(into <out>_parts/) and joins them with ffmpeg at the end. Only needs Python 3 and ffmpeg.
"""
import argparse
import hashlib
import re
import json
import os
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

API = os.environ.get("MDS_API_URL", "https://api.mdstudios.dev")


def call(method, url, key, data=None, raw=False, accept=(), ctype="application/octet-stream"):
    """One API call. Error codes listed in `accept` return their JSON body (with "_status") instead of exiting."""
    headers = {"authorization": f"Bearer {key}", "user-agent": "render_mds"}
    if data is not None:
        headers["content-type"] = ctype
    req = urllib.request.Request(url if url.startswith("http") else API + url, method=method, data=data, headers=headers)
    for attempt in range(5):                      # network hiccups: retry the call, not the render
        try:
            with urllib.request.urlopen(req, timeout=600) as r:
                body = r.read()
                return body if raw else json.loads(body)
        except urllib.error.HTTPError as e:
            if e.code in accept:
                body = json.loads(e.read() or b"{}")
                body["_status"] = e.code
                return body
            if e.code < 500:
                sys.exit(f"API error {e.code}: {e.read().decode(errors='replace')[:300]}")
        except (urllib.error.URLError, TimeoutError):
            pass
        time.sleep(5 * (attempt + 1))
    sys.exit("API unreachable")


def fmt(seconds):
    return "--:--" if seconds is None else f"{int(seconds) // 60:02d}:{int(seconds) % 60:02d}"


def render(key, query, blend, out, fps, hold=None):
    """Launch one render, show its progress, download each part as soon as it is done and join them into `out`.
    hold = seconds each one-frame part lasts in the video (samples), instead of one frame.
    Returns the final GET /v2/renders/{id}, or the 409 body when the API asks for a sample first."""
    parts_dir = os.path.splitext(out)[0] + "_parts"
    os.makedirs(parts_dir, exist_ok=True)
    r = call("POST", f"/v2/renders?{query}", key, blend, accept=(409,))
    if r.get("_status") == 409:
        return r
    rid = r["id"]
    print(f"render {rid}: {r['parts']} parts", flush=True)

    got = {}                                       # index -> local MP4
    while True:
        r = call("GET", f"/v2/renders/{rid}", key)
        for p in r["parts"]:
            if p["status"] == "DONE" and p["index"] not in got:
                data = call("GET", p["file_url"], key, raw=True)
                path = os.path.join(parts_dir, f"part_{p['index']:04d}")
                if data[:4] == b"\x89PNG":         # a one-frame part comes back as PNG: make it a 1-frame MP4
                    open(path + ".png", "wb").write(data)
                    # a sample holds each frame `hold` seconds (and pads odd sizes, which libx264 refuses)
                    length = ["-loop", "1", "-t", str(hold)] if hold else []
                    tail = ["-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2"] if hold else ["-frames:v", "1"]
                    subprocess.run(["ffmpeg", "-loglevel", "error", "-y", *length, "-framerate", str(fps), "-i", path + ".png",
                                    *tail, "-c:v", "libx264", "-pix_fmt", "yuv420p", path + ".mp4"], check=True)
                else:
                    open(path + ".mp4", "wb").write(data)
                got[p["index"]] = path + ".mp4"
        bar = "#" * int(r["progress_pct"] / 5)
        print(f"\r[{bar:<20}] {r['progress_pct']:5.1f}%  frames {r['frames_done']}/{r['frames']}  "
              f"parts {r['done']}/{r['total']} (downloaded {len(got)})  {fmt(r['elapsed_seconds'])} "
              f"ETA {fmt(r['eta_seconds'])}  ${r['price_usd']:.3f}   ", end="", flush=True)
        if r["status"] != "RUNNING":
            break
        time.sleep(5)
    print()
    if r["status"] != "COMPLETED":
        failed = [p for p in r["parts"] if p["status"] == "FAILED"]
        for p in failed:
            print(f"part {p['index']} (frames {p['frame_start']}-{p['frame_end']}) failed: {p.get('error')}")
        sys.exit(f"render {r['status']}; finished parts are in {parts_dir}")

    lst = os.path.join(parts_dir, "list.txt")
    with open(lst, "w") as fh:
        fh.writelines(f"file '{got[i]}'\n" for i in sorted(got))
    # re-encode (no -c copy): copying across joins can drop a frame at each seam
    subprocess.run(["ffmpeg", "-loglevel", "error", "-y", "-f", "concat", "-safe", "0", "-i", lst,
                    "-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p", "-r", str(fps), out], check=True)
    print(f"saved {out}: {r['frames'] if not hold else r['total']} frames, {fmt(r['elapsed_seconds'])} of render, "
          f"${r['price_usd']:.4f}, {r['gpu_seconds']} GPU s")
    return r


def sample(key, a, blend, out, name):
    """Render the sample of this .blend over the requested range and save it as <out>_muestra.mp4."""
    path = os.path.splitext(out)[0] + "_muestra.mp4"
    query = f"frame_start={a.start}&frame_end={a.end}&preset=sample&fps={a.fps}&video_id={a.video}"
    query += "&name=" + urllib.parse.quote((name[:56].strip() + " muestra").strip())
    print("sample: a few frames of this .blend at 25 %, 1 sample, to check it before the real render", flush=True)
    render(key, query, blend, path, a.fps, hold=1)
    print(f"SAMPLE: {path}")
    print("check it: missing textures (magenta), missing fonts (boxes), lights, framing", flush=True)
    return path


def video_for(key, a):
    """The id of the video this render belongs to: --video, or the one remembered for --label in this folder
    (.mds_videos.json next to the .blend), or a new one made by the API."""
    if a.video:
        return a.video
    if not a.label:
        sys.exit("say which video this is: --label \"NAME\" (a new or remembered video) or --video vid_...")
    memo = os.path.join(os.path.dirname(os.path.abspath(a.blend)), ".mds_videos.json")
    try:
        with open(memo) as fh:
            known = json.load(fh)
    except (OSError, ValueError):
        known = {}
    if a.label in known and not a.new_video:
        return known[a.label]
    v = call("POST", "/v2/videos", key, json.dumps({"label": a.label}).encode(), ctype="application/json")
    known[a.label] = v["video_id"]
    with open(memo, "w") as fh:
        json.dump(known, fh, indent=2, ensure_ascii=False)
    print(f"new video {v['video_id']} ({a.label}); its id is kept in {memo}", flush=True)
    return v["video_id"]


def approve(key, sha):
    r = call("POST", f"/v2/blends/{sha}/approve", key, b"", accept=(409,))
    if r.get("_status") == 409:
        sys.exit(f"cannot approve: {r.get('message') or r.get('error')}")
    print(f"approved .blend {sha}", flush=True)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("blend")
    ap.add_argument("--start", type=int, required=True)
    ap.add_argument("--end", type=int, required=True)
    ap.add_argument("--mode", choices=("preview", "final"), default="preview")
    ap.add_argument("--out", required=True)
    ap.add_argument("--fps", type=int, default=30)
    ap.add_argument("--chunk", type=int, help="frames per part (default: 300 preview, 120 final)")
    ap.add_argument("--label", help="the video's name, e.g. GALLINA (may repeat; the video id is what groups renders)")
    ap.add_argument("--video", help="the video's id (vid_...), when you have it; otherwise --label finds or makes it")
    ap.add_argument("--new-video", action="store_true", help="start a new video with this --label instead of reusing it")
    ap.add_argument("--name", help="name of this render inside the video, e.g. C1 (default: the --out file name)")
    ap.add_argument("--sample-only", action="store_true",
                    help="only render the sample of this .blend (<out>_muestra.mp4) and exit, to look at it first")
    ap.add_argument("--approve", action="store_true",
                    help="approve this .blend's finished sample without asking, then render --mode")
    a = ap.parse_args()
    key = os.environ.get("MDS_API_KEY") or sys.exit("set MDS_API_KEY")
    out = os.path.abspath(a.out)
    a.video = video_for(key, a)
    query = (f"frame_start={a.start}&frame_end={a.end}&preset={a.mode}&fps={a.fps}&video_id={a.video}"
             + (f"&chunk={a.chunk}" if a.chunk else ""))
    name = a.name or os.path.splitext(os.path.basename(out))[0]
    name = re.sub(r"[^\w .-]", "_", name)[:64].strip()   # the API takes letters, digits, spaces, _ . - (max 64)
    if name:
        query += "&name=" + urllib.parse.quote(name)
    with open(a.blend, "rb") as fh:
        blend = fh.read()
    sha = hashlib.sha256(blend).hexdigest()[:16]          # the API's fingerprint of this .blend (blend_sha)

    state = call("GET", f"/v2/blends/{sha}", key)
    if a.sample_only:
        sample(key, a, blend, out, name)
        print(f"look at it; if it is fine run again with --approve, otherwise fix the .blend and run again")
        return
    if not state["approved"]:
        if a.approve and (state.get("sample") or {}).get("status") == "COMPLETED":
            approve(key, sha)
        else:
            if a.approve:
                print("this .blend has no finished sample yet: rendering it first", flush=True)
            sample(key, a, blend, out, name)
            try:
                ok = input("¿Está bien la muestra? (s/n) ").strip().lower() in ("s", "si", "sí", "y", "yes")
            except EOFError:
                sys.exit("no answer (no terminal): look at the sample, then run again with --approve")
            if not ok:
                sys.exit("not approved: fix the .blend (pack textures and fonts, lights, camera) and run again; "
                         "the new .blend gets its own sample")
            approve(key, sha)

    r = render(key, query, blend, out, a.fps)
    if r.get("_status") == 409:
        sys.exit(f"API: {r.get('message') or r.get('error')}")

if __name__ == "__main__":
    main()
