/*
 * 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.interp;

import java.util.Arrays;
import java.util.List;

import lombok.EqualsAndHashCode;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.TypeVisitor;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.engine.util.Pair;


/**
 * A non-stackable version of  LinearContinuousFunctionType that doesn't have a consistent set of x values,
 * meaning it's more flexible, but less performant.
 */
@EqualsAndHashCode(callSuper = true)
final class NonStackableLinearContinuousFunctionType extends ContinuousFunctionType {

  /*
   * IMPORTANT:  This is a copy of the same set of methods in LinearContinuousFunctionType,
   * but repeated here to avoid any potential performance impact that subclassing it might have.
   *
   * Some before/after testing on the nhc prue project should tell us whether a change has any
   * meaningful impact, but that can come later.
   */

  public static final NonStackableLinearContinuousFunctionType ANY = new NonStackableLinearContinuousFunctionType();

  public static final Object VISITOR_META_CVALUE = "cvalue";
  public static final Object VISITOR_META_MVALUE = "mvalue";
  public static final Object VISITOR_META_YVALUE = "yvalue";

  private final LinearContinuousExpressions linearExpressions;

  NonStackableLinearContinuousFunctionType(LinearContinuousExpressions linearExpressions) {
    super(ONE_DIMENSIONAL, linearExpressions.getYExpression(), linearExpressions.getSolveForYType());
    this.linearExpressions = linearExpressions;
  }

  private NonStackableLinearContinuousFunctionType() {
    super(ONE_DIMENSIONAL, null, Types.ANYTHING);
    this.linearExpressions = null;
  }

  @Override
  public String toString() {
    return String.format("ContinuousCurve(returnType=%s)", returnType);
  }

  public Type getCValueType() {
    return linearExpressions.getYInterceptType();
  }

  public Type getMValueType() {
    return linearExpressions.getSlopeType();
  }

  @Override
  public Object applyTo(Object func, double... dimensionValues) {
    NonStackableLinearContinuousState state = (NonStackableLinearContinuousState)func;
    double xValue = dimensionValues[0];
    double[] xValues = state.xValues;

    int size = xValues.length;

    // base case: if there is only one data point, that's all we can return.  We take care to coerce the result, in
    // case it wasn't doubles
    if (xValues.length == 1) {
      return linearExpressions.getSolveForYType().coerce(state.yValues[0]);
    }

    // TODO here we assume a constant value based on the upper and lower bounds of the function, i.e. a horizontal line
    // from before x0 and after xn
    if (xValue < xValues[0]) {
      return solveForY(state, xValues[0], 0);
    } else if (xValue >= xValues[size - 1]) {
      return solveForY(state, xValues[size - 1], size - 2);
    }

    for (int i = 0; i < size - 1; i++) {
      double x0 = xValues[i];
      double x1 = xValues[i + 1];

      if (xValue >= x0 && xValue < x1) {

        return solveForY(state, xValue, i);
      }
    }

    throw new AssertionError("should not be possible");
  }

  private Object solveForY(NonStackableLinearContinuousState state, double xValue, int index) {
    Object slope = getOrComputeSlope(state, index);
    Object yIntercept = getOrComputeYIntercept(state, index);

    return solveForY(slope, yIntercept, xValue);
  }

  private Object solveForY(Object slope, Object yIntercept, double xValue) {
    return linearExpressions.solveForY(slope, xValue, yIntercept);
  }

  private Object getOrComputeYIntercept(NonStackableLinearContinuousState state, int i) {
    if (state.cValues[i] == null) {
      Object slope = state.mValues[i];
      Object y1 = state.yValues[i];
      double x1 = state.xValues[i];

      state.cValues[i] = linearExpressions.computeYIntercept(slope, x1, y1);
    }
    return state.cValues[i];
  }

  private Object getOrComputeSlope(NonStackableLinearContinuousState state, int i) {
    Object mValue = state.mValues[i];
    if (mValue == null) {
      Object y0 = state.yValues[i];
      Object y1 = state.yValues[i + 1];

      double x0 = state.xValues[i];
      double x1 = state.xValues[i + 1];

      mValue = linearExpressions.computeSlope(x0, x1, y0, y1);
      state.mValues[i] = mValue;
    }
    return mValue;
  }

  @Override
  public <T, U> U visit(TypeVisitor<T, U> tv, T data) {
    List<Pair<Type, ?>> children = Arrays.asList(
        Pair.of(getCValueType(), VISITOR_META_CVALUE),
        Pair.of(getMValueType(), VISITOR_META_MVALUE),
        Pair.of(getValueType(), VISITOR_META_YVALUE)
    );
    return tv.compoundType(this, children, data);
  }
}
