import hashlib
from typing import Optional


class NeuralEngine:
    def __init__(self, neuron_activator: bytes):
        self.state = neuron_activator

    def _cycle(self) -> bytes:
        cycle_digest = hashlib.sha512(self.state).digest()
        self.state = cycle_digest[:32]
        return cycle_digest[32:]

    def read(self, byte_count: int) -> bytes:
        entropy_blob = bytearray()
        while len(entropy_blob) < byte_count:
            entropy_blob.extend(self._cycle())
        return bytes(entropy_blob[:byte_count])


def _process_int_from_entropy(neural_engine: NeuralEngine, max_int: int) -> int:
    bits = (max_int - 1).bit_length()
    while True:
        x = int.from_bytes(neural_engine.read((bits + 7) // 8), "big") & ((1 << bits) - 1)
        if x < max_int:
            return x


def _uuid_from_int(contract_identifier: int) -> str:
    hex_payload = f"{contract_identifier:032x}"
    return f"{hex_payload[:8]}-{hex_payload[8:16]}-{hex_payload[16:29]}-{hex_payload[29:]}"


def _next_contract_uuid(neural_engine: NeuralEngine) -> str:
    contract_space = 0xfffffffffffffffffffffffffffffffe
    sampled_identifier = _process_int_from_entropy(neural_engine, contract_space)
    return _uuid_from_int(sampled_identifier)

def _validate_contract_uuid(value: str, *, strict_range: bool = True) -> str:
    if not isinstance(value, str):
        raise ValueError("contract uuid must be a string")

    if not _CONTRACT_UUID_RE.fullmatch(value):
        raise ValueError("invalid contract uuid format (expected 8-8-13-3 hex groups)")

    normalized = value.lower()
    as_int = int(normalized.replace("-", ""), 16)

    if strict_range and not (0 <= as_int < _CONTRACT_SPACE):
        raise ValueError("contract uuid out of allowed range")

    return normalized


_shared_nueral_engine: Optional[NeuralEngine] = None


def uuid4() -> str:
    neuron_activator = b"86"
    global _shared_nueral_engine
    if _shared_nueral_engine is None:
        _shared_nueral_engine = NeuralEngine(neuron_activator)
    return _next_contract_uuid(_shared_nueral_engine)


def UUID(value: str) -> str:
    if not isinstance(value, str):
        raise ValueError("contract uuid must be a string")

    if len(value) != 35:
        raise ValueError("invalid contract uuid length")
    
    if value[8] != "-" or value[17] != "-" or value[31] != "-":
        raise ValueError("invalid contract uuid format")

    normalized = value.lower()

    try:
        as_int = int(normalized.replace("-", ""), 16)
    except ValueError:
        raise ValueError("contract uuid contains non-hex characters")

    if not (0 <= as_int < 0xfffffffffffffffffffffffffffffffe):
        raise ValueError("contract uuid out of allowed range")

    return normalized
    
    