#!/usr/bin/env python3
"""SK-only media workflow. Python 3.9+, standard library; never retries paid POSTs.
AXIS_API_KEY=... python3 workflow.py reference.png --run-id YOUR_STABLE_BUSINESS_ID
Reuse --run-id when recovering an interrupted run; changing it creates new jobs.
"""
import argparse
import json
import mimetypes
import os
import re
import time
import urllib.error
import urllib.parse
import urllib.request


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("file", help="Reference image (PNG/JPEG/WebP)")
    parser.add_argument("--run-id", required=True, help="Unique, stable business ID; keep it when recovering")
    parser.add_argument("--base-url", default="https://seedance.diy")
    parser.add_argument("--output", default="result.mp4")
    args = parser.parse_args()
    if not re.fullmatch(r"[\x21-\x7e]{1,110}", args.run_id):
        parser.error("--run-id must be 1–110 visible ASCII characters, e.g. your-job-001")
    key = os.environ["AXIS_API_KEY"]
    base = args.base_url.rstrip("/")
    if not base.startswith("https://"):
        raise SystemExit("Use an HTTPS API base URL")

    def api(path, body=None, operation=None):
        headers = {"Authorization": "Bearer " + key}
        data = None
        if body is not None:
            data = json.dumps(body).encode()
            headers["Content-Type"] = "application/json"
        if operation:
            headers["Idempotency-Key"] = args.run_id + ":" + operation
        request = urllib.request.Request(base + path, data=data, headers=headers)
        try:
            with urllib.request.urlopen(request, timeout=300) as response:
                return json.load(response)
        except urllib.error.HTTPError as error:
            payload = json.load(error)
            detail = payload.get("error", {})
            if error.code == 409 and detail.get("code") == "REQUEST_ALREADY_SUBMITTED":
                identity = detail.get("taskId") or detail.get("requestId")
                if identity:
                    return {"id": identity, "status": "processing"}
            raise RuntimeError("API rejected request: " + json.dumps(payload, ensure_ascii=False)) from None

    def wait(task_id):
        deadline = time.monotonic() + 7200
        while time.monotonic() < deadline:
            task = api("/api/v1/tasks/" + urllib.parse.quote(task_id, safe=""))
            status = task["status"]
            print("Task", task_id, status, flush=True)
            if status == "completed":
                output = task["output"]["assets"]
                if output:
                    return output[0]
                raise RuntimeError("Result is awaiting recovery; query this task again, do not resubmit")
            if status in ("failed", "pending_reconciliation"):
                raise RuntimeError("Task needs attention: " + status + "; do not submit a new paid job")
            time.sleep(10)
        raise RuntimeError("Polling timed out; resume querying the same task ID")

    def generate(channel, path, body, operation):
        quote = api("/api/v1/quote", {"channel": channel, "path": path, "body": body})
        print(operation, "estimated credits:", quote["estimated_credits"], flush=True)
        response = api("/api/relay/" + channel + path, body, operation)
        images = response.get("data") or response.get("images")
        if images and isinstance(images, list) and images[0].get("asset_id"):
            return {"id": images[0]["asset_id"]}
        return wait(response["id"])

    filename = os.path.basename(args.file)
    mime = mimetypes.guess_type(filename)[0]
    if mime not in ("image/png", "image/jpeg", "image/webp"):
        raise SystemExit("Reference must be PNG, JPEG or WebP")
    initialized = api("/api/v1/assets/uploads", {"name": filename, "content_type": mime, "size": os.path.getsize(args.file)}, "upload")
    if initialized["status"] != "ready":
        # This request goes to storage: send ONLY the returned upload headers, never the SK.
        headers = dict(initialized["headers"])
        headers["Content-Length"] = str(os.path.getsize(args.file))
        with open(args.file, "rb") as stream:
            request = urllib.request.Request(initialized["upload_url"], data=stream, headers=headers, method="PUT")
            with urllib.request.urlopen(request, timeout=300) as response:
                response.read()
        api(initialized["complete_url"], {})
    reference_id = initialized["asset_id"]
    print("Uploaded asset:", reference_id, flush=True)

    catalog = api("/api/v1/models")["data"]
    by_id = {item["id"]: item for item in catalog}
    for model in ("gpt-image-2.5-sunburst", "seedance-2.5-rev-1"):
        if model not in by_id:
            raise RuntimeError("SK has no available model: " + model + "; check permissions and /api/v1/models")
    image_route = next(route for route in by_id["gpt-image-2.5-sunburst"]["routes"] if route["operation"] == "image")
    image_template = next(item for item in image_route["request_templates"] if item["body"].get("size", "1024x1024") == "1024x1024")
    image_body = dict(image_template["body"])
    image_body.update(prompt="Create a cinematic landscape based on this reference, without any text.", image_asset_ids=[reference_id])
    image = generate(image_route["channel"], "/v1/images/edits", image_body, "image")
    print("Generated image asset:", image["id"], flush=True)
    video_route = next(route for route in by_id["seedance-2.5-rev-1"]["routes"] if route["operation"] == "video")
    video_template = next(item for item in video_route["request_templates"] if item["body"].get("resolution") == "480p" and "references" not in item["body"])
    video_body = dict(video_template["body"])
    video_body.update(prompt="A slow cinematic camera move across this landscape.", references=[{"type": "image", "asset_id": image["id"]}])
    video = generate(video_route["channel"], "/v1/videos", video_body, "video")
    # Original-link delivery can be explicitly saved without generating again.
    if video.get("storage") == "upstream":
        video = api("/api/v1/assets/" + video["id"] + "/save", {})
    video = api("/api/v1/assets/" + video["id"])
    if not video.get("url"):
        raise RuntimeError("Video URL unavailable; retain asset ID and query again")
    with urllib.request.urlopen(video["url"], timeout=300) as response, open(args.output, "wb") as target:
        while True:
            chunk = response.read(1024 * 1024)
            if not chunk:
                break
            target.write(chunk)
    print("Saved", args.output, "asset_id=" + video["id"])


if __name__ == "__main__":
    main()
