/*
 * 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.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

import nz.org.riskscape.ReflectionUtils;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.io.TypeIO;
import nz.org.riskscape.engine.io.TypeIOBuilder;
import nz.org.riskscape.engine.io.TypeIOConstructor;
import nz.org.riskscape.engine.typexp.AST.Symbol;
import nz.org.riskscape.engine.typexp.TypeBuilder;
import nz.org.riskscape.engine.typexp.TypeBuildingException;
import nz.org.riskscape.engine.typexp.TypeConstructor;

/**
 * Represents the simplest single-value type, e.g. integer, where any instance of the type
 * is equal to any other instance
 */
public abstract class SimpleType implements Type, TypeIO, TypeIOConstructor, TypeConstructor {

  public static final String DEFAULT_MEMBER_NAME = "value";
  private static final Map<Class<? extends SimpleType>, SimpleType> INSTANCES = new ConcurrentHashMap<>();
  private static final Map<Class<? extends SimpleType>, TypeInformation> TYPE_INFORMATION = new ConcurrentHashMap<>();

  /**
   * @return a singleton instance of a particular {@link SimpleType}.  {@link SimpleType}s only need one instance - this
   * is their defining characteristic
   */
  @SuppressWarnings("unchecked")
  public static final <T extends SimpleType> T getInstance(Class<T> clazz) {
    return (T) INSTANCES.computeIfAbsent(clazz, c -> ReflectionUtils.newInstance(
        clazz,
        e -> new RiskscapeException("Simple types must declare a public no-arg constructor - " + c, e)
    ));
  }

  /**
   * @return the {@link TypeInformation} for a particular {@link SimpleType} class
   */
  public static final TypeInformation getTypeInformation(Class<? extends SimpleType> clazz) {
    return TYPE_INFORMATION.computeIfAbsent(clazz, c -> {
      SimpleType instance = getInstance(clazz);
      return new TypeInformation(
          instance.getTypeInformationId(),
          c,
          instance.internalType(),
          instance,
          Optional.of(instance)
      );
    });
  }

  /**
   * @return true if typeToTest is a SimpleType, without any wrapping.  A glorified `instanceof`, but wrapped in an API
   */
  public static boolean isSimpleType(Type typeToTest) {
    return typeToTest instanceof SimpleType;
  }

  private final Struct structed = Struct.of(DEFAULT_MEMBER_NAME, this);

  @Override
  public final boolean equals(Object rhs) {
    return this.getClass().equals(rhs == null ? rhs : rhs.getClass());
  }

  @Override
  public final int hashCode() {
    return this.getClass().hashCode();
  }

  @Override
  public final Struct asStruct() {
    return structed;
  }

  @Override
  public final String toString() {
    return getClass().getSimpleName();
  }

  @Override
  public final TypeIO build(Type type, TypeIOBuilder builder) {
    return this;
  }

  @Override
  public final Type writesType() {
    return this;
  }

  @Override
  public Type construct(TypeBuilder typeBuilder, Symbol symbol) throws TypeBuildingException {
    return INSTANCES.computeIfAbsent(this.getClass(), clazz -> {
      try {
        return this.getClass().newInstance();
      } catch (InstantiationException | IllegalAccessException e) {
        throw new TypeBuildingException("Simple types must declare a public no-arg constructor - " + this.getClass());
      }
    });
  }

  /**
   * @return a description string to use for this {@link SimpleType}s {@link TypeInformation} object.
   */
  protected String getTypeInformationDescription() {
    return String.format("Wraps a java %s type", internalType().getSimpleName());
  }

  /**
   * @return an identifier for this {@link SimpleType}s {@link TypeInformation} object.
   */
  protected String getTypeInformationId() {
    return getClass().getSimpleName().toLowerCase();
  }

  @Override
  public <T, U> U visit(TypeVisitor<T, U> tv, T data) {
    // XXX do we ever want to allow a simple type to not be atomic?  We might feel comfortable in the future to mark
    // this method as final as a way of putting a more solid stake in the ground than a feeble comment
    return tv.atomicType(this, data);
  }

}
