"""Example 1 — Vector addition: the "Hello world" of GPUs.

Concepts: kernel, global index, grid of blocks, memory transfers.

    python examples/01_vector_addition.py [device]
"""

import numpy as np
from common import choose_device, size

import unigpu as gpu


@gpu.jit
def addition(a, b, c):
    # Each thread computes ONE element of the result.
    i = gpu.grid(1)          # = blockIdx.x * blockDim.x + threadIdx.x
    if i < c.size:           # the grid can be larger than the array
        c[i] = a[i] + b[i]


def main():
    """Run the example on the device given as an argument (the best one otherwise)."""
    choose_device()
    n = size(100_000, 2_000)
    a = np.random.rand(n).astype(np.float32)
    b = np.random.rand(n).astype(np.float32)

    # 1. Allocation and copy to device memory (host -> GPU)
    d_a = gpu.to_device(a)
    d_b = gpu.to_device(b)
    d_c = gpu.device_array(n, np.float32)

    # 2. Grid configuration: enough blocks to cover n elements
    threads_per_block = 256
    blocks = (n + threads_per_block - 1) // threads_per_block
    addition[blocks, threads_per_block](d_a, d_b, d_c)

    # 3. Copy of the result to the host (GPU -> host)
    c = d_c.copy_to_host()
    assert np.allclose(c, a + b)
    print(f"OK: {n} additions on {blocks} blocks of {threads_per_block} threads")


if __name__ == "__main__":
    main()
