from qiskit import QuantumCircuit, transpile
from qiskit_ibm_runtime import SamplerV2 as Sampler
from .client import get_service

def generate_bits(num_bits: int = 8, api_key: str = None, instance: str = None, use_simulator: bool = False) -> str:  # ← add instance
    """Generate truly random bits using IBM Quantum hardware or simulator."""

    if use_simulator:
        from qiskit_aer import AerSimulator
        backend = AerSimulator()
        run = lambda qc: backend.run(qc, shots=1).result().get_counts()
        random_bits = ""
        for _ in range(num_bits):
            qc = QuantumCircuit(1, 1)
            qc.h(0)
            qc.measure(0, 0)
            counts = run(qc)
            random_bits += list(counts.keys())[0]
        return random_bits

    # Real IBM Quantum hardware
    service = get_service(api_key, instance)  # ← pass instance
    backend = service.least_busy(operational=True, simulator=False)

    qc = QuantumCircuit(num_bits, num_bits)
    for i in range(num_bits):
        qc.h(i)
    qc.measure(range(num_bits), range(num_bits))

    qc_transpiled = transpile(qc, backend=backend, optimization_level=1)

    sampler = Sampler(backend)
    job = sampler.run([qc_transpiled], shots=1)
    result = job.result()
    counts = result[0].data
    register_name = list(counts.keys())[0]
    bits = list(getattr(counts, register_name).get_counts().keys())[0]
    return bits.replace(" ", "")