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

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import nz.org.riskscape.engine.RiskscapeException;

public class ReflectionUtils {

  /**
   * @return all fields annotated with the desired annotation in the class hierarchy of the given class
   */
  public static List<Field> getAnnotatedFields(Class<?> parameterClass, Class<? extends Annotation> annotationClass) {
    List<Field> annotated = Arrays.asList(parameterClass.getDeclaredFields())
      .stream()
      .filter(field -> field.isAnnotationPresent(annotationClass))
      .collect(Collectors.toList());

    Class<?> superClass = parameterClass.getSuperclass();
    if (superClass != null) {
      List<Field> extra = getAnnotatedFields(superClass, annotationClass);
      extra.addAll(annotated);
      return extra;
    } else {
      return annotated;
    }
  }

  /**
   * @return all interfaces that a class implements by following the class hierarchy up to object.
   *
   * It does not include
   * interfaces that are inherited by implemented interfaces.  E.g. class foo implements bar.  interface bar extends
   * baz, getInterfaces(Foo.class) returns bar, but not baz.
   */
  public static List<Class<?>> getInterfaces(Class<?> clazz) {
    List<Class<?>> interfaces = Lists.newArrayList();

    while (clazz != Object.class) {
      interfaces.addAll(Arrays.asList(clazz.getInterfaces()));
      clazz = clazz.getSuperclass();
    }

    return interfaces;
  }

  /**
   * Search through both classes hierarchies, looking for the most recent ancestor that is either equal to `lookFor` or
   * an ancestor that implements `lookFor`.  See ReflectionUtilsTest for examples.
   * @param lhs a type to search through
   * @param rhs another type to search through
   * @param lookFor either a parent class in the shared ancestry, or an interface a shared ancestor should implement.
   * @return empty if lhs and rhs have no common ancestor of lookFor.  If they have a common ancestor that is either
   * exactly lookFor, or implements lookFor, then the ancestor is returned.
   */
  public static Optional<Class<?>> findCommonAncestorOfType(Class<?> lhs, Class<?> rhs, Class<?> lookFor) {
    // get lists of each classes ancestors, from Object to specific type
    Iterator<Class<?>> lhsHierarchy = hierarchy(lhs).iterator();
    Iterator<Class<?>> rhsHierarchy = hierarchy(rhs).iterator();

    // now 'zip' the lists, breaking when they no longer match -
    List<Class<?>> members = Lists.newArrayList();
    while (lhsHierarchy.hasNext() && rhsHierarchy.hasNext()) {
      Class<?> lhsPtr = lhsHierarchy.next();
      Class<?> rhsPtr = rhsHierarchy.next();

      if (lhsPtr.equals(rhsPtr)) {
        members.add(lhsPtr);
      } else {
        break;
      }
    }
    // we now have a list of shared ancestors from most specific to Object
    Collections.reverse(members);

    // we go through that list of shared ancestry, looking for `lookFor`
    for (Class<?> ancestor : members) {
      if (ancestor.equals(lookFor) || Sets.newHashSet(ancestor.getInterfaces()).contains(lookFor)) {
        return Optional.of(ancestor);
      }
    }

    return Optional.empty();
  }

  private static List<Class<?>> hierarchy(Class<?> class3) {

    List<Class<?>> toReturn = new ArrayList<>();
    Class<?> ptr = class3;
    do {
      toReturn.add(ptr);
      ptr = ptr.getSuperclass();
    } while (ptr != null);

    Collections.reverse(toReturn);

    return toReturn;
  }

  public enum SearchOptions {
    /**
     * will search through interfaces for the desired interface, as well as classes
     */
    SEARCH_INTERFACES,
  }


  /**
   * Search through a class's hierarchy for an interface, returning the class or interface that implemented it.  See
   * ReflectionUtilsTest for more details.
   * @param <T> The type of the interface we're looking for
   * @param iface the class instance for the interface we're looking for
   * @param search where to start searching from
   * @param optionsArray search options
   * @return The implementing class.  Will never return null, but can throw a {@link RiskscapeException} if the
   * interface is implemented multiple times or is not found given the {@link SearchOptions}.
   */
  @SuppressWarnings("unchecked")
  public static <T> Class<? extends T> findImplementingClass(
      Class<T> iface,
      Class<? extends T> search,
      SearchOptions... optionsArray
  ) {
    List<SearchOptions> options = Arrays.asList(optionsArray);
    ArrayList<Class<?>> toSearch = new ArrayList<>();
    toSearch.add(search);
    Set<Class<? extends T>> found = new HashSet<>();

    while (!toSearch.isEmpty()) {
      Class<?> searching = toSearch.remove(0);

      Class<?> parent = searching.getSuperclass();
      if (parent != null && parent != Object.class) {
        toSearch.add(parent);
      }
      Class<?>[] interfaces = searching.getInterfaces();

      if (interfaces != null) {
        for (Class<?> candidateIface : searching.getInterfaces()) {
          if (candidateIface == iface) {
            found.add((Class<? extends T>) searching);
          } else {
            if (options.contains(SearchOptions.SEARCH_INTERFACES)) {
              toSearch.add(candidateIface);
            }
          }
        }
      }
    }

    if (found.size() == 1) {
      return found.iterator().next();
    } else {
      // this is a coding error - all Realized things should implement exactly one realized interface
      throw new RiskscapeException(String.format(
          "Expected class %s to implement %s exactly once but was implemented by: %s",
          search,
          iface,
          found));
    }
  }

  /**
   * Calls `clazz.newInstance`, wrapping the checked exceptions in an unchecked runtime exception
   */
  public static <T> T newInstance(Class<T> clazz) {
    return newInstance(clazz, e -> new RuntimeException("Failed to create an instance of class " + clazz, e));
  }

  /**
   * Calls `clazz.newInstance`, wrapping the checked exceptions in an exception provided from `constructor`
   */
  public static <T, E extends Exception> T newInstance(Class<T> clazz, Function<Exception, E> constructor) throws E {
    try {
      return clazz.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
      throw constructor.apply(e);
    }
  }

  /**
   * Calls field.set(instance, value), wrapping the checked exception in an unchecked runtime exception
   *
   * Also ensures that the field is set to accessible before attempting to set the value.
   */
  public static void setField(Field field, Object instance, Object value) {
    if (!field.isAccessible()) {
      field.setAccessible(true);
    }

    try {
      field.set(instance, value);
    } catch (IllegalArgumentException | IllegalAccessException e) {
      throw new RuntimeException("Unable to set value to field " + field, e);
    }
  }

  /**
   * Very simple public field lookup method that returns empty if no such field exists
   */
  public static Optional<Field> getPublicField(Class<?> clazz, String fieldName) {
    try {
      return Optional.of(clazz.getField(fieldName));
    } catch (NoSuchFieldException e) {
      return Optional.empty();
    }
  }

  public static <T> Class<T> findParameterClass(Class<?> subclass) {
    return findParameterClass(subclass, 0);

  }
  /**
   * Extracts the parameterized type (The `T` from `MyClass<T>`) from a parameterized subclass (e.g.
   * `Foo extends MyClass<Bar>`).  Normally, java's generics are runtime only, but subclasses keep
   * their declared parameter types in their class metadata, and these are available in the reflection API - this
   * method will extract a parameterized type and return it, as well as fudging the casting.
   * @param subclass a class that declares type arguments
   * @param parameterIndex the index of the declared type argument
   */
  @SuppressWarnings("unchecked")
  public static <T> Class<T> findParameterClass(Class<?> subclass, int parameterIndex) {
    ParameterizedType genericSuperclass;
    try {
      genericSuperclass = (ParameterizedType) subclass.getGenericSuperclass();
    } catch (ClassCastException e) {
      throw new RuntimeException("Parameterized classes must declare a generic type: " + subclass, e);
    }

    try {
      return (Class<T>) genericSuperclass.getActualTypeArguments()[parameterIndex];
    } catch (ArrayIndexOutOfBoundsException ex) {
      throw new RuntimeException("Parameterized classes must declare a generic type: " + subclass, ex);
    }
  }
}
