"""OpenPix video API v2 example. Submit only when explicitly requested."""

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


BASE = "https://openpix.cc"
TASK = re.compile(r"task_[A-Za-z0-9_-]{5,160}")
RECEIPT = re.compile(r"[A-Za-z0-9_-]{8,100}")


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, *_):
        return None


class Station:
    def __init__(self, key):
        self.key = key
        self.http = build_opener(NoRedirect())

    def request(self, path, method="GET", data=None, content_type=None, timeout=40):
        url = urljoin(BASE, path)
        parsed = urlsplit(url)
        if parsed.scheme != "https" or not parsed.hostname or parsed.username is not None:
            raise ValueError("Invalid HTTPS address")
        headers = {}
        if parsed.netloc == urlsplit(BASE).netloc:
            headers["Authorization"] = "Bearer " + self.key
        if content_type:
            headers["Content-Type"] = content_type
        try:
            return self.http.open(Request(url, data, headers, method=method), timeout=timeout)
        except HTTPError as reply:
            return reply

    def json(self, path, method="GET", body=None):
        data = json.dumps(body, ensure_ascii=False).encode() if body is not None else None
        with self.request(path, method, data, "application/json" if data else None) as reply:
            raw = reply.read(1024 * 1024 + 1)
            obj = json.loads(raw) if raw and reply.headers.get_content_type() == "application/json" else {}
            return reply.code, obj, reply.headers.get("Retry-After")

    def download(self, task, output):
        url = BASE + "/v2/videos/" + task + "/content"
        partial = output.with_name(output.name + ".part")
        for _ in range(5):
            with self.request(url, timeout=90) as reply:
                if reply.code in (301, 302, 303, 307, 308) and reply.headers.get("Location"):
                    url = urljoin(url, reply.headers["Location"])
                    continue
                if reply.code != 200:
                    raise ValueError(f"Download HTTP {reply.code}. Keep the original task ID.")
                head = reply.read(32)
                if head[4:8] != b"ftyp":
                    raise ValueError("Expected MP4 from the download endpoint")
                length = reply.headers.get("Content-Length", "")
                created = False
                try:
                    with partial.open("xb") as file:
                        created = True
                        file.write(head)
                        while chunk := reply.read(256 * 1024):
                            file.write(chunk)
                    if length.isdigit() and partial.stat().st_size != int(length):
                        raise ValueError("Incomplete download")
                    os.link(partial, output)
                finally:
                    if created:
                        partial.unlink(missing_ok=True)
                return
        raise ValueError("Download redirected too many times")


def save(path, data, create=False):
    if create:
        with path.open("x", encoding="utf-8") as file:
            json.dump(data, file)
        return
    part = path.with_name(path.name + ".writing")
    part.write_text(json.dumps(data), encoding="utf-8")
    os.replace(part, path)


def wait_delay(header):
    return int(header) if header and len(header) <= 9 and header.isascii() and header.isdigit() else 5


def check_id(value, pattern):
    if not isinstance(value, str) or not pattern.fullmatch(value):
        raise ValueError("Expected an OpenPix task or receipt ID")
    return value


def submit_or_resume(station, args):
    if args.state.exists():
        return json.loads(args.state.read_text(encoding="utf-8"))
    if args.task:
        rec = {"task": check_id(args.task, TASK)}
        save(args.state, rec, create=True)
        return rec
    if not args.submit or not args.request:
        raise ValueError("New orders require --request and explicit --submit")
    payload = json.loads(args.request.read_text(encoding="utf-8"))
    rec = {"request": str(uuid4())}
    save(args.state, rec, create=True)
    try:
        status, result, _ = station.json("/v2/videos/requests/" + rec["request"], "POST", payload)
    except (OSError, URLError, ValueError):
        print("Submission unresolved. Checking the original receipt.", file=sys.stderr)
        return rec
    if result.get("remote_id"):
        rec["task"] = check_id(result["remote_id"], TASK)
        save(args.state, rec)
    elif status not in (200, 201, 202, 409, 429) and status < 500:
        raise ValueError(f"Submission HTTP {status}. Check the original receipt and order.")
    return rec


def poll(station, rec, state, until):
    while time.monotonic() < until:
        try:
            if not rec.get("task"):
                receipt = check_id(rec.get("request"), RECEIPT)
                status, result, retry = station.json("/v2/videos/requests/" + receipt)
                if status == 200 and result.get("remote_id"):
                    rec["task"] = check_id(result["remote_id"], TASK)
                    save(state, rec)
                    continue
                if status in (401, 403) or result.get("state") in ("rejected", "unknown"):
                    raise ValueError(f"Receipt needs review ({status}). Keep the original order.")
            else:
                task = check_id(rec["task"], TASK)
                status, result, retry = station.json("/v2/videos/" + task)
                if status == 200:
                    if result.get("id") != task:
                        raise ValueError("Task ID in response does not match")
                    if result.get("status") == "completed":
                        return task
                    if result.get("status") == "failed":
                        raise ValueError("Generation failed. Check the original order and bill.")
                elif status in (401, 403, 404):
                    raise ValueError(f"Task lookup HTTP {status}. Check the original Key and task.")
        except OSError:
            retry = None
        time.sleep(min(wait_delay(retry), max(0, until - time.monotonic())))
    raise ValueError("Local wait ended. Run again with the same --state to resume.")


def upload(station, filename, mime):
    size = filename.stat().st_size
    with filename.open("rb") as file:
        digest = hashlib.file_digest(file, "sha256").hexdigest()
        status, result, _ = station.json("/v2/video-uploads", "POST",
            {"sha256": digest, "bytes": size, "mime": mime})
        if status != 200:
            raise ValueError(f"Upload initialization HTTP {status}")
        uid = result.get("id")
        if not isinstance(uid, str) or not re.fullmatch(r"[a-f0-9]{40}", uid):
            raise ValueError("Invalid upload identifier")
        step = result.get("chunk_bytes")
        if type(step) is not int or not 0 < step <= 4 * 1024 * 1024:
            raise ValueError("Invalid upload chunk size")
        while not result.get("url"):
            offset = result.get("offset")
            if type(offset) is not int or not 0 <= offset < size:
                raise ValueError("Invalid upload offset")
            file.seek(offset)
            with station.request(f"/v2/video-uploads/{uid}/{offset}", "PUT",
                                 file.read(step), "application/octet-stream") as reply:
                if reply.code != 200:
                    raise ValueError(f"Upload HTTP {reply.code}. Re-run to resume upload.")
                result = json.load(reply)
            if not result.get("url") and result.get("offset", -1) <= offset:
                raise ValueError("Upload offset did not advance. Re-run to resume upload.")
    url = result["url"]
    if not re.fullmatch(r"https://openpix\.cc/v2/video-inputs/[a-f0-9]{64}", url):
        raise ValueError("Invalid completed media URL")
    return url


def main():
    cli = argparse.ArgumentParser(description=__doc__)
    cli.add_argument("--request", type=Path)
    cli.add_argument("--state", type=Path)
    cli.add_argument("--output", type=Path)
    cli.add_argument("--submit", action="store_true")
    cli.add_argument("--task")
    cli.add_argument("--wait", type=int, default=1200)
    cli.add_argument("--upload", type=Path)
    cli.add_argument("--mime")
    args = cli.parse_args()
    key = os.environ.get("MXB_API_KEY", "").strip()
    if not key:
        cli.error("Set MXB_API_KEY in your environment")
    station = Station(key)
    try:
        if args.upload and args.mime:
            print(upload(station, args.upload, args.mime))
            return
        if args.upload or args.mime or not args.state or not args.output or args.wait <= 0:
            cli.error("Provide --upload with --mime, or --state with --output and a positive wait")
        if args.output.exists():
            raise ValueError("Output file already exists")
        rec = submit_or_resume(station, args)
        task = poll(station, rec, args.state, time.monotonic() + args.wait)
        station.download(task, args.output)
    except (OSError, ValueError) as error:
        print(str(error), file=sys.stderr)
        return 1


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