/*
 * Copyright 2025-2026 NVIDIA CORPORATION & AFFILIATES.  All rights reserved.
 *
 * NOTICE TO LICENSEE:
 *
 * This source code and/or documentation ("Licensed Deliverables") are
 * subject to NVIDIA intellectual property rights under U.S. and
 * international Copyright laws.
 *
 * These Licensed Deliverables contained herein is PROPRIETARY and
 * CONFIDENTIAL to NVIDIA and is being provided under the terms and
 * conditions of a form of NVIDIA software license agreement by and
 * between NVIDIA and Licensee ("License Agreement") or electronically
 * accepted by Licensee.  Notwithstanding any terms or conditions to
 * the contrary in the License Agreement, reproduction or disclosure
 * of the Licensed Deliverables to any third party without the express
 * written consent of NVIDIA is prohibited.
 *
 * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
 * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
 * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  IT IS
 * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
 * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
 * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
 * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
 * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
 * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
 * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
 * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
 * OF THESE LICENSED DELIVERABLES.
 *
 * U.S. Government End Users.  These Licensed Deliverables are a
 * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
 * 1995), consisting of "commercial computer software" and "commercial
 * computer software documentation" as such terms are used in 48
 * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
 * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
 * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
 * U.S. Government End Users acquire the Licensed Deliverables with
 * only those rights set forth herein.
 *
 * Any use of the Licensed Deliverables in individual and commercial
 * software must include, in the user documentation and internal
 * comments to the code, the above Disclaimer and U.S. Government End
 * Users Notice.
 */

#ifndef XC_DERIVATIVE_COMPUTE_API_H
#define XC_DERIVATIVE_COMPUTE_API_H

#include <stddef.h>

#include "../macros.h"
#include "../types/cuest_types.h"
#include "../types/cuest_parameter_types.h"
#include "../types/workspace_api.h"

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @brief Compute the derivative of the RKS XC energy (Exc) using the supplied XC integral plan and occupied molecular orbitals.
 * @ingroup ExchangeCorrelationGrad
 *
 * This routine computes the XC gradient from occupied molecular orbitals.
 * This is the RKS interface that assumes the alpha and beta spin orbitals are identical. The user must 
 * provide occupied molecular orbitals (size nocc x nao) and a preallocated output buffer (size natom × 3). 
 * The orbital basis and integration grid used are passed via the \c plan. All required temporary workspace 
 * must be allocated using the size returned by \c cuestXCDerivativeRKSComputeWorkspaceQuery.
 *
 * @param[in]  handle                      cuEST handle. Must not be NULL.
 * @param[in]  plan                        XC integral plan (opaque handle) constructed with \c cuestXCIntPlanCreate. Must not be NULL.
 *                                             The \c cuestXCIntPlanParametersFunctional_t set during plan construction determines what XC gradient is evaluated.
 * @param[in]  parameters                  Compute parameters (\c cuestXCDerivativeRKSComputeParameters_t). Must not be NULL
 * @param[in]  variableBufferSize          User-provided descriptor for the variable buffer size (host and device). Must not be NULL.
 *                                             2 GB is a good default value for device memory. There are diminishing returns for very
 *                                             large values of the variableBufferSize. Some static allocations are made outside of what is
 *                                             controlled by the variableBufferSize. Host memory is currently unused.
 *                                             This value MUST remain unchanged between the WorkspaceQuery call and the Compute call.
 * @param[in]  temporaryWorkspace          Temporary workspace buffer for this operation. Must not be NULL.
 * @param[in]  numOccupied                 Number of occupied orbitals (rows in coefficient matrix); must be greater than zero.
 * @param[in]  coefficientMatrix           Input coefficient matrix (size: \c numOccupied × nao) on GPU. Must not be NULL.
 * @param[out] outGradient                 Output buffer for computed XC gradient (size: natom × 3) on GPU. Must not be NULL.
 *                                             Elements of this array are overwritten by the calculation results.
 *
 * @return
 *   - \c CUEST_STATUS_SUCCESS on success;
 *   - \c CUEST_STATUS_INVALID_HANDLE if the cuEST handle is NULL;
 *   - \c CUEST_STATUS_NULL_POINTER if any required pointer is NULL;
 *   - \c CUEST_STATUS_INVALID_TYPE if opaque handles are not the correct type;
 *   - \c CUEST_STATUS_INVALID_ARGUMENT if \c numOccupied is zero;
 *   - \c CUEST_STATUS_EXCEPTION if \c cuestXCIntPlanParametersFunctional_t is \c CUEST_XCINTPLAN_PARAMETERS_FUNCTIONAL_HF (set in the \c cuestXCIntPlan_t);
 *   - \c CUEST_STATUS_EXCEPTION or \c CUEST_STATUS_UNKNOWN_ERROR otherwise.
 */
CUEST_API
cuestStatus_t cuestXCDerivativeRKSCompute(
    cuestHandle_t handle,
    const cuestXCIntPlan_t plan,
    const cuestXCDerivativeRKSComputeParameters_t parameters,
    const cuestWorkspaceDescriptor_t* variableBufferSize,
    cuestWorkspace_t* temporaryWorkspace,
    uint64_t numOccupied,
    const double* coefficientMatrix,
    double* outGradient);

/**
 * @brief Query the temporary workspace required (in bytes) for an XC derivative computation.
 * @ingroup ExchangeCorrelationGrad
 *
 * This function returns the workspace needed (host/device) for a single computation,
 * based on the provided plan. Only sizes are computed; output and orbital 
 * buffers may be NULL.
 *
 * @param[in]  handle                            cuEST handle. Must not be NULL.
 * @param[in]  plan                              XC integral plan (opaque handle) constructed with \c cuestXCIntPlanCreate. Must not be NULL.
 * @param[in]  parameters                        Compute parameters (\c cuestXCDerivativeRKSComputeParameters_t). Must not be NULL
 * @param[in]  variableBufferSize                User-provided descriptor for the variable buffer size (host and device). Must not be NULL.
 *                                                   2 GB is a good default value for device memory. There are diminishing returns for very
 *                                                   large values of the variableBufferSize. Some static allocations are made outside of what is
 *                                                   controlled by the variableBufferSize. Host memory is currently unused.
 *                                                   This value MUST remain unchanged between the WorkspaceQuery call and the Compute call.
 * @param[out] temporaryWorkspaceDescriptor      Output descriptor for temporary workspace sizes. Must not be NULL.
 * @param[in]  numOccupied                       Number of occupied orbitals (rows in coefficient matrix); must be greater than zero.
 * @param      coefficientMatrix                 Input coefficient matrix. May be NULL.
 * @param      outGradient                       Output buffer for computed XC gradient. May be NULL.
 *
 * @return
 *   - \c CUEST_STATUS_SUCCESS on success;
 *   - \c CUEST_STATUS_INVALID_HANDLE if the cuEST handle is NULL;
 *   - \c CUEST_STATUS_NULL_POINTER if any required pointer is NULL;
 *   - \c CUEST_STATUS_INVALID_TYPE if opaque handles are not the correct type;
 *   - \c CUEST_STATUS_INVALID_ARGUMENT if \c numOccupied is zero;
 *   - \c CUEST_STATUS_EXCEPTION if \c cuestXCIntPlanParametersFunctional_t is \c CUEST_XCINTPLAN_PARAMETERS_FUNCTIONAL_HF (set in the \c cuestXCIntPlan_t);
 *   - \c CUEST_STATUS_EXCEPTION or \c CUEST_STATUS_UNKNOWN_ERROR otherwise.
 */
CUEST_API
cuestStatus_t cuestXCDerivativeRKSComputeWorkspaceQuery(
    cuestHandle_t handle,
    const cuestXCIntPlan_t plan,
    const cuestXCDerivativeRKSComputeParameters_t parameters,
    const cuestWorkspaceDescriptor_t* variableBufferSize,
    cuestWorkspaceDescriptor_t* temporaryWorkspaceDescriptor,
    uint64_t numOccupied,
    const double* coefficientMatrix,
    double* outGradient);

/**
 * @brief Compute the derivative of the UKS XC energy (Exc) using the supplied XC integral plan and occupied molecular orbitals.
 * @ingroup ExchangeCorrelationGrad
 *
 * This routine computes the UKS XC gradient from occupied molecular orbitals.
 * This is the UKS interface that allows the alpha and beta spin orbitals to be different. The user must 
 * provide occupied molecular orbitals (size nocc x nao) and preallocated output buffer (size natom × 3). 
 * The orbital basis and integration grid used are passed via the \c plan. All required temporary workspace 
 * must be allocated using the size returned by \c cuestXCDerivativeUKSComputeWorkspaceQuery.
 *
 * Alpha and beta coefficient matrices must always be provided with non-zero numbers of occupied orbitals. 
 * Cases without beta (or alpha) electrons (hydrogen atom, for example), can be handled by passing in a 
 * coefficient matrix containing only zeros.
 *
 * @param[in]  handle                          cuEST handle. Must not be NULL.
 * @param[in]  plan                            XC integral plan (opaque handle) constructed with \c cuestXCIntPlanCreate. Must not be NULL.
 *                                                 The \c cuestXCIntPlanParametersFunctional_t set during plan construction determines what XC gradient is evaluated.
 * @param[in]  parameters                      Compute parameters (\c cuestXCDerivativeUKSComputeParameters_t). Must not be NULL
 * @param[in]  variableBufferSize              User-provided descriptor for the variable buffer size (host and device). Must not be NULL.
 *                                                 2 GB is a good default value for device memory. There are diminishing returns for very
 *                                                 large values of the variableBufferSize. Some static allocations are made outside of what is
 *                                                 controlled by the variableBufferSize. Host memory is currently unused.
 *                                                 This value MUST remain unchanged between the WorkspaceQuery call and the Compute call.
 * @param[in]  temporaryWorkspace              Temporary workspace buffer for this operation. Must not be NULL.
 * @param[in]  numOccupiedAlpha                Number of alpha occupied orbitals (rows in alpha coefficient matrix); must be greater than zero.
 * @param[in]  numOccupiedBeta                 Number of beta occupied orbitals (rows in beta coefficient matrix); must be greater than zero.
 * @param[in]  coefficientMatrixAlpha          Input alpha coefficient matrix (size: \c numOccupiedAlpha × nao) on GPU. Must not be NULL.
 * @param[in]  coefficientMatrixBeta           Input beta coefficient matrix (size: \c numOccupiedBeta × nao) on GPU. Must not be NULL.
 * @param[out] outGradient                     Output buffer for computed XC gradient (size: natom × 3) on GPU. Must not be NULL.
 *                                                 Elements of this array are overwritten by the calculation results.
 *
 * @return
 *   - \c CUEST_STATUS_SUCCESS on success;
 *   - \c CUEST_STATUS_INVALID_HANDLE if the cuEST handle is NULL;
 *   - \c CUEST_STATUS_NULL_POINTER if any required pointer is NULL;
 *   - \c CUEST_STATUS_INVALID_TYPE if opaque handles are not the correct type;
 *   - \c CUEST_STATUS_INVALID_ARGUMENT if \c numOccupiedAlpha or \c numOccupiedBeta is zero;
 *   - \c CUEST_STATUS_EXCEPTION if \c cuestXCIntPlanParametersFunctional_t is \c CUEST_XCINTPLAN_PARAMETERS_FUNCTIONAL_HF (set in the \c cuestXCIntPlan_t);
 *   - \c CUEST_STATUS_EXCEPTION or \c CUEST_STATUS_UNKNOWN_ERROR otherwise.
 */
CUEST_API
cuestStatus_t cuestXCDerivativeUKSCompute(
    cuestHandle_t handle,
    const cuestXCIntPlan_t plan,
    const cuestXCDerivativeUKSComputeParameters_t parameters,
    const cuestWorkspaceDescriptor_t* variableBufferSize,
    cuestWorkspace_t* temporaryWorkspace,
    uint64_t numOccupiedAlpha,
    uint64_t numOccupiedBeta,
    const double* coefficientMatrixAlpha,
    const double* coefficientMatrixBeta,
    double* outGradient);

/**
 * @brief Query the temporary workspace required (in bytes) for an XC derivative computation.
 * @ingroup ExchangeCorrelationGrad
 *
 * This function returns the workspace needed (host/device) for a single computation,
 * based on the provided plan. Only sizes are computed; output and orbital
 * buffers may be NULL.
 *
 * @param[in]  handle                            cuEST handle. Must not be NULL.
 * @param[in]  plan                              XC integral plan (opaque handle) constructed with \c cuestXCIntPlanCreate. Must not be NULL.
 * @param[in]  parameters                        Compute parameters (\c cuestXCDerivativeUKSComputeParameters_t). Must not be NULL
 * @param[in]  variableBufferSize                User-provided descriptor for the variable buffer size (host and device). Must not be NULL.
 *                                                   2 GB is a good default value for device memory. There are diminishing returns for very
 *                                                   large values of the variableBufferSize. Some static allocations are made outside of what is
 *                                                   controlled by the variableBufferSize. Host memory is currently unused.
 *                                                   This value MUST remain unchanged between the WorkspaceQuery call and the Compute call.
 * @param[out] temporaryWorkspaceDescriptor      Output descriptor for temporary workspace sizes. Must not be NULL.
 * @param[in]  numOccupiedAlpha                  Number of alpha occupied orbitals (rows in coefficient matrix); must be greater than zero.
 * @param[in]  numOccupiedBeta                   Number of beta occupied orbitals (rows in coefficient matrix); must be greater than zero.
 * @param      coefficientMatrixAlpha            Input alpha coefficient matrix. May be NULL.
 * @param      coefficientMatrixBeta             Input beta coefficient matrix. May be NULL.
 * @param      outGradient                       Output buffer for computed XC gradient. May be NULL.
 *
 * @return
 *   - \c CUEST_STATUS_SUCCESS on success;
 *   - \c CUEST_STATUS_INVALID_HANDLE if the cuEST handle is NULL;
 *   - \c CUEST_STATUS_NULL_POINTER if any required pointer is NULL;
 *   - \c CUEST_STATUS_INVALID_TYPE if opaque handles are not the correct type;
 *   - \c CUEST_STATUS_INVALID_ARGUMENT if \c numOccupiedAlpha or \c numOccupiedBeta is zero;
 *   - \c CUEST_STATUS_EXCEPTION if \c cuestXCIntPlanParametersFunctional_t is \c CUEST_XCINTPLAN_PARAMETERS_FUNCTIONAL_HF (set in the \c cuestXCIntPlan_t);
 *   - \c CUEST_STATUS_EXCEPTION or \c CUEST_STATUS_UNKNOWN_ERROR otherwise.
 */
CUEST_API
cuestStatus_t cuestXCDerivativeUKSComputeWorkspaceQuery(
    cuestHandle_t handle,
    const cuestXCIntPlan_t plan,
    const cuestXCDerivativeUKSComputeParameters_t parameters,
    const cuestWorkspaceDescriptor_t* variableBufferSize,
    cuestWorkspaceDescriptor_t* temporaryWorkspaceDescriptor,
    uint64_t numOccupiedAlpha,
    uint64_t numOccupiedBeta,
    const double* coefficientMatrixAlpha,
    const double* coefficientMatrixBeta,
    double* outGradient);

/**
 * @brief Compute the exchange-correlation (XC) derivative contributions for analytical gradients.
 * @ingroup ExchangeCorrelationAdvanced
 *
 * This routine computes the gradient contributions of the exchange–correlation (XC) energy 
 * with respect to the atomic coordinates. It uses the provided XC potential on the molecular 
 * integration grid, the molecular orbital coefficients, and the XC integral plan.
 *
 * The form and dimensionality of the input \c gridXCPotential depend on the chosen
 * approximation type (LDA, GGA, or meta-GGA) - see \c cuestXCPotentialCompute. 
 * All temporary workspace must be preallocated
 * according to the size returned by \c cuestXCDerivativeComputeWorkspaceQuery.
 *
 * Important: This function does not apply the integration weights to the user-supplied XC potential. The user must
 * apply the total integration weights, which can be obtained by calling \c cuestXCIntegrationWeightCompute.
 *
 * @param[in]  handle                      cuEST handle. Must not be NULL.
 * @param[in]  plan                        XC integral plan (opaque handle) constructed with \c cuestXCIntPlanCreate. Must not be NULL.
 * @param[in]  approximation               Specifies the XC approximation: LDA, GGA, or meta-GGA.
 * @param[in]  parameters                  Compute parameters (\c cuestXCDerivativeComputeParameters_t). Must not be NULL
 * @param[in]  variableBufferSize          User-provided descriptor for the variable buffer size (host and device). Must not be NULL.
 *                                             2 GB is a good default value for device memory. There are diminishing returns for very
 *                                             large values of the variableBufferSize. Some static allocations are made outside of what is
 *                                             controlled by the variableBufferSize. Host memory is currently unused.
 *                                             This value MUST remain unchanged between the WorkspaceQuery call and the Compute call.
 * @param[in]  temporaryWorkspace          Preallocated temporary workspace buffer for this operation. Must not be NULL.
 * @param[in]  numOccupied                 Number of occupied orbitals in the input coefficient matrix. Must be greater than zero.
 * @param[in]  coefficientMatrix           Input orbital coefficient matrix (size: \c numOccupied × nao) on GPU. Must not be NULL.
 * @param[in]  gridXCPotential             Input grid exchange-correlation potential array (size: \c npoint × ndim) on GPU. Must not be NULL.
 * @param[out] outBasisGradient            Output buffer for basis function center gradient contributions (size: natom × 3) on GPU. Must not be NULL.
 *                                             Elements of this array are overwritten by the calculation results.
 * @param[out] outGridGradient             Output buffer for grid point gradient contributions (size: npoint × 3) on GPU. Must not be NULL.
 *                                             Elements of this array are overwritten by the calculation results.
 *
 * @return
 *   - \c CUEST_STATUS_SUCCESS on success;
 *   - \c CUEST_STATUS_INVALID_HANDLE if the cuEST handle is NULL;
 *   - \c CUEST_STATUS_NULL_POINTER if any required pointer is NULL;
 *   - \c CUEST_STATUS_INVALID_TYPE if handle types are incorrect;
 *   - \c CUEST_STATUS_INVALID_ARGUMENT if \c numOccupied is zero or approximation invalid;
 *   - \c CUEST_STATUS_EXCEPTION on device or internal error;
 *   - \c CUEST_STATUS_UNKNOWN_ERROR otherwise.
 *
 * In order to compute the derivative of the XC energy,
 * \f[ \frac{\rm d}{{\rm d}R_A} E_{xc} = \frac{\rm d}{{\rm d}R_A} \sum_{P}^{\rm npoint} w_{P} e_{xc,P} \f]
 * where \f$ A \f$ indexes atom centers and \f$ P \f$ are the grid points, there are two terms to evaluate.
 * \f[ \frac{\rm d}{{\rm d}R_A} E_{xc} = \sum_{P}^{\rm npoint} \frac{{\rm d} w_{P}}{{\rm d}R_A} e_{xc,P} + \sum_{P}^{\rm npoint} w_{P} \frac{{\rm d} e_{xc,P}}{{\rm d}R_A} \f]
 * Contributions from the second term, \f$ \sum_{P}^{\rm npoint} w_{P} \frac{{\rm d} e_{xc,P}}{{\rm d}R_A} \f$ are evaluated by this function. Specifically,
 * this function computes \c outBasisGradient computed as \f$ \sum_{P}^{\rm npoint} w_{P} \frac{\partial e_{xc,P}}{\partial R_A} \f$, where \f$ R_A \f$ are the basis
 * function centers (treated as separate from grid point centers). It also computes \c outGridGradient as \f$ \sum_{P}^{\rm npoint} w_{P} \frac{\partial e_{xc,P}}{\partial R_Q} \f$,
 * where \f$ R_Q \f$ are the grid points. The \c outBasisGradient contributed directly to the derivative of the XC energy. The \c outGridGradient array should be included
 * in a subsequent call to \c cuestXCGridDerivativeCompute to assemble additional contributions to the gradient.
 *
 */
CUEST_API
cuestStatus_t cuestXCDerivativeCompute(
    cuestHandle_t handle,
    const cuestXCIntPlan_t plan,
    cuestXCAdvancedComputeParametersApproximation_t approximation,
    const cuestXCDerivativeComputeParameters_t parameters,
    const cuestWorkspaceDescriptor_t* variableBufferSize,
    cuestWorkspace_t* temporaryWorkspace,
    uint64_t numOccupied,
    const double* coefficientMatrix,
    const double* gridXCPotential,
    double* outBasisGradient,
    double* outGridGradient);

/**
 * @brief Query the temporary workspace required (in bytes) for an XC derivative computation.
 * @ingroup ExchangeCorrelationAdvanced
 *
 * Determines the required GPU workspace size to compute exchange–correlation (XC) energy gradient 
 * contributions. This query prepares for \c cuestXCDerivativeCompute by reporting the necessary 
 * temporary memory allocation given the chosen approximation and molecular system.
 *
 * Only workspace sizes are computed; inputs/outputs may be NULL. 
 * The same \c variableBufferSize descriptor must be reused for the corresponding compute call.
 *
 * @param[in]  handle                            cuEST handle. Must not be NULL.
 * @param[in]  plan                              XC integral plan (opaque handle) constructed with \c cuestXCIntPlanCreate. Must not be NULL.
 * @param[in]  approximation                     Specifies the XC approximation: LDA, GGA, or meta-GGA.
 * @param[in]  parameters                        Compute parameters (\c cuestXCDerivativeComputeParameters_t). Must not be NULL
 * @param[in]  variableBufferSize                User-provided descriptor for the variable buffer size (host and device). Must not be NULL.
 *                                                   2 GB is a good default value for device memory. There are diminishing returns for very
 *                                                   large values of the variableBufferSize. Some static allocations are made outside of what is
 *                                                   controlled by the variableBufferSize. Host memory is currently unused.
 *                                                   This value MUST remain unchanged between the WorkspaceQuery call and the Compute call.
 * @param[out] temporaryWorkspaceDescriptor      Output descriptor with required workspace sizes (in bytes). Must not be NULL.
 * @param[in]  numOccupied                       Number of occupied orbitals. Must be greater than zero.
 * @param      coefficientMatrix                 Input coefficient matrix. May be NULL.
 * @param      gridXCPotential                   Input grid XC potential array. May be NULL.
 * @param      outBasisGradient                  Output buffer for basis function center gradient contributions. May be NULL.
 * @param      outGridGradient                   Output buffer for grid point gradient contributions. May be NULL.
 *
 * @return
 *   - \c CUEST_STATUS_SUCCESS on success;
 *   - \c CUEST_STATUS_INVALID_HANDLE if the cuEST handle is NULL;
 *   - \c CUEST_STATUS_NULL_POINTER if any required pointer is NULL;
 *   - \c CUEST_STATUS_INVALID_TYPE if handle types are incorrect;
 *   - \c CUEST_STATUS_INVALID_ARGUMENT if \c numOccupied is zero or approximation invalid;
 *   - \c CUEST_STATUS_EXCEPTION on device or internal error;
 *   - \c CUEST_STATUS_UNKNOWN_ERROR otherwise.
 */
CUEST_API
cuestStatus_t cuestXCDerivativeComputeWorkspaceQuery(
    cuestHandle_t handle,
    const cuestXCIntPlan_t plan,
    cuestXCAdvancedComputeParametersApproximation_t approximation,
    const cuestXCDerivativeComputeParameters_t parameters,
    const cuestWorkspaceDescriptor_t* variableBufferSize,
    cuestWorkspaceDescriptor_t* temporaryWorkspaceDescriptor,
    uint64_t numOccupied,
    const double* coefficientMatrix,
    const double* gridXCPotential,
    double* outBasisGradient,
    double* outGridGradient);

/**
 * @brief Compute total XC energy gradient from grid XC energy and its spatial derivatives.
 * @ingroup ExchangeCorrelationAdvanced
 *
 * This routine combines grid-resolved XC energy densities and their spatial gradients
 * to produce the total (molecular) XC gradient with respect to atomic coordinates.
 * It serves as the final step in assembling analytical derivatives after the
 * grid-level contributions have been computed.
 *
 * The operation uses the molecular grid and AO basis data embedded in the provided XC plan.
 * All required workspace should be preallocated according to the size returned by 
 * \c cuestXCGridDerivativeComputeWorkspaceQuery.
 *
 * Important: This function does apply integration weights to the user-supplied XC energy. The user must
 * supply the bare \f$ e_{xc,P} \f$ array as shown in:
 * \f[ E_{xc} = \sum_{P}^{\rm npoint} w_{P} e_{xc,P} \f] 
 *
 * @param[in]  handle             cuEST handle. Must not be NULL.
 * @param[in]  plan               XC integral plan (opaque handle) constructed with \c cuestXCIntPlanCreate. Must not be NULL.
 * @param[in]  parameters         Compute parameters (\c cuestXCGridDerivativeComputeParameters_t). Must not be NULL
 * @param[in]  temporaryWorkspace Preallocated GPU workspace buffer for temporary data. Must not be NULL.
 * @param[in]  gridXCEnergy       Input grid XC energy density values (size: npoint × 1) on GPU. Must not be NULL.
 * @param[in]  gridGradient       Input grid spatial gradient contributions (size: npoint × 3) on GPU. Must not be NULL.
 * @param[out] outGradient        Output total (atomic) gradient of XC energy (size: natom × 3) on GPU. Must not be NULL.
 *                                    Elements of this array are overwritten by the calculation results.
 *
 * @return
 *   - \c CUEST_STATUS_SUCCESS on success;
 *   - \c CUEST_STATUS_INVALID_HANDLE if the cuEST handle is NULL;
 *   - \c CUEST_STATUS_NULL_POINTER if any required pointer is NULL;
 *   - \c CUEST_STATUS_INVALID_TYPE if handle types are incorrect;
 *   - \c CUEST_STATUS_EXCEPTION on device or internal error;
 *   - \c CUEST_STATUS_UNKNOWN_ERROR otherwise.
 *
 * This function is expected to be called after \c cuestXCDerivativeCompute. The purpose of this function
 * is to evaluate contributions to the XC gradient resulting from derivatives of the integration weight
 * \f$ \sum_{P}^{\rm npoint} \frac{{\rm d} w_{P}}{{\rm d}R_A} e_{xc,P} \f$ and to incorporate contributions
 * from grid point motion: \f$ \sum_{P}^{\rm npoint} w_{P} \frac{\partial e_{xc,P}}{\partial R_Q} \frac{\partial R_Q}{\partial R_A} \f$.
 * Here \f$ R_Q \f$ are the grid points and \f$ R_A \f$ are the atomic centers defining the grid.
 *
 * The sum of \c outGradient computed by this routine and \c outBasisGradient computed by \c cuestXCDerivativeCompute (scaled appropriately)
 * is the derivative of the XC energy: \f$ \frac{\rm d}{{\rm d}R_A} E_{xc} \f$. In the case of UKS calculations, \c cuestXCDerivativeCompute
 * will need to be called twice, but \c cuestXCGridDerivativeCompute only needs to be called once.
 */
CUEST_API
cuestStatus_t cuestXCGridDerivativeCompute(
    cuestHandle_t handle,
    const cuestXCIntPlan_t plan,
    const cuestXCGridDerivativeComputeParameters_t parameters,
    cuestWorkspace_t* temporaryWorkspace,
    const double* gridXCEnergy,
    const double* gridGradient,
    double* outGradient);

/**
 * @brief Query the temporary workspace required (in bytes) for an XC grid derivative computation.
 * @ingroup ExchangeCorrelationAdvanced
 *
 * Estimates the GPU memory workspace required to compute the grid-based exchange–correlation (XC)
 * gradient using molecular grid data. This function reports the necessary device buffer size
 * for \c cuestXCGridDerivativeCompute.
 *
 * Only workspace sizes are computed; input and output buffers may be NULL.
 *
 * @param[in]  handle                       cuEST handle. Must not be NULL.
 * @param[in]  plan                         XC integral plan (opaque handle) constructed with \c cuestXCIntPlanCreate. Must not be NULL.
 * @param[in]  parameters                   Compute parameters (\c cuestXCGridDerivativeComputeParameters_t). Must not be NULL
 * @param[out] temporaryWorkspaceDescriptor Output descriptor with required temporary workspace sizes (in bytes). Must not be NULL.
 * @param      gridXCEnergy                 Input grid XC energy density. May be NULL.
 * @param      gridGradient                 Input grid gradient contributions. May be NULL.
 * @param      outGradient                  Output total (atomic) gradient array. May be NULL.
 *
 * @return
 *   - \c CUEST_STATUS_SUCCESS on success;
 *   - \c CUEST_STATUS_INVALID_HANDLE if the cuEST handle is NULL;
 *   - \c CUEST_STATUS_NULL_POINTER if any required pointer is NULL;
 *   - \c CUEST_STATUS_INVALID_TYPE if handle types are incorrect;
 *   - \c CUEST_STATUS_EXCEPTION on device or internal error;
 *   - \c CUEST_STATUS_UNKNOWN_ERROR otherwise.
 */
CUEST_API
cuestStatus_t cuestXCGridDerivativeComputeWorkspaceQuery(
    cuestHandle_t handle,
    const cuestXCIntPlan_t plan,
    const cuestXCGridDerivativeComputeParameters_t parameters,
    cuestWorkspaceDescriptor_t* temporaryWorkspaceDescriptor,
    const double* gridXCEnergy,
    const double* gridGradient,
    double* outGradient);

/**
 * @brief Compute the nonsymmetric exchange-correlation (XC) derivative contributions for analytical gradients.
 * @ingroup ExchangeCorrelationAdvanced
 *
 * This routine computes the gradient contributions of the exchange–correlation (XC) energy
 * with respect to the atomic coordinates using a nonsymmetric density. It uses the provided XC
 * potential on the molecular integration grid, a left and a right set of molecular orbital
 * coefficients, and the XC integral plan. This is the generalization of \c cuestXCDerivativeCompute,
 * which uses the same coefficients for both left and right.
 *
 * The form and dimensionality of the input \c gridXCPotential depend on the chosen
 * approximation type (LDA, GGA, or meta-GGA) — see \c cuestXCPotentialCompute.
 * All temporary workspace must be preallocated according to the size returned by
 * \c cuestXCNonsymmetricDerivativeComputeWorkspaceQuery.
 *
 * Important: This function does not apply the integration weights to the user-supplied XC potential. The user must
 * apply the total integration weights, which can be obtained by calling \c cuestXCIntegrationWeightCompute.
 *
 * @param[in]  handle                      cuEST handle. Must not be NULL.
 * @param[in]  plan                        XC integral plan (opaque handle) constructed with \c cuestXCIntPlanCreate. Must not be NULL.
 * @param[in]  approximation               Specifies the XC approximation: LDA, GGA, or meta-GGA.
 * @param[in]  parameters                  Compute parameters (\c cuestXCNonsymmetricDerivativeComputeParameters_t). Must not be NULL.
 * @param[in]  variableBufferSize          User-provided descriptor for the variable buffer size (host and device). Must not be NULL.
 *                                             2 GB is a good default value for device memory. There are diminishing returns for very
 *                                             large values of the variableBufferSize. Host memory is currently unused.
 *                                             This value MUST remain unchanged between the WorkspaceQuery call and the Compute call.
 * @param[in]  temporaryWorkspace          Preallocated temporary workspace buffer for this operation. Must not be NULL.
 * @param[in]  numOccupied                 Number of occupied orbitals in each coefficient matrix. Must be greater than zero.
 * @param[in]  leftCoefficientMatrix       Input left orbital coefficient matrix (size: \c numOccupied × nao) on GPU. Must not be NULL.
 * @param[in]  rightCoefficientMatrix      Input right orbital coefficient matrix (size: \c numOccupied × nao) on GPU. Must not be NULL.
 * @param[in]  gridXCPotential             Input grid exchange-correlation potential array (size: \c npoint × ndim) on GPU. Must not be NULL.
 * @param[out] outBasisGradient            Output buffer for basis function center gradient contributions (size: natom × 3) on GPU. Must not be NULL.
 *                                             Elements of this array are overwritten by the calculation results.
 * @param[out] outGridGradient             Output buffer for grid point gradient contributions (size: npoint × 3) on GPU. Must not be NULL.
 *                                             Elements of this array are overwritten by the calculation results.
 *
 * @return
 *   - \c CUEST_STATUS_SUCCESS on success;
 *   - \c CUEST_STATUS_INVALID_HANDLE if the cuEST handle is NULL;
 *   - \c CUEST_STATUS_NULL_POINTER if any required pointer is NULL;
 *   - \c CUEST_STATUS_INVALID_TYPE if handle types are incorrect;
 *   - \c CUEST_STATUS_INVALID_ARGUMENT if \c numOccupied is zero or approximation invalid;
 *   - \c CUEST_STATUS_EXCEPTION on device or internal error;
 *   - \c CUEST_STATUS_UNKNOWN_ERROR otherwise.
 */
CUEST_API
cuestStatus_t cuestXCNonsymmetricDerivativeCompute(
    cuestHandle_t handle,
    const cuestXCIntPlan_t plan,
    cuestXCAdvancedComputeParametersApproximation_t approximation,
    const cuestXCNonsymmetricDerivativeComputeParameters_t parameters,
    const cuestWorkspaceDescriptor_t* variableBufferSize,
    cuestWorkspace_t* temporaryWorkspace,
    uint64_t numOccupied,
    const double* leftCoefficientMatrix,
    const double* rightCoefficientMatrix,
    const double* gridXCPotential,
    double* outBasisGradient,
    double* outGridGradient);

/**
 * @brief Query the temporary workspace required (in bytes) for an XC nonsymmetric derivative computation.
 * @ingroup ExchangeCorrelationAdvanced
 *
 * Determines the required GPU workspace size to compute nonsymmetric exchange–correlation (XC) energy gradient
 * contributions. This query prepares for \c cuestXCNonsymmetricDerivativeCompute by reporting the necessary
 * temporary memory allocation given the chosen approximation and molecular system.
 *
 * Only workspace sizes are computed; inputs/outputs may be NULL.
 * The same \c variableBufferSize descriptor must be reused for the corresponding compute call.
 *
 * @param[in]  handle                            cuEST handle. Must not be NULL.
 * @param[in]  plan                              XC integral plan (opaque handle) constructed with \c cuestXCIntPlanCreate. Must not be NULL.
 * @param[in]  approximation                     Specifies the XC approximation: LDA, GGA, or meta-GGA.
 * @param[in]  parameters                        Compute parameters (\c cuestXCNonsymmetricDerivativeComputeParameters_t). Must not be NULL.
 * @param[in]  variableBufferSize                User-provided descriptor for the variable buffer size (host and device). Must not be NULL.
 *                                                   2 GB is a good default value for device memory. There are diminishing returns for very
 *                                                   large values of the variableBufferSize. Host memory is currently unused.
 *                                                   This value MUST remain unchanged between the WorkspaceQuery call and the Compute call.
 * @param[out] temporaryWorkspaceDescriptor      Output descriptor with required workspace sizes (in bytes). Must not be NULL.
 * @param[in]  numOccupied                       Number of occupied orbitals. Must be greater than zero.
 * @param      leftCoefficientMatrix             Input left coefficient matrix. May be NULL.
 * @param      rightCoefficientMatrix            Input right coefficient matrix. May be NULL.
 * @param      gridXCPotential                   Input grid XC potential array. May be NULL.
 * @param      outBasisGradient                  Output buffer for basis function center gradient contributions. May be NULL.
 * @param      outGridGradient                   Output buffer for grid point gradient contributions. May be NULL.
 *
 * @return
 *   - \c CUEST_STATUS_SUCCESS on success;
 *   - \c CUEST_STATUS_INVALID_HANDLE if the cuEST handle is NULL;
 *   - \c CUEST_STATUS_NULL_POINTER if any required pointer is NULL;
 *   - \c CUEST_STATUS_INVALID_TYPE if handle types are incorrect;
 *   - \c CUEST_STATUS_INVALID_ARGUMENT if \c numOccupied is zero or approximation invalid;
 *   - \c CUEST_STATUS_EXCEPTION on device or internal error;
 *   - \c CUEST_STATUS_UNKNOWN_ERROR otherwise.
 */
CUEST_API
cuestStatus_t cuestXCNonsymmetricDerivativeComputeWorkspaceQuery(
    cuestHandle_t handle,
    const cuestXCIntPlan_t plan,
    cuestXCAdvancedComputeParametersApproximation_t approximation,
    const cuestXCNonsymmetricDerivativeComputeParameters_t parameters,
    const cuestWorkspaceDescriptor_t* variableBufferSize,
    cuestWorkspaceDescriptor_t* temporaryWorkspaceDescriptor,
    uint64_t numOccupied,
    const double* leftCoefficientMatrix,
    const double* rightCoefficientMatrix,
    const double* gridXCPotential,
    double* outBasisGradient,
    double* outGridGradient);

#ifdef __cplusplus
}
#endif

#endif /* XC_DERIVATIVE_COMPUTE_API_H */
