/*
 * RiskScape™ Copyright New Zealand Institute for Earth Science Limited
 * (Earth Sciences New Zealand) is distributed for research purposes only
 * under the terms of AGPLv3.
 *
 * RiskScape™ Copyright 2026 New Zealand Institute for Earth Science
 * Limited (Earth Sciences New Zealand). All rights reserved. Source code
 * available under the AGPLv3.
 * 
 * This program is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU Affero General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option) any
 *  later version.
 * 
 * This program is distributed for RESEARCH PURPOSES ONLY, in the hope that it will
 * be useful for research and education initiatives.
 * 
 * If you are not a researcher, or you are a researcher who wishes to use this
 * program on terms other than AGPLv3 (including those who wish to restrict the
 * distribution of any source code created using this program), please contact:
 * https://riskscape.org.nz
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.  You should have received a copy
 * of the GNU Affero General Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 * 
 * By way of summary only, under the AGPLv3:
 *     • Permissions of this strongest copyleft license are conditioned
 *       on making available complete source code of licensed works and
 *       modifications, which include larger works using a licensed work,
 *       under the same license.
 *     • Copyright and license notices must be preserved.
 *     • Contributors provide an express grant of patent rights.
 *     • When a modified version is used to provide a service over a
 *       network, the complete source code of the modified version must be made
 *       available.
 */
package nz.org.riskscape.defaults.curves;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.math3.util.FastMath;

import nz.org.riskscape.engine.Identified;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.bind.ParameterSet;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * Interface for some code that can fit a function to a set of 2d data points
 *@param T the type of object returned from bind.
 *
 * TODO remove the generics from here as they help more than hinder.  Collections of generic things like the curve
 * fitter that have different types really upset Java's generics and results in a lot of raw types to make things
 * compile.  We can always add a TypeSafeCurveFitter base class to improve things
 */
public interface CurveFitter<T> extends Identified {
  /**
   * Compute the r2 value of a {@link FitCurve}
   * https://en.wikipedia.org/wiki/Coefficient_of_determination
   */
  static <T> double computeRSquared(FitCurve<T> curve) {
    ObservedPoints points = curve.getObservedPoints();
    // compute ȳ - the mean of the observed points
    double yMean = points.getYValues().reduce(0D, (a, b) -> a + b) / points.size();

    // compute SStot
    double ssTot = points.getYValues().map(y -> FastMath.pow(y - yMean, 2)).reduce(0D, (a, b) -> a + b);

    // compute SSres
    double ssRes = points.stream().map(point -> {
      double y = point.getY(); // `yi`
      double x = point.getX();
      double computedY = ((Number)curve.getFunction().call(Collections.singletonList(x))).doubleValue(); // `fi`
      return Math.pow(y - computedY, 2D);
    }).reduce(0D, (a, b) -> a + b);

    return 1D - (ssRes / ssTot);
  }
  /**
   * The parameters for this fitter
   */
  ParameterSet getParameters();

  /**
   * Bind any curve fitting parameters in to an object that is used for the fit function.  This is done in this way
   * (as opposed to passing in unbound to fit or even bound parameters) to allow each curve fitter to do any
   * parameter binding and up-front computation once and then use this for many fits.
   */
  ResultOrProblems<T> bind(BindingContext context, Map<String, List<?>> unbound);

  /**
   * The type that `bind` returns and `fit` accepts.
   */
  Class<T> getBindingClass();

  /**
   * Attempt to fit the given points to this curve/function, using the given start parameters.
   * @throws {@link CannotFitCurveException} if the given data is invalid for this CurveFitter.
   */
  FitCurve<T> fit(T parameters, ObservedPoints points);

}
