/*
 * 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.engine.cli.model;

import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.ini4j.Ini;
import org.ini4j.Profile;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import nz.org.riskscape.engine.Project;
import nz.org.riskscape.engine.RiskscapeIOException;
import nz.org.riskscape.engine.bind.BoundParameters;
import nz.org.riskscape.engine.bind.ParamProblems;
import nz.org.riskscape.engine.cli.ApplicationCommand;
import nz.org.riskscape.engine.cli.ExitException;
import nz.org.riskscape.engine.cli.PipelineRenderer;
import nz.org.riskscape.engine.cli.pipeline.CliPipelineRunnerOptions;
import nz.org.riskscape.engine.ini.IniParser;
import nz.org.riskscape.engine.model.Model;
import nz.org.riskscape.engine.output.Format;
import nz.org.riskscape.engine.pipeline.ExecutionContext;
import nz.org.riskscape.engine.pipeline.PipelineProblems;
import nz.org.riskscape.engine.pipeline.RealizedPipeline;
import nz.org.riskscape.engine.pipeline.RealizedStep;
import nz.org.riskscape.engine.pipeline.SinkConstructor;
import nz.org.riskscape.engine.pipeline.sink.SaveSinkConstructor;
import nz.org.riskscape.engine.problem.ProblemFactory;
import nz.org.riskscape.engine.resource.FileResourceLoader;
import nz.org.riskscape.engine.resource.Resource;
import nz.org.riskscape.engine.resource.ResourceLoadingException;
import nz.org.riskscape.picocli.CommandLine.Mixin;
import nz.org.riskscape.picocli.CommandLine.Option;
import nz.org.riskscape.picocli.CommandLine.Parameters;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemSink;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

public abstract class BaseModelRunCommand extends ApplicationCommand implements PipelineRenderer {

  public interface LocalProblems extends ProblemFactory {
    Problem cannotOverrideSaveFormat(String saveFormat);

    Problem noModelOrSingleSection(Path parametersFile, String modelId);
  }

  @Parameters(arity = "1", index = "0")
  public String modelId;

  @Mixin
  public CliPipelineRunnerOptions runnerOptions = new CliPipelineRunnerOptions();

  @Option(names = {"--parameters"})
  public Path parametersFile;

  @Option(names = {"-p", "--param", "--parameter"})
  public List<String> parameters = new ArrayList<>();

  /**
   * Prints a warning to the terminal if the given pipeline looks to have an explicit format set for various steps
   * that disagree with the --format option the user has specified.  The pipeline shouldn't have been 'capped' with
   * default save sinks, otherwise it's going to cause spurious warning.
   *
   * NB I considered moving this logic in to the CliPipelineRunner, so that other model running commands can use this
   * feature, but the batch command has specific logic in there to avoid spamming the user with warnings.
   */
  protected void warnIfCannotOverrideFormat(RealizedPipeline pipeline, ProblemSink problemSink) {
    if (runnerOptions.format == null) {
      // no need to warn if the user hasn't specified a format.
      return;
    }

    Format formatOverride = runnerOptions.getFormat(getExecutionContext());

    // we haven't applied any default step-capping to the realized pipeline yet, so any
    // SinkConstructor steps at this point mean that save steps are baked into the model itself
    for (RealizedStep step : pipeline.getRealizedSteps()) {
      if (step.getStepType() == SinkConstructor.class) {

        // the format for the save step may have been omitted (or it may match the override
        // specified by the user), in which case the user will still get their desired format
        Optional<Format> explicitSaveFormat = step.getResult().map(
            save -> ((SaveSinkConstructor) save).getParameters().format)
            .orElse(Optional.empty());

        if (explicitSaveFormat.isPresent() && explicitSaveFormat.get() != formatOverride) {
          // otherwise warn them that their --format might not take effect
          problemSink.log(
              Problems.get(RunCommand.LocalProblems.class).cannotOverrideSaveFormat(runnerOptions.format)
                  .withSeverity(Problem.Severity.WARNING));
          return;
        }
      }
    }

  }

  protected Map<String, List<String>> getCliParameterMap() {
    // We start by getting parameters from the parameters file. This will be an empty map if there
    // is no parameters file
    Map<String, List<String>> cliParameters = parametersFile != null ? getParametersFromFile() : Maps.newHashMap();

    // Now we add individual parameters to it. This will mean individual cli parameters will replace
    // those from the parameter file if they are specified in both places.
    cliParameters.putAll(getIndividualCliParameters());
    return cliParameters;
  }

  private Map<String, List<String>> getIndividualCliParameters() {
    Map<String, List<String>> cliParameters = new HashMap<>(parameters.size());

    for (String string : parameters) {
      String[] keyValue = string.split("=", 2);

      if (keyValue.length != 2) {
        // setting -p foo will clear the default - maybe this should be an error and have an explicit syntax for this?
        cliParameters.put(keyValue[0], Collections.emptyList());
        continue;
      }
      // we trim the key and value to allow users to enter parameters like:
      // `-p "foo = value" which is the format often used in ini files.
      String key   = keyValue[0].trim();
      String value = keyValue[1].trim();

      cliParameters.computeIfAbsent(key, k -> new ArrayList<>(1)).add(value);
    }

    makeRelativeTo(Paths.get(".").toUri(), cliParameters);
    return cliParameters;
  }

  private Map<String, List<String>> getParametersFromFile() {
    Map<String, List<String>> fileParameters = new HashMap<>();
    Resource parameterFileResource;
    Ini parametersIni;

    try {
      parameterFileResource = new FileResourceLoader().load(parametersFile.toUri());
      parametersIni = IniParser.parse(parameterFileResource.getContentStream());
    } catch (ResourceLoadingException | RiskscapeIOException e) {
      throw new ExitException(Problems.foundWith("--parameters", Problems.caught(e)));
    }

    // First we check for an INI section whose name matches the model
    Profile.Section section = parametersIni.get(modelId);
    if (section == null) {
      // there is no section with the same name as the model.
      // if there is only one section use that, else we error
      if (parametersIni.size() == 1) {
        section = parametersIni.values().iterator().next();
      } else {
        throw new ExitException(Problems.foundWith("--parameters",
            Problems.get(RunCommand.LocalProblems.class).noModelOrSingleSection(parametersFile, modelId)));
      }
    }
    for (String key: section.keySet()) {
      fileParameters.computeIfAbsent(key, k -> Lists.newArrayList())
          .addAll(section.getAll(key));
    }

    makeRelativeTo(parameterFileResource.getLocation(), fileParameters);
    return fileParameters;
  }

  /**
   * Processes the parameterMap looking for any parameter values that start with './'
   * in which case the value is updated to be resolved against relativeTo.
   * @param relativeTo    uri to resolve parameter values agains
   * @param parameterMap  parameters to make relative should they start with './'
   */
  private void makeRelativeTo(URI relativeTo, Map<String, List<String>> parameterMap) {
    // NB: this only works for unquoted filepaths, so won't work for pipeline models
    // where the filepath is a quoted text string. The solution is to define the parameter
    // with `param.NAME.properties = bookmark` so you can specify unquoted filepaths

    // TODO Should we be using UriHelper here? makeRelativeIfDotSlash would remove the quotes for us
    for (Map.Entry<String, List<String>> entry : parameterMap.entrySet()) {
      entry.setValue(entry.getValue().stream()
          .map(e -> {
            if (e.startsWith("./")) {
              return relativeTo.resolve(e).toString();
            }
            return e;
          })
          .collect(Collectors.toList())
      );
    }
  }

  protected Model updateParameters(Model model, Map<String, List<String>> cliParameters) {
    BoundParameters origBuildParameters = model.getFrameworkParameters();
    Project project = origBuildParameters.getContext().getProject();

    // we're going to bind everything again, so use the original unbound values as
    // a starting point (otherwise we'll lose the original non-Java input completely)
    LinkedHashMap<String, List<?>> newUnboundParams = new LinkedHashMap<>();

    // try to add in overrides in the order they were configured
    for (Map.Entry<String, List<?>> originalEntry : origBuildParameters.getUnbound().entrySet()) {
      List<?> override = cliParameters.remove(originalEntry.getKey());
      newUnboundParams.put(originalEntry.getKey(), override == null ? originalEntry.getValue() : override);
    }

    // anything that wasn't in the original config is dumped at the end.  the wizard is likely to complain about it
    newUnboundParams.putAll(cliParameters);

    BoundParameters newParameters =
        origBuildParameters.getBoundTo().bind(origBuildParameters.getContext(), newUnboundParams);

    // rebuild the model (providing the new parameters are valid)
    ResultOrProblems<Model> newModel = newParameters.flatMap(
        p -> model.getFramework().build(project, p));

    if (newModel.hasErrors()) {
      throw new ExitException(ParamProblems.get().invalidFor(model)
          .withChildren(newModel.getProblems()));
    }

    return newModel.drainWarnings(getTerminal()).get();
  }

  protected RealizedPipeline realize(Model model, ExecutionContext executionContext) {
    ResultOrProblems<RealizedPipeline> realizedOr = model.realize(executionContext);

    if (realizedOr.hasErrors()) {
      throw new ExitException(PipelineProblems.get().cannotRealize(Model.class)
          .withChildren(realizedOr.getProblems()));
    }

    return realizedOr.get();
  }

  protected LocalDateTime getCurrentTime() {
    return LocalDateTime.now();
  }

}
