"""Bounded scoped broker transitions, without putting lease secrets in argv/logs."""
import hmac
import json
import os
import socket
import time

import model_gate as gate

CONTROL_SOCKET = "/run/ollama-unify/gpu-negotiator.sock"
MAX_REPLY_BYTES = 128 * 1024


class ScopedGpuLease:
    def __init__(self, owner, gpu_uuids, control_socket=CONTROL_SOCKET, environ=None,
                 socket_factory=socket.socket, timeout=10):
        environment = os.environ if environ is None else environ
        token = environment.get("OLLAMA_UNIFY_GPU_LEASE", "")
        gate.require(isinstance(token, str) and 16 <= len(token) <= 1024,
                     "supervisor-owned GPU lease environment is required")
        gate.require(isinstance(owner, str) and bool(owner) and isinstance(gpu_uuids, list)
                     and 0 < len(gpu_uuids) <= 3 and len(set(gpu_uuids)) == len(gpu_uuids)
                     and all(isinstance(value, str) and gate.GPU_ID.fullmatch(value) for value in gpu_uuids),
                     "exact lease owner and GPU scope required")
        gate.require(0 < timeout <= 30, "lease transition timeout is outside bounds")
        self._token, self.owner, self.gpu_uuids = token, owner, list(gpu_uuids)
        self.control_socket, self.socket_factory, self.timeout = control_socket, socket_factory, timeout

    def _transition(self, action, expected_state):
        # Do not return or log the broker's raw response: it includes the token.
        try:
            deadline = time.monotonic() + self.timeout
            with self.socket_factory(socket.AF_UNIX, socket.SOCK_STREAM) as stream:
                stream.settimeout(self.timeout)
                stream.connect(self.control_socket)
                stream.sendall(json.dumps({"action": action, "token": self._token}).encode() + b"\n")
                raw = bytearray()
                while b"\n" not in raw:
                    remaining = deadline - time.monotonic()
                    gate.require(remaining > 0, "lease transition timed out")
                    stream.settimeout(remaining)
                    block = stream.recv(min(4096, MAX_REPLY_BYTES + 1 - len(raw)))
                    gate.require(bool(block), "broker closed before transition confirmation")
                    raw.extend(block)
                    gate.require(len(raw) <= MAX_REPLY_BYTES, "broker reply exceeds bound")
                response = gate.strict_json(bytes(raw).split(b"\n", 1)[0])
            lease = response.get("lease", {})
            gate.require(response.get("ok") is True and isinstance(lease, dict), "broker denied transition")
            token = lease.get("token")
            gate.require(isinstance(token, str) and hmac.compare_digest(token, self._token)
                         and lease.get("owner") == self.owner
                         and lease.get("gpu_uuids") == self.gpu_uuids
                         and lease.get("state") == expected_state, "broker transition identity mismatch")
        except Exception:
            # Even an unexpected broker exception/JSON field must not leak a secret.
            raise gate.GateError(f"GPU lease {action} was not confirmed; no further CUDA work is permitted") from None
        return {"action": action, "owner": self.owner, "gpu_uuids": self.gpu_uuids,
                "state": expected_state}

    def prepare(self):
        return self._transition("prepare", "pending")

    def ready(self):
        return self._transition("ready", "active")
