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

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.ReflectionUtils;
import nz.org.riskscape.engine.bind.JavaParameterSet;
import nz.org.riskscape.engine.bind.ParamProblems;
import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.engine.bind.ParameterSet;
import nz.org.riskscape.engine.pipeline.ExecutionContext;
import nz.org.riskscape.engine.pipeline.PipelineRealizer;
import nz.org.riskscape.engine.problem.ProblemPlaceholder;
import nz.org.riskscape.engine.resource.CreateHandle;
import nz.org.riskscape.engine.types.Geom;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.Expression;
import nz.org.riskscape.rl.ast.StructDeclaration;

/**
 * Simple base class for {@link Format} implementations that covers some of the basic housekeeping
 */
@RequiredArgsConstructor
@EqualsAndHashCode(of = "id")
public abstract class BaseFormat<T> implements Format {

  /**
   * Useful method for determining if there's at least a single geometry member we can use to support writing tuples of
   * this type to a spatial format
   */
  public static boolean containsGeometry(Struct struct) {
    for (Struct.StructMember member : struct.getMembers()) {
      Type memberType = Nullable.strip(member.getType());
      if (memberType.find(Geom.class).isPresent()) {
        return true;
      }
      boolean foundInNested = memberType.find(Struct.class)
          .map(BaseFormat::containsGeometry)
          .orElse(false);
      if (foundInNested) {
        return foundInNested;
      }
    }

    return false;
  }

  @Getter
  private final String id;

  @Getter
  private final String extension;

  @Getter
  private final String mediaType;

  @Getter
  private final EnumSet<Characteristics> characteristics;

  public BaseFormat(String id, String extension, String mediaType) {
    this(id, extension, mediaType, EnumSet.noneOf(Characteristics.class));
  }

  public BaseFormat(String id, String extension, String mediaType, Characteristics first, Characteristics... rest) {
    this(id, extension, mediaType, EnumSet.of(first, rest));
  }

  @Override
  public String toString() {
    return String.format("Format[id=%s, extension=%s, mediaType=%s]", id, extension, mediaType);
  }

  /**
   * @return the class of `T` - default implementation gets it from the generic type
   */
  protected Class<T> getParameterClass() {
    return ReflectionUtils.findParameterClass(this.getClass());
  }

  @Override
  public JavaParameterSet<T> getWriterParameters() {
    return JavaParameterSet.fromBindingClass(getParameterClass());
  }

  /**
   * Binds the given struct declaration against this BaseFormat's options
   * @return bound and validated writer options
   */

  protected final ResultOrProblems<T> bindWriterOptions(
          ExecutionContext context, Struct input, CreateHandle handle, StructDeclaration rawOptions) {

    JavaParameterSet<T> parameterSet = getWriterParameters();

    List<Problem> realizingProblems = new ArrayList<>();
    Set<String> surplus = new HashSet<>();
    // NB if ast tokens kept a reference to their source (a URI) we could bind to ConfigString instead and get better
    // error messages
    Map<String, List<?>> paramMap = new HashMap<>();
    for (StructDeclaration.Member member : rawOptions.getMembers()) {
      if (!member.isJSONStyle()) {
        // TODO needs a better error
        return ResultOrProblems.failed(Problems.foundWith("struct syntax"));
      }

      String memberName = member.getName().orElseThrow();
      Expression argExpression = member.getExpression();

      if (!parameterSet.contains(memberName)) {
        // make sure we get a binding error for the 'spurious' member
        surplus.add(memberName);
        // bail early - we want to do parameter set look ups without fear of exceptions
        continue;
      }

      Parameter parameter = parameterSet.get(memberName);

      PipelineRealizer.populateUnboundFromExpression(
          context.getRealizationContext(),
          parameter,
          argExpression,
          paramMap,
          probs -> {
            if (!probs.isEmpty()) {
              realizingProblems.add(Problems.foundWith(member, probs));
            }
          }
      );
    }

    if (!surplus.isEmpty()) {
      realizingProblems.add(ParamProblems.get()
          .ignoredWithHints(
              surplus,
              parameterSet.getDeclared().stream().map(Parameter::getName).collect(Collectors.toSet())
          )
      );
    }

    // avoid binding if some of the constants failed to realize
    if (Problem.hasErrors(realizingProblems)) {
      return ResultOrProblems.failed(realizingProblems);
    }

    return parameterSet
        .bind(context.getBindingContext(), ParameterSet.normaliseParameterMap(paramMap))
        .map(bp -> parameterSet.bindToObject(bp).getBoundToObject())
        // tack on any warnings from binding parameters
        .withMoreProblems(realizingProblems);
  }

  /**
   * Support some higher-level validation on the format-specific options
   * NB might be 'nicer' if we had a base options class that included various niceties
   */
  protected ResultOrProblems<T> validateWriterOptions(
      ExecutionContext context, Struct input, CreateHandle handle, T bound) {
    return ResultOrProblems.of(bound);
  }

  /*
   * So far, all extensions of BaseFormat have supported writing, if that stops being the case we will want to either
   * split out the writing part from BaseFormat, or have some mechanism to 'opt out' of being a writer (as that's likely
   * the less likely case)   *
   */
  @Override
  public final Optional<WriterConstructor> getWriterConstructor() {
    return Optional.of((context, type, handle, optionsStruct) -> {
      return bindWriterOptions(context, type, handle, optionsStruct)
          .flatMap(bound -> validateWriterOptions(context, type, handle, bound))
          // any problems we have are from the options, so compose in a found with options to give the user some
          // context
          .composeProblems(Problems.foundWith(ProblemPlaceholder.of(getParameterClass(), getId())))
          .flatMap(bound -> newWriter(context, type, handle, bound));
    });
  }

  /**
   * @return a new RiskscapeWriter for the given bound and validated options
   * NB we could remove the ResultOrProblems here if our implementations made sure to do their binding in the bind
   * method, then we could catch any exceptions from this method and wrap them (given they're likely to be io errors
   * at that point)
   */
  protected abstract ResultOrProblems<? extends RiskscapeWriter> newWriter(
      ExecutionContext context, Struct input, CreateHandle handle, T bound);

}
