"""Run with Python 3 and requests. State contains request/result data; keep it private."""
import json
import os
from pathlib import Path
import time
import uuid
import requests

base = os.environ.get("MUSESPARK_BASE_URL", "https://api.musespark.ai").rstrip("/")
headers = {"Authorization": "Bearer " + os.environ["MUSESPARK_API_KEY"]}
state_path = Path(os.environ.get("MUSESPARK_TASK_STATE", "musespark-task.json"))

def save(state):
    temporary = state_path.with_name(state_path.name + ".tmp")
    with open(temporary, "w", encoding="utf-8") as handle:
        os.chmod(temporary, 0o600)
        json.dump(state, handle, indent=2)
    os.replace(temporary, state_path)

def read(response):
    response.raise_for_status()
    payload = response.json()
    if payload.get("code") != 200:
        raise RuntimeError(payload.get("msg", "Request failed"))
    return payload["data"]

if state_path.exists():
    state = json.loads(state_path.read_text(encoding="utf-8"))
    if state["base_url"] != base:
        raise RuntimeError("This state belongs to a different API base URL")
    if not state.get("task_id"):
        raise RuntimeError("A submission may already exist. Reconcile it before retrying; preserve the saved request_id and request.")
else:
    state = {
        "base_url": base,
        "request_id": str(uuid.uuid4()),
        "request": {"item_key": "nano-banana", "parameters": {
            "prompt": "A paper city under soft morning light",
            "aspect_ratio": "1:1", "resolution": "1K", "batch_size": 1,
        }},
    }
    save(state)  # Persist the request identity before sending any paid work.
    print("Request state:", state_path)
    created = read(requests.post(
        base + "/api/v1/openapi/task",
        headers={**headers, "X-Idempotency-Key": state["request_id"]},
        json=state["request"], timeout=30,
    ))
    state["task_id"] = created["task_id"]
    save(state)

if "result" in state:
    print(json.dumps(state["result"], indent=2))
else:
    print("Task:", state["task_id"])
    deadline = time.monotonic() + 600
    delay = 2
    while time.monotonic() < deadline:
        task = read(requests.get(
            base + "/api/v1/openapi/task/status/" + state["task_id"],
            headers=headers, timeout=30,
        ))
        if task["status"] == "completed":
            state["result"] = task.get("result", {})
            save(state)
            print(json.dumps(state["result"], indent=2))
            break
        if task["status"] in ("failed", "cancelled"):
            state["terminal_status"] = task["status"]
            state["error"] = task.get("error") or task.get("message")
            save(state)
            raise RuntimeError(state["error"] or state["terminal_status"])
        if task["status"] not in ("pending", "running", "finalizing"):
            raise RuntimeError("Unknown task status: " + task["status"])
        time.sleep(delay)
        delay = min(delay * 1.5, 15)
    else:
        raise TimeoutError("Polling stopped. Run again with the same state file to resume the existing task.")
