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

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.rl.ExpressionRealizer;
import nz.org.riskscape.engine.sort.SortBy.Direction;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemCode;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.engine.types.Type;

/**
 * Abstract base class for sorting.
 */
public class TupleComparator {

  public enum ProblemCodes implements ProblemCode {
    /**
     * When the type produced by expression is not comparable.
     */
    EXPRESSION_RESULT_NOT_COMPARABLE,
  }

  public static final Comparator<Tuple> NONE = (l, r) -> 0;

  /**
   * Build a tuple comparator for {@link Tuple}s of {@link Struct} type.
   * @param targetType type of struct that will be compared
   * @param sortBy to sort tuples in order of precedence
   * @param expressionRealizer to realize expressions with
   * @return ResultOrProblems indicating success or otherwise, with any problems encountered.
   */
  public static ResultOrProblems<Comparator<Tuple>> createComparator(Struct targetType, final SortBy sortBy,
      ExpressionRealizer expressionRealizer) {
    List<Problem> problems = new ArrayList<>();
    Comparator<Tuple> comparator = NONE;
    SortBy next = sortBy;

    while (!next.equals(SortBy.NONE)) {
      ResultOrProblems<Comparator<Tuple>> nextComparator = comparing(next, targetType, expressionRealizer);
      if (nextComparator.isPresent()) {
        if (comparator == NONE) {
          comparator = nextComparator.get();
        } else {
          comparator = comparator.thenComparing(nextComparator.get());
        }
      }
      problems.addAll(nextComparator.getProblems());
      next = next.getNext();
    }
    if (Problem.hasErrors(problems)) {
      return ResultOrProblems.failed(problems);
    }
    return ResultOrProblems.ofNullable(comparator, problems);
  }

  /**
   * Constructs a single comparator for the {@link SortBy}.
   * @param comparison to make
   * @param tupleType {@link Struct} type that will be evaluated against
   * @param expressionRealizer to realize expressions with
   * @return comparator and/or any problems encountered
   */
  private static ResultOrProblems<Comparator<Tuple>> comparing(SortBy comparison, Struct tupleType,
      ExpressionRealizer expressionRealizer) {
    return expressionRealizer.realize(tupleType, comparison.getExpr())
        .flatMap(realizedExpression -> {

          Type comparedType = Nullable.unwrap(realizedExpression.getResultType());
          if (! isComparable(comparedType, true)) {
            return ResultOrProblems.failed(
                Problem.error(ProblemCodes.EXPRESSION_RESULT_NOT_COMPARABLE,
                    realizedExpression.getExpression().toSource(), comparedType));
          }

          Comparator<Tuple> newComparator = (t1, t2) -> {
            //We evaluate the expression and use a Nullable of the expected type to coerce the result to ensure that
            //the compared values are both of the same type.
            //This will give us either null or an Object of the underlying type, which itself is Comparable.
            Type nullableType = Nullable.of(comparedType);
            Object lhs = nullableType.coerce(realizedExpression.evaluate(t1));
            Object rhs = nullableType.coerce(realizedExpression.evaluate(t2));

            return stableCompareTo(lhs, rhs);
          };
          if (comparison.getDirection() == Direction.DESC) {
            newComparator = newComparator.reversed();
          }
          return ResultOrProblems.of(newComparator);
        });
  }

  private static boolean isComparable(Type toCompare, boolean allowTuples) {
    if (allowTuples && toCompare instanceof Struct) {
      Struct asStruct = (Struct)toCompare;
      for (StructMember member: asStruct.getMembers()) {
        if (! isComparable(Nullable.strip(member.getType()), false)) {
          return false;
        }
      }
      // all members are comparable
      return true;
    }
    return Comparable.class.isAssignableFrom(toCompare.internalType());
  }

  /**
   * Compares two object using the comparable interface or if a tuple using it's members comparable interface.
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  private static int stableCompareTo(Object lhs, Object rhs) {
    if (lhs == null || rhs == null) {
      if (lhs == null && rhs == null) {
        return 0;
      } else if (lhs == null) {
        return -1;
      }
      return 1;
    }
    if (lhs instanceof Comparable) {
      return ((Comparable) lhs).compareTo(rhs);
    } else if (lhs instanceof Tuple) {
      int signum = 0;
      Tuple lhsTuple = (Tuple) lhs;
      Tuple rhsTuple = (Tuple) rhs;
      for (Struct.StructMember member : lhsTuple.getStruct().getMembers()) {
        Object lhsMember = lhsTuple.fetch(member);
        Object rhsMember = rhsTuple.fetch(member);

        signum = stableCompareTo(lhsMember, rhsMember);

        if (signum != 0) {
          return signum;
        }
      }

      return signum;
    } else {
      throw new IllegalArgumentException("Can not cast to comparable or tuple " + lhs.getClass());
    }
  }
}
