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

import java.util.function.Predicate;

import nz.org.riskscape.engine.rl.ExpressionRealizer;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.rl.TokenTypes;
import nz.org.riskscape.rl.ast.BinaryOperation;
import nz.org.riskscape.rl.ast.PropertyAccess;

import lombok.RequiredArgsConstructor;

/**
 * Abstract {@link JoinIndexer} for creating indexers that perform some kind of comparison with
 * a boolean yielding {@link RealizedExpression}. Most likely lhs-rhs comparison of some kind.
 */
public abstract class RealizedExpressionJoinIndexer extends JoinIndexer {

  /**
   * Determines if a {@link RealizedExpression} accesses one side of the join, but not the other.
   */
  @RequiredArgsConstructor
  private static class RealizedExpressionTest {

    static boolean matches(RealizedExpression toTest, Predicate<String> firstNodeTest) {
      RealizedExpressionTest tester = new RealizedExpressionTest(firstNodeTest);
      tester.testPropertyExpression(toTest);
      return tester.matches();
    }

    private final Predicate<String> firstNodeTest;
    private boolean foundMatchedPropertyAccess;
    private boolean foundUnmatchedPropertyAccess;

    boolean matches() {
      //matches if we found the property access we are looking for, and none that we weren't
      return foundMatchedPropertyAccess && !foundUnmatchedPropertyAccess;
    }

    /**
     * Determines if the input expression only accesses structs(via property accesses) that only
     * match propertyAccessFirstPathTest
     *
     * @param input to test
     */
    private void testPropertyExpression(RealizedExpression input) {
      //Need to access the desired property to pass
      if (input.getExpression() instanceof PropertyAccess) {
        PropertyAccess pa = (PropertyAccess) input.getExpression();
        if (!pa.getReceiver().isPresent()) {
          //We don't check property accesses that have a receiver, we only want ones that are accessing
          //structs directly
          if (firstNodeTest.test(pa.getIdentifiers().get(0).getValue())) {
            foundMatchedPropertyAccess = true;
          } else {
            foundUnmatchedPropertyAccess = true;
          }
        }

      }
      for (RealizedExpression dep : input.getDependencies()) {
        //recurse in dependencies so we find all the property accesses.
        testPropertyExpression(dep);
      }
    }

  }

  /**
   * Yields the lhs value of the join condition - used for querying the index once built
   */
  protected RealizedExpression lhsExpression;


  /**
   * Expression yielding the rhs value - this will be the indexed object
   */
  protected RealizedExpression rhsExpression;

  /**
   * The comparison operator between lhs and rhs.
   */
  protected RealizedExpression operator;

  public RealizedExpressionJoinIndexer(Join join, ExpressionRealizer expressionRealizer) {
    super(join, expressionRealizer);
    processIndexableMetadata();
  }

  /**
   * Validates that {@link RealizedExpression} is able to be used for indexing.
   *
   * The minimum requirement is the expression must return boolean.
   *
   * @param expression to check
   * @return true if expression can be applied to this indexer
   */
  protected boolean isAllowed(RealizedExpression expression) {
    return Nullable.strip(expression.getResultType()).equals(Types.BOOLEAN);
  }

  @Override
  public boolean isUsable() {
    return this.rhsExpression != null && this.lhsExpression != null;
  }

  /**
   * Inspects the {@link JoinCondition} to determine if it is suitable for indexing.
   *
   * If it is then the lhs and rhs Expressions will be set.
   */
  protected final void processIndexableMetadata() {

    // check join is compatible
    if (!(join.getOn() instanceof ExpressionJoinCondition)) {
      return;
    }

    ExpressionJoinCondition filtered = (ExpressionJoinCondition) join.getOn();

    processFilter(filtered.getExpression());
  }

  /**
   * Checks the filter out for suitability as well as memoizing a few fields for later use
   *
   * @param filter
   */
  private void processFilter(RealizedExpression filter) {
    if (filter.getExpression() instanceof BinaryOperation) {
      BinaryOperation operation = (BinaryOperation) filter.getExpression();
      if (operation.getNormalizedOperator() == TokenTypes.OR) {
        //you can't index with an or condition because the other side may evaluate true
        return;
      }

      if (operation.getNormalizedOperator() == TokenTypes.AND) {
        // we need to pick one child to be the indexed one - maybe just the first one that is a Binary comparison?
        for (RealizedExpression childFilter : filter.getDependencies()) {
          if (isAllowed(childFilter)) {
            processFilter(childFilter);
            if (isUsable()) {
              //This child is usable we are done. Otherwise keep looking
              return;
            }
          }
        }
        //And expression has no children that are applicable. So we bail.
        return;
      }
    }

    if (!isAllowed(filter)) {
      return;
    }

    //Now we are good, set up the required realized expresssions.
    this.operator = filter;

    RealizedExpression effectiveConstantExpression = findEffectiveConstantExpression(operator);
    RealizedExpression indexableExpression = findIndexableExpression(operator);
    if (effectiveConstantExpression == null || indexableExpression == null) {
      return;
    }
    this.lhsExpression = expressionRealizer.realize(
        join.getLhs(),
        effectiveConstantExpression.getExpression()
    ).orElse(null);

    this.rhsExpression = expressionRealizer.realize(
        join.getRhs(),
        indexableExpression.getExpression()
    ).orElse(null);
  }

  /**
   * Find the dependency of comparisionOperator that only accesses the LHS of the join.
   *
   * This could be a direct property access like 'lhs.value' or a function like
   * 'strLength(lhs.value)'
   *
   * @param comparisonOperator expression to find LHS yeilding expression from
   * @return
   */
  private RealizedExpression findEffectiveConstantExpression(RealizedExpression comparisonOperator) {
    for (RealizedExpression dep: comparisonOperator.getDependencies()) {
      if (RealizedExpressionTest.matches(dep, firstPath -> join.getLhs().hasMember(firstPath))) {
        return dep;
      }
    }
    return null;
  }

  /**
   * Find the dependency of comparisionOperator that only accesses the RHS of the join.
   *
   * This could be a direct property access like 'rhs.value' or a function like
   * 'strLength(rhs.value)'
   *
   * @param comparisonOperator expression to find RHS yeilding expression from
   * @return
   */
  private RealizedExpression findIndexableExpression(RealizedExpression comparisonOperator) {
    for (RealizedExpression dep: comparisonOperator.getDependencies()) {
      if (RealizedExpressionTest.matches(dep, firstPath -> join.getRhs().hasMember(firstPath))) {
        return dep;
      }
    }
    return null;
  }

}
