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

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import nz.org.riskscape.engine.typeset.LinkedType;
import nz.org.riskscape.util.ListUtils;

/**
 * The root interface for Riskscape's type system.  Each instance of type
 * offers a coerce method for checking that a given object corresponds to
 * the type.
 */
public interface Type {

  /**
   * Attempt to convert the given value in to one represented by this type.
   * @param value  The value to coerce
   * @return A value that conforms to this type
   * @throws CoercionException if the given object can not be converted to
   * something represented by this type
   */
  Object coerce(Object value) throws CoercionException;

  /**
   * The underlying java class used to represent this type.
   */
  Class<?> internalType();

  /**
   * Indicates if this {@link Type} is numeric. E.g {@link Integer}, {@link Floating} or {@link Decimal}.
   * @return true is this Type is a numeric type
   */
  default boolean isNumeric() {
    return Number.class.isAssignableFrom(internalType());
  }

  default void checkForNull(Object value) {
    if (value == null) {
      throw new CoercionException(value, this, "null is not a valid value for type " + this.toString());
    }
  }

  /**
   * @return the first type that actually holds the value (and is not just adding type metadata)
   */
  default Type getUnwrappedType() {
    if (this instanceof WrappingType) {
      return ((WrappingType) this).getUnderlyingType().getUnwrappedType();
    } else {
      return this;
    }
  }

  /**
   * Type-safe way to find a particular Type by recursing through this type and any types that it wraps.  This
   * doesn't (and shouldn't) consider types with member types, such as structs and lists - this is meant as a
   * more sound method of doing instanceof, considering {@link WrappingType}s
   */
  default <T extends Type> Optional<T> find(Class<T> type) {
    if (this.isA(type)) {
      return Optional.of(type.cast(this));
    } else if (this instanceof WrappingType) {
      WrappingType wthis = (WrappingType) this;
      return wthis.getUnderlyingType().find(type);
    } else if (this instanceof LinkedType) {
      LinkedType linkedType = (LinkedType) this;
      return linkedType.getUnderlyingType().find(type);
    } else {
      return Optional.empty();
    }
  }

  /**
   * Convenience for `Nullable.strip(this).find(type)`
   */
  default <T extends Type> Optional<T> findAllowNull(Class<T> type) {
    return Nullable.strip(this).find(type);
  }

  default <T extends Type> boolean isA(Class<T> type) {
    // allow instance of to be over-ridden - this allows exceptions to the normal rules (see linked types)
    return getClass().equals(type) || (type.isInterface() && type.isInstance(this));
  }

  /**
   * @return true if this type is a wrapping type
   */
  default boolean isWrapped() {
    return this != getUnwrappedType();
  }

  Struct asStruct();

  /**
   * Estimate the number of bytes used to serialize the given value to an output stream.
   * @param entry the value of this type to measure.  Must be of {@link #internalType()} or a {@link ClassCastException}
   * is going to happen
   * @return the estimated number of bytes, or zero if no estimation was possible.
   */
  int estimateSize(Object entry);

  void toBytes(DataOutputStream os, Object toWrite) throws IOException;

  Object fromBytes(DataInputStream in) throws IOException;

  /**
   * @return true if this type can be set to nothing
   *TODO this might need to be final and do an instanceof check *somewhere* - we always
   *want nullable to be on the outside
   */
  default boolean isNullable() {
    return false;
  }

  /**
   * A Riskscape specific toString of the given value, as an alternative to the java type's native toString
   * representation.
   */
  default String toString(Object value) {
    return Objects.toString(value);
  }

  /**
   * @return a {@link List} of all the types that are wrapped by this type, including this one, in depth-first-search
   *  order.  This will mean the simple unwrapped type is the first element of the list.
   */
  default List<Type> unwrap() {
    if (this instanceof WrappingType) {
      WrappingType wt = (WrappingType) this;
      return ListUtils.prepend(this, wt.getUnderlyingType().unwrap());
    } else {
      return Collections.singletonList(this);
    }
  }

  /**
   * Type specific visiting logic.  Types must decide whether they are atomic or compound and call the relevant method
   * on {@link TypeVisitor}.  It's up to each compound type to decide how they want to structure their children, e.g.
   * order, metadata, and what's considered a child or not.
   */
  <T, U> U visit(TypeVisitor<T, U> tv, T data);
}
