"""
PictureFlow Send: sends a render to its shot's Review page from Nuke, from Deadline when a render finishes, or from
the command line. One file, Python 3 standard library only (nothing to pip install).

Set up once (on each workstation and render node):

    PICTUREFLOW_KEY=pf_live_...     Settings > API keys, with "Change Tracker shows"
    PICTUREFLOW_SHOW=SAL            the show's code (or its id), as on the show's Settings page

It works out the shot and step from the file name or its folders (SAL_002_0010_comp_v012.####.exr is shot
SAL_002_0010, step comp) and sends the path. The render stays on your storage: PictureFlow keeps only where it is,
so PictureFlow Review can open it. Add a small review copy (an H.264 MP4) and it plays on the website too, from
the storage you connected in Tracker Settings.

Command line:
    python pictureflow_send.py /renders/SAL_002_0010/comp/v012/SAL_002_0010_comp_v012.####.exr --comment "Sky warmer"
    python pictureflow_send.py render.exr --shot SAL_002_0010 --step comp --review render_h264.mp4

Nuke (add to ~/.nuke/menu.py, with this file in ~/.nuke):
    import pictureflow_send
    pictureflow_send.nuke_menu()
  Then select a Write node and choose PictureFlow > Send to review.

Deadline: in the submitter, set this file as the job's Post Job Script. When the job finishes, its output is sent.
  Optional job Extra Info: PictureFlowShot=SAL_002_0010, PictureFlowStep=comp, PictureFlowReview=/path/review.mp4.
  The job's comment goes with it. Set PICTUREFLOW_KEY and PICTUREFLOW_SHOW on the render nodes or in the job's
  environment.

Docs: https://www.pictureflow.pro/developers
"""
import hashlib
import json
import mimetypes
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

API = os.environ.get("PICTUREFLOW_API", "https://www.pictureflow.pro/api/v1").rstrip("/")
__version__ = "1.0"


class SendError(Exception):
    pass


def _request(method, path, body=None, key=None, idem=None, retries=4):
    key = key or os.environ.get("PICTUREFLOW_KEY")
    if not key:
        raise SendError("Set PICTUREFLOW_KEY to an API key from Settings > API keys.")
    headers = {"Authorization": "Bearer " + key, "Accept": "application/json", "User-Agent": "pictureflow-send/" + __version__}
    data = None
    if body is not None:
        data = json.dumps(body).encode("utf-8")
        headers["Content-Type"] = "application/json"
    if idem:
        headers["Idempotency-Key"] = idem
    url = path if path.startswith("http") else API + path
    for attempt in range(retries + 1):
        try:
            with urllib.request.urlopen(urllib.request.Request(url, data=data, headers=headers, method=method), timeout=60) as r:
                return json.loads(r.read().decode("utf-8") or "{}")
        except urllib.error.HTTPError as e:
            if e.code in (429, 500, 502, 503, 504) and attempt < retries:
                time.sleep(int(e.headers.get("Retry-After") or 2 ** attempt))
                continue
            try:
                err = json.loads(e.read().decode("utf-8")).get("error", {})
            except Exception:
                err = {}
            raise SendError("%s %s" % (e.code, err.get("message") or e.reason), err.get("code"))
        except urllib.error.URLError:
            if attempt == retries:
                raise SendError("Couldn't reach PictureFlow. Check this computer's internet connection.")
            time.sleep(2 ** attempt)


def _get(path, **params):
    q = urllib.parse.urlencode({k: v for k, v in params.items() if v is not None})
    return _request("GET", path + ("?" + q if q else ""))


def find_show(show=None):
    """The show by id or code (PICTUREFLOW_SHOW when not given)."""
    show = (show or os.environ.get("PICTUREFLOW_SHOW") or "").strip()
    if not show:
        raise SendError("Set PICTUREFLOW_SHOW to the show's code, or pass --show.")
    shows = _get("/shows")["data"]
    for s in shows:
        if s["id"] == show or (s.get("code") or "").lower() == show.lower() or s["name"].lower() == show.lower():
            return s
    raise SendError("No show called %s for this key. Shows it can reach: %s" % (show, ", ".join(s.get("code") or s["name"] for s in shows) or "none"))


def _words(path):
    """The file name and its folders, nearest first, without frame numbers or extensions."""
    parts = re.split(r"[\\/]+", os.path.normpath(path))
    name = re.sub(r"\.(#+|@+|%0?\d*d|\$F\d*|\d{3,8})(?=\.[A-Za-z0-9]+$)", "", parts[-1])
    out = [os.path.splitext(name)[0]] + [p for p in reversed(parts[:-1]) if p]
    return out[:6]


def guess(path, show):
    """(shot code candidates, step id) read from the path, using the show's pipeline steps."""
    codes, step = [], None
    steps = show.get("steps") or []
    for w in _words(path):
        tokens = [t for t in re.split(r"[_.\-\s]+", w) if t]
        # Longest first: SAL_002_0010_comp_v012, SAL_002_0010_comp, SAL_002_0010, SAL_002...
        for n in range(len(tokens), 0, -1):
            c = "_".join(tokens[:n])
            if c not in codes and not re.fullmatch(r"v\d+", c, re.I):
                codes.append(c)
        if not step:
            for t in tokens:
                for s in steps:
                    if t.lower() in (s["id"].lower(), (s.get("short") or "").lower(), s["name"].lower()):
                        step = s["id"]
                        break
                if step:
                    break
    return codes[:40], step


def find_shot(show, codes):
    """The first code (longest first) that is a shot on the show, matching case-insensitively."""
    if not codes:
        return None
    variants = []
    for c in codes:
        for v in (c, c.upper(), c.lower()):
            if v not in variants:
                variants.append(v)
    found = {s["code"].lower(): s for s in _get("/shows/%s/shots" % show["id"], code=",".join(variants[:100]), limit=100)["data"]}
    for c in codes:
        if c.lower() in found:
            return found[c.lower()]
    return None


def _upload(show_id, path, kind):
    ctype = "video/quicktime" if path.lower().endswith(".mov") else (mimetypes.guess_type(path)[0] or "application/octet-stream")
    up = _request("POST", "/shows/%s/uploads" % show_id, {"kind": kind, "content_type": ctype, "size": os.path.getsize(path), "filename": os.path.basename(path)})
    with open(path, "rb") as f:
        headers = dict(up["upload"]["headers"], **{"Content-Length": str(os.path.getsize(path))})
        urllib.request.urlopen(urllib.request.Request(up["upload"]["url"], data=f, headers=headers, method="PUT"), timeout=3600).close()
    return up["id"]


def send(path, shot=None, step=None, comment=None, review=None, thumbnail=None, show=None, url=None, log=print):
    """Sends a render to its shot's Review page and returns the new version. path is where it sits on your storage."""
    show = find_show(show)
    codes, guessed = guess(path, show)
    s = find_shot(show, [shot] if shot else codes)
    if not s:
        raise SendError("Couldn't tell which shot %s is. Put the shot code in the file or folder name, or pass --shot." % os.path.basename(path))
    step = step or guessed
    # Where it sits, as this computer sees it (a drive letter, a share or a mount): PictureFlow Review maps it per computer.
    body = {"source_path": path if re.match(r"^([A-Za-z]:|//|\\\\)", path) else os.path.abspath(path)}
    if url:
        body["source_url"] = url
    if step:
        body["step_id"] = step
    if comment:
        body["comment"] = comment[:2000]
    for kind, file in (("review", review), ("thumbnail", thumbnail)):
        if not file:
            continue
        try:
            body[kind + "_upload_id"] = _upload(show["id"], file, kind)
        except SendError as e:
            if e.args[1:] and e.args[1] == "no_hosted_storage":
                log("PictureFlow: no storage connected in Tracker Settings, so the %s copy stays on your side. Sending the path only." % kind)
            else:
                raise
    # The same render sent twice (a re-queued Deadline job, a double click) makes one version, not two.
    idem = "send-" + hashlib.sha256(("%s|%s|%s" % (s["id"], body["source_path"], step or "")).encode("utf-8")).hexdigest()[:40]
    v = _request("POST", "/shots/%s/versions" % s["id"], body, idem=idem)
    label = next((x["name"] for x in show.get("steps") or [] if x["id"] == step), step)
    log("PictureFlow: sent %s %s%s for review." % (s["code"], v.get("name") or "", " (%s)" % label if label else ""))
    return v


# ───────────────────────────── Nuke ─────────────────────────────


def nuke_send(node=None):
    """Sends the selected Write node's render. Asks for a comment first."""
    import nuke  # noqa: only inside Nuke

    node = node or (nuke.selectedNodes("Write") or [None])[0]
    if node is None:
        nuke.message("Select a Write node first.")
        return None
    path = nuke.filename(node) or node["file"].getValue()
    if not path:
        nuke.message("This Write node has no file yet.")
        return None
    comment = nuke.getInput("Note for the reviewers (optional)", "")
    if comment is None:
        return None
    try:
        v = send(path, comment=comment or None, log=lambda m: nuke.tprint(m))
        nuke.message("Sent %s to review." % (v.get("name") or ""))
        return v
    except SendError as e:
        nuke.message("PictureFlow couldn't send it:\n%s" % e.args[0])
    return None


def nuke_after_render():
    """For a Write node's afterRender: sends what it just rendered, with no questions."""
    import nuke  # noqa: only inside Nuke

    try:
        send(nuke.filename(nuke.thisNode()) or nuke.thisNode()["file"].getValue(), log=lambda m: nuke.tprint(m))
    except SendError as e:
        nuke.tprint("PictureFlow couldn't send it: %s" % e.args[0])


def nuke_menu():
    import nuke  # noqa: only inside Nuke

    m = nuke.menu("Nuke").addMenu("PictureFlow")
    m.addCommand("Send to review", "import pictureflow_send; pictureflow_send.nuke_send()")
    m.addCommand("Send after every render of this Write", "import nuke; [n['afterRender'].setValue('import pictureflow_send; pictureflow_send.nuke_after_render()') for n in nuke.selectedNodes('Write')]")


# ───────────────────────────── Deadline ─────────────────────────────


def __main__(*args):
    """Deadline Post Job Script: sends the finished job's first output."""
    plugin = args[0]
    job = plugin.GetJob()
    dirs, names = list(job.JobOutputDirectories), list(job.JobOutputFileNames)
    if not dirs or not names:
        plugin.LogWarning("PictureFlow: the job has no output to send.")
        return
    path = os.path.join(dirs[0], names[0])
    extra = lambda k: (job.GetJobExtraInfoKeyValue(k) or None)
    for k in ("PICTUREFLOW_KEY", "PICTUREFLOW_SHOW"):
        if not os.environ.get(k) and job.GetJobEnvironmentKeyValue(k):
            os.environ[k] = job.GetJobEnvironmentKeyValue(k)
    try:
        send(path, shot=extra("PictureFlowShot"), step=extra("PictureFlowStep"), review=extra("PictureFlowReview"), comment=job.JobComment or None, log=plugin.LogInfo)
    except SendError as e:
        # A failed send never fails the render.
        plugin.LogWarning("PictureFlow couldn't send it: %s" % e.args[0])


# ───────────────────────────── Command line ─────────────────────────────


def main(argv=None):
    import argparse

    p = argparse.ArgumentParser(description="Send a render to its shot's Review page in PictureFlow.")
    p.add_argument("path", help="The render on your storage (a movie, or a frame sequence like shot_v012.####.exr)")
    p.add_argument("--show", help="The show's code or id (default: PICTUREFLOW_SHOW)")
    p.add_argument("--shot", help="The shot code, when the path doesn't say")
    p.add_argument("--step", help="The pipeline step id, like comp")
    p.add_argument("--comment", help="A note for the reviewers")
    p.add_argument("--review", help="A small review copy (H.264 MP4) to play on the website")
    p.add_argument("--thumbnail", help="A still (JPEG or PNG)")
    p.add_argument("--url", help="A link to the render on your storage, shown as Watch")
    a = p.parse_args(argv)
    try:
        send(a.path, shot=a.shot, step=a.step, comment=a.comment, review=a.review, thumbnail=a.thumbnail, show=a.show, url=a.url)
    except SendError as e:
        print("PictureFlow couldn't send it: %s" % e.args[0], file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
