# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393

#' Create a FeaturedSpace object
#'
#' Constructs a MaxEnt FeaturedSpace from background point count,
#' occurrence sample indices, and a list of Feature objects.
#'
#' @param num_points     Integer: number of background points.
#' @param sample_indices Integer vector: 0-based indices of occurrence samples
#'   in the background array.
#' @param feature_ptrs   List of external pointers to Feature objects
#'   (from \code{create_linear_feature()} etc.).
#' @param bias_weights   Optional numeric vector of per-point bias weights
#'   (length \code{num_points}).  When supplied, background density is
#'   computed as \code{bias[i] * exp(lp[i] - lpn)} instead of the standard
#'   \code{exp(lp[i] - lpn)}.  Pass an empty vector (default) for uniform
#'   (unbiased) background.
#' @return External pointer to a FeaturedSpace object.
#' @export
maxent_featured_space_create <- function(num_points, sample_indices, feature_ptrs, bias_weights = numeric(0)) {
    .Call(`_maxentcpp_maxent_featured_space_create`, num_points, sample_indices, feature_ptrs, bias_weights)
}

#' Train a FeaturedSpace model
#'
#' Runs the sequential coordinate-ascent MaxEnt optimization.
#'
#' @param fs_ptr            External pointer to a FeaturedSpace object.
#' @param max_iter          Maximum number of training iterations (default 500).
#' @param convergence       Convergence threshold (default 1e-5).
#' @param beta_multiplier   Regularization multiplier (default 1.0).
#' @param min_deviation     Minimum sample deviation floor (default 0.001).
#' @return Named list with elements: \code{loss}, \code{entropy},
#'   \code{iterations}, \code{converged}, \code{lambdas}.
#' @export
maxent_train <- function(fs_ptr, max_iter = 500L, convergence = 1e-5, beta_multiplier = 1.0, min_deviation = 0.001) {
    .Call(`_maxentcpp_maxent_train`, fs_ptr, max_iter, convergence, beta_multiplier, min_deviation)
}

#' Predict with a trained FeaturedSpace model
#'
#' Computes raw Gibbs distribution scores for new environmental data.
#'
#' @param fs_ptr    External pointer to a trained FeaturedSpace object.
#' @param new_data  Numeric matrix with one row per new point and one column
#'   per feature (values must be pre-evaluated, i.e., the feature
#'   transformation already applied).
#' @return Numeric vector of raw scores (unnormalized).
#' @export
maxent_predict <- function(fs_ptr, new_data) {
    .Call(`_maxentcpp_maxent_predict`, fs_ptr, new_data)
}

#' Get current distribution weights from a FeaturedSpace
#'
#' @param fs_ptr External pointer to a FeaturedSpace object.
#' @return Numeric vector of normalized weights (sums to 1).
#' @export
maxent_get_weights <- function(fs_ptr) {
    .Call(`_maxentcpp_maxent_get_weights`, fs_ptr)
}

#' Get entropy of a FeaturedSpace distribution
#'
#' @param fs_ptr External pointer to a FeaturedSpace object.
#' @return Shannon entropy (non-negative scalar).
#' @export
maxent_get_entropy <- function(fs_ptr) {
    .Call(`_maxentcpp_maxent_get_entropy`, fs_ptr)
}

#' Get current loss of a FeaturedSpace
#'
#' @param fs_ptr External pointer to a FeaturedSpace object.
#' @return Scalar loss value (negative log-likelihood).
#' @export
maxent_get_loss <- function(fs_ptr) {
    .Call(`_maxentcpp_maxent_get_loss`, fs_ptr)
}

#' Write feature lambdas to a file
#'
#' Saves the trained model coefficients in CSV format compatible with
#' the original Java Maxent .lambdas file format.
#'
#' @param fs_ptr   External pointer to a trained FeaturedSpace object.
#' @param filename Character: path to the output file.
#' @return Called for side effects; returns invisibly.
#' @export
maxent_write_lambdas <- function(fs_ptr, filename) {
    invisible(.Call(`_maxentcpp_maxent_write_lambdas`, fs_ptr, filename))
}

#' Read feature lambdas from a file
#'
#' Restores model coefficients from a .lambdas file.  The FeaturedSpace
#' must have been created with the same features (same names and order).
#'
#' @param fs_ptr   External pointer to a FeaturedSpace object.
#' @param filename Character: path to the lambdas file.
#' @return Called for side effects; returns invisibly.
#' @export
maxent_read_lambdas <- function(fs_ptr, filename) {
    invisible(.Call(`_maxentcpp_maxent_read_lambdas`, fs_ptr, filename))
}

#' Set sample expectations for a FeaturedSpace
#'
#' Computes sample expectations and regularization deviations for each feature.
#' Called automatically by \code{maxent_train()}, but exposed for advanced use.
#'
#' @param fs_ptr          External pointer to a FeaturedSpace object.
#' @param beta_multiplier Regularization multiplier (default 1.0).
#' @param min_deviation   Minimum sample deviation (default 0.001).
#' @return Called for side effects; returns invisibly.
#' @export
maxent_set_sample_expectations <- function(fs_ptr, beta_multiplier = 1.0, min_deviation = 0.001) {
    invisible(.Call(`_maxentcpp_maxent_set_sample_expectations`, fs_ptr, beta_multiplier, min_deviation))
}

#' Train a FeaturedSpace with the Sequential optimizer (trajectory-capable)
#'
#' Runs the full \code{density.Sequential} optimizer ported from the original
#' Java Maxent, with optional per-iteration trajectory snapshots.  Unlike
#' \code{maxent_train()} which uses a \code{goodAlpha}-only loop, this trainer
#' reproduces the real Java optimizer's feature-selection (\code{deltaLossBound}),
#' Newton step, 1-D line search, and every-10-iter \code{doParallelUpdate}
#' with undo on loss-violating batch steps.
#'
#' @param fs_ptr                   External pointer to a FeaturedSpace object.
#' @param max_iter                 Maximum number of iterations (default 500).
#' @param convergence              Convergence threshold on \code{newLoss - oldLoss}
#'   (default \code{1e-5}).  Ignored when \code{disable_convergence_test=TRUE}.
#' @param beta_multiplier          Regularization multiplier (default 1.0).
#' @param min_deviation            Minimum sample deviation floor (default 0.001).
#' @param parallel_update_frequency Iteration frequency at which
#'   \code{doParallelUpdate} runs (default 10, matching Java).
#' @param disable_convergence_test When \code{TRUE}, the loop runs a fixed
#'   \code{max_iter} iterations with no early stop.  Needed for deterministic
#'   per-iteration trajectory comparisons against the Java oracle.
#' @param trajectory_iterations    Integer vector of 1-based iteration indices
#'   at which to capture \code{(loss, entropy, lambdas)} snapshots.  May be
#'   empty.  Snapshots outside \code{[1, max_iter]} are silently dropped.
#' @return Named list with elements:
#'   \code{loss}, \code{entropy}, \code{iterations}, \code{converged},
#'   \code{lambdas}, and \code{trajectory} — a data.frame with columns
#'   \code{iteration, loss, entropy, lambda_0, ..., lambda_{J-1}} holding
#'   one row per requested checkpoint that was actually reached.
#' @keywords internal
maxent_sequential_train <- function(fs_ptr, max_iter = 500L, convergence = 1e-5, beta_multiplier = 1.0, min_deviation = 0.001, parallel_update_frequency = 10L, disable_convergence_test = FALSE, trajectory_iterations = as.integer( c())) {
    .Call(`_maxentcpp_maxent_sequential_train`, fs_ptr, max_iter, convergence, beta_multiplier, min_deviation, parallel_update_frequency, disable_convergence_test, trajectory_iterations)
}

#' Get FeaturedSpace metadata
#'
#' @param fs_ptr External pointer to a FeaturedSpace object.
#' @return Named list with num_points, num_samples, num_features,
#'   density_normalizer, linear_predictor_normalizer, has_bias.
#' @export
maxent_featured_space_info <- function(fs_ptr) {
    .Call(`_maxentcpp_maxent_featured_space_info`, fs_ptr)
}

#' Enable or disable streaming-eval mode on a FeaturedSpace
#'
#' @param fs_ptr External pointer to a FeaturedSpace object.
#' @param enabled Logical flag.
#' @return Called for side effects; returns invisibly.
#' @keywords internal
maxent_set_streaming_eval <- function(fs_ptr, enabled = TRUE) {
    invisible(.Call(`_maxentcpp_maxent_set_streaming_eval`, fs_ptr, enabled))
}

#' Create a FeaturedSpace from a streaming background provider
#'
#' Builds a \code{FeaturedSpace} by draining a callback-style background
#' provider (typically backed by a \code{terra::SpatRaster} block loop)
#' one tile at a time, then constructing features from the concatenated
#' \code{(num_points x num_layers)} matrix via \code{\link{generate_features}}.
#'
#' This is the C++ entry point used by
#' \code{\link{maxent_featured_space_from_rast}}; end users should prefer
#' that R-level wrapper.
#'
#' @param num_points      Integer: total number of finite background points
#'   the provider will emit (sum of \code{nrow()} across tiles).
#' @param num_layers      Integer: number of environmental variables / raster
#'   layers per tile row.
#' @param layer_names     Character vector of length \code{num_layers}
#'   giving the name for each layer / column (used when generating feature
#'   names such as \code{bio1^2}, \code{bio1*bio2}).
#' @param sample_indices  Integer vector: 0-based indices of occurrence
#'   samples in the concatenated background stream.
#' @param feature_types   Character vector of feature types to generate.
#'   See \code{\link{maxent_generate_features}}.
#' @param n_thresholds    Number of threshold knots per variable.
#' @param n_hinges        Number of hinge knots per variable.
#' @param next_tile_fn    R function returning the next tile as a numeric
#'   matrix (nrow x num_layers), or a 0-row matrix / \code{NULL} when the
#'   stream is exhausted. The function is responsible for filtering out
#'   rows containing NAs.
#' @param reset_fn        R function (no arguments) that rewinds the
#'   underlying stream to the beginning.
#' @param use_cache Logical; wrap the callback stream in
#'   \code{CachingBackgroundProvider}.
#' @return External pointer to a \code{FeaturedSpace} object.
#' @export
maxent_featured_space_from_callback <- function(num_points, num_layers, layer_names, sample_indices, feature_types, n_thresholds, n_hinges, next_tile_fn, reset_fn, use_cache = TRUE) {
    .Call(`_maxentcpp_maxent_featured_space_from_callback`, num_points, num_layers, layer_names, sample_indices, feature_types, n_thresholds, n_hinges, next_tile_fn, reset_fn, use_cache)
}

#' Create a FeaturedSpace from a terra SpatRaster callback stream
#'
#' Same as \code{maxent_featured_space_from_callback()}, but also preserves
#' the source \code{SpatRaster} S4 object for provider lifetime safety and
#' can enable streaming-eval mode immediately.
#'
#' @param preserved_rast A terra \code{SpatRaster} S4 object to preserve.
#' @param rast_xptr External pointer extracted from the raster object
#'   (used for contract validation).
#' @param num_points Integer; total number of finite background points.
#' @param num_layers Integer; number of environmental variables per row.
#' @param layer_names Character vector of layer names (length num_layers).
#' @param sample_indices Integer vector; 0-based indices of presence samples.
#' @param feature_types Character vector of feature types to generate.
#' @param n_thresholds Integer; number of threshold knots per variable.
#' @param n_hinges Integer; number of hinge knots per variable.
#' @param next_tile_fn R function returning the next tile or NULL/0-row matrix.
#' @param reset_fn R function (no args) that rewinds the underlying stream.
#' @param enable_streaming_eval Logical; whether to enable streaming eval mode.
#' @param use_cache Logical; wrap the stream in \code{CachingBackgroundProvider}.
#' @return External pointer to a FeaturedSpace object.
#' @keywords internal
maxent_featured_space_from_spatraster_callback <- function(preserved_rast, rast_xptr, num_points, num_layers, layer_names, sample_indices, feature_types, n_thresholds, n_hinges, next_tile_fn, reset_fn, enable_streaming_eval = TRUE, use_cache = TRUE) {
    .Call(`_maxentcpp_maxent_featured_space_from_spatraster_callback`, preserved_rast, rast_xptr, num_points, num_layers, layer_names, sample_indices, feature_types, n_thresholds, n_hinges, next_tile_fn, reset_fn, enable_streaming_eval, use_cache)
}

#' Extract occurrence environmental values from a callback stream
#'
#' Drains a callback background stream once and returns the rows at the
#' requested 0-based finite-stream indices.
#'
#' @param num_points Integer; total finite background rows in stream.
#' @param num_layers Integer; number of environmental variables per row.
#' @param occurrence_indices Integer vector of 0-based finite-stream indices.
#' @param next_tile_fn R function returning the next tile or NULL/0-row matrix.
#' @param reset_fn R function (no args) that rewinds the underlying stream.
#' @param preserved_rast Optional SpatRaster object to preserve during read.
#' @return Numeric matrix with one row per requested occurrence index.
#' @keywords internal
maxent_extract_occurrence_from_callback <- function(num_points, num_layers, occurrence_indices, next_tile_fn, reset_fn, preserved_rast = NULL) {
    .Call(`_maxentcpp_maxent_extract_occurrence_from_callback`, num_points, num_layers, occurrence_indices, next_tile_fn, reset_fn, preserved_rast)
}

#' Create a LinearFeature object
#'
#' Creates a linear (normalized) feature: eval(i) = (values[i] - min) / (max - min).
#' Returns 0 when min == max.
#'
#' @param values Numeric vector of environmental variable values
#' @param name Feature name/identifier
#' @param min_val Minimum value for normalization
#' @param max_val Maximum value for normalization
#' @return External pointer to LinearFeature object
#' @export
create_linear_feature <- function(values, name, min_val, max_val) {
    .Call(`_maxentcpp_create_linear_feature`, values, name, min_val, max_val)
}

#' Create a QuadraticFeature object
#'
#' Creates a quadratic feature: eval(i) = linear_val^2 where
#' linear_val = (values[i] - min) / (max - min).
#'
#' @param values Numeric vector of environmental variable values
#' @param name Feature name/identifier
#' @param min_val Minimum value for normalization
#' @param max_val Maximum value for normalization
#' @return External pointer to QuadraticFeature object
#' @export
create_quadratic_feature <- function(values, name, min_val, max_val) {
    .Call(`_maxentcpp_create_quadratic_feature`, values, name, min_val, max_val)
}

#' Create a ProductFeature object
#'
#' Creates a product (interaction) feature between two environmental variables:
#' eval(i) = norm(values1[i]) * norm(values2[i]).
#'
#' @param values1 Numeric vector for the first environmental variable
#' @param values2 Numeric vector for the second environmental variable
#' @param name Feature name/identifier
#' @param min1 Minimum of the first variable
#' @param max1 Maximum of the first variable
#' @param min2 Minimum of the second variable
#' @param max2 Maximum of the second variable
#' @return External pointer to ProductFeature object
#' @export
create_product_feature <- function(values1, values2, name, min1, max1, min2, max2) {
    .Call(`_maxentcpp_create_product_feature`, values1, values2, name, min1, max1, min2, max2)
}

#' Create a ThresholdFeature object
#'
#' Creates a binary step feature: eval(i) = 1.0 if values[i] > threshold, else 0.0.
#'
#' @param values Numeric vector of environmental variable values
#' @param name Feature name/identifier
#' @param threshold The threshold value
#' @return External pointer to ThresholdFeature object
#' @export
create_threshold_feature <- function(values, name, threshold) {
    .Call(`_maxentcpp_create_threshold_feature`, values, name, threshold)
}

#' Create a HingeFeature object
#'
#' Creates a piecewise-linear hinge feature.
#' Forward hinge: eval(i) = (values[i] > min_knot) ? (values[i] - min_knot) / (max_knot - min_knot) : 0.
#' Reverse hinge: eval(i) = (values[i] < max_knot) ? (max_knot - values[i]) / (max_knot - min_knot) : 0.
#'
#' @param values Numeric vector of environmental variable values
#' @param name Feature name/identifier
#' @param min_knot Lower knot of the hinge
#' @param max_knot Upper knot of the hinge (must be > min_knot)
#' @param is_reverse If TRUE, use reverse hinge; if FALSE (default), use forward hinge
#' @return External pointer to HingeFeature object
#' @export
create_hinge_feature <- function(values, name, min_knot, max_knot, is_reverse = FALSE) {
    .Call(`_maxentcpp_create_hinge_feature`, values, name, min_knot, max_knot, is_reverse)
}

#' Evaluate a feature at a given index
#'
#' @param feature_ptr External pointer to a Feature object
#' @param index 0-based index into the data vector
#' @return Feature value at that index (double)
#' @export
feature_eval <- function(feature_ptr, index) {
    .Call(`_maxentcpp_feature_eval`, feature_ptr, index)
}

#' Get feature metadata
#'
#' Returns a list with name, type, lambda, min, and max values.
#'
#' @param feature_ptr External pointer to a Feature object
#' @return Named list with feature properties
#' @export
feature_get_info <- function(feature_ptr) {
    .Call(`_maxentcpp_feature_get_info`, feature_ptr)
}

#' Generate features from a list of environmental variable vectors
#'
#' Generates all configured feature types (linear, quadratic, product,
#' threshold, hinge) from the supplied data vectors.
#'
#' @param data_list Named list of numeric vectors, one per environmental variable
#' @param feature_types Character vector of feature types to generate.
#'   Valid values: "linear", "quadratic", "product", "threshold", "hinge".
#'   Defaults to all types.
#' @param n_thresholds Number of threshold knots per variable (default: 10)
#' @param n_hinges Number of hinge knots per variable (default: 10)
#' @return List of external pointers to Feature objects
#' @export
generate_features <- function(data_list, feature_types = as.character( c("linear", "quadratic",                                                    "product", "threshold", "hinge")), n_thresholds = 10L, n_hinges = 10L) {
    .Call(`_maxentcpp_generate_features`, data_list, feature_types, n_thresholds, n_hinges)
}

#' Read an ESRI ASCII grid (.asc) file
#'
#' Reads an ASC raster file and returns a float Grid external pointer.
#'
#' @param filename Path to the .asc file.
#' @return External pointer to a GridFloat object.
#' @export
grid_read_asc <- function(filename) {
    .Call(`_maxentcpp_grid_read_asc`, filename)
}

#' Write a float Grid to an ESRI ASCII (.asc) file
#'
#' @param grid_ptr   External pointer to a GridFloat object.
#' @param filename   Output file path.
#' @param scientific Logical: use scientific notation (default TRUE).
#' @return Called for side effects; returns invisibly.
#' @export
grid_write_asc <- function(grid_ptr, filename, scientific = TRUE) {
    invisible(.Call(`_maxentcpp_grid_write_asc`, grid_ptr, filename, scientific))
}

#' Read a grid from file (auto-detect format)
#'
#' Currently supports .asc format. Returns a float Grid.
#'
#' @param filename Path to the grid file.
#' @return External pointer to a GridFloat object.
#' @export
grid_read_file <- function(filename) {
    .Call(`_maxentcpp_grid_read_file`, filename)
}

#' Get grid information for an ASC-loaded grid
#'
#' Returns metadata and basic statistics for a GridFloat.
#'
#' @param grid_ptr External pointer to a GridFloat object.
#' @return Named list with nrows, ncols, xll, yll, cellsize, nodata,
#'   name, count_data.
#' @export
grid_float_info <- function(grid_ptr) {
    .Call(`_maxentcpp_grid_float_info`, grid_ptr)
}

#' Extract the data from a GridFloat as an R matrix
#'
#' @param grid_ptr External pointer to a GridFloat object.
#' @return Numeric matrix (nrows × ncols). NODATA cells are set to NA.
#' @export
grid_float_to_matrix <- function(grid_ptr) {
    .Call(`_maxentcpp_grid_float_to_matrix`, grid_ptr)
}

#' Create a GridFloat from an R matrix
#'
#' @param mat       Numeric matrix with grid data (NA becomes NODATA).
#' @param xll       X coordinate of lower-left corner.
#' @param yll       Y coordinate of lower-left corner.
#' @param cellsize  Cell size.
#' @param nodata    NODATA value (default -9999).
#' @param name      Grid name (default "").
#' @return External pointer to a GridFloat object.
#' @export
grid_float_from_matrix <- function(mat, xll, yll, cellsize, nodata = -9999.0, name = "") {
    .Call(`_maxentcpp_grid_float_from_matrix`, mat, xll, yll, cellsize, nodata, name)
}

#' Open a CSV file for reading
#'
#' @param filename   Path to the CSV file.
#' @param has_header Logical: first line contains column names (default TRUE).
#' @return External pointer to a CsvReader object.
#' @export
csv_open <- function(filename, has_header = TRUE) {
    .Call(`_maxentcpp_csv_open`, filename, has_header)
}

#' Get CSV column headers
#'
#' @param reader_ptr External pointer to a CsvReader object.
#' @return Character vector of header names.
#' @export
csv_headers <- function(reader_ptr) {
    .Call(`_maxentcpp_csv_headers`, reader_ptr)
}

#' Read the next CSV record
#'
#' @param reader_ptr External pointer to a CsvReader object.
#' @return Character vector of field values, or NULL on EOF.
#' @export
csv_next_record <- function(reader_ptr) {
    .Call(`_maxentcpp_csv_next_record`, reader_ptr)
}

#' Read an entire named column as doubles
#'
#' Reads from the current position to EOF.
#'
#' @param reader_ptr External pointer to a CsvReader object.
#' @param field      Column name.
#' @return Numeric vector.
#' @export
csv_read_double_column <- function(reader_ptr, field) {
    .Call(`_maxentcpp_csv_read_double_column`, reader_ptr, field)
}

#' Close a CsvReader
#'
#' @param reader_ptr External pointer to a CsvReader object.
#' @return Called for side effects; returns invisibly.
#' @export
csv_close <- function(reader_ptr) {
    invisible(.Call(`_maxentcpp_csv_close`, reader_ptr))
}

#' Open a CSV file for writing
#'
#' @param filename  Path to the output CSV file.
#' @param append    Logical: append to existing file (default FALSE).
#' @param precision Number of decimal places for doubles (default 4).
#' @return External pointer to a CsvWriter object.
#' @export
csv_writer_open <- function(filename, append = FALSE, precision = 4L) {
    .Call(`_maxentcpp_csv_writer_open`, filename, append, precision)
}

#' Write a value into the current row of a CSV
#'
#' @param writer_ptr External pointer to a CsvWriter object.
#' @param column     Column name.
#' @param value      Value to write (character).
#' @return Called for side effects; returns invisibly.
#' @export
csv_writer_print <- function(writer_ptr, column, value) {
    invisible(.Call(`_maxentcpp_csv_writer_print`, writer_ptr, column, value))
}

#' Write a numeric value into the current row of a CSV
#'
#' @param writer_ptr External pointer to a CsvWriter object.
#' @param column     Column name.
#' @param value      Numeric value.
#' @return Called for side effects; returns invisibly.
#' @export
csv_writer_print_double <- function(writer_ptr, column, value) {
    invisible(.Call(`_maxentcpp_csv_writer_print_double`, writer_ptr, column, value))
}

#' Flush the current CSV row to disk
#'
#' @param writer_ptr External pointer to a CsvWriter object.
#' @return Called for side effects; returns invisibly.
#' @export
csv_writer_println <- function(writer_ptr) {
    invisible(.Call(`_maxentcpp_csv_writer_println`, writer_ptr))
}

#' Close a CsvWriter
#'
#' @param writer_ptr External pointer to a CsvWriter object.
#' @return Called for side effects; returns invisibly.
#' @export
csv_writer_close <- function(writer_ptr) {
    invisible(.Call(`_maxentcpp_csv_writer_close`, writer_ptr))
}

#' Create a Layer metadata object
#'
#' @param name      Layer name.
#' @param type_str  Type string: "Continuous", "Categorical", "Bias",
#'   "Mask", "Probability", "Cumulative", "DebiasAvg", or "Unknown".
#' @return External pointer to a Layer object.
#' @export
create_layer <- function(name, type_str) {
    .Call(`_maxentcpp_create_layer`, name, type_str)
}

#' Get layer metadata
#'
#' @param layer_ptr External pointer to a Layer object.
#' @return Named list with name and type (string).
#' @export
get_layer_info <- function(layer_ptr) {
    .Call(`_maxentcpp_get_layer_info`, layer_ptr)
}

#' Extract a layer name from a file path
#'
#' Strips directory and extension, e.g. "/data/bio1.asc" → "bio1".
#'
#' @param path File path.
#' @return Character: layer name.
#' @export
layer_name_from_path <- function(path) {
    .Call(`_maxentcpp_layer_name_from_path`, path)
}

#' Create a GridDimension object
#'
#' Creates a grid dimension specifying the spatial extent and resolution
#' 
#' @param nrows Number of rows
#' @param ncols Number of columns
#' @param xll X coordinate of lower-left corner
#' @param yll Y coordinate of lower-left corner
#' @param cellsize Cell size (assumed square cells)
#' @return External pointer to GridDimension object
#' @export
create_grid_dimension <- function(nrows, ncols, xll, yll, cellsize) {
    .Call(`_maxentcpp_create_grid_dimension`, nrows, ncols, xll, yll, cellsize)
}

#' Get grid dimension properties
#'
#' @param dim_ptr External pointer to GridDimension
#' @return List with dimension properties
#' @export
get_grid_dimension_info <- function(dim_ptr) {
    .Call(`_maxentcpp_get_grid_dimension_info`, dim_ptr)
}

#' Convert geographic coordinates to row/col
#'
#' @param dim_ptr External pointer to GridDimension
#' @param lon Longitude
#' @param lat Latitude
#' @return Integer vector with row and column indices
#' @export
coords_to_rowcol <- function(dim_ptr, lon, lat) {
    .Call(`_maxentcpp_coords_to_rowcol`, dim_ptr, lon, lat)
}

#' Create a Sample object
#'
#' Creates a species occurrence sample point
#'
#' @param point Point identifier
#' @param row Row index in grid
#' @param col Column index in grid
#' @param lat Latitude coordinate
#' @param lon Longitude coordinate
#' @param name Sample name/identifier
#' @return External pointer to Sample object
#' @export
create_sample <- function(point, row, col, lat, lon, name) {
    .Call(`_maxentcpp_create_sample`, point, row, col, lat, lon, name)
}

#' Get sample properties
#'
#' @param sample_ptr External pointer to Sample
#' @return List with sample properties
#' @export
get_sample_info <- function(sample_ptr) {
    .Call(`_maxentcpp_get_sample_info`, sample_ptr)
}

#' Set feature value on a sample
#'
#' @param sample_ptr External pointer to Sample
#' @param feature_name Name of the feature
#' @param value Feature value
#' @return Called for side effects; returns invisibly.
#' @export
sample_set_feature <- function(sample_ptr, feature_name, value) {
    invisible(.Call(`_maxentcpp_sample_set_feature`, sample_ptr, feature_name, value))
}

#' Get feature value from a sample
#'
#' @param sample_ptr External pointer to Sample
#' @param feature_name Name of the feature
#' @param default_val Default value if feature not found
#' @return Feature value
#' @export
sample_get_feature <- function(sample_ptr, feature_name, default_val = 0.0) {
    .Call(`_maxentcpp_sample_get_feature`, sample_ptr, feature_name, default_val)
}

#' Create a float Grid object
#'
#' Creates a raster grid for environmental variables
#'
#' @param dim_ptr External pointer to GridDimension
#' @param name Grid layer name
#' @param nodata_value Value representing missing data
#' @return External pointer to Grid<float> object
#' @export
create_grid_float <- function(dim_ptr, name, nodata_value = -9999.0) {
    .Call(`_maxentcpp_create_grid_float`, dim_ptr, name, nodata_value)
}

#' Get grid value
#'
#' @param grid_ptr External pointer to Grid
#' @param row Row index
#' @param col Column index
#' @return Grid value
#' @export
grid_get_value <- function(grid_ptr, row, col) {
    .Call(`_maxentcpp_grid_get_value`, grid_ptr, row, col)
}

#' Set grid value
#'
#' @param grid_ptr External pointer to Grid
#' @param row Row index
#' @param col Column index
#' @param value Value to set
#' @return Called for side effects; returns invisibly.
#' @export
grid_set_value <- function(grid_ptr, row, col, value) {
    invisible(.Call(`_maxentcpp_grid_set_value`, grid_ptr, row, col, value))
}

#' Check if grid cell has data
#'
#' @param grid_ptr External pointer to Grid
#' @param row Row index
#' @param col Column index
#' @return TRUE if cell has valid data
#' @export
grid_has_data <- function(grid_ptr, row, col) {
    .Call(`_maxentcpp_grid_has_data`, grid_ptr, row, col)
}

#' Get grid as matrix
#'
#' @param grid_ptr External pointer to Grid
#' @return Numeric matrix of grid values
#' @export
grid_to_matrix <- function(grid_ptr) {
    .Call(`_maxentcpp_grid_to_matrix`, grid_ptr)
}

#' Extract multiple values from a Grid at given row/col indices (batch)
#'
#' @param grid_ptr External pointer to a Grid<float>.
#' @param rows     Integer vector of 0-based row indices.
#' @param cols     Integer vector of 0-based column indices.
#' @return Numeric vector of extracted values (NA for NODATA cells).
#' @export
grid_get_values_batch <- function(grid_ptr, rows, cols) {
    .Call(`_maxentcpp_grid_get_values_batch`, grid_ptr, rows, cols)
}

#' Set grid from matrix
#'
#' @param grid_ptr External pointer to Grid
#' @param mat Numeric matrix of values
#' @return Called for side effects; returns invisibly.
#' @export
grid_from_matrix <- function(grid_ptr, mat) {
    invisible(.Call(`_maxentcpp_grid_from_matrix`, grid_ptr, mat))
}

#' Compute Permutation Importance
#'
#' Measures how much each environmental variable contributes to model
#' prediction quality by permuting each variable and measuring AUC drop.
#'
#' @param fs_ptr         External pointer to a FeaturedSpace object.
#' @param grid_ptrs      List of external pointers to Grid<float> objects.
#' @param feature_names  Character vector of environment variable names.
#' @param presence_rows  Integer vector of presence site row indices.
#' @param presence_cols  Integer vector of presence site column indices.
#' @param absence_rows   Integer vector of absence site row indices.
#' @param absence_cols   Integer vector of absence site column indices.
#' @param seed           Random seed for reproducibility.
#' @return A data.frame with columns: name, permutation_importance.
#' @export
compute_permutation_importance <- function(fs_ptr, grid_ptrs, feature_names, presence_rows, presence_cols, absence_rows, absence_cols, seed = 42L) {
    .Call(`_maxentcpp_compute_permutation_importance`, fs_ptr, grid_ptrs, feature_names, presence_rows, presence_cols, absence_rows, absence_cols, seed)
}

#' Compute Percent Contribution
#'
#' Computes variable contribution based on sum of absolute lambda values
#' for features derived from each variable.
#'
#' @param fs_ptr         External pointer to a FeaturedSpace object.
#' @param feature_names  Character vector of base variable names.
#' @return A data.frame with columns: name, contribution.
#' @export
compute_percent_contribution <- function(fs_ptr, feature_names) {
    .Call(`_maxentcpp_compute_percent_contribution`, fs_ptr, feature_names)
}

#' Compute Java-compatible Marginal Response Curve
#'
#' Like compute_response_curve() but applies the Java Maxent cloglog:
#'   cloglog_java = 1 - exp(-exp(H) * raw_java)
#'
#' This matches the response curves produced by Java Maxent and dismo.
#'
#' @param fs_ptr         External pointer to a FeaturedSpace object.
#' @param grid_ptrs      List of external pointers to Grid<float> objects.
#' @param feature_names  Character vector of environment variable names.
#' @param var_index      0-based index of the variable to vary.
#' @param n_steps        Number of steps across the variable range.
#' @return A data.frame with columns: value, prediction.
#' @export
compute_response_curve <- function(fs_ptr, grid_ptrs, feature_names, var_index, n_steps = 100L) {
    .Call(`_maxentcpp_compute_response_curve`, fs_ptr, grid_ptrs, feature_names, var_index, n_steps)
}

#' Compute Java-compatible Response Curve with Fixed Values
#'
#' Like compute_response_curve_fixed() but applies the Java Maxent cloglog:
#'   cloglog_java = 1 - exp(-exp(H) * raw_java)
#'
#' @param fs_ptr         External pointer to a FeaturedSpace object.
#' @param fixed_values   Numeric vector of fixed values for each variable.
#' @param feature_names  Character vector of environment variable names.
#' @param var_index      0-based index of the variable to vary.
#' @param var_min        Minimum value of the target variable.
#' @param var_max        Maximum value of the target variable.
#' @param n_steps        Number of steps.
#' @return A data.frame with columns: value, prediction.
#' @export
compute_response_curve_fixed <- function(fs_ptr, fixed_values, feature_names, var_index, var_min, var_max, n_steps = 100L) {
    .Call(`_maxentcpp_compute_response_curve_fixed`, fs_ptr, fixed_values, feature_names, var_index, var_min, var_max, n_steps)
}

#' Clamp Environmental Grids
#'
#' Restricts environmental variable values to the training range.
#' Returns clamped grids and a clamping indicator grid.
#'
#' @param grid_ptrs List of external pointers to Grid<float> objects.
#' @param var_mins  Numeric vector of minimum training values per variable.
#' @param var_maxs  Numeric vector of maximum training values per variable.
#' @return A named list with:
#'   \describe{
#'     \item{clamped_grids}{List of external pointers to clamped Grid<float>}
#'     \item{clamp_grid}{External pointer to Grid<float> with clamping magnitudes}
#'   }
#' @export
clamp_grids <- function(grid_ptrs, var_mins, var_maxs) {
    .Call(`_maxentcpp_clamp_grids`, grid_ptrs, var_mins, var_maxs)
}

#' Compute Variable Ranges from Grids
#'
#' Scans all valid cells to determine min/max of each variable.
#'
#' @param grid_ptrs List of external pointers to Grid<float> objects.
#' @return A data.frame with columns: min, max.
#' @export
compute_variable_ranges <- function(grid_ptrs) {
    .Call(`_maxentcpp_compute_variable_ranges`, grid_ptrs)
}

#' Compute MESS (Multivariate Environmental Similarity Surface)
#'
#' Measures how similar each cell is to the training environment.
#' Negative values indicate novel (non-analog) conditions.
#'
#' @param grid_ptrs         List of external pointers to Grid<float> objects.
#' @param reference_values  List of numeric vectors with reference values
#'   for each variable (e.g. values at training sites).
#' @param feature_names     Character vector of variable names.
#' @return A named list with:
#'   \describe{
#'     \item{mess_grid}{External pointer to Grid<float> with MESS values}
#'     \item{mod_grid}{External pointer to Grid<float> with MoD variable index (1-based)}
#'   }
#' @export
compute_mess <- function(grid_ptrs, reference_values, feature_names) {
    .Call(`_maxentcpp_compute_mess`, grid_ptrs, reference_values, feature_names)
}

#' Compute MESS from Min/Max Ranges
#'
#' Simplified MESS using only the min/max of reference data.
#'
#' @param grid_ptrs List of external pointers to Grid<float> objects.
#' @param var_mins  Numeric vector of minimum reference values.
#' @param var_maxs  Numeric vector of maximum reference values.
#' @return A named list with mess_grid and mod_grid (external pointers).
#' @export
compute_mess_range <- function(grid_ptrs, var_mins, var_maxs) {
    .Call(`_maxentcpp_compute_mess_range`, grid_ptrs, var_mins, var_maxs)
}

#' Compute AUC (Area Under the ROC Curve)
#'
#' Computes the Wilcoxon-Mann-Whitney AUC statistic from prediction scores
#' at presence and absence sites.
#'
#' @param presence Numeric vector of prediction scores at presence sites.
#' @param absence  Numeric vector of prediction scores at absence sites.
#' @return A named list with elements: auc, max_kappa, max_kappa_thresh.
#' @export
eval_auc <- function(presence, absence) {
    .Call(`_maxentcpp_eval_auc`, presence, absence)
}

#' Compute Pearson Correlation
#'
#' Computes Pearson correlation coefficient between two numeric vectors.
#'
#' @param x Numeric vector.
#' @param y Numeric vector (same length as x).
#' @return Correlation coefficient in [-1, 1].
#' @export
eval_correlation <- function(x, y) {
    .Call(`_maxentcpp_eval_correlation`, x, y)
}

#' Compute Log-Loss
#'
#' Computes average cross-entropy log-loss from predictions at
#' presence and absence sites.
#'
#' @param presence Numeric vector of prediction scores at presence sites.
#' @param absence  Numeric vector of prediction scores at absence sites.
#' @return Average log-loss value.
#' @export
eval_logloss <- function(presence, absence) {
    .Call(`_maxentcpp_eval_logloss`, presence, absence)
}

#' Compute Mean Squared Error
#'
#' Presence sites contribute (1-pred)^2, absence sites contribute pred^2.
#'
#' @param presence Numeric vector of prediction scores at presence sites.
#' @param absence  Numeric vector of prediction scores at absence sites.
#' @return Mean squared error.
#' @export
eval_square_error <- function(presence, absence) {
    .Call(`_maxentcpp_eval_square_error`, presence, absence)
}

#' Compute Misclassification Rate
#'
#' Fraction of misclassified samples at threshold 0.5.
#'
#' @param presence Numeric vector of prediction scores at presence sites.
#' @param absence  Numeric vector of prediction scores at absence sites.
#' @return Misclassification rate in [0, 1].
#' @export
eval_misclassification <- function(presence, absence) {
    .Call(`_maxentcpp_eval_misclassification`, presence, absence)
}

#' Full Model Evaluation
#'
#' Computes all evaluation metrics at once: AUC, correlation, log-loss,
#' squared error, misclassification, max kappa, and prevalence.
#'
#' @param presence Numeric vector of prediction scores at presence sites.
#' @param absence  Numeric vector of prediction scores at absence sites.
#' @return A named list with: auc, max_kappa, max_kappa_thresh,
#'   correlation, square_error, logloss, misclassification, prevalence.
#' @export
eval_model <- function(presence, absence) {
    .Call(`_maxentcpp_eval_model`, presence, absence)
}

#' Project Model onto Grids (Java-compatible raw output)
#'
#' Applies a trained FeaturedSpace model to produce Java Maxent "raw" scores:
#'   raw_java = exp(lp - lpNorm) / densityNorm
#'
#' This matches the raw output of the Java Maxent software and the dismo
#' R package.
#'
#' @param fs_ptr         External pointer to a FeaturedSpace object.
#' @param grid_ptrs      List of external pointers to Grid<float> objects.
#' @param feature_names  Character vector of environment variable names.
#' @return External pointer to a Grid<float> with Java raw scores.
#' @export
project_raw <- function(fs_ptr, grid_ptrs, feature_names) {
    .Call(`_maxentcpp_project_raw`, fs_ptr, grid_ptrs, feature_names)
}

#' Project Model onto Grids (Java-compatible cloglog output)
#'
#' Applies the Java Maxent cloglog formula:
#'   cloglog_java = 1 - exp(-exp(H) * raw_java)
#'
#' where H is the model entropy and raw_java is the normalised probability.
#' This matches the cloglog output of Java Maxent and dismo.
#'
#' @param fs_ptr         External pointer to a FeaturedSpace object.
#' @param grid_ptrs      List of external pointers to Grid<float> objects.
#' @param feature_names  Character vector of environment variable names.
#' @return External pointer to a Grid<float> with Java cloglog scores in [0, 1].
#' @export
project_cloglog <- function(fs_ptr, grid_ptrs, feature_names) {
    .Call(`_maxentcpp_project_cloglog`, fs_ptr, grid_ptrs, feature_names)
}

#' Project Model onto Grids (Java-compatible logistic output)
#'
#' Applies the Java Maxent logistic formula:
#'   logistic_java = (exp(H) * raw_java) / (1 + exp(H) * raw_java)
#'
#' where H is the model entropy and raw_java is the normalised probability.
#' This matches the logistic output of Java Maxent and dismo.
#'
#' @param fs_ptr         External pointer to a FeaturedSpace object.
#' @param grid_ptrs      List of external pointers to Grid<float> objects.
#' @param feature_names  Character vector of environment variable names.
#' @return External pointer to a Grid<float> with Java logistic scores in [0, 1].
#' @export
project_logistic <- function(fs_ptr, grid_ptrs, feature_names) {
    .Call(`_maxentcpp_project_logistic`, fs_ptr, grid_ptrs, feature_names)
}

#' Extract Java-compatible Raw Predictions at Sample Locations
#'
#' Gets Java Maxent raw scores (raw_java = exp(lp - lpNorm) / densityNorm)
#' at specific grid cell locations.
#'
#' @param fs_ptr         External pointer to a FeaturedSpace object.
#' @param grid_ptrs      List of external pointers to Grid<float> objects.
#' @param feature_names  Character vector of environment variable names.
#' @param rows           Integer vector of row indices.
#' @param cols           Integer vector of column indices.
#' @return Numeric vector of Java raw scores. NaN for NODATA cells.
#' @export
extract_predictions_raw <- function(fs_ptr, grid_ptrs, feature_names, rows, cols) {
    .Call(`_maxentcpp_extract_predictions_raw`, fs_ptr, grid_ptrs, feature_names, rows, cols)
}

