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


import java.util.ArrayList;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.expr.StructMemberAccessExpression;
import nz.org.riskscape.engine.relation.InvalidTupleException;
import nz.org.riskscape.engine.relation.TypeCheckingOptions;
import nz.org.riskscape.engine.rl.EvalException;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.types.CoercionException;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.SimpleType;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.typeset.TypeSet;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problem.Severity;
import nz.org.riskscape.problem.ProblemCode;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.Expression;
import nz.org.riskscape.rl.ast.PropertyAccess;

/**
 * Projects from one type of tuple to another.  Differs from select mostly in that a select is free form and creates a
 * type, whereas the {@link TypeProjection} imposes a type on a type.
 */
@RequiredArgsConstructor
public class TypeProjection implements Projection {

  public enum ProblemCodes implements ProblemCode {
    MISSING_MEMBER,
    BAD_MAPPING,
    MISSING_TARGET
  }

  @RequiredArgsConstructor
  protected static class Pair {
    final RealizedExpression source;
    final StructMember target;
  }

  @RequiredArgsConstructor
  protected static class Mapping {
    public final Struct targetType;
    public final List<Pair> memberList;
  }

  @RequiredArgsConstructor
  protected class TypeProjector implements Projector {

    @Getter
    final Struct sourceType;
    @Getter
    final Struct producedType;
    final List<Pair> memberList;

    @Override
    public Tuple apply(Tuple sourceTuple) {
      Tuple targetTuple = new Tuple(producedType);
      for (Pair pair : memberList) {

        Object sourceValue;
        try {
          sourceValue = pair.source.evaluate(sourceTuple);
        } catch (EvalException ex) {
          throw new InvalidTupleException(
              sourceTuple,
              Problem.error(
                  "Failed to evaluate expression '%s' against %s for attribute %s[%s]",
                  pair.source.getExpression().toSource(),
                  sourceTuple,
                  pair.target.getKey(),
                  pair.target.getType()
                ).withChildren(Problems.caught(ex)),
              ex.getCause());
        }

        try {
          if (options.contains(TypeCheckingOptions.COERCE)) {
              sourceValue = pair.target.getType().coerce(sourceValue);
          }

        } catch (CoercionException ex) {
          throw new InvalidTupleException(
              sourceTuple,
              String.format(
                  "Failed to coerce '%s' for %s[%s] from %s - %s",
                  sourceValue,
                  pair.target.getKey(),
                  pair.target.getType(),
                  sourceTuple,
                  ex.getMessage()),
              ex);
        }

        targetTuple.set(pair.target, sourceValue);
      }

      return targetTuple;
    }

    @Override
    public Map<List<StructMember>, List<StructMember>> getDirectMapping() {
      Map<List<StructMember>, List<StructMember>> mappings = Maps.newHashMap();
      memberList.stream().forEach(pair -> {
        if ((pair.target.getType().getUnwrappedType() instanceof SimpleType)
            && (pair.source.getExpression() instanceof PropertyAccess)) {
          PropertyAccess pa = (PropertyAccess)pair.source.getExpression();

          if (! pa.getReceiver().isPresent()) {

            ResultOrProblems<StructMemberAccessExpression> sae = StructMemberAccessExpression.build(sourceType,
                pa.getIdentifiers().stream()
                    .map(t -> t.value)
                    .collect(Collectors.toList()));
            if (sae.isPresent()) {
              mappings.put(Lists.newArrayList(pair.target), sae.get().getSegments());
            }
          }
        }
      });
      return mappings;
    }
  }

  private final Struct targetType;

  private final Map<String, Expression> mapAttributes;

  private final EnumSet<TypeCheckingOptions> options;

  private final RealizationContext realizationContext;

  public TypeProjection(Struct targetType, RealizationContext realizationContext) {
    this(targetType, ImmutableMap.of(), EnumSet.of(TypeCheckingOptions.COERCE), realizationContext);
  }

  public TypeProjection(Struct targetType, Map<String, Expression> attributeMap,
      RealizationContext realizationContext) {
    this(targetType, attributeMap, EnumSet.of(TypeCheckingOptions.COERCE), realizationContext);
  }

  @Override
  public ResultOrProblems<Struct> projectType(Struct source) {
    return ResultOrProblems.of(targetType);
  }

  @Override
  public ResultOrProblems<Projector> getProjectionFunction(Struct sourceType) {
    return buildMemberList(sourceType)
        .map(mapping -> new TypeProjector(sourceType, mapping.targetType, mapping.memberList));
  }

  protected ResultOrProblems<Mapping> buildMemberList(Struct sourceType) {
    // The actual target type may be a little different than set to targetType.
    // This is to allow us to keep wrapping type information where the source type is assignable
    // to the target type.
    Struct provisionalTargetType = targetType;
    TypeSet typeSet = realizationContext.getProject().getTypeSet();

    LinkedHashMap<String, RealizedExpression> memberMap = new LinkedHashMap<>(targetType.getMembers().size());
    List<Problem> problems = new ArrayList<>();
    for (StructMember targetMember : targetType.getMembers()) {
      String targetKey = targetMember.getKey();
      Expression sourceExpr = mapAttributes.get(targetKey);
      if (sourceExpr == null) {

        if (sourceType.hasMember(targetMember.getKey())) {
          sourceExpr = PropertyAccess.of(targetMember.getKey());
        } else {
          if (!targetMember.getType().isNullable()) {
            problems.add(Problem.error(ProblemCodes.MISSING_MEMBER, targetKey));
          }
          continue;
        }
      }
      ResultOrProblems<RealizedExpression> realizedSourceExpr =
          realizationContext.getExpressionRealizer().realize(sourceType, sourceExpr);

      if (realizedSourceExpr.hasProblems(Severity.ERROR)) {
        problems.add(Problem.error(ProblemCodes.BAD_MAPPING,
            targetKey,
            sourceExpr.toSource()).withChildren(realizedSourceExpr.getProblems()));

      } else {
        memberMap.put(targetMember.getKey(), realizedSourceExpr.get());
        boolean nullableTarget = Nullable.is(targetMember.getType());
        Type targetMemberType = Nullable.strip(targetMember.getType());
        Type sourceMemberType = realizedSourceExpr.get().getResultType();
        if (! sourceMemberType.equals(targetMemberType)
            && typeSet.isAssignable(sourceMemberType, targetMemberType)) {
          // actual source type is a wrapped type. we keep the actual type so we don't
          // lose any wrapping metadata like CRS. This is fine as the source type is directly assignable
          // to the target.
          provisionalTargetType = provisionalTargetType.replace(targetMember.getKey(),
              Nullable.ifTrue(nullableTarget, sourceMemberType));
        }
      }
    }
    //Check that map attributes exist in targetType
    for (String mapped: mapAttributes.keySet()) {
      if (! targetType.hasMember(mapped)) {
        problems.add(Problem.error(ProblemCodes.MISSING_TARGET, mapped, targetType.toString()));

      }
    }
    if (Problem.hasErrors(problems)) {
      return ResultOrProblems.failed(problems);
    }

    Struct actualTargetType = provisionalTargetType;
    List<Pair> memberList = memberMap.entrySet().stream()
        .map(entry -> new Pair(entry.getValue(), actualTargetType.getEntry(entry.getKey())))
        .collect(Collectors.toList());
    return ResultOrProblems.of(new Mapping(actualTargetType, memberList), problems);
  }

}
