#!/usr/bin/env python3
"""zgpu: call curated Hugging Face ZeroGPU Spaces by task, with one command and one result shape.

    python3 zgpu.py search sound effect            # find a task
    python3 zgpu.py describe sound-effects         # inputs, defaults, outputs, license
    python3 zgpu.py run sound-effects prompt="short laser zap" duration=2 --out assets/audio
    python3 zgpu.py run background-removal f=./sprite.png --out out/
    python3 zgpu.py serve --port 8770              # local unified OpenAPI at http://127.0.0.1:8770/openapi.json

Inputs are key=value (or --json '{...}'). Files are URLs or local paths; local files are uploaded for you.
Numbers, booleans and dropdown choices are coerced to the types the Space expects, and recommended defaults are
filled in. The result is JSON on stdout: {"ok", "task", "space", "outputs": [{"name", "kind", "file"|"value"}], ...}.

Your HF token comes from HF_TOKEN or the local Hugging Face login. It is sent only to the upstream Space (so the
call uses your own ZeroGPU quota) and is never printed. Standard library only; Python 3.9+.
"""
import argparse, base64, difflib, json, math, mimetypes, os, random, re, sys, time, uuid
import urllib.error, urllib.parse, urllib.request

DEFAULT_CATALOG = "https://townbox-zerogpu-tool-catalog.static.hf.space/tasks.json"
UA = "zgpu/2"


class ZError(Exception):
    def __init__(self, code, message, hint=None):
        super().__init__(message); self.code, self.message, self.hint = code, message, hint

    def as_dict(self):
        d = {"ok": False, "error": {"code": self.code, "message": self.message}}
        if self.hint: d["error"]["hint"] = self.hint
        return d


# ----------------------------------------------------------------------------- catalog and token

def load_catalog(src=None):
    here = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tasks.json")
    src = src or os.environ.get("ZGPU_CATALOG") or (here if os.path.exists(here) else DEFAULT_CATALOG)
    try:
        if re.match(r"https?://", src):
            with urllib.request.urlopen(urllib.request.Request(src, headers={"User-Agent": UA}), timeout=60) as r:
                return json.load(r)
        with open(src, encoding="utf-8") as f:
            return json.load(f)
    except (OSError, ValueError) as e:
        raise ZError("catalog_unavailable", f"could not load the task catalog from {src}: {e}")


def find_token():
    for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
        if os.environ.get(k, "").strip(): return os.environ[k].strip()
    home = os.environ.get("HF_HOME") or os.path.join(os.path.expanduser("~"), ".cache", "huggingface")
    for p in (os.environ.get("HF_TOKEN_PATH"), os.path.join(home, "token")):
        if p and os.path.isfile(p):
            t = open(p, encoding="utf-8").read().strip()
            if t: return t
    return None


def get_task(cat, task_id):
    tasks = {t["id"]: t for t in cat["tasks"]}
    if task_id in tasks: return tasks[task_id]
    near = difflib.get_close_matches(task_id, list(tasks), n=4, cutoff=0.4) or [t["id"] for t in search(cat, task_id)[:4]]
    raise ZError("unknown_task", f"no task named {task_id!r}", "did you mean: " + ", ".join(near) if near else "run: zgpu.py list")


def get_lane(task, lane):
    if lane in task["lanes"]: return task["lanes"][lane]
    raise ZError("unknown_lane", f"task {task['id']!r} has no {lane!r} lane", "lanes: " + ", ".join(task["lanes"]))


def search(cat, query):
    """Rank tasks by query words, weighting rare words above common ones ("video" appears in many tasks, "under" in few)."""
    stop = {"a", "an", "the", "for", "of", "to", "and", "or", "in", "on", "with", "my", "me", "make", "some", "from", "into",
            "game", "i", "want", "need", "using", "use", "tool", "generate", "create"}
    stem = lambda w: w[:-1] if len(w) > 3 and w.endswith("s") and not w.endswith("ss") else w
    toks = lambda text: {stem(w) for w in re.findall(r"[a-z0-9]+", text.lower())}
    words = [stem(w) for w in re.findall(r"[a-z0-9]+", query.lower()) if len(w) > 1 and w not in stop]
    docs = [(t, toks(f"{t['id']} {t['title']} {t.get('keywords', '')}"), toks(f"{t['need']} {t['category']} {t['summary']} {' '.join(t['output'])}"))
            for t in cat["tasks"]]
    n = len(docs)
    idf = {w: math.log((n + 1) / (1 + sum(w in h or w in b for _, h, b in docs))) + 0.1 for w in words}
    scored = []
    for t, head, body in docs:
        s = sum(idf[w] * (3 if w in head else 1 if w in body else 0.5 if any(x.startswith(w[:4]) for x in head) else 0)
                for w in words)
        if s: scored.append((s, t))
    return [t for s, t in sorted(scored, key=lambda x: -x[0])]


# ----------------------------------------------------------------------------- HTTP

def _req(method, url, token=None, body=None, headers=None, timeout=60):
    h = {"User-Agent": UA, **(headers or {})}
    if token: h["Authorization"] = f"Bearer {token}"
    return urllib.request.urlopen(urllib.request.Request(url, data=body, headers=h, method=method), timeout=timeout)


def _http_error(e, what):
    try: detail = e.read().decode("utf-8", "replace")[:300]
    except Exception: detail = ""
    code = {401: "unauthorized", 403: "forbidden", 404: "not_found", 413: "too_large", 422: "invalid_input",
            429: "rate_limited"}.get(e.code, "upstream_unavailable" if e.code >= 500 else "upstream_error")
    return ZError(code, f"{what} failed with HTTP {e.code}: {detail}".strip())


def upload(host, path, token):
    name = os.path.basename(path); boundary = uuid.uuid4().hex
    ctype = mimetypes.guess_type(name)[0] or "application/octet-stream"
    with open(path, "rb") as f: data = f.read()
    body = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"files\"; filename=\"{name}\"\r\n"
            f"Content-Type: {ctype}\r\n\r\n").encode() + data + f"\r\n--{boundary}--\r\n".encode()
    try:
        with _req("POST", host + "/gradio_api/upload", token, body,
                  {"Content-Type": f"multipart/form-data; boundary={boundary}"}, timeout=300) as r:
            return json.load(r)[0]
    except urllib.error.HTTPError as e:
        raise _http_error(e, f"uploading {name}")
    except (urllib.error.URLError, TimeoutError, OSError) as e:
        raise ZError("upstream_unavailable", f"could not upload {name}: {e}", "the Space may be asleep or restarting; retry")


# ----------------------------------------------------------------------------- inputs

def _file_data(v, host, token, uploads):
    if isinstance(v, dict): return v                       # already a Gradio FileData
    v = str(v)
    if re.match(r"(https?://|data:)", v): return {"path": v, "url": v, "orig_name": None, "meta": {"_type": "gradio.FileData"}}
    p = os.path.expanduser(v)
    if not os.path.isfile(p): raise ZError("invalid_input", f"file not found: {v}", "pass a URL or an existing local path")
    if p not in uploads: uploads[p] = upload(host, p, token)
    return {"path": uploads[p], "orig_name": os.path.basename(p), "meta": {"_type": "gradio.FileData"}}


def _coerce(name, v, sch):
    if v is None: return None
    if "enum" in sch:
        m = [x for x in sch["enum"] if str(x) == str(v)]
        if not m: raise ZError("invalid_input", f"{name}={v!r} is not one of {sch['enum']}")
        return m[0]
    t = sch.get("type")
    try:
        if t == "integer": return int(float(v)) if not isinstance(v, bool) else int(v)
        if t == "number":   # send 1024, not 1024.0: Gradio UIs send JSON integers and some Spaces call range() on them
            f = float(v); return int(f) if f.is_integer() else f
        if t == "boolean":
            if isinstance(v, bool): return v
            if str(v).lower() in ("true", "1", "yes", "on"): return True
            if str(v).lower() in ("false", "0", "no", "off"): return False
            raise ValueError
        if t in ("array", "object") and isinstance(v, str): return json.loads(v)
    except (ValueError, TypeError):
        raise ZError("invalid_input", f"{name}={v!r} is not a valid {t}")
    return v


def _check_range(name, v, sch):
    if isinstance(v, (int, float)) and not isinstance(v, bool):
        lo, hi = sch.get("minimum"), sch.get("maximum")
        if (lo is not None and v < lo) or (hi is not None and v > hi):
            raise ZError("invalid_input", f"{name}={v} is outside {lo}..{hi}")
    return v


FILE_ALIASES = ("image", "file", "input", "audio", "video", "source")
TEXT_ALIASES = ("prompt", "text")


def resolve_aliases(lane, inputs):
    """Map the universal names (image/file/audio/video, prompt/text) onto this lane's own parameter names."""
    props = lane["inputs"]["properties"]; inputs = dict(inputs)
    single_files = [p["name"] for p in lane["params"] if p["kind"] in ("file", "fileobj")]
    for k in [k for k in inputs if k not in props]:
        if k in FILE_ALIASES and len(single_files) == 1 and single_files[0] not in inputs:
            inputs[single_files[0]] = inputs.pop(k)
        elif k in TEXT_ALIASES:
            other = [n for n in TEXT_ALIASES if n != k and n in props and n not in inputs]
            if other: inputs[other[0]] = inputs.pop(k)
    return inputs


def build_payload(lane, inputs, token):
    props, req = lane["inputs"]["properties"], lane["inputs"].get("required", [])
    inputs = resolve_aliases(lane, inputs)
    unknown = sorted(set(inputs) - set(props))
    if unknown:
        raise ZError("invalid_input", f"unknown input(s): {', '.join(unknown)}", "inputs: " + ", ".join(props))
    kinds = {p["name"]: p["kind"] for p in lane["params"]}
    missing = [k for k in req if inputs.get(k) is None or (inputs.get(k) == "" and kinds.get(k))]   # "" is a valid text value
    if missing: raise ZError("invalid_input", f"missing required input(s): {', '.join(missing)}")
    host, uploads, values = lane["host"], {}, {}
    for p in lane["params"]:
        n, sch = p["name"], props[p["name"]]
        if n in inputs: v = inputs[n]
        elif sch.get("x-random-if-omitted"):
            v = random.randint(max(1, int(sch.get("minimum", 1))), int(min(sch.get("maximum", 2**31 - 2), 2**31 - 2)))
        elif "default" in sch: v = sch["default"]
        else: v = p["default"]
        if n == "prompt" and lane.get("prompt_template") and isinstance(v, str) and v:
            v = lane["prompt_template"].format(prompt=v)
        k = p["kind"]
        if k == "file": v = None if v in (None, "") else _file_data(v, host, token, uploads)
        elif k == "fileobj":
            ff = p.get("file_fields", {})
            if v in (None, ""): v = None
            elif not isinstance(v, (str, dict)):
                raise ZError("invalid_input", f"{n} takes one URL/path or an object with fields {', '.join(ff)}")
            elif isinstance(v, str) and not v.lstrip().startswith("{"):
                fd = _file_data(v, host, token, uploads)
                main = [f for f in ff if f in ("video", "image", "background", "composite", "audio", "file")] or list(ff)[:1]
                v = {f: (fd if f in main else [] if kind == "files" else None) for f, kind in ff.items()}
            else:
                obj = json.loads(v) if isinstance(v, str) else dict(v)
                for f, kind in ff.items():
                    if isinstance(obj.get(f), str): obj[f] = _file_data(obj[f], host, token, uploads)
                    elif kind == "files" and isinstance(obj.get(f), list):
                        obj[f] = [x if isinstance(x, dict) else _file_data(x, host, token, uploads) for x in obj[f]]
                v = obj
        elif k in ("files", "gallery"):
            items = [] if v in (None, "") else (json.loads(v) if isinstance(v, str) and v.startswith("[") else v)
            items = items if isinstance(items, list) else [items]
            if k == "gallery" and items and all(isinstance(x, dict) and ("image" in x or "video" in x) for x in items):
                values[n] = items; continue          # a gallery fed from a previous step, already on the Space
            fds = [_file_data(x, host, token, uploads) for x in items]
            if k == "gallery":
                fds = [{("video" if (mimetypes.guess_type(str(f.get("orig_name") or f["path"]))[0] or "").startswith("video") else "image"): f,
                        "caption": None} for f in fds]
            v = fds
        elif k == "paths":   # a plain list of file path strings (gr.api functions): upload local files, keep URLs
            items = [] if v in (None, "") else (json.loads(v) if isinstance(v, str) and v.startswith("[") else v)
            v = [_file_data(x, host, token, uploads)["path"] for x in (items if isinstance(items, list) else [items])]
        else:
            v = _coerce(n, v, sch)
            if n in inputs: _check_range(n, v, sch)
        values[n] = v
    return values


# ----------------------------------------------------------------------------- call

def _classify(msg):
    m = (msg or "").lower()
    if "too many zerogpu credits allocated" in m or "gpu task aborted" in m:
        return ZError("gpu_busy", msg, "your other ZeroGPU jobs are still running, or the GPU worker was pre-empted: wait a few seconds and retry; run fewer jobs at once")
    if "quota" in m or "gpu duration" in m or "zerogpu" in m and "exceed" in m:
        return ZError("quota_exhausted", msg, "ZeroGPU quota used up: wait for the daily reset, sign in (HF_TOKEN), or use PRO")
    if "not in the list of choices" in m or "validation" in m or "invalid" in m:
        return ZError("invalid_input", msg)
    if "moderat" in m or "nsfw" in m or "safety" in m or "blocked" in m:
        return ZError("moderation_blocked", msg)
    return ZError("upstream_error", msg or "the Space returned an error without a message",
                  "the Space may be restarting or busy; retry, or try the other lane")


def _stream(url, token, timeout):
    """Read Gradio's SSE result stream and return the `complete` payload."""
    deadline = time.time() + timeout
    try:
        with _req("GET", url, token, headers={"Accept": "text/event-stream"}, timeout=timeout) as r:
            event, data = None, []
            for raw in r:
                if time.time() > deadline: raise ZError("timeout", f"no result within {timeout} s")
                line = raw.decode("utf-8", "replace").rstrip("\r\n")
                if line.startswith("event:"): event = line[6:].strip()
                elif line.startswith("data:"): data.append(line[5:].strip())
                elif line == "" and event:
                    payload = "\n".join(data); event_name, event, data = event, None, []
                    if event_name == "complete":
                        return json.loads(payload) if payload else []
                    if event_name == "error":
                        try: obj = json.loads(payload) if payload else None
                        except ValueError: obj = payload
                        msg = obj.get("error") or obj.get("message") if isinstance(obj, dict) else (obj if isinstance(obj, str) else None)
                        raise _classify(msg)
    except urllib.error.HTTPError as e:
        raise _http_error(e, "reading the result")
    except (urllib.error.URLError, TimeoutError, OSError) as e:
        raise ZError("upstream_unavailable", f"lost the result stream: {e}", "the Space may be asleep or restarting; retry")
    raise ZError("upstream_error", "the result stream ended without a result", "retry; the Space may have restarted")


def _ext(fd, kind):
    for k in ("orig_name", "path", "url"):
        e = os.path.splitext(urllib.parse.urlparse(str(fd.get(k) or "")).path)[1]
        if 1 < len(e) <= 6: return e
    return {"image": ".png", "images": ".png", "audio": ".wav", "video": ".mp4", "model3d": ".glb"}.get(kind, ".bin")


def _is_fd(x):
    if not isinstance(x, dict) or not (x.get("url") or x.get("path")): return False
    return (x.get("meta") or {}).get("_type") == "gradio.FileData" or ("url" in x and "path" in x)


def _files_in(v):
    if _is_fd(v): return [v]
    if isinstance(v, dict):
        return [f for k in ("image", "video", "audio", "value") if k in v for f in _files_in(v[k])]
    if isinstance(v, (list, tuple)): return [f for x in v for f in _files_in(x)]
    return []


DATA_URI = re.compile(r"^data:([\w.+-]+/[\w.+-]+);base64,")
EXT = {"audio/wav": ".wav", "audio/x-wav": ".wav", "audio/mpeg": ".mp3", "audio/flac": ".flac", "image/webp": ".webp"}
MIME_KIND = {"audio": "audio", "image": "image", "video": "video"}


def _inline_media(v, dest_stem):
    """Some Spaces return media as base64 data URIs inside a JSON value (e.g. MiniMax Music). Save each to a file and put
    the file path in its place. Returns (value with paths, [(field, kind, path)])."""
    if isinstance(v, str) and v[:1] in "{[" and len(v) > 2048 and "data:" in v:
        try: v = json.loads(v)
        except ValueError: return v, []
    saved = []

    def walk(o, key):
        if isinstance(o, dict): return {k: walk(x, k) for k, x in o.items()}
        if isinstance(o, list): return [walk(x, key) for x in o]
        if isinstance(o, str) and len(o) > 1024 and (m := DATA_URI.match(o)):
            mime = m.group(1); ext = EXT.get(mime) or mimetypes.guess_extension(mime) or ".bin"
            path = f"{dest_stem}-{key or 'data'}{'' if not saved else '-' + str(len(saved))}{ext}"
            with open(path, "wb") as f: f.write(base64.b64decode(o[m.end():]))
            saved.append((key or "data", MIME_KIND.get(mime.split("/")[0], "file"), path))
            return path
        return o
    return walk(v, None), saved


def _get_retry(url, token, timeout, tries=3):
    """GET with retries on dropped connections (idempotent): ZeroGPU file servers reset connections now and then."""
    for i in range(tries):
        try: return _req("GET", url, token, timeout=timeout)
        except urllib.error.HTTPError as e:
            if e.code < 500 or i == tries - 1: raise
        except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as e:
            if i == tries - 1: raise ZError("upstream_unavailable", f"could not download an output: {e}", "retry the call")
        time.sleep(1 + 2 * i)


def _download(fd, host, token, dest):
    url = fd.get("url") or (host + "/gradio_api/file=" + fd["path"])
    try:
        with _get_retry(url, token, 600) as r, open(dest, "wb") as f:
            while chunk := r.read(1 << 20): f.write(chunk)
        with open(dest, "rb") as f: head = f.read(7)
        if head == b"#EXTM3U": dest = _join_hls(url, dest, token)
    except urllib.error.HTTPError as e:
        raise _http_error(e, "downloading an output")
    except (urllib.error.URLError, TimeoutError, OSError) as e:
        raise ZError("upstream_unavailable", f"the download of an output broke off: {e}", "retry the call")
    return dest


def _join_hls(url, dest, token):
    """Streaming outputs (e.g. Drama-3 audio) come back as an HLS playlist: fetch its segments and join them into one file."""
    with open(dest) as f: segs = [ln.strip() for ln in f if ln.strip() and not ln.startswith("#")]
    if not segs: raise ZError("upstream_error", "the Space returned an empty media stream")
    ext = os.path.splitext(urllib.parse.urlparse(segs[0]).path)[1] or ".bin"
    out = os.path.splitext(dest)[0] + ext
    with open(out, "wb") as f:
        for seg in segs:
            with _get_retry(urllib.parse.urljoin(url, seg), token, 120) as r: f.write(r.read())
    if out != dest: os.remove(dest)
    return out


def _call(b, step, payload, token, timeout):
    """Submit one endpoint call and return its outputs. `step` has endpoint/style/prefix/params (a lane or a pipeline step)."""
    pre, api = step["prefix"], step["endpoint"]
    url = b["host"] + (f"/gradio_api/call/v2/{api}" if step["style"] == "v2" else f"{pre}/call/{api}")
    body = payload if step["style"] == "v2" else {"data": [payload[p["name"]] for p in step["params"]]}
    try:
        with _req("POST", url, token, json.dumps(body).encode(), {"Content-Type": "application/json"}, timeout=120) as r:
            event_id = json.load(r).get("event_id")
    except urllib.error.HTTPError as e:
        raise _http_error(e, f"submitting to {b['space']}")
    except (urllib.error.URLError, OSError) as e:
        raise ZError("upstream_unavailable", f"could not reach {b['space']}: {e}")
    if not event_id: raise ZError("upstream_error", "the Space did not return an event id")
    return _stream(f"{b['host']}{pre}/call/{api}/{event_id}", token, timeout)


def _run_pipeline(b, inputs, token, timeout):
    """Chain the steps: each step gets the agent's inputs that belong to it plus the outputs fed from the step before.
    Fed values are passed as returned (server-side FileData), so nothing is downloaded or re-uploaded in between."""
    inputs = resolve_aliases(b, inputs)
    unknown = sorted(set(inputs) - set(b["inputs"]["properties"]))
    if unknown: raise ZError("invalid_input", f"unknown input(s): {', '.join(unknown)}", "inputs: " + ", ".join(b["inputs"]["properties"]))
    missing = [k for k in b["inputs"].get("required", []) if inputs.get(k) is None]
    if missing: raise ZError("invalid_input", f"missing required input(s): {', '.join(missing)}")
    prev = None
    for i, st in enumerate(b["pipeline"]):
        props = st["inputs"]["properties"]
        step_in = {k: v for k, v in inputs.items() if k in props}
        for k, idx in st["feed"].items():
            v = prev[idx] if isinstance(prev, list) and idx < len(prev) else None
            if v is None: raise ZError("upstream_error", f"step {i} ({st['endpoint']}) got no output #{idx} from the step before")
            step_in[k] = v.get("value", v) if isinstance(v, dict) and "__type__" in v else v
        lane = dict(b, inputs=st["inputs"], params=st["params"])
        prev = _call(b, st, build_payload(lane, step_in, token), token, timeout)
    return prev


def run(cat, task_id, inputs, lane="default", out_dir=".", token=None, timeout=900, name=None):
    task = get_task(cat, task_id); b = get_lane(task, lane)
    token = token if token is not None else find_token()
    t0 = time.time()
    if b.get("pipeline"): data = _run_pipeline(b, inputs, token, timeout)
    else: data = _call(b, b, build_payload(b, inputs, token), token, timeout)
    os.makedirs(out_dir, exist_ok=True)
    stem = re.sub(r"[^A-Za-z0-9_.-]+", "-", name or f"{task_id}-{time.strftime('%Y%m%d-%H%M%S')}-{uuid.uuid4().hex[:4]}")
    outs, specs = [], b["outputs"]
    for i, v in enumerate(data if isinstance(data, list) else [data]):
        spec = specs[i] if i < len(specs) else {"name": f"output_{i}", "kind": "json"}
        files = _files_in(v)
        if files:
            for j, fd in enumerate(files):
                suffix = "" if len(data) == 1 and len(files) == 1 else f"-{i}" + (f"-{j}" if len(files) > 1 else "")
                dest = os.path.join(out_dir, stem + suffix + _ext(fd, spec["kind"]))
                o = {"name": spec["name"], "kind": spec["kind"], "file": _download(fd, b["host"], token, dest)}
                if fd.get("orig_name"): o["orig_name"] = fd["orig_name"]   # often the only label (e.g. which stem is which)
                outs.append(o)
        else:
            v, saved = _inline_media(v, os.path.join(out_dir, stem + ("" if len(data) == 1 else f"-{i}")))
            for key, kind, path in saved: outs.append({"name": f"{spec['name']}.{key}", "kind": kind, "file": path})
            outs.append({"name": spec["name"], "kind": spec["kind"], "value": v})
    return {"ok": True, "task": task_id, "lane": lane, "space": b["space"], "model": b["model"], "license": b["license"],
            "license_class": b["license_class"], "elapsed_s": round(time.time() - t0, 1), "outputs": outs}


# ----------------------------------------------------------------------------- describe

def describe(task, lane="default"):
    b = get_lane(task, lane); props, req = b["inputs"]["properties"], b["inputs"].get("required", [])
    def show(n):
        s = props[n]; t = "file" if s.get("description", "").endswith("local file path.") else "files" if s.get("items") == {"type": "string"} and "URLs" in s.get("description", "") else s.get("type", "any")
        extra = f" one of {s['enum']}" if "enum" in s else ""
        dflt = " (random)" if s.get("x-random-if-omitted") else f" = {json.dumps(s['default'])}" if "default" in s else ""
        return f"  {n}: {t}{extra}{dflt}"
    lines = [f"{task['id']} [{lane}]: {task['title']} ({task['category']})", f"  {task['need']}",
             f"model: {b['model']}  space: {b['space']}  license: {b['license']} ({b['license_class']})",
             f"gpu seconds booked: {b['gpu_seconds']}", "required:"] + [show(n) for n in req] + \
            ["optional:"] + [show(n) for n in props if n not in req] + \
            ["outputs: " + ", ".join(f"{o['name']} ({o['kind']})" for o in b["outputs"])]
    files = [p["name"] for p in b["params"] if p["kind"] in ("file", "fileobj")]
    if len(files) == 1 and files[0] not in FILE_ALIASES: lines.append(f"alias: image/file/audio/video -> {files[0]}")
    if b.get("prompt_template"): lines.append(f"prompt is wrapped as: {b['prompt_template']}")
    if b.get("tips"): lines.append(f"tips: {b['tips']}")
    if b.get("caveats"): lines.append(f"caveats: {b['caveats']}")
    if len(task["lanes"]) > 1: lines.append("other lanes: " + ", ".join(l for l in task["lanes"] if l != lane))
    files = [p["name"] for p in b["params"] if p["kind"] in ("file", "fileobj")]
    alias = {files[0]: "image"} if len(files) == 1 and files[0] not in FILE_ALIASES else {}
    ex = " ".join(f'{alias.get(n, n)}="..."' for n in req)
    lines.append(f"example: python3 zgpu.py run {task['id']} {ex}" + ("" if lane == "default" else f" --lane {lane}"))
    return "\n".join(lines)


# ----------------------------------------------------------------------------- local unified OpenAPI server

def openapi(cat, base="http://127.0.0.1:8770"):
    def strip_x(s):
        if isinstance(s, dict): return {k: strip_x(v) for k, v in s.items() if not k.startswith("x-")}
        if isinstance(s, list): return [strip_x(x) for x in s]
        return s
    result = {"type": "object", "properties": {
        "ok": {"type": "boolean"}, "task": {"type": "string"}, "lane": {"type": "string"}, "space": {"type": "string"},
        "model": {"type": "string"}, "license": {"type": "string"}, "elapsed_s": {"type": "number"},
        "outputs": {"type": "array", "items": {"type": "object", "properties": {
            "name": {"type": "string"}, "kind": {"type": "string"}, "file": {"type": "string", "description": "Local path of the saved output"},
            "url": {"type": "string", "description": "Where this server serves the saved file"}, "value": {}}}},
        "error": {"type": "object", "properties": {"code": {"type": "string"}, "message": {"type": "string"}, "hint": {"type": "string"}}}}}
    paths = {"/v1/tasks": {"get": {"operationId": "list_tasks", "summary": "List every task with its output kinds and lanes",
                                   "responses": {"200": {"description": "Tasks", "content": {"application/json": {"schema": {"type": "array", "items": {"type": "object"}}}}}}}}}
    for t in cat["tasks"]:
        for lane, b in t["lanes"].items():
            op = t["id"].replace("-", "_") + ("" if lane == "default" else "_" + lane)
            desc = (f"{t['need']} Model: {b['model']} ({b['space']}). License: {b['license']}."
                    + (f" Tips: {b['tips']}" if b.get("tips") else "") + (f" Caveats: {b['caveats']}" if b.get("caveats") else "") + " Files: pass a URL or a local path.")
            paths[f"/v1/{t['id']}" + ("" if lane == "default" else f"/{lane}")] = {"post": {
                "operationId": op, "summary": f"{t['title']}" + ("" if lane == "default" else f" ({lane} use)"),
                "description": desc[:1500], "tags": [t["category"]],
                "requestBody": {"required": True, "content": {"application/json": {"schema": strip_x(b["inputs"])}}},
                "responses": {"200": {"description": "Finished; outputs saved locally", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Result"}}}},
                              "4XX": {"description": "Bad input or upstream refusal", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Result"}}}},
                              "5XX": {"description": "Upstream unavailable", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Result"}}}}}}}
    return {"openapi": "3.0.3", "info": {"title": "ZeroGPU tasks (local)", "version": str(cat.get("schemas_read", ""))[:10],
            "description": "One synchronous operation per task. Runs on this machine: each call goes straight to the upstream "
                           "ZeroGPU Space with your own HF token, and outputs are saved locally."},
            "servers": [{"url": base}], "paths": paths, "components": {"schemas": {"Result": result}}}


STATUS = {"unknown_task": 404, "unknown_lane": 404, "invalid_input": 422, "unauthorized": 401, "forbidden": 403,
          "quota_exhausted": 429, "rate_limited": 429, "moderation_blocked": 422, "timeout": 504, "too_large": 413,
          "upstream_unavailable": 502, "upstream_error": 502, "not_found": 502, "catalog_unavailable": 500}


def serve(cat, host="127.0.0.1", port=8770, out_dir="zgpu-out", timeout=900):
    from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
    base = f"http://{host}:{port}"; spec = openapi(cat, base); out_dir = os.path.abspath(out_dir)

    class H(BaseHTTPRequestHandler):
        def log_message(self, *a): pass                              # no request logs, so no header can leak

        def _send(self, code, obj, ctype="application/json"):
            body = obj if isinstance(obj, bytes) else json.dumps(obj, ensure_ascii=False).encode()
            self.send_response(code); self.send_header("Content-Type", ctype); self.send_header("Content-Length", str(len(body)))
            self.end_headers(); self.wfile.write(body)

        def do_GET(self):
            p = urllib.parse.urlparse(self.path).path
            if p in ("/", "/openapi.json"): return self._send(200, spec)
            if p == "/v1/tasks":
                return self._send(200, [{"id": t["id"], "title": t["title"], "category": t["category"], "need": t["need"],
                                         "output": t["output"], "lanes": list(t["lanes"])} for t in cat["tasks"]])
            if p.startswith("/files/"):
                f = os.path.join(out_dir, os.path.basename(urllib.parse.unquote(p[7:])))
                if os.path.isfile(f):
                    with open(f, "rb") as fh: data = fh.read()
                    return self._send(200, data, mimetypes.guess_type(f)[0] or "application/octet-stream")
            self._send(404, ZError("not_found", f"no route {p}").as_dict())

        def do_POST(self):
            m = re.fullmatch(r"/v1/([a-z0-9-]+)(?:/([a-z]+))?", urllib.parse.urlparse(self.path).path)
            if not m: return self._send(404, ZError("not_found", "POST /v1/<task>").as_dict())
            try:
                n = int(self.headers.get("Content-Length") or 0)
                inputs = json.loads(self.rfile.read(n) or b"{}")
                if not isinstance(inputs, dict): raise ZError("invalid_input", "the body must be a JSON object of inputs")
                auth = self.headers.get("Authorization", "")
                tok = auth[7:].strip() if auth.lower().startswith("bearer ") else None
                res = run(cat, m.group(1), inputs, m.group(2) or "default", out_dir, tok, timeout)
                for o in res["outputs"]:
                    if "file" in o: o["url"] = f"{base}/files/{urllib.parse.quote(os.path.basename(o['file']))}"
                self._send(200, res)
            except ZError as e:
                self._send(STATUS.get(e.code, 500), e.as_dict())
            except ValueError as e:
                self._send(422, ZError("invalid_input", f"bad JSON body: {e}").as_dict())

    srv = ThreadingHTTPServer((host, port), H)
    print(f"zgpu: serving {len(cat['tasks'])} tasks at {base}/openapi.json (outputs in {out_dir})", file=sys.stderr, flush=True)
    try: srv.serve_forever()
    except KeyboardInterrupt: pass
    return srv


# ----------------------------------------------------------------------------- CLI

def _kv(pairs):
    out = {}
    for s in pairs:
        if "=" not in s: raise ZError("invalid_input", f"expected key=value, got {s!r}")
        k, v = s.split("=", 1)
        if k in out: out[k] = (out[k] if isinstance(out[k], list) else [out[k]]) + [v]   # repeat a key for lists
        else: out[k] = v
    return out


def main(argv=None):
    ap = argparse.ArgumentParser(prog="zgpu.py", description=__doc__.split("\n\n")[0])
    ap.add_argument("--catalog", help="tasks.json path or URL (default: next to this file, $ZGPU_CATALOG, or the public catalog)")
    sub = ap.add_subparsers(dest="cmd", required=True)
    p = sub.add_parser("list", help="list tasks"); p.add_argument("--category"); p.add_argument("--json", action="store_true")
    p = sub.add_parser("search", help="find tasks by words"); p.add_argument("words", nargs="+")
    p = sub.add_parser("describe", help="show a task's inputs and outputs"); p.add_argument("task"); p.add_argument("--lane", default="default")
    p.add_argument("--json", action="store_true")
    p = sub.add_parser("run", help="run a task"); p.add_argument("task"); p.add_argument("inputs", nargs="*", metavar="key=value")
    p.add_argument("--json", dest="json_inputs", help="inputs as a JSON object"); p.add_argument("--lane", default="default",
                   help="default, or commercial for commercial-use picks"); p.add_argument("--out", default=".")
    p.add_argument("--name", help="output file stem"); p.add_argument("--timeout", type=int, default=900)
    p = sub.add_parser("serve", help="serve a unified OpenAPI on localhost"); p.add_argument("--port", type=int, default=8770)
    p.add_argument("--out", default="zgpu-out"); p.add_argument("--timeout", type=int, default=900)
    a = ap.parse_args(argv)
    try:
        cat = load_catalog(a.catalog)
        if a.cmd == "list":
            ts = [t for t in cat["tasks"] if not a.category or a.category.lower() in t["category"].lower()]
            if a.json: print(json.dumps([{k: t[k] for k in ("id", "title", "category", "need", "output", "commercial_lane")} for t in ts], indent=1))
            else:
                for t in ts: print(f"{t['id']:<38} {'/'.join(t['output']) or '-':<16} {t['need']}")
        elif a.cmd == "search":
            for t in search(cat, " ".join(a.words))[:8]: print(f"{t['id']:<38} {t['need']}")
        elif a.cmd == "describe":
            t = get_task(cat, a.task)
            print(json.dumps({**{k: t[k] for k in ("id", "title", "need")}, "lane": a.lane, **get_lane(t, a.lane)}, indent=1) if a.json else describe(t, a.lane))
        elif a.cmd == "run":
            inputs = _kv(a.inputs)
            if a.json_inputs: inputs.update(json.loads(a.json_inputs))
            print(json.dumps(run(cat, a.task, inputs, a.lane, a.out, None, a.timeout, a.name), indent=1, ensure_ascii=False))
        elif a.cmd == "serve":
            serve(cat, port=a.port, out_dir=a.out, timeout=a.timeout)
        return 0
    except ZError as e:
        print(json.dumps(e.as_dict(), indent=1), file=sys.stdout if a.cmd == "run" else sys.stderr)
        return 2


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