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

import nz.org.riskscape.engine.RiskscapeIOException;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.problem.ProblemFactory;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problems;

/**
 * Combines several underlying relations into a single relation
 */
public class ZipRelation extends BaseRelation {

  private final List<BaseRelation> relations;

  public interface LocalProblems extends ProblemFactory {

    /**
     * Tried to zip two relations that have a differing number of rows
     */
    Problem mismatchingRows();
  }

  public static final LocalProblems PROBLEMS = Problems.get(LocalProblems.class);

  private static Struct buildType(List<BaseRelation> underlyingRelations) {
    Struct struct = Struct.EMPTY_STRUCT;
    for (BaseRelation relation : underlyingRelations) {
      struct = struct.and(relation.getType());
    }
    return struct;
  }

  /**
   * @return a list of *distinct* sizes for the given relations, if known
   */
  private static List<Long> distinctSizes(List<BaseRelation> toCheck) {
    return toCheck.stream()
      .filter(r -> r.size().isPresent())
      .map(r -> r.size().get())
      .distinct()
      .collect(Collectors.toList());
  }

  public ZipRelation(List<BaseRelation> relations) {
    super(buildType(relations));
    // in order to zip the relations, they must all produce the same number of tuples (if known)
    if (distinctSizes(relations).size() > 1) {
      throw new RiskscapeIOException(PROBLEMS.mismatchingRows());
    }

    this.relations = relations;
  }

  public ZipRelation(BaseRelation... relations) {
    this(Arrays.asList(relations));
  }

  protected ZipRelation(Fields fields, List<BaseRelation> relations) {
    super(fields);
    this.relations = relations;
  }

  @Override
  protected TupleIterator rawIterator() {
    List<TupleIterator> iterators = new ArrayList<>();

    // open an iterator for each underlying relation
    for (BaseRelation relation : relations) {
      iterators.add(relation.rawIterator());
    }

    return new TupleIterator() {
      @Override
      public boolean hasNext() {
        // check the iterators all agree (i.e. they all have the same number of rows)
        boolean allHaveNext = iterators.stream()
            .map(iter -> iter.hasNext())
            .allMatch(b -> b);
        boolean anyHasNext = iterators.stream()
            .map(iter -> iter.hasNext())
            .anyMatch(b -> b);

        // TODO currently we error out here, but maybe we should warn and continue instead.
        // It depends a bit on the context: ignoring 1-2 rows is fine, but ignoring half the
        // dataset is more serious than just a warning. Currently nothing will actually hit
        // this, it's just a safeguard for the future
        if (anyHasNext != allHaveNext) {
          throw new RiskscapeIOException(PROBLEMS.mismatchingRows());
        }
        return allHaveNext;
      }

      @Override
      public Tuple next() {
        // read raw values from each relation and combine them into a single tuple
        HashMap<String, Object> rawValues = new HashMap<>();

        for (TupleIterator iter : iterators) {
          Tuple tuple = iter.next();
          for (String attrName : tuple.getStruct().getMemberKeys()) {
            rawValues.put(attrName, tuple.fetch(attrName));
          }
        }
        return Tuple.coerce(ZipRelation.this.getRawType(), rawValues);
      }

      @Override
      public void close() {
        iterators.forEach(iter -> iter.close());
      }
    };
  }

  @Override
  protected BaseRelation clone(Fields fields) {
    return new ZipRelation(fields, relations);
  }

  @Override
  public String getSourceInformation() {
    return "Zip[" + relations.stream()
        .map(r -> r.getSourceInformation())
        .collect(Collectors.joining(", ")) + "]";
  }

  @Override
  public Optional<Long> size() {
    List<Long> distinctSizes = distinctSizes(relations);
    if (distinctSizes.size() != 1 || relations.stream().anyMatch(r -> !r.size().isPresent())) {
      // size is unknown for some relations
      return Optional.empty();
    }
    return Optional.of(distinctSizes.get(0));
  }
}
