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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import org.geotools.api.filter.expression.ExpressionVisitor;
import org.geotools.api.filter.expression.PropertyName;
import org.xml.sax.helpers.NamespaceSupport;

import org.locationtech.jts.geom.Geometry;

import lombok.EqualsAndHashCode;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.query.TupleUtils;
import nz.org.riskscape.engine.query.TupleUtils.FindOption;
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.ResultOrProblems;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;


/**
 * Access properties by path inside riskscape Tuples
 *
 * # Thread Safety
 *
 * This class is not thread-safe, but is probably safe to use in some specific circumstances.  It is known not to work
 * and generally perform poorly when a) the same expression is used to access tuples of different types b) that is done
 * across different threads (which can cause IllegalArgumentExceptions to be thrown).  In these cases, it's best to
 * use the {@link nz.org.riskscape.engine.rl.ExpressionRealizer} to rebuild and expression or a filter against a
 * specific struct and use this.  It will perform quicker and fail fast in cases of type mismatch.
 */
@EqualsAndHashCode
public class StructAccessExpression implements PropertyName, TypedExpression {

  public static final String SPLIT_ON = "\\.";
  public static final String SPLIT_ON_UNESCAPED = ".";

  private final String propertyName;
  private final List<String> segments;
  // delegate to this for faster access
  private StructMemberAccessExpression structAccess;

  public StructAccessExpression(String propertyName) {
    this.propertyName = propertyName;
    this.segments = Arrays.asList(propertyName.split(SPLIT_ON));
  }

  public StructAccessExpression(String... segmentsParam) {
    this(Arrays.asList(segmentsParam));
  }

  public StructAccessExpression(List<String> segments) {
    this.segments = segments;
    this.propertyName = this.segments.stream().collect(Collectors.joining("."));
  }

  /**
   * Creates a new struct access expression by adding additionalPath to this one.
   * @param additionalPath additional path element
   * @return new struct access expression
   */
  public StructAccessExpression and(String additionalPath) {
    List<String> newSegments = new ArrayList<>();
    this.segments.stream().forEach(s -> newSegments.add(s));
    newSegments.add(additionalPath);
    return new StructAccessExpression(Collections.unmodifiableList(newSegments));
  }

  @Override
  public ResultOrProblems<Type> evaluateType(Type sourceType) {
    return StructMemberAccessExpression.build(sourceType, segments)
          .flatMap((expr, problems) -> expr.evaluateType(sourceType));
  }

  @Override
  public Object evaluate(Object object) {
    if (object == null) {
      return null;
    }
    if (object instanceof Tuple) {
      return evaluate((Tuple)object);
    } else {
      throw new IllegalArgumentException("this expression extracts properties from riskscape Tuple objects, can "
          + "not work with " + object);
    }
  }

  private Object evaluate(Tuple map) {
    if (structAccess == null || map.getStruct() != structAccess.getRootStruct()) {
      structAccess = StructMemberAccessExpression.build(map.getStruct(), segments).get();
    }

    return structAccess.evaluate(map);
  }

  @SuppressWarnings("unchecked")
  @Override
  public <T> T evaluate(Object object, Class<T> context) {
    // we could possible support Value wrapping here, if we cared about it
    Object raw = evaluate(object);

    // here we provide a convenience where if context is geometry and the fetched property is a tuple, we treat it like
    // a feature, which has a natural location, and return the geometry only
    // TODO reuse the converter api?
    if (Geometry.class.isAssignableFrom(context) && (raw instanceof Tuple)) {
      Tuple fetched = (Tuple) raw;
      StructMember geometryMember = TupleUtils.findGeometryMember(fetched.getStruct(), FindOption.ONE_REQUIRED, ()
          -> new IllegalArgumentException(String.format(
            "Geometry requested, but tuple does not contain a geometry member: %s",
            fetched.getStruct())));

      return fetched.fetch(geometryMember);
    } else if (raw != null && !context.isInstance(raw)){
      Type mappedType = Nullable.of(Types.fromStrictJavaTypeOptional(context).orElseThrow(()
          -> new ClassCastException("Unsupported type for coercion - " + context)));

      return (T) mappedType.coerce(raw);
    } else {
      return (T) raw;
    }
  }

  @Override
  public String toString() {
    return this.propertyName;
  }

  @Override
  public Object accept(ExpressionVisitor visitor, Object extraData) {
    return visitor.visit(this, extraData);
  }

  @Override
  public String getPropertyName() {
    return this.propertyName;
  }

  public List<String> getSegments() {
    return Collections.unmodifiableList(this.segments);
  }

  /**
   * Shortcut to {@link StructMemberAccessExpression#build(Type, List)}
   */
  public ResultOrProblems<StructMemberAccessExpression> getExpressionFor(Struct sourceType) {
    return StructMemberAccessExpression.build(sourceType, segments);
  }
  /**
   * @return a possibly null {@link StructMemberAccessExpression} that has been built to make subsequent lookups faster
   */
  public StructMemberAccessExpression getCachedExpression() {
    return structAccess;
  }

  /**
   * Set the structAccess to use for faster expression evalution.  Mostly here for testing/spy purposes, hence package
   * level visibility.
   */
  void setCachedExpression(StructMemberAccessExpression ex) {
    this.structAccess = ex;
  }

  @Override
  public NamespaceSupport getNamespaceContext() {
    return null;
  }

}
