// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

#include <cupo/tuples.h>
#include <cupo/version.h>
#include <cuda_runtime_api.h>
#include <stdint.h>
#include <stdio.h>

#define CUDA_CHECK(call) do { \
    cudaError_t status = (call); \
    if (status != cudaSuccess) { \
        fprintf(stderr, "%s\n", cudaGetErrorString(status)); \
        goto cleanup; \
    } \
} while (0)

#define CUPO_CHECK(call) do { \
    if ((call) != CUPO_SUCCESS) { \
        fprintf(stderr, "%s\n", cupo_last_error()); \
        goto cleanup; \
    } \
} while (0)

int main(void)
{
    int result = 1;
    cupo_tuples_handle handle = NULL;
    void *device_positions = NULL;
    int64_t *device_forces = NULL;
    double *device_energy = NULL;

    /* Two atoms separated by 0.2 nm; the fourth component is unused. */
    const double positions[2][4] = {{0, 0, 0, 0}, {0.2, 0, 0, 0}};
    int64_t forces[6];
    double energy;
    const cupo_tuples_bond bond = {
        .atoms = {0, 1},
        .parameters = {.length = 0.1, .k = 1000.0},
        .use_pbc = 0,
        .group = 0
    };
    const cupo_tuples_term_batch batch = {
        .kind = CUPO_TUPLES_HARMONIC_BOND, .count = 1, .terms = &bond
    };

    if (cupo_abi_version() != CUPO_ABI_VERSION) {
        fprintf(stderr, "cuPotential headers and library have different ABIs\n");
        return 1;
    }
    CUDA_CHECK(cudaSetDevice(0));
    CUPO_CHECK(cupo_tuples_create(2, 1, &batch, CUPO_TUPLES_FLOAT64, &handle));
    CUDA_CHECK(cudaMalloc(&device_positions, sizeof(positions)));
    CUDA_CHECK(cudaMalloc((void **)&device_forces, sizeof(forces)));
    CUDA_CHECK(cudaMalloc((void **)&device_energy, sizeof(energy)));
    CUDA_CHECK(cudaMemcpy(device_positions, positions, sizeof(positions),
                          cudaMemcpyHostToDevice));

    /* Execution adds to the outputs, so clear them before this calculation. */
    CUDA_CHECK(cudaMemset(device_forces, 0, sizeof(forces)));
    CUDA_CHECK(cudaMemset(device_energy, 0, sizeof(energy)));
    CUPO_CHECK(cupo_tuples_execute(handle, device_positions, NULL,
        device_forces, 2, device_energy, 1u, NULL));
    CUDA_CHECK(cudaDeviceSynchronize());
    CUDA_CHECK(cudaMemcpy(&energy, device_energy, sizeof(energy),
                          cudaMemcpyDeviceToHost));
    CUDA_CHECK(cudaMemcpy(forces, device_forces, sizeof(forces),
                          cudaMemcpyDeviceToHost));

    /* x, y, and z are separate force planes, each with stride 2. */
    printf("Energy: %.6f kJ/mol\n", energy);
    printf("Forces along x: %.6f, %.6f kJ/(mol*nm)\n",
           (double)forces[0] / 4294967296.0,
           (double)forces[1] / 4294967296.0);
    result = 0;

cleanup:
    cudaDeviceSynchronize();
    cupo_tuples_destroy(handle);
    cudaFree(device_energy);
    cudaFree(device_forces);
    cudaFree(device_positions);
    return result;
}
