/*
 * 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.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import lombok.NonNull;
import nz.org.riskscape.engine.types.RelationType;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.TypeProblems;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * Links a {@link Bookmark} to a {@link BookmarkResolver} in order to access the useful data.
 * A {@link ResolvedBookmark} indicates that a {@link BookmarkResolver} has said that the bookmark looks like it
 * can be accessed by a particular resolver.  However, the {@link BookmarkResolver} may already have spotted errors
 * with the bookmark that prevent it being opened, such as a missing or invalid option.  These sorts of errors
 * should be returned by the {@link #validate()} method.
 *
 * A {@link ResolvedBookmark} can also return any failure information when the actual data was opened, in addition to
 * any validation {@link Problem}s.  These should be returned alongside the validation errors in the problems
 * associated with the {@link #getData(Class)} method.
 *
 * It is expected that implementations will not attempt to reopen a bookmark with each call to access the data, so
 * implementations are free to memoize any validation errors or constructed objects.
 */
public interface ResolvedBookmark {
  /**
   * Useful testing constructor to return a pre-constructed Object with a fake Bookmark object that
   * has the desired bookmarkId.
   */
  static ResolvedBookmark withId(String bookmarkId, Object object) {
    return withId(bookmarkId, object, Collections.emptyList(), Collections.emptyList());
  }

  /**
   * Useful testing constructor to return a pre-constructed Object with a fake Bookmark object that
   * has the desired bookmarkId.
   */
  static ResolvedBookmark withId(
      @NonNull String bookmarkId,
      @NonNull Object object,
      @NonNull List<Problem> dataProblems,
      @NonNull List<Problem> validationProblems
  ) {
    // we must assign a location to our bookmark, otherwise resolving will fail ('cos of a slightly dubious assertion
    // at the beginning of DefaultBookmarkResolver that bookmarks must have a location)
    URI pseudoUri = URI.create("test:" + bookmarkId);
    Bookmark bookmark = new Bookmark(bookmarkId, null, null, pseudoUri, Collections.emptyMap());

    return stub(bookmark, object, dataProblems, validationProblems);
  }

  /**
   * Useful testing constructor to return a pre-constructed Object derived from the given Bookmark
   */
  static ResolvedBookmark stub(
      @NonNull Bookmark bookmark,
      @NonNull Object object
  ) {
    return stub(bookmark, object, List.of(), List.of());
  }

  /**
   * Useful testing constructor to return a pre-constructed Object with the given Bookmark
   */
  static ResolvedBookmark stub(
      @NonNull Bookmark bookmark,
      @NonNull Object object,
      @NonNull List<Problem> dataProblems,
      @NonNull List<Problem> validationProblems
  ) {

    // rather than return anything, we throw here, as this is used for tests and it'll be useful to get feedback on
    // un-mapped types
    Type scalarType = SelfDescribingScalarData.getScalarDataType(object).get();

    return new ResolvedBookmark() {

      @Override
      public <T> Optional<ResultOrProblems<T>> getIfType(Class<T> requiredType) {
        if (requiredType.isInstance(object)) {
          return Optional.of(ResultOrProblems.of(requiredType.cast(object), dataProblems));
        } else {
          return Optional.empty();
        }
      }

      @Override
      public Class<?> getDataType() {
        return object.getClass();
      }

      @Override
      public Bookmark getBookmark() {
        return bookmark;
      }

      @Override
      public Type getScalarType() {
        return scalarType;
      }

      @Override
      public List<Problem> validate() {
        return validationProblems;
      }
    };
  }

  /**
   * Shortcut for{@link #getBookmark()} and {@link Bookmark#getId()}
   * @return the id of the {@link Bookmark}
   */
  default String getId() {
    return getBookmark().getId();
  }

  /**
   * @return the Bookmark that has been resolved
   */
  Bookmark getBookmark();

  /**
   * @return the underlying data in the required type, or empty with an error if the data isn't of that type
   * the result may contain errors that were encountered when trying to open the data with the given options
   * which might be further to those that were encountered during validation.
   *
   * If {@link #validate()} returned errors, then this method should return an empty result with an error
   * saying there were validation errors stopping the data from being accessed
   */
  default <T> ResultOrProblems<T> getData(Class<T> requiredType) {
    return getIfType(requiredType).orElse(ResultOrProblems.failed(
        Problems.get(TypeProblems.class).mismatch(this.getBookmark(), requiredType, getDataType())));
  }

  /**
   * Performs a conditional cast of the resolved thing, even if there are validation issues that stopped the data
   * from being accessed
   * If {@link #validate()} returned errors, then this method should return an empty result with an error
   * saying there were validation errors stopping the data from being accessed
   * @return {@link Optional#empty()} if the wrong type, or an optional of the required type.
   */
  <T> Optional<ResultOrProblems<T>> getIfType(Class<T> requiredType);

  /**
   * @return the type of the resolved thing, regardless of whether it was successfully built or not.
   */
  Class<?> getDataType();

  /**
   * @return true if the resolved thing is of the given type
   */
  default boolean isType(Class<?> requiredType) {
    return getIfType(requiredType).isPresent();
  }

  /**
   * @return a {@link List} of {@link Problem}s encountered when performing a check of the bookmark's options.
   * Implementations should avoid checking the data itself at this point, so that this can remain a "light" operation.
   */
  List<Problem> validate();

  /**
   * Returns the RiskScape type that represents this data when extracted from a project and added in to a pipeline or
   * expression as a scalar value.
   *
   * It is referred to as the scalar type to make it clear it's not the same as the {@link Type} of the data contained
   * within it, e.g. the {@link Struct} type of the relation (non-scalar) vs {@link RelationType} that represents the
   * relation itself (scalar).
   */
  Type getScalarType();

  /**
   * @return true if there are problems returned from validation that are errors (or worse)
   */
  default boolean hasValidationErrors() {
    return Problem.hasErrors(validate());
  }

}
