/*
 * 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 com.google.common.primitives.Doubles;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.rl.ScopedLambdaExpression;
import nz.org.riskscape.engine.types.Struct;
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;


/**
 * The riskscape type representing a continuous function resulting from the {@link CreateContinuousFunction} function.
 *
 * Has the logic and static state (x values and realized expressions) required for computing y values for a
 * {@link ContinuousState} object.  You might expect that this logic and state would on the {@link
 * ContinuousState} object instead, but to keep that code clean we would want to have all the type-static state to
 * live on the ContinuousState which would blow out its memory footprint.  Otherwise we'd need to structure the
 * ContinuousState methods so that they took a type as their first argument, like some sort of mad, twisted python
 * program.
 *
 * Marked final to (possibly) help the JVM to optimize this code.  Can be removed if a future refactor deems it awkward.
 */
@EqualsAndHashCode(callSuper = true, of = {"xValues"})
final class LinearContinuousFunctionType extends StackableContinuousFunctionType<LinearContinuousState> {

  /*
   * IMPORTANT:  This is a copy of the same set of methods in NonStackableLinearContinuousFunctionType
   */

  public static final LinearContinuousFunctionType ANY = new LinearContinuousFunctionType();

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

  @Getter
  private final double[] xValues;

  private final LinearContinuousExpressions linearExpressions;

  LinearContinuousFunctionType(double[] xValues, LinearContinuousExpressions linearExpressions) {
    super(ONE_DIMENSIONAL, linearExpressions.getYExpression(),
        linearExpressions.getSolveForYType(), false);
    this.xValues = xValues;
    this.linearExpressions = linearExpressions;
  }

  private LinearContinuousFunctionType() {
    super(ONE_DIMENSIONAL, null, Types.ANYTHING, false);
    this.xValues = new double[0];
    linearExpressions = null;
  }

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

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

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

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


    int size = xValues.length;
    // 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(LinearContinuousState state, double xValue, int index) {
    Object slope = getOrComputeSlope(state, index);
    Object yIntercept = getOrComputeYIntercept(state, index);

    return linearExpressions.solveForY(slope, xValue, yIntercept);
  }

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

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

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

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

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

    return state.mValues[i];
  }

  @Override
  protected Object getOrComputeValue(LinearContinuousState state, int i) {
    Object currentValue = getValue(state, i);

    if (currentValue == null) {
      // NB we could lock here instead?
      Tuple inputTuple = state.lambda.buildCallingScope((Struct) valueExpression.getInputType(), xValues[i]);
      inputTuple.set(inputTuple.size() - 1, xValues[i]);
      currentValue = valueExpression.evaluate(inputTuple);
      setValue(state, i, currentValue);
    }

    return currentValue;
  }

  @Override
  LinearContinuousState newFunction(ScopedLambdaExpression lambda) {
    return new LinearContinuousState(lambda, this);
  }

  @Override
  public int getSize() {
    return xValues.length;
  }

  @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);
  }
}
