# RentGPUPower compute API - thin Python client. One file, standard library only,
# so it works before anyone has run pip.
#
#   from gpurent import GpuRent            # download from /sdk/gpurent.py
#   gr = GpuRent("https://your-marketplace", os.environ["GPURENT_API_KEY"])
#   job = gr.run_job(command="nvidia-smi", min_vram_gb=16)["job"]
#   print(gr.wait_job(job["id"])["output"])
#
# Deliberately adds NOTHING over the HTTP API it wraps - same endpoints, same
# field names - so the reference on /developers is also this client's
# reference. Errors raise GpuRentError with .status and .code verbatim from
# the server's JSON.
import json
from urllib.parse import urlencode
import time
import urllib.parse
import urllib.request
import urllib.error


class GpuRentError(Exception):
    def __init__(self, status, code, message):
        super().__init__(message)
        self.status = status
        self.code = code


class GpuRent:
    def __init__(self, base_url, api_key, timeout=120):
        self.base = base_url.rstrip("/") + "/api/v1/compute"
        self.key = api_key
        self.timeout = timeout

    def _req(self, method, path, body=None, headers=None):
        data = None if body is None else json.dumps(body).encode()
        req = urllib.request.Request(self.base + path, data=data, method=method)
        req.add_header("Authorization", "Bearer " + self.key)
        if data is not None:
            req.add_header("Content-Type", "application/json")
        for k, v in (headers or {}).items():
            req.add_header(k, v)
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as r:
                return json.loads(r.read().decode() or "{}")
        except urllib.error.HTTPError as e:
            try:
                payload = json.loads(e.read().decode() or "{}")
            except Exception:
                payload = {}
            # Two shapes: {error, code} from the compute API, and OpenAI's
            # {error: {message, type, code}} from the chat gateway.
            inner = payload.get("error") if isinstance(payload.get("error"), dict) else {}
            message = inner.get("message") or payload.get("message") or (payload.get("error") if isinstance(payload.get("error"), str) else None)
            raise GpuRentError(e.code, inner.get("code") or inner.get("type") or payload.get("code"),
                               message or ("HTTP %d" % e.code)) from None

    def _spend(self, method, path, opts):
        """The calls that spend take idempotency_key=: sent as the Idempotency-Key
        header, so a retry after a lost answer gets that answer back instead
        of booking twice."""
        opts = dict(opts)
        key = opts.pop("idempotency_key", None)
        return self._req(method, path, opts, {"Idempotency-Key": str(key)} if key else None)

    # ---- account ----
    def me(self): return self._req("GET", "/me")
    def balance(self): return self._req("GET", "/balance")
    # lines (ledger), has_more, inference totals, and days: seven UTC-day buckets
    # (jobs, instances, spent_cents, gpu_seconds), oldest first, ending today.
    def usage(self): return self._req("GET", "/usage")

    # ---- the pool ----
    def gpus(self, **filters):
        """Public pool catalog + floor prices. Filters: gpu_model, min_vram_gb,
        region, max_price_cents_hour, min_gpu_count."""
        q = urlencode({k: v for k, v in filters.items() if v is not None})
        return self._req("GET", "/gpus" + ("?" + q if q else ""))

    def capacity(self, **filters):
        """What can I run right now? Same filters as run_job; returns
        pool.available_now, per-model breakdown, retry_hint_s when full,
        and your balance / running work / rate-limit budget."""
        q = urlencode({k: v for k, v in filters.items() if v is not None})
        return self._req("GET", "/capacity" + ("?" + q if q else ""))

    # ---- serverless jobs ----
    def run_job(self, **opts): return self._spend("POST", "/jobs", opts)
    def job(self, job_id): return self._req("GET", "/jobs/%d" % int(job_id))
    def cancel_job(self, job_id): return self._req("DELETE", "/jobs/%d" % int(job_id))

    # ---- SSH: keys on the account, and SSH on in a rental you hold ----
    # Connect with the CLI (gpurent ssh <id>): the bytes ride /tunnel/<id>?port=22.
    def ssh_keys(self): return self._req("GET", "/ssh-keys")
    def add_ssh_key(self, public_key, name=None): return self._req("POST", "/ssh-keys", {"public_key": public_key, "name": name})
    def remove_ssh_key(self, key_id): return self._req("DELETE", "/ssh-keys/%d" % int(key_id))
    def enable_ssh(self, rental_id, public_key=None):
        return self._req("POST", "/ssh/%d" % int(rental_id), {"public_key": public_key} if public_key else {})
    def ssh_status(self, rental_id): return self._req("GET", "/ssh/%d" % int(rental_id))

    # ---- batches: one request, up to 100,000 tasks over the whole pool ----
    def run_batch(self, **opts):
        """command, tasks= or inputs= (one per task), max_parallel, max_attempts,
        budget_cents, deadline_s, name, timeout_s, webhook_url, gpu_model, ...
        Each task sees GPURENT_TASK_INDEX, GPURENT_TASK_COUNT, GPURENT_TASK_ATTEMPT
        and GPURENT_TASK_INPUT (its inputs entry)."""
        return self._spend("POST", "/batches", opts)
    def batch(self, batch_id): return self._req("GET", "/batches/%s" % batch_id)
    def batches(self, **opts):
        q = urlencode({k: v for k, v in opts.items() if v is not None})
        return self._req("GET", "/batches" + ("?" + q if q else ""))
    def batch_tasks(self, batch_id, **opts):
        """after=, limit=, status=, output=1 — page with the reply's next_after."""
        q = urlencode({k: v for k, v in opts.items() if v is not None})
        return self._req("GET", "/batches/%s/tasks" % batch_id + ("?" + q if q else ""))
    def cancel_batch(self, batch_id): return self._req("POST", "/batches/%s/cancel" % batch_id)

    def wait_batch(self, batch_id, interval=5.0, timeout=7 * 86400.0):
        t0 = time.time()
        while True:
            b = self.batch(batch_id)["batch"]
            if b["status"] != "running":
                return b
            if time.time() - t0 > timeout:
                raise GpuRentError(0, "timeout", "wait_batch timed out")
            time.sleep(interval)

    def all_batch_tasks(self, batch_id, **opts):
        """Every task, page after page (outputs included with output=1)."""
        out, after = [], None
        while True:
            page = self.batch_tasks(batch_id, **dict(opts, **({"after": after} if after is not None else {})))
            out.extend(page["tasks"])
            if not page["has_more"]:
                return out
            after = page["next_after"]

    def jobs(self, **opts):
        q = "&".join("%s=%s" % (k, v) for k, v in opts.items())
        return self._req("GET", "/jobs" + ("?" + q if q else ""))

    def wait_job(self, job_id, interval=2.0, timeout=3600.0):
        t0 = time.time()
        while True:
            j = self.job(job_id)["job"]
            # 'queued' (a queue_s job waiting for a GPU) is not finished either.
            if j["status"] not in ("queued", "scheduling", "running"):
                return j
            if time.time() - t0 > timeout:
                raise GpuRentError(0, "timeout", "wait_job timed out")
            time.sleep(interval)

    def stream_job(self, job_id, on_event=None):
        """Live output via SSE. on_event receives dicts with 'event' plus the
        payload for 'output' (delta text), 'status' and 'done'. Returns the
        done event, or None if the server closed without one."""
        req = urllib.request.Request(self.base + "/jobs/%d/stream" % int(job_id))
        req.add_header("Authorization", "Bearer " + self.key)
        with urllib.request.urlopen(req, timeout=self.timeout) as r:
            event, data = None, None
            for raw in r:
                line = raw.decode().rstrip("\n").rstrip("\r")
                if line.startswith("event: "):
                    event = line[7:]
                elif line.startswith("data: "):
                    data = line[6:]
                elif line == "" and event and data is not None:
                    payload = dict(json.loads(data))
                    payload["event"] = event
                    if on_event:
                        on_event(payload)
                    if event == "done":
                        return payload
                    event, data = None, None
        return None

    # ---- per-second instances ----
    def create_instance(self, **opts): return self._spend("POST", "/instances", opts)
    def instance(self, iid): return self._req("GET", "/instances/%d" % int(iid))
    def extend_instance(self, iid, **opts): return self._spend("POST", "/instances/%d/extend" % int(iid), opts)
    def destroy_instance(self, iid): return self._req("DELETE", "/instances/%d" % int(iid))
    def ready(self, iid): return self._req("GET", "/instances/%d/ready" % int(iid))
    def instances(self): return self._req("GET", "/instances")

    # ---- clusters: several machines on one private network ----
    def quote_cluster(self, **opts): return self._req("POST", "/clusters/quote", opts)   # count=, kind='gpu'|'cpu'|'memory', gpu_model=, min_vram_gb=, min_cores=, min_ram_gb=, same_region=, hours= | listing_ids=
    def create_cluster(self, **opts): return self._spend("POST", "/clusters", opts)    # hours=, count= + filters | listing_ids=, expected_total_cents=
    def cluster(self, cid): return self._req("GET", "/clusters/%d" % int(cid))
    def clusters(self): return self._req("GET", "/clusters")
    def run_on_cluster(self, cid, **opts): return self._req("POST", "/clusters/%d/run" % int(cid), opts)   # command=
    def cluster_jobs(self, cid, job_ids): return self._req("GET", "/clusters/%d/jobs?ids=%s" % (int(cid), ",".join(str(int(j)) for j in job_ids)))
    def extend_cluster(self, cid, **opts): return self._spend("POST", "/clusters/%d/extend" % int(cid), opts)   # hours=
    def stop_cluster(self, cid): return self._req("DELETE", "/clusters/%d" % int(cid))

    # ---- credits from code ----
    def create_topup(self, **opts): return self._spend("POST", "/topups", opts)   # amount_cents — then stripe_intent, then confirm_topup(id, method='stripe')
    def topup(self, tid): return self._req("GET", "/topups/%d" % int(tid))
    def stripe_intent(self, tid): return self._req("POST", "/topups/%d/stripe-intent" % int(tid), {})
    def confirm_topup(self, tid, **body): return self._req("POST", "/topups/%d/confirm" % int(tid), body)

    # ---- OpenAI-compatible chat: your running instance, or a shared model priced per token ----
    def chat(self, **body): return self._req("POST", "/chat/completions", body)
    # The same call in Anthropic's shape (its Messages API): same key, same models, same price.
    def messages(self, **body): return self._req("POST", "/messages", body)   # model, max_tokens, messages, system=…, tools=…
    def count_tokens(self, **body): return self._req("POST", "/messages/count_tokens", body)
    def models(self): return self._req("GET", "/models")
    def model(self, model_id): return self._req("GET", "/models/" + urllib.parse.quote(str(model_id), safe=""))

    # ---- text embeddings, computed by phones (OpenAI's shape) ----
    def embeddings(self, **body): return self._req("POST", "/embeddings", body)   # input=text or [texts]
