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

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.projection.TypeProjection.Pair;
import nz.org.riskscape.engine.relation.InvalidTupleException;
import nz.org.riskscape.engine.rl.EvalException;
import nz.org.riskscape.engine.rl.ExpressionRealizer;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructBuilder;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.problem.Problem;
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;

/**
 * Allows attributes to be replaced or added to the input via a set of arbitrary expressions against the input.  Similar
 * to `{*, new_attribute: foo, replace_me: bar}`.
 *
 * This projection could be replaced or implemented with a select expression once/if
 * https://gitlab.catalyst.net.nz/riskscape/riskscape/-/issues/300 is implemented
 */
@RequiredArgsConstructor
public class SetAttributeProjection implements Projection {

  @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());
        }
        targetTuple.set(pair.target, sourceValue);
      }

      return targetTuple;
    }

    @Override
    public Map<List<StructMember>, List<StructMember>> getDirectMapping() {
      return Collections.emptyMap();
      // this is untested, so leaving it out for now lest it introduce bugs - working code over fast code.

//      Map<List<StructMember>, List<StructMember>> mappings = Maps.newHashMap();
//    memberList.stream().forEach(pair -> {
//      if ((pair.target.getType().getUnwrappedType() instanceof SimpleType)
//          && (mappable(pair.source.getExpression()))) {
//        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;
//
//      /**
//       * @return true if the given expression is a property access expression without a receiver, i.e. it will always
//       * equal
//       * a value from the input
//       */
//      private boolean mappable(Expression expr) {
//        return expr.isA(PropertyAccess.class)
//            .map(pa -> !pa.getReceiver().isPresent())
//            .orElse(false);
//      }
    }
  }

  private final Map<String, Expression> setAttributes;

  private final ExpressionRealizer expressionRealizer;

  @Override
  public ResultOrProblems<Projector> getProjectionFunction(Struct sourceType) {
    // Start by creating mappings for everything that is the source type
    Map<String, Expression> mappings = new LinkedHashMap<>();
    sourceType.getMembers().stream()
        .forEach(member ->  mappings.put(member.getKey(), PropertyAccess.of(member.getKey())));

    // Now add/overwrite mappings from the set attributes
    setAttributes.entrySet().stream()
        .forEach(e -> mappings.put(e.getKey(), e.getValue()));

    List<Problem> problems = new ArrayList<>();
    Map<String, RealizedExpression> realizedMappings = new LinkedHashMap<>();
    mappings.entrySet().stream()
        .forEach(mapping -> {
          expressionRealizer.realize(sourceType, mapping.getValue())
          .composeProblems(Problems.foundWith(mapping.getValue()))
          // TODO maybe have some sort of value class so we can internationalize this via ObjectRenderer?
          .composeProblems(Problems.foundWith("attribute " + mapping.getKey()))
          .addProblemsTo(problems)
          .ifPresent(r -> realizedMappings.put(mapping.getKey(), r));
        });

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

    StructBuilder targetTypeBuilder = Struct.builder();
    realizedMappings.entrySet().stream()
        .forEach(realized -> targetTypeBuilder.add(realized.getKey(), realized.getValue().getResultType()));
    Struct targetType = targetTypeBuilder.build();

    List<Pair> memberList = realizedMappings.entrySet().stream()
        .map(realized -> new Pair(realized.getValue(), targetType.getEntry(realized.getKey())))
        .collect(Collectors.toList());

    return ResultOrProblems.of(new TypeProjector(sourceType, targetType, memberList));
  }

}
