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

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Consumer;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;

import nz.org.riskscape.config.ConfigSection;
import nz.org.riskscape.engine.Project;
import nz.org.riskscape.engine.ini.IdentifiedObjectBuilder;
import nz.org.riskscape.engine.types.Struct.StructBuilder;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.typeset.CanonicalType;
import nz.org.riskscape.engine.typeset.TypeSet;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * Can add {@link Type}s to a {@link TypeSet} via an ini file and the riskscape type expression dsl
 */
public class IniFileTypeBuilder extends IdentifiedObjectBuilder.Base<CanonicalType> {

  private final Project project;

  /**
   * The key to use to identify a type that is described in a single line, e.g.
   * ```
   * [my-type]
   * type = nullable(text)
   * ```
   */
  public static final String TYPE = "type";

  /**
   * The prefix of keys to use to identify struct member type definitions across many lines, e.g.
   * ```
   * [my-type]
   * type.animal = enum('cat', 'dog', 'pig')
   * type.weight = range(floating, 0, 1000000)
   * ```
   */
  public static final String MULTILINE_TYPE_PREFIX = TYPE + ".";

  /**
   * The INI section keyword to look for, e.g.
   * ```
   * [type my-type]
   * ...
   * ```
   */
  public static final String TYPE_KEY = "type";

  public IniFileTypeBuilder(Project project) {
    super(CanonicalType.class, TYPE_KEY);
    this.project = project;
  }

  public ResultOrProblems<Type> buildType(TypeBuilder builder, ConfigSection sectionValues) {
    List<Problem> problems = Lists.newArrayList();
    Consumer<List<Problem>> addProblems = ps -> problems.addAll(problems);
    String type = sectionValues.getOne(TYPE).map(or -> or.orElse(addProblems, "")).orElse(null);

    if (!Strings.isNullOrEmpty(type)) {
      return buildType(builder, type);
    } else {
      StructBuilder structBuilder = new StructBuilder();
      Map<String, List<String>> map = sectionValues.toMultiMap();
      for (Entry<String, List<String>> entry : map.entrySet()) {
        String key = entry.getKey();
        List<String> values = entry.getValue();

        if (key.startsWith(MULTILINE_TYPE_PREFIX)) {
          String attrName = key.substring(MULTILINE_TYPE_PREFIX.length());

          if (values.size() > 1) {
            problems.add(Problem.error("Attribute '%s' has been defined more than once", attrName));
          } else {
            String typeExpression = values.get(0);
            ResultOrProblems<Type> attrTypeMaybe = buildType(builder, typeExpression);

            attrTypeMaybe.ifPresent(attrType -> structBuilder.add(attrName, attrType));

            if (attrTypeMaybe.hasProblems()) {
              problems.add(Problem.composite(attrTypeMaybe.getProblems(), "Attribute %s has problems:", attrName));
            }
          }
        } else {
          problems.add(Problem.warning("spurious attribute - %s", key));
        }
      }

      if (Problem.hasErrors(problems)) {
        // we shouldn't return a partial type if there have been errors detected.
        return ResultOrProblems.failed(problems);
      } else if (structBuilder.isEmpty()) {
        // no type info detected (possibly because the user entered spurious attributes)
        return ResultOrProblems.failed(
            Problem.error("requires either a type or type.<ATTR_NAME> entry(s)")
              .withChildren(problems));
      } else {
        return ResultOrProblems.of(structBuilder.build(), problems);
      }
    }
  }

  private ResultOrProblems<Type> buildType(TypeBuilder builder, String typeExpression) {
    try {
      return ResultOrProblems.of(builder.build(typeExpression));
    } catch (TypeBuildingException ex) {
      return ResultOrProblems.failed(Problems.caught(ex));
    } catch (RuntimeException ex) {
      return ResultOrProblems.failed(Problem.error(
          ex,
          "Unexpected error building type from '%s' - %s",
          typeExpression,
          ex.getMessage()));
    }
  }

  @Override
  public ResultOrProblems<CanonicalType> build(String id, ConfigSection section) {
    // build the type and then map it to an Identified CanonicalType
    return buildType(project.getTypeBuilder(), section)
        .map(type -> new CanonicalType(id, type) {
          @Override
          public TypeSet getTypeSet() {
            return project.getTypeSet();
          }
        });
  }

}
