# CUDA-Q statevector benchmark: QFT and a random layered circuit, timed per qubit count.
# usage: python cudaq_bench.py <target> <option|-> <nmin> <nmax> [depth]
import sys, time, math, random
import cudaq

target, option, nmin, nmax = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4])
depth = int(sys.argv[5]) if len(sys.argv) > 5 else 20
if option != "-":
    cudaq.set_target(target, option=option)
else:
    cudaq.set_target(target)

@cudaq.kernel
def qft(n: int):
    q = cudaq.qvector(n)
    x(q[0])
    h(q)                       # a non-trivial input state
    for i in range(n):
        h(q[i])
        for j in range(i + 1, n):
            r1.ctrl(math.pi / (2 ** (j - i)), q[j], q[i])
    for i in range(n // 2):
        swap(q[i], q[n - 1 - i])
    mz(q)

@cudaq.kernel
def layered(n: int, depth: int, angles: list[float]):
    q = cudaq.qvector(n)
    k = 0
    for d in range(depth):
        for i in range(n):
            rx(angles[k], q[i]); k += 1
            ry(angles[k], q[i]); k += 1
        start = d % 2
        for i in range(start, n - 1, 2):
            x.ctrl(q[i], q[i + 1])
    mz(q)

def timed(fn):
    t = time.perf_counter(); fn(); return time.perf_counter() - t

random.seed(1)
cudaq.sample(qft, 10, shots_count=100)  # warm-up / JIT
print(f"# target={target} option={option} depth={depth}", flush=True)
for n in range(nmin, nmax + 1):
    gates_qft = n + n * (n - 1) // 2 + n // 2 + n
    angles = [random.uniform(0, 2 * math.pi) for _ in range(2 * n * depth)]
    try:
        t1 = timed(lambda: cudaq.sample(qft, n, shots_count=1000))
        t2 = timed(lambda: cudaq.sample(qft, n, shots_count=1000))
        l1 = timed(lambda: cudaq.sample(layered, n, depth, angles, shots_count=1000))
        l2 = timed(lambda: cudaq.sample(layered, n, depth, angles, shots_count=1000))
        print(f"n={n} qft_gates={gates_qft} qft_s={min(t1,t2):.3f} layered_gates={depth*(2*n+(n-1)//2)} layered_s={min(l1,l2):.3f}", flush=True)
    except Exception as e:
        print(f"n={n} FAILED {type(e).__name__}: {str(e)[:200]}", flush=True)
        break
