/*
 * 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.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import lombok.Data;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.problem.ProblemFactory;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.rl.agg.Accumulator;
import nz.org.riskscape.engine.rl.agg.AggregationFunction;
import nz.org.riskscape.engine.rl.agg.RealizedAggregateExpression;
import nz.org.riskscape.engine.types.FunctionType;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.TypeProblems;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.engine.util.SegmentedList;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.FunctionCall;

/**
 * Aggregate function for fitting a collected set of x/y values to a curve.  So far, we've only got power law, but I
 * expect this to be extended to a range of functions, and allow options for different types of functions, e.g.
 * try the different positively monotonic functions for loss curves, or perhaps just pick from an explicit list.
 *
 * TODO add support for selecting which curves and setting the curve fitting parameters
 */
@RequiredArgsConstructor
public class FitCurveFunction implements AggregationFunction {

  public interface LocalProblems extends ProblemFactory {
    Problem fittingFailed(String fitterId);
    Problem nothingFits();
  }

  public static final LocalProblems PROBLEMS = Problems.get(LocalProblems.class);

  private static final Struct FIT_RESULT = Struct.of(
      "function", new FunctionType(Collections.singletonList(Types.FLOATING), Types.FLOATING),
      "fit", Types.TEXT,
      "score", Types.FLOATING
  );

  @Data
  private static class FitterAndParams {
    final CurveFitter fitter;
    final Object params;

    public <T> FitCurve<T> fit(ObservedPoints points) {
      Object castParams = fitter.getBindingClass().cast(params);
      return fitter.fit(castParams, points);
    }
  }
  @Getter
  private final ArgumentList arguments = ArgumentList.create(
    "x-value", Types.FLOATING,
    "y-value", Types.FLOATING,
    "fitters", Nullable.of(Struct.EMPTY_STRUCT)
  );

  @Getter
  private final Type returnType = FIT_RESULT;

  private final List<CurveFitter<?>> fitters;

  @Override
  public ResultOrProblems<RealizedAggregateExpression> realize(RealizationContext context, Type inputType,
      FunctionCall fc) {

    return ProblemException.catching(() -> {

      RealizedExpression xExpression = realize(context, inputType, fc, "x-value");
      RealizedExpression yExpression = realize(context, inputType, fc, "y-value");

      // we need a binding context to build the empty/default parameters.  Eventually we'll want to allow the caller
      // to tell us which functions to try and fit and which parameters to use when trying to fit them
      BindingContext bindingContext = context.getBindingContext();

      List<FitterAndParams> fittersAndParams;
      Optional<FunctionCall.Argument> fittersArgs = arguments.getArgument(fc, "fitters");
      if (fittersArgs.isPresent()) {
        Tuple tuple = arguments.evaluateConstant(context, fc, "fitters", Tuple.class, Struct.EMPTY_STRUCT).getOrThrow();

        fittersAndParams = new ArrayList<>(tuple.size());
        for (String fitterId : tuple.getStruct().getMemberKeys()) {

          Object params = tuple.fetch(fitterId);
          Map<String, List<?>> unbound;
          if (params instanceof String) {
            unbound = Collections.emptyMap();
            fitterId = (String) params;
          } else if (params instanceof Tuple) {
            unbound = tupleToParamMap((Tuple) params);
          } else {
            unbound = null;
            // bail
          }

          String finalFitterId = fitterId;
          CurveFitter<?> found =
              this.fitters.stream().filter(cf -> cf.getId().equals(finalFitterId)).findAny().orElse(null);

          if (found == null) {
            throw new ProblemException(GeneralProblems.get().noSuchObjectExists(fitterId, CurveFitter.class));
          }
          Object boundObject = found.bind(bindingContext, unbound)
              .orElseThrow(problems -> new ProblemException(Problems.foundWith(finalFitterId + " options", problems)));

          fittersAndParams.add(new FitterAndParams(found, boundObject));
        }
      } else {
        fittersAndParams = fitters.stream()
            .map(fitter -> new FitterAndParams(fitter,
                // get should be fine here - no fitters should require default parameters.  If they eventually do,
                // we can just filter those out and log a warning?
                fitter.getBindingClass().cast(fitter.bind(bindingContext, Collections.emptyMap()).get()))
            )
            .collect(Collectors.toList());
      }

      Struct resultType = context.normalizeStruct(FIT_RESULT);

      return RealizedAggregateExpression.create(inputType, resultType, fc, () ->
        new AccumImpl(resultType, fittersAndParams, xExpression, yExpression)
      );
    });
  }

  private Map<String, List<?>> tupleToParamMap(Tuple tuple) {
    Map<String, List<?>> optionsMap = new HashMap<>(tuple.size());
    for (String key : tuple.getStruct().getMemberKeys()) {
      Object value = tuple.fetch(key);
      optionsMap.put(key, Collections.singletonList(value.toString())); // TODO check for numbers and strings only?
    }
    return optionsMap;
  }

  private RealizedExpression realize(
      RealizationContext context,
      Type inputType,
      FunctionCall fc,
      String argName
  ) throws ProblemException {
    RealizedExpression realized = context.getExpressionRealizer()
        .realize(inputType, arguments.getRequiredArgument(fc, argName).getOrThrow().getExpression())
        .getOrThrow(Problems.foundWith(arguments.get(argName)));

    if (!realized.getResultType().isNumeric()) {
      throw new ProblemException(
        TypeProblems.get().mismatch(arguments.get(argName), Types.FLOATING, realized.getResultType())
      );
    }

    return realized;
  }

  @RequiredArgsConstructor
  private static final class AccumImpl implements Accumulator {

    final Struct resultType;
    final List<FitterAndParams> fittersAndParams;
    final RealizedExpression xExpression;
    final RealizedExpression yExpression;

    List<Double> xValues = SegmentedList.forClass(Double.class);
    List<Double> yValues = SegmentedList.forClass(Double.class);

    @Override
    public Accumulator combine(Accumulator rhs) {
      AccumImpl impl = (AccumImpl) rhs;
      this.xValues.addAll(impl.xValues);
      this.yValues.addAll(impl.yValues);
      return this;
    }

    @Override
    public void accumulate(Object input) {
      Number xValue = (Number) xExpression.evaluate(input);
      Number yValue = (Number) yExpression.evaluate(input);

      if (xValue == null || yValue == null) {
        return;
      }

      xValues.add(xValue.doubleValue());
      yValues.add(yValue.doubleValue());
    }

    @Override
    public Object process() {
      ObservedPoints points = new ObservedPoints(xValues, yValues);

      FitCurve<?> winning = null;
      List<Problem> problems = new ArrayList<>();

      for (FitterAndParams fitter : fittersAndParams) {
        FitCurve<?> curve;
        try {
          curve = doFit(fitter, points);
        } catch (CannotFitCurveException e) {
          problems.add(PROBLEMS.fittingFailed(fitter.fitter.getId()).withChildren(Problems.caught(e)));
          continue;
        }

        if (winning == null || curve.getFitScore() > winning.getFitScore()) {
          winning = curve;
        }
      }

      // this catches the case where a specific fitter was asked for and it didn't fit, as well as skipping a misfitting
      // fitter when none has been asked for
      if (winning == null) {
        throw new CannotFitCurveException(PROBLEMS.nothingFits().withChildren(problems));
      }

      return Tuple.ofValues(resultType, winning.getFunction(), winning.getFitter().getId(), winning.getFitScore());
    }

    // extricated in to a private method to allow generics to work around java's awkward handling of mixed type lists in
    // loops
    private <T> FitCurve<?> doFit(FitterAndParams fitter, ObservedPoints points) {
      return fitter.fit(points);
    }

    @Override
    public boolean isEmpty() {
      return xValues.isEmpty();
    }
  }
}
