"""Private parent-owned CUDA lease channel. This module imports only stdlib.

The parent acquires before spawning us. It alone holds the negotiator token.
Every model operation shares one prepare/synchronize/ready critical section.
"""
import json
import os
import re
import socket
import threading
from contextlib import contextmanager


class CudaLeaseFatal(BaseException):
    """Cannot be swallowed by ordinary ASR/consensus error recovery."""


def _terminate(message):
    os.write(2, ("Live Whisper CUDA lease failed: " + str(message) + "\n").encode())
    # Includes consensus-thread failures: no other thread may keep using CUDA.
    os._exit(70)


class WhisperCudaControl:
    def __init__(self, channel, fatal=_terminate):
        self.channel = channel
        self.fatal = fatal
        self.lock = threading.Lock()
        self.sequence = 0
        self.active = False
        self.failed = False

    @classmethod
    def from_environment(cls):
        uuid = os.environ.get("CUDA_VISIBLE_DEVICES", "")
        if (os.environ.get("OMNIUS_ASR_GPU_CONTROL_FD") != "3"
                or os.environ.get("OMNIUS_ASR_CUDA_DEVICE") != "0"
                or not re.fullmatch(r"GPU-[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", uuid)):
            raise CudaLeaseFatal("Live Whisper requires its Omnius scoped CUDA supervisor (FD 3 and one explicit GPU UUID); direct/unleased launch is refused before CUDA imports.")
        try:
            channel = socket.socket(fileno=3)
            # live-whisper may exec its managed venv before loading dependencies.
            os.set_inheritable(3, True)
            return cls(channel)
        except Exception as error:
            raise CudaLeaseFatal("Live Whisper GPU control FD 3 is unavailable") from error

    def abort(self, error):
        self.failed = True
        self.fatal(str(error))
        raise CudaLeaseFatal(str(error))

    def request(self, action):
        if self.failed:
            self.abort("previous control failure")
        self.sequence += 1
        try:
            self.channel.sendall((json.dumps({"id": self.sequence, "action": action, "device": "cuda:0"}) + "\n").encode())
            data = bytearray()
            while not data.endswith(b"\n"):
                part = self.channel.recv(1)
                if not part or len(data) >= 8192:
                    raise ValueError("closed or oversized parent response")
                data.extend(part)
            reply = json.loads(data)
            if reply != {"id": self.sequence, "ok": True}:
                raise ValueError("parent refused CUDA operation")
        except Exception as error:
            self.abort(error)

    def loaded(self, synchronize):
        with self.lock:
            try:
                synchronize()
                self.request("ready")
                self.active = True
            except Exception as error:
                self.abort(error)

    @contextmanager
    def operation(self, synchronize):
        with self.lock:
            if not self.active or self.failed:
                self.abort("CUDA operation before resident acknowledgement")
            self.request("prepare")
            self.active = False
            try:
                yield
            finally:
                try:
                    synchronize()
                    self.request("ready")
                    self.active = True
                except Exception as error:
                    self.abort(error)
