/*
 * 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 DENSITY_FITTED_DERIVATIVE_COMPUTE_API_H
#define DENSITY_FITTED_DERIVATIVE_COMPUTE_API_H

#include <stddef.h>
#include <stdint.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 nuclear gradient of the symmetric DF J/K matrices contracted
 *        with a density matrix and multiple coefficient matrices.
 * @ingroup JKGrad
 *
 * This routine evaluates the nuclear derivatives (gradients) of the Coulomb (J) and
 * exchange (K) matrices in density fitting approximation, where the J matrix is
 * contracted with a single density matrix and the K matrices are contracted with
 * multiple occupied orbital coefficient matrices. The result overwrites the
 * output gradient buffer (size: natom × 3).
 *
 * All required temporary workspace must be sized using the corresponding workspace
 * query function. A \c variableBufferSize descriptor must also be provided to
 * constrain the memory usage.
 *
 * \b Kernel and precision selection. This routine can use JIT-compiled kernels and/or reduced-precision
 * "ffloat" compute, selected through the compute parameters:
 *   - \c CUEST_DFSYMMETRICDERIVATIVECOMPUTE_PARAMETERS_JIT_USAGE_MODE (\c cuestJITUsageMode_t): \c CUEST_JIT_USAGE_MODE_ON
 *     uses JIT-compiled kernels, \c CUEST_JIT_USAGE_MODE_OFF uses AOT-compiled kernels. JIT-compiled kernels
 *     are only available in the cuEST CUDA 13 package; the default is \c CUEST_JIT_USAGE_MODE_ON in the
 *     cuEST CUDA 13 package and \c CUEST_JIT_USAGE_MODE_OFF in the cuEST CUDA 12 package. Requesting
 *     \c CUEST_JIT_USAGE_MODE_ON with the cuEST CUDA 12 package returns \c CUEST_STATUS_INVALID_ARGUMENT.
 *   - \c CUEST_DFSYMMETRICDERIVATIVECOMPUTE_PARAMETERS_FFLOAT_USAGE_MODE (\c cuestFfloatUsageMode_t) selects the compute precision:
 *     \c CUEST_FFLOAT_USAGE_MODE_ON requests ffloat compute, \c CUEST_FFLOAT_USAGE_MODE_OFF requests fp64
 *     compute, and \c CUEST_FFLOAT_USAGE_MODE_DEFAULT requests ffloat compute when it is expected to provide
 *     a performance advantage on the present GPU architecture.
 *   - ffloat compute is only compatible with JIT-compiled kernels. Requesting ffloat compute while JIT is
 *     disabled (\c CUEST_FFLOAT_USAGE_MODE_ON together with \c CUEST_JIT_USAGE_MODE_OFF) is not supported and
 *     returns \c CUEST_STATUS_INVALID_ARGUMENT.
 *
 * @param[in]  handle                       cuEST handle. Must not be NULL.
 * @param[in]  plan                         DF integral computation plan (opaque handle). Must not be NULL.
 * @param[in]  parameters                   Compute parameters (\c cuestDFSymmetricDerivativeComputeParameters_t). Must not be NULL
 * @param[in]  variableBufferSize           The variableBufferSize determines the size of an internal scratch buffer
 *                                              used for certain transformations. A buffer of 2GB is a reasonable default value.
 *                                              Host memory is currently unused. Note that the variableBufferSize does not limit total 
 *                                              memory usage. The value of the variableBufferSize must not change between WorkspaceQuery
 *                                              and Compute calls.
 * @param[in]  temporaryWorkspace           Temporary workspace buffers (preallocated for
 *                                              this operation using the query function).
 *                                              Must not be NULL.
 * @param[in]  densityScale                 Scaling factor for the J (Coulomb) contribution.
 * @param[in]  densityMatrix                Input density matrix (size: nao × nao) on GPU.
 *                                              Must not be NULL.
 * @param[in]  coefficientScale             Scaling factor for each K (exchange) contribution.
 * @param[in]  numCoefficientMatrices       Number of coefficient matrices. Must be > 0 when exchange is active; may be 0 for pure functionals.
 * @param[in]  numOccupied                  Array of occupied orbital counts for each
 *                                              coefficient matrix (size: \c numCoefficientMatrices) on CPU.
 *                                              Each entry must be > 0 when exchange is active; for pure functionals the array may be NULL or contain zeros.
 * @param[in]  coefficientMatrices          Concatenated coefficient matrices. Each matrix
 *                                              has shape [\c numOccupied[i], nao] on GPU. Total size:
 *                                              sum(\c numOccupied[i]) × nao. Must not be NULL when exchange
 *                                              is active; may be NULL for pure functionals (if provided, it is ignored).
 * @param[out] outGradient                  Output nuclear gradient (size: natom × 3) on GPU.
 *                                              Gradient results overwrite this buffer.
 *                                              Must not 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_PLAN if the \c cuestDFIntPlan_t is not correctly configured or in a dirty state;
 *   - \c CUEST_STATUS_INVALID_ARGUMENT if \c coefficientScale != 0.0 and 
 *             if \c numCoefficientMatrices == 0 or any \c numOccupied[i] == 0;
 *             or if \c CUEST_DFINTPLAN_PARAMETERS_EXCHANGE_FRACTION or \c CUEST_DFINTPLAN_PARAMETERS_LRC_EXCHANGE_FRACTION
 *             != 0.0 and 
 *             if \c numCoefficientMatrices == 0 or any \c numOccupied[i] == 0;
 *   - \c CUEST_STATUS_INVALID_ARGUMENT if a parameter value is invalid, if JIT-compiled kernels are requested
 *     with the cuEST CUDA 12 package, or if ffloat compute is requested while JIT is disabled (incompatible
 *     JIT/ffloat combination);
 *   - \c CUEST_STATUS_EXCEPTION or \c CUEST_STATUS_UNKNOWN_ERROR otherwise.
 *
 * The bare Coulomb and exchange energies are given as:
 *
 * \f[ E_{J}     = \sum_{\mu\nu\lambda\sigma} D_{\mu\nu} (\mu\nu|\lambda\sigma) D_{\lambda\sigma} \f]
 * \f[ E_{K}^{N} = \sum_{\mu\nu\lambda\sigma} \sum_{ij} 
 *                 \left[ f_{\rm HF} (\mu\lambda|\frac{1}{r}|\nu\sigma) + f_{\rm LRC} (\mu\lambda|\frac{{\rm erf}(\omega r)}{r}|\nu\sigma) \right]
 *                 C_{i\mu}^{N} C_{i\nu}^{N} C_{j\lambda}^{N} C_{j\sigma}^{N} \f]
 *
 * An effective J/K energy can be written as:
 *
 * \f[ E_{JK} = s_D * E_{J} + \sum_{N} s_C * E_{K}^{N} \f]
 *
 * where
 *   - \f$ s_D \f$ is a density scaling factor \c densityScale,
 *   - \f$ s_C \f$ is a coefficient scaling factor \c coefficientScale,
 *   - \f$ f_{\rm HF} \f$ is the fraction of Hartree-Fock exchange to add, \c CUEST_DFINTPLAN_PARAMETERS_EXCHANGE_FRACTION
 *   - \f$ f_{\rm LRC} \f$ is the fraction of long-range range-separated exchange to add, \c CUEST_DFINTPLAN_PARAMETERS_LRC_EXCHANGE_FRACTION
 *   - \f$ \omega \f$ is the range-separation parameter to use, \c CUEST_DFINTPLAN_PARAMETERS_LRC_EXCHANGE_OMEGA
 *
 * This function computes: \f$dE_{JK}/dR\f$, where R represents the basis function centers of the electron
 * repulsion integrals. 
 *
 * \c CUEST_DFINTPLAN_PARAMETERS_EXCHANGE_FRACTION, \c CUEST_DFINTPLAN_PARAMETERS_LRC_EXCHANGE_FRACTION, and \c CUEST_DFINTPLAN_PARAMETERS_LRC_EXCHANGE_OMEGA
 * are set when the \c cuestDFIntPlan_t is constructed and is intended to
 * describe the exchange parameterization in hybrid and range-separated hybrid functionals.
 *
 * The \c densityScale and \c coefficientScale parameters are intended to account for the spin summations needed to obtain
 * the correct two-electron energy.
 *
 * For example, in a B3LYP RKS computation the intended usage would be:
 *   - \c CUEST_DFINTPLAN_PARAMETERS_EXCHANGE_FRACTION = 0.2
 *   - \c CUEST_DFINTPLAN_PARAMETERS_LRC_EXCHANGE_FRACTION = 0.0
 *   - \c CUEST_DFINTPLAN_PARAMETERS_LRC_EXCHANGE_OMEGA unused
 *   - \c densityScale = 2.0
 *   - \c coefficientScale = -1.0
 *   - \c numCoefficientMatrices = 1
 *   - \f$ D_{mn} = \sum_{i} C_{im} C_{in} \f$
 *   - \f$ I_{ij} = \sum_{mn} C_{im} S_{mn} C_{jn} \f$
 *
 * For a PBE0 UKS computation the intended usage would be:
 *   - \c CUEST_DFINTPLAN_PARAMETERS_EXCHANGE_FRACTION = 0.25
 *   - \c CUEST_DFINTPLAN_PARAMETERS_LRC_EXCHANGE_FRACTION = 0.0
 *   - \c CUEST_DFINTPLAN_PARAMETERS_LRC_EXCHANGE_OMEGA unused
 *   - \c densityScale = 0.5
 *   - \c coefficientScale = -0.5
 *   - \c numCoefficientMatrices = 2
 *   -  \f$D_{mn} = \sum_{i} C_{im}^{\alpha} C_{in}^{\alpha} + \sum_{i} C_{im}^{\beta} C_{in}^{\beta} \f$
 *   -  \f$I_{ij} = \sum_{mn} C_{im}^{\alpha} S_{mn} C_{jn}^{\alpha} \f$
 *   -  \f$I_{ij} = \sum_{mn} C_{im}^{\beta} S_{mn} C_{jn}^{\beta} \f$
 *
 * For pure functionals, where \c coefficientScale = 0.0 (\c CUEST_DFINTPLAN_PARAMETERS_EXCHANGE_FRACTION 
 * and \c CUEST_DFINTPLAN_PARAMETERS_LRC_EXCHANGE_FRACTION are zero),
 * the coefficient matrices do not need to be provided (if they are, they will not be used). For the pure 
 * functional case, the \c numCoefficientMatrices can be 0. The \c numOccupied array can be NULL (or contain zeros).
 * The \c coefficientMatrices array can be NULL.
 *
 * The following memory usage considerations apply only to cases where the fraction of Hartree-Fock exchange is non-zero.
 *
 * The memory usage during the gradient evaluation can be changed at a high level by CUEST_DFSYMMETRICDERIVATIVECOMPUTE_PARAMETERS_MEMORY_POLICY. 
 * - \c CUEST_DFSYMMETRICDERIVATIVECOMPUTE_MEMORY_POLICY_DEVICECACHE: Default. This will provide good performance, but may try to allocate a large
 *     amount of GPU memory.
 * - \c CUEST_DFSYMMETRICDERIVATIVECOMPUTE_MEMORY_POLICY_HOSTCACHE: Provides similar performance, but will allocate that memory on the CPU,
 *     incurring a bit of overhead transferring memory to/from the CPU.
 * - \c CUEST_DFSYMMETRICDERIVATIVECOMPUTE_MEMORY_POLICY_OVERWRITE: Preferred, where possible.
 *     This memory policy avoids any additional large allocations and/or host/device memory transfers by overwriting some of the temporary data in
 *     the \c cuestDFIntPlan_t. This corrupts the \c cuestDFIntPlan_t and should be destroyed following this call.
 *     If the gradient evaluation is the final function call
 *     using the \c cuestDFIntPlan_t, then this is optimal (this is often the case in usual HF/DFT gradient calculations).
 *     If the \c cuestDFIntPlan_t will be needed again, then this option is not suitable.
 * - \c CUEST_DFSYMMETRICDERIVATIVECOMPUTE_MEMORY_POLICY_RECOMPUTE: This memory policy does not require any additional allocations or memory transfers.
 *     It corrupts the data in the \c cuestDFIntPlan_t during the gradient calculation. However, following the gradient call, it returns the 
 *     \c cuestDFIntPlan_t to a usable state by recomputing (and replacing) any corrupted data. This may add significantly to the cost of the 
 *     gradient evaluation. 
 *
 * Note that variableBufferSize only applies to the formation of certain intermediates during the cuestDFSymmetricDerivativeCompute and will not
 * limit overall memory usage. We recommend a buffer size of at least 2 GB with modest performance improvements possible if larger buffers can be provided.
 *
 */
CUEST_API
cuestStatus_t cuestDFSymmetricDerivativeCompute(
    cuestHandle_t handle,
    cuestDFIntPlan_t plan,
    const cuestDFSymmetricDerivativeComputeParameters_t parameters,
    const cuestWorkspaceDescriptor_t* variableBufferSize,
    cuestWorkspace_t* temporaryWorkspace,
    double densityScale,
    const double* densityMatrix,
    double coefficientScale,
    uint64_t numCoefficientMatrices,
    const uint64_t* numOccupied,
    const double* coefficientMatrices,
    double* outGradient);

/**
 * @brief Query the temporary workspace required for a DF J/K nuclear gradient computation.
 * @ingroup JKGrad
 *
 * This function determines the workspace required for a symmetric DF J/K gradient
 * evaluation with the given plan, density matrix, coefficient matrices, and maximum
 * workspace constraint. The output descriptor is filled on success and can be used
 * to allocate host and device workspace buffers prior to calling
 * \c cuestDFSymmetricDerivativeCompute.
 *
 * Some input pointers (\c densityMatrix, \c coefficientMatrices, \c outGradient) are optional
 * and may be NULL.
 *
 * \b Kernel and precision selection. This routine can use JIT-compiled kernels and/or reduced-precision
 * "ffloat" compute, selected through the compute parameters:
 *   - \c CUEST_DFSYMMETRICDERIVATIVECOMPUTE_PARAMETERS_JIT_USAGE_MODE (\c cuestJITUsageMode_t): \c CUEST_JIT_USAGE_MODE_ON
 *     uses JIT-compiled kernels, \c CUEST_JIT_USAGE_MODE_OFF uses AOT-compiled kernels. JIT-compiled kernels
 *     are only available in the cuEST CUDA 13 package; the default is \c CUEST_JIT_USAGE_MODE_ON in the
 *     cuEST CUDA 13 package and \c CUEST_JIT_USAGE_MODE_OFF in the cuEST CUDA 12 package. Requesting
 *     \c CUEST_JIT_USAGE_MODE_ON with the cuEST CUDA 12 package returns \c CUEST_STATUS_INVALID_ARGUMENT.
 *   - \c CUEST_DFSYMMETRICDERIVATIVECOMPUTE_PARAMETERS_FFLOAT_USAGE_MODE (\c cuestFfloatUsageMode_t) selects the compute precision:
 *     \c CUEST_FFLOAT_USAGE_MODE_ON requests ffloat compute, \c CUEST_FFLOAT_USAGE_MODE_OFF requests fp64
 *     compute, and \c CUEST_FFLOAT_USAGE_MODE_DEFAULT requests ffloat compute when it is expected to provide
 *     a performance advantage on the present GPU architecture.
 *   - ffloat compute is only compatible with JIT-compiled kernels. Requesting ffloat compute while JIT is
 *     disabled (\c CUEST_FFLOAT_USAGE_MODE_ON together with \c CUEST_JIT_USAGE_MODE_OFF) is not supported and
 *     returns \c CUEST_STATUS_INVALID_ARGUMENT.
 *
 * @param[in]  handle                       cuEST handle. Must not be NULL.
 * @param[in]  plan                         DF integral computation plan (opaque handle). Must not be NULL.
 * @param[in]  parameters                   Compute parameters (\c cuestDFSymmetricDerivativeComputeParameters_t). Must not be NULL
 * @param[in]  variableBufferSize           The variableBufferSize determines the size of an internal scratch buffer
 *                                              used for certain transformations. A buffer of 2GB is a reasonable default value.
 *                                              Host memory is currently unused. Note that the variableBufferSize does not limit total 
 *                                              memory usage. The value of the variableBufferSize must not change between WorkspaceQuery
 *                                              and Compute calls.
 * @param[out] temporaryWorkspaceDescriptor Output descriptor for required temporary workspace
 *                                              sizes (host and device). Must not be NULL.
 * @param[in]  densityScale                 Scaling factor for the J (Coulomb) contribution.
 * @param      densityMatrix                Optional density matrix. May be NULL.
 * @param[in]  coefficientScale             Scaling factor for each K (exchange) contribution.
 * @param[in]  numCoefficientMatrices       Number of coefficient matrices. Must be > 0 when exchange is active; may be 0 for pure functionals.
 * @param[in]  numOccupied                  Array of occupied orbital counts for each
 *                                              coefficient matrix (size: \c numCoefficientMatrices) on CPU.
 *                                              Each entry must be > 0 when exchange is active; for pure functionals the array may be NULL or contain zeros.
 * @param      coefficientMatrices          Optional concatenated coefficient matrices. May be NULL.
 * @param      outGradient                  Optional output gradient buffer. 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_PLAN if the \c cuestDFIntPlan_t is not correctly configured or in a dirty state;
 *   - \c CUEST_STATUS_INVALID_ARGUMENT if \c coefficientScale != 0.0 and 
 *             if \c numCoefficientMatrices == 0 or any \c numOccupied[i] == 0;
 *             or if \c CUEST_DFINTPLAN_PARAMETERS_EXCHANGE_FRACTION or \c CUEST_DFINTPLAN_PARAMETERS_LRC_EXCHANGE_FRACTION
 *             != 0.0 and 
 *             if \c numCoefficientMatrices == 0 or any \c numOccupied[i] == 0;
 *   - \c CUEST_STATUS_INVALID_ARGUMENT if a parameter value is invalid, if JIT-compiled kernels are requested
 *     with the cuEST CUDA 12 package, or if ffloat compute is requested while JIT is disabled (incompatible
 *     JIT/ffloat combination);
 *   - \c CUEST_STATUS_EXCEPTION or \c CUEST_STATUS_UNKNOWN_ERROR otherwise.
 */
CUEST_API
cuestStatus_t cuestDFSymmetricDerivativeComputeWorkspaceQuery(
    cuestHandle_t handle,
    cuestDFIntPlan_t plan,
    const cuestDFSymmetricDerivativeComputeParameters_t parameters,
    const cuestWorkspaceDescriptor_t* variableBufferSize,
    cuestWorkspaceDescriptor_t* temporaryWorkspaceDescriptor,
    double densityScale,
    const double* densityMatrix,
    double coefficientScale,
    uint64_t numCoefficientMatrices,
    const uint64_t* numOccupied,
    const double* coefficientMatrices,
    double* outGradient);


#ifdef __cplusplus
}
#endif

#endif /* DENSITY_FITTED_DERIVATIVE_COMPUTE_API_H */
