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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import nz.org.riskscape.config.ConfigProblems;
import nz.org.riskscape.config.ConfigSection;
import nz.org.riskscape.engine.Project;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.bind.ParameterProperties;
import nz.org.riskscape.engine.bind.ParameterProperty;
import nz.org.riskscape.engine.bind.ParameterTemplate;
import nz.org.riskscape.engine.bind.ParameterTemplate.Choice;
import nz.org.riskscape.engine.bind.TypedProperty;
import nz.org.riskscape.engine.bind.UserDefinedParameter;
import nz.org.riskscape.engine.problem.ProblemFactory;
import nz.org.riskscape.engine.resource.UriHelper;
import nz.org.riskscape.engine.util.Pair;
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.ExpressionParser;
import nz.org.riskscape.rl.ast.Expression;
import nz.org.riskscape.rl.ast.StructDeclaration;
import nz.org.riskscape.rl.ast.StructDeclaration.Member;

/**
 * Builds a user-defined parameter from an INI definition.
 */
public class IniFileParameterBuilder extends IdentifiedObjectBuilder.Base<UserDefinedParameter> {

  private final Project project;

  // we use a binding context to parse the parameter 'properties' values. Currently we only
  // support numeric values, so this might be a bit overkill, but later we might need more
  // sophisticated bookmark-related properties, e.g. `compatible-with-bookmark: foo`
  private BindingContext context;

  /**
   * The INI file keyword, i.e. denotes a `[parameter foo]` section.
   */
  public static final String PARAMETER_KEY = "parameter";

  public static final String TEMPLATE = "template";

  private static final String LABEL = "label";
  private static final String DESCRIPTION = "description";
  private static final String PROPERTIES = "properties";
  private static final String CHOICES = "choices";
  private static final String DEFAULT = "default";

  /**
   * Specifies the INI file keys that the `[parameter xyz]` section can contain
   */
  public static final List<String> KEYS = Arrays.asList(LABEL, DESCRIPTION, CHOICES, PROPERTIES, TEMPLATE, DEFAULT);

  interface LocalProblems extends ProblemFactory {
    Problem couldNotParseOption(String option);
  }

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

  /**
   * @return the effective settings for a {@link ParameterTemplate}, i.e. the
   *         config required to build it
   */
  public static List<Pair<String, String>> getSettings(ParameterTemplate template) {
    List<Pair<String, String>> settings = new ArrayList<>();

    template.getLabel().ifPresent(label -> settings.add(Pair.of(LABEL, label)));
    template.getDescription().ifPresent(desc -> settings.add(Pair.of(DESCRIPTION, desc)));

    String properties = template.getProperties().stream()
        .map(p -> p.getKeyword() + p.getValueOr().map(val -> ": " + val.toString()).orElse(""))
        .collect(Collectors.joining(", "));
    if (properties.length() > 0) {
      settings.add(Pair.of(PROPERTIES, properties));
    }

    String choices = template.getChoices().stream()
        .map(c -> c.getLabel().map(key -> key + ": ").orElse("") + c.getValue().toString())
        .collect(Collectors.joining(", "));
    if (choices.length() > 0) {
      settings.add(Pair.of(CHOICES, choices));
    }
    return settings;
  }

  public IniFileParameterBuilder(Project project) {
    super(UserDefinedParameter.class, PARAMETER_KEY);
    this.project = project;
    this.context = project.newBindingContext();
  }

  public ParameterTemplate build(Map<String, List<String>> config) throws ProblemException {
    ParameterTemplate base = ParameterTemplate.EMPTY;

    // the parameter template can be based off another template. We don't store the base template
    // itself, but just inherit the settings it has. The inherited settings can then be overridden,
    // e.g. this let's you inherit common properties but just tweak the label or description displayed
    if (config.containsKey(TEMPLATE)) {
      String templateId = config.get(TEMPLATE).get(0);
      base = project.getParameterTemplates()
          .getOr(templateId)
          // templates can have warnings that will need to be drained to prevent nasty looking logs
          // unrecognized parameter keywords for instance
          .drainWarnings(project.getProblemSink())
          .map(p -> p.getTemplate())
          .getOrThrow();
    }

    Optional<String> description = base.getDescription();
    Optional<String> label = base.getLabel();
    Set<ParameterProperty> properties = base.getProperties();
    List<Choice> choices = base.getChoices();
    Optional<String> defaultValue = base.getDefaultValue();

    if (config.containsKey(DESCRIPTION)) {
      description = Optional.of(String.join(" ", config.get(DESCRIPTION)));
    }

    if (config.containsKey(LABEL)) {
      label = Optional.of(String.join(" ", config.get(LABEL)));
    }

    if (config.containsKey(PROPERTIES)) {
      properties = new LinkedHashSet<>();
      for (String configLine : config.get(PROPERTIES)) {
        // config might have multiple properties per line, e.g. number, min: 0
        for (String toParse : configLine.split(",")) {
          // the property can be a simple string like 'hidden' or it could be a key-value pair like 'min: 0'
          String[] parts = toParse.split(":", 2);
          String keyword = parts[0].trim();
          Optional<String> value = parts.length > 1 ? Optional.of(parts[1].trim()) : Optional.empty();

          ParameterProperty property = ParameterProperties.build(context, keyword, value).getOrThrow();

          // sanity-check the user-supplied properties are compatible
          List<Problem> problems = ParameterProperties.checkCompatible(property, properties);
          if (!problems.isEmpty()) {
            throw new ProblemException(Problems.foundWith(ParameterProperties.class, problems));
          }
          properties.add(property);
        }
      }
    }

    if (config.containsKey(CHOICES)) {
      choices = new ArrayList<>();
      for (String choice : config.get(CHOICES)) {
        // we reuse the struct expression syntax here for specifying the choices, E.g.
        // either `choice1, choice2, choice3` or `label1: choice1, label2: choice2, label3: choice3`
        Expression expression = ExpressionParser.INSTANCE.parseOr("{" + choice + "}")
            .getOrThrow(PROBLEMS.couldNotParseOption(choice));

        StructDeclaration struct = expression.isA(StructDeclaration.class).orElseThrow(() ->
        new ProblemException(PROBLEMS.couldNotParseOption(choice)));

        for (Member member : struct.getMembers()) {
          String value = makeRelativeIfNeeded(member.getExpression().toSource(), properties);
          choices.add(new Choice(value, member.getName()));
        }
      }
    }

    if (config.containsKey(DEFAULT) && !config.get(DEFAULT).isEmpty()) {
      String value = config.get(DEFAULT).get(0);
      defaultValue = Optional.of(makeRelativeIfNeeded(value, properties));
    }

    return new ParameterTemplate(label, description, properties, choices, defaultValue);
  }

  /**
   * If something looks like a path, expand it relative to the file it's defined in - otherwise you'd get a
   * different file depending on where you're using the template
   */
  private String makeRelativeIfNeeded(String value, Set<ParameterProperty> properties) {
    boolean isFile = properties.contains(TypedProperty.FILE) || properties.contains(TypedProperty.BOOKMARK);
    if (isFile) {
      return UriHelper.makeRelativeToIfDotSlash(value, context.getRelativeTo());
    } else {
      return value;
    }
  }

  private List<Problem> collectWarnings(ConfigSection section) {
    List<Problem> warnings = new ArrayList<>();
    Set<String> spuriousKeys = section.toMultiMap().keySet().stream()
        .filter(x -> !KEYS.contains(x))
        .collect(Collectors.toSet());
    if (!spuriousKeys.isEmpty()) {
      warnings.add(ConfigProblems.get().spuriousKeys(section, spuriousKeys));
    }
    return warnings;
  }

  @Override
  public ResultOrProblems<UserDefinedParameter> build(String id, ConfigSection section) {
    context = context.withNewRelativeTo(section.getLocation());
    return ProblemException.catching(() -> build(section.toMultiMap()))
        .map(template -> UserDefinedParameter.wrap(id, template))
        .withMoreProblems(collectWarnings(section))
        .composeProblems(Problems.foundWith(section));
  }
}
