"""Process one small JPEG with the MetaGhost Cloud API using Python 3.10+."""

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


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


def wait_for(read, pending, ready):
    deadline = time.monotonic() + 180
    while time.monotonic() < deadline:
        value = read()
        state = value["state"]
        if state == ready:
            return value
        if state not in pending:
            raise ValueError(f"Stopped in state {state} ({value.get('errorCode', 'no error code')}).")
        time.sleep(2)
    raise TimeoutError("Wait limit reached. Check the existing asset or batch before trying again.")


def process(source, output, credit_limit):
    base = os.environ["METAGHOST_BASE_URL"].rstrip("/")
    token = os.environ["METAGHOST_API_KEY"]
    parsed = urlsplit(base)
    local = parsed.scheme == "http" and parsed.hostname in ("127.0.0.1", "localhost", "::1")
    if (not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment
            or parsed.path != "/api/cloud/v1" or (parsed.scheme != "https" and not local)):
        raise ValueError("Use the Cloud API base URL shown in your account.")
    if not token or any(c.isspace() for c in token):
        raise ValueError("Set METAGHOST_API_KEY to your Cloud API key.")
    if source.suffix.lower() not in (".jpeg", ".jpg") or output.exists() or not output.parent.is_dir():
        raise ValueError("Choose a JPEG and a new output file in an existing directory.")
    with source.open("rb") as file:
        data = file.read(5 * 1024**2 + 1)
    if not 0 < len(data) <= 5 * 1024**2 or not data.startswith(b"\xff\xd8\xff"):
        raise ValueError("This example accepts a JPEG up to 5 MiB.")

    opener = build_opener(NoRedirect())

    def call(path, body=None, request_key=None):
        headers = {"Authorization": f"Bearer {token}"}
        if body is not None:
            headers.update({"Content-Type": "application/json", "Idempotency-Key": request_key or uuid4().hex})
        request = Request(base + path, data=json.dumps(body).encode() if body is not None else None,
                          headers=headers)
        with opener.open(request, timeout=30) as response:
            return json.load(response)

    def storage_request(url, **kwargs):
        target = urlsplit(url)
        if target.scheme != "https" or not target.hostname or target.username or target.password:
            raise ValueError("The API did not return a valid HTTPS transfer URL.")
        return opener.open(Request(url, **kwargs), timeout=30)

    proof = {"byteLength": len(data), "sha256": hashlib.sha256(data).hexdigest()}
    upload = call("/assets", {**proof, "filename": source.name, "mediaType": "image/jpeg"})
    asset_path = "/assets/" + upload["asset"]["assetId"]
    with storage_request(upload["uploadUrl"], method="PUT", data=data, headers=upload["requiredHeaders"]):
        pass
    call(asset_path + "/finalize", proof)
    print(f"Asset: {upload['asset']['assetId']}", flush=True)
    asset = wait_for(lambda: call(asset_path), {"uploading", "inspecting"}, "ready")

    quote = call("/quotes", {"operation": "image.spoof.simple", "options": {}, "inputs": [
        {"asset": {"assetId": asset["assetId"], "version": asset["version"]}, "variants": 1},
    ]})
    quoted = quote["maxCredits"]
    if type(quoted) is not int or not 0 <= quoted <= credit_limit:
        raise ValueError(f"Quote is {quoted} credits and exceeds the accepted limit of {credit_limit}.")
    batch_body = {"quoteId": quote["quoteId"], "maxCredits": quoted}
    batch_key = uuid4().hex
    print(f"Submitting {json.dumps(batch_body)} with Idempotency-Key {batch_key}.", flush=True)
    batch = call("/batches", batch_body, batch_key)
    batch_path = "/batches/" + batch["batchId"]
    print(f"Batch: {batch['batchId']}", flush=True)
    completed = wait_for(lambda: call(batch_path), {"queued", "running", "cancelling"}, "succeeded")
    job, = call(batch_path + "/jobs")["jobs"]
    if job["state"] != "succeeded":
        raise ValueError("The job has not produced a result. Check the existing batch.")
    result = call("/results/" + job["resultId"])
    length = result["byteLength"]
    if not 0 < length <= 20 * 1024**2:
        raise ValueError("Result is too large for this example. Use the result endpoint to download it.")
    with storage_request(result["downloadUrl"]) as response:
        saved = response.read(length + 1)
    if len(saved) != length or hashlib.sha256(saved).hexdigest() != result["sha256"]:
        raise ValueError("The downloaded bytes do not match the result checksum.")
    with output.open("xb") as file:
        file.write(saved)
    print(f"Saved {output}. Charged credits: {completed['capturedCredits']}.")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source", type=Path)
    parser.add_argument("output", type=Path)
    parser.add_argument("--max-credits", type=int, required=True, help="Maximum approved credits for this example")
    args = parser.parse_args()
    if args.max_credits < 0:
        parser.error("--max-credits must be zero or more.")
    try:
        process(args.source, args.output, args.max_credits)
    except HTTPError as error:
        print(f"HTTP {error.code}. Check the request and any existing batch before retrying.", file=sys.stderr)
        sys.exit(1)
    except URLError:
        print("Connection interrupted. Recover any submitted batch before retrying.", file=sys.stderr)
        sys.exit(1)
    except (OSError, ValueError, KeyError) as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
