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

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.BaseRealizableFunction;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.problem.ProblemFactory;
import nz.org.riskscape.engine.problem.SeverityLevel;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.RSList;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
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;

public class SelectFunction extends BaseRealizableFunction {

  public interface LocalProblems extends ProblemFactory {

    /**
     * When there is a mismatch between the number of capture groups and replacements.
     */
    @SeverityLevel(Problem.Severity.WARNING)
    Problem captureGroupMismatch(int groupCount, int replacements);

    /**
     * When no attributes have been matched so the result is an empty struct.
     *
     * XXX maybe this should be an error.
     */
    @SeverityLevel(Problem.Severity.WARNING)
    Problem noAttributesMatched(String pattern, Struct amongst);

    /**
     * When a duplicate key has been generated.
     *
     * Caused by capture group/replacements removing the unique parts of attribute names.
     */
    Problem duplicateKeyGenerated(String sourceKey, String newKey, Struct newStruct);
  }

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

  public SelectFunction() {
    super(
        ArgumentList.create(
            "struct", Types.ANYTHING,
            "pattern", Types.TEXT,
            "replacements", Nullable.of(RSList.create(Types.TEXT))
        ),
        Struct.EMPTY_STRUCT
    );
  }

  @Override
  protected ResultOrProblems<RiskscapeFunction> buildFunction(RealizationContext context, FunctionCall functionCall,
      List<Type> givenTypes) {

    List<Problem> warnings = new ArrayList<>();
    return ProblemException.catching(() -> {
      String pattern = arguments.getRequiredArgument(functionCall, "pattern").getOrThrow()
          .evaluateConstant(context, String.class, Types.TEXT).getOrThrow();

      List<String> replacements = null;
      if (givenTypes.size() == 3) {
        replacements = arguments.getRequiredArgument(functionCall, "replacements").getOrThrow()
            .evaluateConstant(context, List.class, RSList.create(Types.TEXT)).getOrThrow();
      }

      Pattern compiled;
      try {
        compiled = Pattern.compile(pattern);
      } catch (PatternSyntaxException e) {
        throw new ProblemException(Problems.foundWith(
            arguments.getRequiredArgument(functionCall, "pattern").get(),
            Problems.caught(e)
        ));
      }

      Struct sourceStruct = givenTypes.get(0).find(Struct.class).get();

      Struct builder = Struct.EMPTY_STRUCT;
      List<Integer> sourceLookups = new ArrayList<>();
      int counter = 0;
      for (Struct.StructMember member : sourceStruct.getMembers()) {
        Matcher matcher = compiled.matcher(member.getKey());

        if (matcher.find()) {
          int replacementCount = replacements == null ? 0 : replacements.size();
          if (warnings.isEmpty() && matcher.groupCount() != replacementCount) {
            warnings.add(PROBLEMS.captureGroupMismatch(matcher.groupCount(), replacementCount));
          }

          String key;
          if (replacements != null) {
            StringBuilder sb = new StringBuilder(member.getKey());
            for (int i = replacements.size() - 1; i >= 0; i--) {
              if (i >= matcher.groupCount() || matcher.group(i + 1) == null) {
                // skip over excess replacements and don't be replacing any groups that have matched nothing
                // (they must be an optional capture)
                continue;
              }
              int start = matcher.start(i + 1);
              int end = matcher.end(i + 1);

              sb.replace(start, end, replacements.get(i));
            }

            key = sb.toString();
          } else {
            key = member.getKey();
          }

          if (builder.hasMember(key)) {
            throw new ProblemException(PROBLEMS.duplicateKeyGenerated(member.getKey(), key, builder));
          }
          builder = builder.add(key, member.getType());
          sourceLookups.add(counter);
        }

        counter++;
      }

      Struct builtStruct = builder;
      if (builtStruct.size() == 0) {
        // NB throw if empty?
        warnings.add(PROBLEMS.noAttributesMatched(pattern, sourceStruct));
      }

      return RiskscapeFunction.create(this, givenTypes, builtStruct, args -> {
        Tuple source = (Tuple) args.get(0);
        Tuple result = Tuple.of(builtStruct);

        int idx = 0;
        for (Integer sourceLookup : sourceLookups) {
          result.set(idx++, source.fetch(sourceLookup));
        }

        return result;
      });
    }).withMoreProblems(warnings);
  }

}
