from .core import generate_bits

class QuantumRandom:
    def __init__(self, api_key: str = None, instance: str = None, use_simulator: bool = False):
        self.api_key = api_key
        self.instance = instance
        self.use_simulator = use_simulator

    def _get_bits(self, n: int) -> str:
        return generate_bits(n, api_key=self.api_key, instance=self.instance, use_simulator=self.use_simulator)

    def random(self) -> float:
        """Return a quantum random float in [0.0, 1.0)"""
        bits = self._get_bits(32)
        return int(bits, 2) / (2**32)

    def randint(self, a: int, b: int) -> int:
        """Return a quantum random integer N such that a <= N <= b"""
        range_size = b - a + 1
        num_bits = range_size.bit_length()
        while True:
            bits = self._get_bits(num_bits)
            value = int(bits, 2)
            if value < range_size:
                return a + value

    def randbytes(self, n: int) -> bytes:
        """Return n quantum random bytes"""
        bits = self._get_bits(n * 8)
        return int(bits, 2).to_bytes(n, "big")

    def choice(self, seq):
        """Return a quantum random element from a non-empty sequence"""
        return seq[self.randint(0, len(seq) - 1)]