#!/usr/bin/env python3
"""Upload one video to Datumwell and write one JSON result page per stdout line."""

import argparse
import getpass
import hashlib
import json
import os
from pathlib import Path
import sys
import time
import uuid
from urllib.error import HTTPError
from urllib.parse import urlsplit
from urllib.request import build_opener, HTTPRedirectHandler, Request


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def run(video, job_id):
    base = (os.getenv("RR_API") or "https://datumwell.io/api/v1").rstrip("/")
    url = urlsplit(base)
    if url.scheme != "https" or not url.hostname or url.username or url.password or url.query or url.fragment:
        raise ValueError("Set RR_API to your trusted HTTPS Datumwell API base.")
    token = os.getenv("ROBOROUTER_TOKEN") or getpass.getpass("Datumwell API token: ")
    if not token:
        raise ValueError("An API token is required.")
    job = f"{base}/hand-pose/jobs/{job_id}"
    client = build_opener(NoRedirect())

    def api(suffix="", body=None):
        data = None if body is None else json.dumps(body).encode()
        headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
        req = Request(job + suffix, data=data, headers=headers)
        for attempt in range(4):
            try:
                with client.open(req, timeout=90) as reply:
                    return json.load(reply)
            except HTTPError as exc:
                if data is not None or exc.code not in (429, 503) or attempt == 3:
                    raise
                wait = exc.headers.get("Retry-After", "")
                exc.close()
                time.sleep(max(1, int(wait)) if wait.isdigit() else 30)

    print(f"Job {job_id} (use --job-id {job_id} to resume this video).", file=sys.stderr)
    with video.open("rb") as source:
        digest = hashlib.sha256()
        for block in iter(lambda: source.read(1024 * 1024), b""):
            digest.update(block)
        state = api("/upload-session", {
            "filename": video.name, "size_bytes": source.tell(), "sha256": digest.hexdigest(),
            "scope": "egocentric_single_wearer",
        })
        upload = state["upload"]
        if upload:
            for part in upload["parts"]:
                if urlsplit(part["url"]).scheme != "https":
                    raise ValueError("Expected an HTTPS storage upload URL.")
                source.seek((part["number"] - 1) * upload["part_size_bytes"])
                data = source.read(part["size_bytes"])
                if len(data) != part["size_bytes"]:
                    raise ValueError("Video changed while uploading.")
                # Signed storage URLs use only the headers supplied for this part.
                put = Request(part["url"], data=data, headers=part["headers"], method="PUT")
                with client.open(put, timeout=180):
                    pass
            api("/upload-complete", {"generation": upload["generation"]})

    if state["status"] == "uploading":
        state = api("/process", {})
    else:
        state = api()
    while state["status"] in ("uploading", "processing"):
        time.sleep(max(3, state.get("poll_after_seconds", 3)))
        state = api()
    if state["status"] != "completed":
        raise RuntimeError(f'{state["status"]}: {state.get("error_code") or job_id}')
    print(f'Charge: USD {int(state["billing"]["charged_microusd"]) / 1_000_000:.6f}', file=sys.stderr)
    offset = 0
    while offset is not None:
        page = api(f"/result?offset={offset}")
        print(json.dumps(page, separators=(",", ":")))
        offset = page["next_offset"]


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("video", type=Path)
    parser.add_argument("--job-id", type=uuid.UUID, help="Reuse the original job with the same file.")
    args = parser.parse_args()
    try:
        run(args.video, args.job_id or uuid.uuid4())
    except HTTPError as exc:
        # Error text can contain a temporary storage URL. Show only the API code.
        try:
            code = json.load(exc).get("error", {}).get("code")
        except (ValueError, AttributeError):
            code = None
        wait = exc.headers.get("Retry-After")
        sys.exit(f"HTTP {exc.code}: {code or exc.reason}." + (f" Retry after {wait}." if wait else ""))
    except (OSError, ValueError, RuntimeError) as exc:
        sys.exit(str(exc))
