"""G9 GPU smoke Space: reports torch-on-CUDA, measures TFLOPS, allocates on demand."""
import json, os, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse

import torch

HELD = []


def info():
    ok = torch.cuda.is_available()
    out = {"cuda": ok, "torch": torch.__version__, "visible": os.environ.get("NVIDIA_VISIBLE_DEVICES")}
    if ok:
        out["device"] = torch.cuda.get_device_name(0)
        out["capability"] = torch.cuda.get_device_capability(0)
        a = torch.ones(512, 512, device="cuda")
        out["matmul_sum"] = float((a @ a).sum())  # 512**3 = 134217728
    return out


def tflops():
    n = 4096
    a = torch.randn(n, n, device="cuda", dtype=torch.float32)
    b = torch.randn(n, n, device="cuda", dtype=torch.float32)
    for _ in range(3):
        a @ b
    torch.cuda.synchronize()
    t = time.perf_counter(); reps = 20
    for _ in range(reps):
        a @ b
    torch.cuda.synchronize()
    return {"tflops_fp32": round(2 * n**3 * reps / (time.perf_counter() - t) / 1e12, 2)}


def alloc(gib, managed=False):
    t = time.time()
    if managed:
        from cuda.bindings import runtime as rt
        err, ptr = rt.cudaMallocManaged(int(gib * 2**30), rt.cudaMemAttachGlobal)
        rt.cudaMemset(ptr, 1, int(gib * 2**30)); rt.cudaDeviceSynchronize()
        HELD.append(("managed", ptr))
    else:
        HELD.append(("tensor", torch.ones(int(gib * 2**28), device="cuda")))  # float32: 4 bytes
        torch.cuda.synchronize()
    return {"held_blocks": len(HELD), "took_s": round(time.time() - t, 2)}


class H(BaseHTTPRequestHandler):
    def do_GET(self):
        u = urlparse(self.path); q = parse_qs(u.query)
        try:
            if u.path == "/":
                body = info()
            elif u.path == "/tflops":
                body = tflops()
            elif u.path in ("/alloc", "/managed"):
                body = alloc(float(q.get("gib", ["1"])[0]), managed=u.path == "/managed")
            elif u.path == "/free":
                HELD.clear(); torch.cuda.empty_cache(); body = {"freed": True}
            else:
                self.send_error(404); return
            code = 200
        except Exception as e:  # report, don't crash the probe target
            body, code = {"error": repr(e)}, 500
        data = json.dumps(body).encode()
        self.send_response(code); self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data)


ThreadingHTTPServer(("0.0.0.0", 7860), H).serve_forever()
