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

#include <stddef.h>

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

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @brief Compute the PCM nuclear gradient.
 * @ingroup PCM
 *
 * This routine computes the derivative of the PCM energy with respect to nuclear coordinates.
 *
 * Converged surface charges are computed using a preconditioned conjugate gradient (PCG) solver.
 * Convergence behavior is controlled by the \c cuestPCMDerivativeComputeParameters_t structure that is packaged inside \c parameters.
 * Both maximum iterations and convergence threshold may be tuned based on the specific problem.
 *
 * The required temporary workspace must be allocated using the sizes returned by \c cuestPCMDerivativeComputeWorkspaceQuery.
 * The number of points, npoint, can be queried from the \c cuestPCMIntPlan_t structure using the \c CUEST_PCMINTPLAN_NUM_POINT query,
 * and is the sum of the \c numAngularPointsPerAtom array used to create the plan.
 *
 * @param[in]  handle                      cuEST handle. Must not be NULL.
 * @param[in]  plan                        PCM integral plan (opaque handle) constructed with \c cuestPCMIntPlanCreate. Must not be NULL.
 * @param[in]  parameters                  PCM derivative parameters (opaque handle) constructed with \c cuestParametersCreate. Must not be NULL.
 * @param[in]  temporaryWorkspace          Temporary workspace buffer for this operation. Must not be NULL.
 * @param[in]  densityMatrix               Total (alpha + beta) AO basis density matrix (size: nao × nao) on the GPU. Must not be NULL.
 * @param[in]  inQ                         Input guess charges (size: npoint) on the GPU; user should initialize this array to zeros if no guess is available. Must not be NULL.
 * @param[out] outQ                        Converged charges (size: npoint) on the GPU. Must not be NULL.
 *                                             Elements of this array are overwritten by the calculation results.
 * @param[out] outPCMResults               PCM results (opaque handle) constructed with \c cuestPCMResultsCreate.
 *                                             Elements contained in this handle are overwritten by the calculation results.
 * @param[out] outPCMGradient              Output PCM derivative (size: natoms × 3) on the GPU. Must not be NULL.
 *                                             Elements of this array are overwritten by the calculation results.
 *
 * It is important to note that the return status is \c CUEST_STATUS_SUCCESS even if the PCM charges did not converge within the maximum number of iterations provided by \c parameters.
 * The caller should check the \c converged member of the \c outPCMResults handle to determine whether the PCM charges returned by \c outQ are converged.
 *
 * In the case where \c maxIterations==0 , no PCG updates of the charges are performed.
 * The values provided in \c inQ are used to evaluate the PCM gradient, and are copied to \c outQ on return.
 * In this mode, a residual is still evaluated and reported through \c outPCMResults, but the charges themselves are not modified.
 *
 * Similarly, if the PCG procedure reaches the maximum number of iterations without satisfying the requested
 * convergence threshold, the gradient is still computed using the resulting (partially converged) charges.
 * It is the caller’s responsibility to inspect the convergence information in \c outPCMResults and decide whether the result is acceptable.
 *
 * @return
 *   - \c CUEST_STATUS_SUCCESS on success, including the case where the PCM charges did not converge within the maximum number of iterations provided by the \c parameters;
 *   - \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; including \c parameters;
 *   - \c CUEST_STATUS_INVALID_ARGUMENT if the \c parameters are configured to have convergence threshold less than or equal to zero;
 *   - \c CUEST_STATUS_EXCEPTION or \c CUEST_STATUS_UNKNOWN_ERROR otherwise.
 */
CUEST_API
cuestStatus_t cuestPCMDerivativeCompute(
    cuestHandle_t handle,
    const cuestPCMIntPlan_t plan,
    const cuestPCMDerivativeComputeParameters_t parameters,
    cuestWorkspace_t* temporaryWorkspace,
    const double *densityMatrix,
    const double *inQ,
    double *outQ,
    cuestPCMResults_t outPCMResults,
    double *outPCMGradient);

/**
 * @brief Query the temporary workspace required for a PCM gradient computation.
 * @ingroup PCM
 *
 * Calculate the memory required for a PCM gradient computation, including the PCG solve for charges,
 * returning host/device workspace buffer sizes in the output descriptor. The user arrays \c densityMatrix, \c inQ,
 * \c outQ, \c outPCMResults, and \c outPCMGradient may be NULL. All parameters and object handles must be valid.
 *
 * @param[in]  handle                        cuEST handle. Must not be NULL.
 * @param[in]  plan                          PCM integral plan constructed with \c cuestPCMIntPlanCreate. Must not be NULL.
 * @param[in]  parameters                    PCM derivative parameters constructed with \c cuestParametersCreate. Must not be NULL.
 * @param[out] temporaryWorkspaceDescriptor  Output descriptor for temporary workspace sizes. Must not be NULL.
 * @param[in]  densityMatrix                 Density matrix. May be NULL.
 * @param[in]  inQ                           Input Q vector. May be NULL.
 * @param[in]  outQ                          Output Q vector. May be NULL.
 * @param[in]  outPCMResults                 PCM results constructed with \c cuestPCMResultsCreate. May be NULL.
 * @param[in]  outPCMGradient                Output PCM nuclear 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; including \c parameters;
 *   - \c CUEST_STATUS_INVALID_ARGUMENT if the \c parameters are configured to have convergence threshold less than or equal to zero;
 *   - \c CUEST_STATUS_EXCEPTION or \c CUEST_STATUS_UNKNOWN_ERROR otherwise.
 */
CUEST_API
cuestStatus_t cuestPCMDerivativeComputeWorkspaceQuery(
    cuestHandle_t handle,
    const cuestPCMIntPlan_t plan,
    const cuestPCMDerivativeComputeParameters_t parameters,
    cuestWorkspaceDescriptor_t* temporaryWorkspaceDescriptor,
    const double *densityMatrix,
    const double *inQ,
    double *outQ,
    cuestPCMResults_t outPCMResults,
    double *outPCMGradient);

#ifdef __cplusplus
}
#endif

#endif /* PCM_DERIVATIVE_COMPUTE_API_H */
