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

import java.io.File;
import java.net.URI;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import nz.org.riskscape.engine.Project;
import nz.org.riskscape.engine.auth.Secret;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.bind.ParameterField;
import nz.org.riskscape.engine.pipeline.ExecutionContext;
import nz.org.riskscape.engine.resource.Resource;
import nz.org.riskscape.engine.resource.ResourceFactory;
import nz.org.riskscape.engine.rl.ExpressionRealizer;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.Problem;

/**
 * Represents the working set of parameters and validation state that is built up during bookmark resolution.  It
 * is intended that {@link BookmarkResolver} subclasses subclass this as well and use it in collaboration with the
 * {@link BaseBookmarkResolver} class to provide options used when constructing relations and coverages (or whatever
 * other data is being pointed to).
 *
 * Fields annotated with {@link ParameterField} are set during validation by binding the set of unparsed
 * bookmark options to these fields.
 */
public abstract class BookmarkParameters {

  /**
   * Pseudo-parameter, set manually, mostly here so the parameter help matches what's available in ini-files
   */
  @ParameterField
  public URI location;

  /**
   * Pseudo-parameter, set manually, mostly here so the parameter help matches what's available in ini-files
   */
  @ParameterField()
  public Optional<String> format = Optional.empty();

  /**
   * Pseudo-parameter, set manually, mostly here so the parameter help matches what's available in ini-files
   */
  @ParameterField()
  public Optional<String> description = Optional.empty();

  /**
   * Indicates that this bookmark will require a {@link Secret} of the given framework to be defined.
   *
   * Useful to provide users good error when secret hasn't not been setup.
   */
  @ParameterField()
  public Optional<String> requiresSecret = Optional.empty();

  /**
   * A collection of problems that get added to during the validation of parameters.  Both the base parameter
   * binding validation uses this as well as sub-class specific validation that is applied afterwards.
   */
  public final List<Problem> problems = new ArrayList<>();

  /**
   * The bookmark that fed in to the set of realised parameters.  Should be set during binding.
   */
  public Bookmark bookmark;

  /**
   * The context these parameters were bound under.  Should be set during binding.
   */
  public BindingContext bindingContext;

  /**
   * The execution context in which resolving is happening.  Should be set during binding.
   */
  ExecutionContext executionContext;

  /**
   * If {@link #getLocation()} was a file that is readable and accessible by the running process, then this should
   * be set with a {@link File} that points to it.
   */
  public Optional<File> validatedFile;

  /**
   * {@link ExpressionRealizer} that may be used to realize any Riskscape expressions required by
   * the bookmark.
   */
  public ExpressionRealizer getExpressionRealizer() {
    return getRealizationContext().getExpressionRealizer();
  }

  /**
   * {@link RealizationContext} that may be used to realize any Riskscape expressions required by
   * the bookmark.
   */
  public RealizationContext getRealizationContext() {
    return executionContext.getRealizationContext();
  }

  /**
   * shortcut for `problems.add(problem)`
   */
  public void add(Problem problem) {
    this.problems.add(problem);
  }

  /**
   * shortcut for bookmark.getLocation
   */
  public URI getLocation() {
    return bookmark.getLocation();
  }

  /**
   * @return the data type that the bookmark will produce given these parameters.  Will be returned from
   * {@link ResolvedBookmark#getDataType()}
   */
  public abstract Class<?> getDataType();

  /**
   * Default method for determining the scalar type of this bookmark data, which fetches the data and hopes that it's an
   * instanceof {@link SelfDescribingScalarData}, falling back to {@link Types#fromJavaType(Class)}.
   *
   * Feel free to override this to provide a possibly cheaper way of determining the scalar type without initializing
   * the data.
   *
   * If no java type matches, it'll return Types.ANYTHING.
   *
   * If the data isn't present, it returns Types.NOTHING
   */
  public Type getScalarType(ResolvedBookmarkImpl<?> resolved) {
    return resolved.getData(Object.class)
        .map(obj -> SelfDescribingScalarData.getScalarDataType(obj).orElse(Types.ANYTHING))
        .orElse(Types.NOTHING);
  }


  /**
   * Get the {@link Path} that should be resolved for the bookmark location.
   *
   * If the bookmark has a validated file, then that is used. Otherwise the
   * {@link ResourceFactory} is used to fetch the resource.
   *
   * @return path to bookmark location
   */
  public Path getBookmarkedPath() {
    if (validatedFile != null && validatedFile.isPresent()) {
      return validatedFile.map(f -> f.toPath()).get();
    }
    Resource resource = bindingContext.getEngine().getResourceFactory().load(getLocation());
    return BaseBookmarkResolver.resourceToPath(resource, executionContext);
  }

  /**
   * @return the {@link Project} that is associated via this {@link BookmarkParameters}'s {@link RealizationContext}
   */
  public Project getProject() {
    return getRealizationContext().getProject();
  }

  public ExecutionContext getExecutionContext() {
    return executionContext;
  }
}
