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

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import lombok.Getter;
import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.Project;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.bind.BoundParameters;
import nz.org.riskscape.engine.bind.JavaParameterSet;
import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.engine.bind.ParameterSet;
import nz.org.riskscape.engine.i18n.MessageSource;
import nz.org.riskscape.engine.model.BaseModel2;
import nz.org.riskscape.engine.model.Model;
import nz.org.riskscape.engine.model.ModelFramework;
import nz.org.riskscape.engine.model.ModelParameter;
import nz.org.riskscape.engine.pipeline.ExecutionContext;
import nz.org.riskscape.engine.pipeline.RealizedPipeline;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.problem.ProblemSink;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.wizard.bld.IncrementalBuildState;
import nz.org.riskscape.wizard.model2.ModelSurvey2;

/**
 * Builds a model from a saved set of wizard answers.
 */
public class WizardModelFramework implements ModelFramework {

  private final Engine engine;

  public WizardModelFramework(Engine engine) {
    this.engine = engine;
  }

  public static class Parameters {
  }

  @Override
  public String getId() {
    return "wizard";
  }

  @Getter
  private final JavaParameterSet<Parameters> buildParameterSet = JavaParameterSet.fromBindingClass(Parameters.class);

  @Override
  public ResultOrProblems<Model> build(Project project, BoundParameters buildParameters) {
    ConfigParser parser = getConfigParser();

    // The current unbound values are the wizard answers plus standard params (in INI form).
    Map<String, List<?>> unbound = new HashMap<>(buildParameters.getUnbound().size());
    // prevent these keys from confusing the configParser
    unbound.putAll(buildParameters.getUnbound());
    unbound.remove("framework");
    unbound.remove("description");

    // We must build the RealizedPipeline/IncrementalBuildState to scrape all the model parameter metadata, then we
    // throw it away (but keep the metadata)
    // TODO using a new execution context that we then throw away probably isn't the right thing to do - change model
    // API build method to accept an ExecutionContext instead of a Project?
    ResultOrProblems<IncrementalBuildState> result;
    try (ExecutionContext context = project.newExecutionContext()) {
      result = loadConfig(parser, project.newExecutionContext(), unbound);
    }

    return result.map(buildState -> new WizardModelImpl(
        buildParameters,
        getBoundParameters(buildState, buildParameters),
        getConfigParser().getModelParameters(buildState),
        unbound
    ));
  }

  private ConfigParser getConfigParser() {
    return new ConfigParser(this::surveyConstructor);
  }

  private BoundParameters getBoundParameters(IncrementalBuildState buildState, BoundParameters buildParameters) {
    Collection<Parameter> parameters = getConfigParser().getModelParameters(buildState).stream()
        .map(mp -> mp.getParameter())
        .collect(Collectors.toList());

    return new ParameterSet(parameters).bind(buildState.getBindingContext(), Collections.emptyMap());
  }

  /**
   * A runnable instance of a wizard-based model (which just basically wraps up a
   * fully self-contained {@link IncrementalBuildState}).
   */
  private class WizardModelImpl extends BaseModel2 {

    private Map<String, List<?>> unbound;

    WizardModelImpl(
        BoundParameters frameworkParams,
        BoundParameters params,
        List<? extends ModelParameter> modelParameters,
        Map<String, List<?>> unbound
    ) {
      super(WizardModelFramework.this, frameworkParams, params, modelParameters);
      this.unbound = unbound;
    }

    @Override
    public ResultOrProblems<RealizedPipeline> realize(ExecutionContext context) {
      // we need to re-build the RealizedPipeline using this fresh context - the one we used when we built the model is
      // now defunct.
      return loadConfig(getConfigParser(), context, unbound)
          // ignore any warnings for the RealizedPipeline or the incremental build state - they should have been
          // logged when the model parameters were bound (when the model was built).
          // NB This looks like it could be swallowing the errors from the RealizedPipeline, but it has been like this
          // for a while.
          .flatMap(buildState -> ResultOrProblems
            .of(buildState.getRealizedPipeline().drainWarnings(ProblemSink.DEVNULL)))
          .drainWarnings(ProblemSink.DEVNULL);
    }
  }

  private ResultOrProblems<IncrementalBuildState> loadConfig(
      ConfigParser parser,
      ExecutionContext context,
      Map<String, List<?>> unbound
  ) {
    try {
      // The parser will rebuild an IncrementalBuildState the same as if the answers had been entered interactively
      return parser.loadConfig(context, unbound);
    } catch (RuntimeException e) {
      // no wrapping with any context here, there's nothing really of use - there should be some code above this that
      // will wrap it with something useful, such as a location or resource
      return ResultOrProblems.failed(Problems.caught(e));
    }
  }

  /**
   * @return the SurveyMin implementation for the given survey id - at the moment this is limited to our hard-coded
   * survey implementations, but the hope is we make it come from an identified collection
   */
  private Survey surveyConstructor(String id) {
    MessageSource messages = engine.getMessages().newMessageSource(Survey.getSurveyMessageBundleName("survey2"));
    ModelSurvey2 newSurvey = new ModelSurvey2(messages);

    // this is very loose, but not worth going overboard until we have an identified collection of surveys
    if (id.equals(newSurvey.getId())) {
      return newSurvey;
    }
    throw new RiskscapeException(GeneralProblems.get().noSuchObjectExists(id, Survey.class)
        .withChildren(WizardProblems.get().configError())
    );
  }
}
