/*
 * 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.Optional;
import java.util.function.Consumer;

import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ExpressionParser;
import nz.org.riskscape.rl.ast.Expression;

@RequiredArgsConstructor
class LinearContinuousFunctionBuilder {

  public final RealizationContext context;

  /**
   * An optional type for whatever the y expression will return, can be set instead of setting the yExpression itself.
   *
   * If the y expression is set, the builder can be 'lazy' and will defer computing the y values along the known points
   * until they are needed.  If that isn't possible, or desired, then the set the yExpressionType instead and be sure
   * to set all the yValues to the LinearContinuousState before using.
   */
  public Optional<Type> yExpressionType = Optional.empty();
  public RealizedExpression yExpression;
  public double[] xValues;
  public Type xType;
  public boolean logScale = false;

  public ResultOrProblems<LinearContinuousFunctionType> build(Consumer<LinearContinuousFunctionBuilder> setupVisitor) {
    setupVisitor.accept(this);

    return buildLinearExpressions().map(exprs -> new LinearContinuousFunctionType(xValues, exprs));
  }

  /**
   * Builds a non stackable continuous function type.
   *
   * Useful in cases where the required x-values are not known at function realization time.
   */
  public ResultOrProblems<NonStackableLinearContinuousFunctionType> buildNonStackable(
      Consumer<LinearContinuousFunctionBuilder> setupVisitor) {
    setupVisitor.accept(this);

    return buildLinearExpressions().map(NonStackableLinearContinuousFunctionType::new);
  }

  public ResultOrProblems<LinearContinuousExpressions> buildLinearExpressions() {
    Type yType = yExpressionType.orElseGet(() -> yExpression.getResultType());

    return ProblemException.catching(() -> {
      //                                       scaling x axis with log            unscaled (linear x)
      String slopeExprString      = logScale ? "(y1 - y0) / (log(x1) - log(x0))" : "(y1 - y0) / (x1 - x0)";
      String yInterceptExprString = logScale ? "y1 - (m * log(x1))"              : "y1 - (m * x1)";
      String solveForYExprString  = logScale ? "(m * log(x)) + c"                : "(m * x) + c";

      Struct slopeInputType = Struct.of(
          "x0", xType,
          "x1", xType,
          "y0", yType, "y1", yType
      );

      RealizedExpression slopeExpression = realize(slopeInputType, slopeExprString);
      Struct yInterceptInputType = Struct.of(
          "y1", yType,
          "m", slopeExpression.getResultType(), "x1", Types.FLOATING
      );

      RealizedExpression yInterceptExpression = realize(yInterceptInputType, yInterceptExprString);
      Struct solveForYExpressionInputType = Struct.of(
          "m", slopeExpression.getResultType(),
          "x", Types.FLOATING,
          "c", yInterceptExpression.getResultType()
      );

      RealizedExpression solveForYExpression = realize(solveForYExpressionInputType, solveForYExprString);

      return new LinearContinuousExpressions(yExpression, slopeInputType, slopeExpression,
          yInterceptInputType, yInterceptExpression,
          solveForYExpressionInputType, solveForYExpression
      );
    });
  }

  private RealizedExpression realize(Struct inputType, String expr) throws ProblemException {
    Expression parsed = ExpressionParser.parseString(expr);
    return context.getExpressionRealizer().realize(inputType, parsed).getOrThrow();
  }
}
