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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.RiskscapeException;

import org.geotools.factory.CommonFactoryFinder;
import org.geotools.api.filter.Filter;
import org.geotools.api.filter.expression.PropertyName;

import lombok.extern.slf4j.Slf4j;
import nz.org.riskscape.engine.gt.ConvertFilter;
import nz.org.riskscape.engine.types.Struct.StructMember;
import org.geotools.api.filter.And;
import org.geotools.api.filter.Or;

/**
 * Supports property renamings/transformations when applying a filter to a projected relation.
 *
 * Parts of the filter subtree may be removed if they cannot be transformed and doing so would not narrow the
 * results to far.
 */
@Slf4j
public class RenameFilter extends ConvertFilter {
  private final Map<String, String> targetBackToSource;

  public enum Outcome {
    /**
     * None of the filter could be renamed.
     */
    NONE,
    /**
     * Parts of the input filter have been excluded.
     */
    PARTIAL,
    /**
     * All of the input filter is renamed.
     */
    COMPLETE;
  }

  @RequiredArgsConstructor
  public static class Result {
    /**
     * The result of rename conversion.
     */
    @Getter
    private final Filter filter;
    /**
     * Indicates to what extent filter reflects the input filter. If not COMPLETE then other steps
     * could be taken to ensure the desired filtering is achieved.
     */
    @Getter
    private final Outcome outcome;
  }

  public RenameFilter(Map<StructMember, StructMember> renamings) {
    super(CommonFactoryFinder.getFilterFactory());
    // invert map so that we go from target to source and map member to strings
    this.targetBackToSource = renamings.entrySet()
        .stream()
        // null value means there was no a->b mapping of attributes
        .filter(entry -> entry.getValue() != null)
        .collect(Collectors.toMap(e -> e.getValue().getKey(), e -> e.getKey().getKey()));
  }

  /**
   * Converts a {@link Filter} to one with any renamings applied to property expressions.
   *
   * This conversion process may exclude parts of the filter tree that are not able to be converted, and return a
   * partial filter. Should this occur warnings will be included.
   *
   * @param original filter to convert
   * @return converted filter and any problems encountered
   */
  protected Result convert(Filter original) {
    //passed to visit methods as extraData for them to increment if they should remove part of the filter.
    AtomicInteger droppedFilterParts = new AtomicInteger();
    try {
      Filter converted = (Filter) original.accept(this, droppedFilterParts);
      Outcome outcome = droppedFilterParts.get() <= 0 ? Outcome.COMPLETE : Outcome.PARTIAL;
      return new Result(converted, outcome);
    } catch (UnmappedExpressionException e) {
      log.debug("Could not apply renamings {} to {}", targetBackToSource, original);
      return new Result(null, Outcome.NONE);
    }
  }

  @Override
  public Object visit(PropertyName expression, Object extraData) {
    String mapped = targetBackToSource.get(expression.getPropertyName());
    if (mapped != null) {
      return filterFactory.property(mapped);
    } else {
      throw new UnmappedExpressionException(String.format("%s cannot be mapped", expression.toString()));
    }
  }

  @Override
  public Object visit(Or filter, Object extraData) {
    List<Filter> children = new ArrayList<>();
    for (Filter child: filter.getChildren()) {
      children.add((Filter)child.accept(this, extraData));
    }
    //We return a reconstructed OR filter of the children because there could be changes in the filter parts.
    return filterFactory.or(children);
  }

  @Override
  public Object visit(And filter, Object extraData) {
   List<Filter> children = new ArrayList<>();
    for (Filter child: filter.getChildren()) {
      try {
        children.add((Filter)child.accept(this, extraData));
      } catch (UnmappedExpressionException e) {
        ((AtomicInteger)extraData).incrementAndGet();
      }
    }
    if (children.isEmpty()) {
      //If there are no good children we throw not target exception up higher.
      throw new UnmappedExpressionException("Filter has no parts that can to lifted. Filter: " + filter.toString());
    } else if (children.size() == 1) {
      //Only one so no need to wrap in and filter
      return children.get(0);
    }
    return filterFactory.and(children);
  }

  private class UnmappedExpressionException extends RiskscapeException {

    UnmappedExpressionException(String message) {
      super(message);
    }

  }
}
