/*
 * 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.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import org.geotools.util.Converters;
import org.locationtech.jts.geom.Geometry;
import org.geotools.api.filter.expression.ExpressionVisitor;
import org.geotools.api.filter.expression.PropertyName;
import org.xml.sax.helpers.NamespaceSupport;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;

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.Problem;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.rl.ExpressionParser;
import nz.org.riskscape.rl.ast.Expression;
import nz.org.riskscape.rl.ast.ExpressionProblems;

/**
 * Access properties inside riskscape values using struct member lookups which gives consistent access times.
 */
@EqualsAndHashCode
public class StructMemberAccessExpression implements PropertyName, TypedExpression {

  /**
   * Construct a StructMemberAccessExpression that will access the given type, using the path expression broken down in
   * to a list of segments.
   * @param sourceType the type of thing being accessed, should be, or wrap, a {@link Struct}, or the result will fail
   * @param segments the list of attributes to traverse when accessing a property.  If these properties don't
   * exist on the given type, and it's child types, then the result will fail.
   */
  public static ResultOrProblems<StructMemberAccessExpression> build(Type sourceType, List<String> segments) {
    Iterator<String> segmentsIter = segments.iterator();
    List<StructMember> memberList = new ArrayList<>(segments.size());
    boolean nullable = sourceType.isNullable();
    Type notNullSourceType = Nullable.strip(sourceType);

    if (!(notNullSourceType instanceof Struct)) {
      return ResultOrProblems.failed(Problem.error("Given type does not contain a struct - %s", sourceType));
    }

    Struct first = (Struct) notNullSourceType;
    Struct next = first;

    while (segmentsIter.hasNext()) {
      String segment = segmentsIter.next();
      StructMember member = next.getEntry(segment);

      if (member == null) {
        return ResultOrProblems.failed(
            ExpressionProblems.get().noSuchStructMember(
                Joiner.on('.').join(segments),
                Struct.flattenMemberKeys(first)
            )
        );
      }
      memberList.add(member);

      Type unwrappedType = Nullable.strip(member.getType()).getUnwrappedType();
      if (unwrappedType instanceof Struct) {
        next = (Struct) unwrappedType;
        nullable = nullable || member.getType().isNullable();
      } else if (segmentsIter.hasNext()) {
        return ResultOrProblems.failed(Problem.error(
            "Property %s of %s is not a struct - was %s", segment, next, member.getType()));
      }
    }

    return ResultOrProblems.of(new StructMemberAccessExpression(nullable, memberList));
  }

  private final String propertyName;
  private final StructMember[] segments;
  private final boolean nullable;

  public StructMemberAccessExpression(boolean nullableResult, StructMember... segmentsParam) {
    this(nullableResult, Arrays.asList(segmentsParam));
  }

  public StructMemberAccessExpression(boolean nullableResult, List<StructMember> segments) {
    this.segments = segments.toArray(new StructMember[segments.size()]);
    this.propertyName = segments.stream().map(s -> s.getKey()).collect(Collectors.joining("."));
    this.nullable = nullableResult;
  }

  /**
   * @return the struct that owns the first path segment in this expression.  All tuples given to this expression's
   * evaluate methods must have the same struct object as this of bad things will happen.
   */
  public Struct getRootStruct() {
    return this.segments[0].getOwner();
  }

  @Override
  public ResultOrProblems<Type> evaluateType(Type sourceType) {
    if (Nullable.strip(sourceType).getUnwrappedType() != this.getRootStruct()) {
      return ResultOrProblems.failed(Problem.error("Given type must be the exact same computed type, but was not"));
    }
    return ResultOrProblems.of(getType());
  }

  public Type getType() {
    Type evaluated = this.segments[this.segments.length - 1].getType();
    return nullable ? Nullable.of(evaluated) : evaluated;
  }

  /**
   * Use this expression to set a value to a tuple, rather than fetch it.  This method is not type-safe in the sense
   * that it allows you to set a invariant value to the tuple - it is on you to check it before it goes in.
   *
   * If a child tuple is null along the way, it will be created using the type found in this member's root struct
   *
   * @param object target tuple to modify.
   * @param toSet a value to set to the tuple (or one of its children)
   * @throws IllegalArgumentException if tuple not of the exact same type used to build this expression
   */
  public void setValue(Tuple object, Object toSet) {
    if (object.getStruct() != getRootStruct()) {
      throw new IllegalArgumentException("object is not of same struct " + getRootStruct());
    }

    Tuple next = object;
    for (int i = 0; i < segments.length - 1; i++) {
      StructMember member = segments[i];
      if (next instanceof Tuple) {
        Tuple nextMap = next;
        next = nextMap.fetch(member);

        if (next == null && member.getType().getUnwrappedType() instanceof Struct) {
          Struct nextType = (Struct) member.getType().getUnwrappedType();
          next = new Tuple(nextType);
          nextMap.set(member, next);
        }

      } else {
        throw new IllegalArgumentException("Can not index non-tuple type " + next.getClass());
      }
    }

    next.set(segments[segments.length - 1], toSet);
  }

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

  private Object evaluate(Tuple map) {
    Object next = map;
    for (StructMember part : segments) {
      if (next instanceof Tuple) {
        Tuple nextMap = (Tuple) next;
        next = nextMap.fetch(part);
        if (next == null) {
          //If next is null we can't look any further.
          return null;
        }

      } else {
        throw new IllegalArgumentException("Can not index non-tuple type " + next.getClass());
      }
    }

    return next;
  }


  @Override
  public <T> T evaluate(Object object, Class<T> context) {
    Object rawType = evaluate(object);

    if (context.isAssignableFrom(getType().internalType())) {
      return context.cast(rawType);
    } else if (rawType instanceof Tuple && Geometry.class.isAssignableFrom(context)) {
      // special case: we allow spatial operations to happen directly on tuples with a single geometry member
      // TODO build this in to expression realization, rather than doing this dynamically
      Tuple tuple = (Tuple) rawType;
      StructMember geometryMember = TupleUtils.findGeometryMember(tuple.getStruct(), FindOption.ONE_REQUIRED, ()
          -> new ClassCastException("Can not find a single geometry member"));

      return context.cast(tuple.fetch(geometryMember));
    } else {
      // TODO a bit like above, we really want to do this up front as part of realization to avoid having to do this
      // with each invocation
      Object converted = Converters.convert(object, context);
      if (converted == null) {
        throw new ClassCastException(String.format("Unable to convert %s to %s", rawType, context));
      } else {
        return context.cast(converted);
      }
    }


  }

  @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<StructMember> getSegments() {
    return ImmutableList.copyOf(segments);
  }

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

  /**
   * @returns a RiskScape EL {@link Expression} that is equivalent to this struct member expression.
   */
  public Expression toExpression() {
    return ExpressionParser.parseString(
        getSegments().stream()
            .map(StructMember::getKey)
            .collect(Collectors.joining("."))
    );
  }

}
