"""Python 3.10+; standard library only. See https://aipaiai.cn/docs/#image-midjourney"""
import base64
import json
import mimetypes
import os
import time
import uuid
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import Request, urlopen

BASE = os.getenv("AIPAI_BASE_URL", "https://aipaiai.cn").rstrip("/")
KEY = os.environ["AIPAI_API_KEY"]
OUT = Path(os.getenv("MJ_OUTPUT_DIR", "mj-output"))
OUT.mkdir(parents=True, exist_ok=True)
RECEIPT = OUT / "task.json"


def api(path, body=None):
    payload = None if body is None else json.dumps(body).encode("utf-8")
    req = Request(BASE + path, data=payload, headers={
        "Authorization": "Bearer " + KEY, "Content-Type": "application/json",
    })
    with urlopen(req, timeout=60) as response:
        result = json.load(response)
    if not isinstance(result, dict):
        raise RuntimeError("Expected a JSON object")
    return result


def main():
    task_id = os.getenv("MJ_TASK_ID", "")
    if not task_id and RECEIPT.exists():
        receipt = json.loads(RECEIPT.read_text(encoding="utf-8"))
        task_id = receipt.get("task_id", "")
        if not task_id:
            raise RuntimeError("Previous submission is uncertain; reconcile its state before a new POST: " + str(RECEIPT))
    if not task_id:
        model = os.getenv("MJ_MODEL", "Midjourney-v8.2")
        flag = {"Midjourney-v8.2": "--v 8.2"}[model]
        resolution = os.getenv("MJ_RESOLUTION", "sd")
        speed = os.getenv("MJ_SPEED", "fast")
        if resolution not in ("sd", "hd") or speed not in ("fast", "relax"):
            raise ValueError("MJ_RESOLUTION=sd|hd; MJ_SPEED=fast|relax")
        # Optional arrays: public image URLs / paths to local images. Limit their count to your own X.
        urls = json.loads(os.getenv("MJ_REFERENCE_URLS", "[]"))
        files = json.loads(os.getenv("MJ_REFERENCE_FILES", "[]"))
        description = os.getenv("MJ_PROMPT", "A friendly blue robot holding a red flower on a white background")
        mode = " --hd" if resolution == "hd" else " --sd"
        prompt = " ".join([*urls, description, flag, "--ar 1:1"]) + mode + " --" + speed
        if len(prompt) > 1024:
            raise ValueError("Keep the complete prompt within 1024 characters")
        images = []
        for name in files:
            mime = mimetypes.guess_type(name)[0]
            if not mime or not mime.startswith("image/"):
                raise ValueError("Unknown image MIME type: " + name)
            images.append("data:" + mime + ";base64," + base64.b64encode(Path(name).read_bytes()).decode("ascii"))
        body = {"model": model, "prompt": prompt, "state": str(uuid.uuid4())}
        if images:
            body["base64Array"] = images
        # Write before POST; a network timeout must not cause an automatic second generation.
        RECEIPT.write_text(json.dumps({"state": body["state"], "submission": "uncertain"}), encoding="utf-8")
        submitted = api("/mj/submit/imagine", body)
        if submitted.get("code") not in (1, 21, 22) or not submitted.get("result"):
            raise RuntimeError("Submission rejected: " + json.dumps(submitted, ensure_ascii=False))
        task_id = submitted["result"]
    RECEIPT.write_text(json.dumps({"task_id": task_id}), encoding="utf-8")
    print("Task:", task_id, "(saved to", str(RECEIPT) + ")", flush=True)
    deadline = time.monotonic() + 1200
    while time.monotonic() < deadline:
        try:
            task = api("/mj/task/" + quote(task_id, safe="") + "/fetch")
        except (HTTPError, URLError, TimeoutError) as error:
            if isinstance(error, HTTPError) and error.code != 429 and error.code < 500:
                raise
            print("Query temporarily unavailable; retrying GET only", flush=True)
            time.sleep(10)
            continue
        if "code" in task:
            raise RuntimeError("Query rejected: " + json.dumps(task, ensure_ascii=False))
        status, split = task.get("status"), task.get("splitStatus")
        print(status, task.get("progress", ""), split, flush=True)
        if status == "FAILURE":
            raise RuntimeError(task.get("failReason") or "Generation failed")
        if split in ("failed", "expired"):
            raise RuntimeError(task.get("splitError") or "Image processing " + split)
        if status == "SUCCESS" and split == "succeeded":
            images = task.get("images", [])
            if len(images) != 4 or sorted(i["index"] for i in images) != [1, 2, 3, 4]:
                raise RuntimeError("Expected four independent images")
            if task.get("expires_at", 0) and task["expires_at"] <= time.time():
                raise RuntimeError("Image links have expired")
            (OUT / "result.json").write_text(json.dumps(task, ensure_ascii=False, indent=2), encoding="utf-8")
            for image in sorted(images, key=lambda i: i["index"]):
                target = OUT / (str(image["index"]) + ".png")
                # Download CDN links without attaching the API key.
                with urlopen(image["url"], timeout=60) as response:
                    target.write_bytes(response.read())
                print(str(target), str(image["width"]) + "x" + str(image["height"]))
            return
        time.sleep(5)
    raise TimeoutError("Still waiting; resume with MJ_TASK_ID=" + task_id + ". Do not submit again.")


if __name__ == "__main__":
    main()
