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

import static org.hamcrest.Matchers.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.hamcrest.TypeSafeMatcher;

import nz.org.riskscape.engine.relation.Relation;
import nz.org.riskscape.engine.types.Struct;

public class RelationMatchers implements MatcherCollection {


  /**
   * A matcher that checks a relation contains single-value tuples that have the given values
   */
  public static Matcher<? super Relation> withValues(Object... values) {
    List<Object> valuesList = Arrays.asList(values);
    return new TypeSafeDiagnosingMatcher<Relation>() {

      @Override
      public void describeTo(Description description) {
        description.appendText("Relation with values " + valuesList);
      }

      @Override
      protected boolean matchesSafely(Relation item, Description desc) {
        List<Object> collectedValues = item
            .stream()
            .map(t -> t.fetch("value"))
            .collect(Collectors.toList());

        desc.appendText("values ").appendValue(collectedValues);

        return collectedValues.equals(valuesList);
      }

    };
  }

  /**
   * A matcher that checks a relation contains single-value tuples that have the given values
   */
  public static Matcher<List<?>> tupleListWithValues(Object... values) {
    List<Object> valuesList = Arrays.asList(values);
    return new TypeSafeDiagnosingMatcher<List<?>>() {

      @Override
      public void describeTo(Description description) {
        description.appendText("Relation with values " + valuesList);
      }

      @Override
      protected boolean matchesSafely(List<?> item, Description desc) {
        List<Object> collectedValues = item
            .stream()
            .map(t -> (Tuple) t)
            .map(t -> t.fetch("value"))
            .collect(Collectors.toList());

        desc.appendText("values ").appendValue(collectedValues);

        return collectedValues.equals(valuesList);
      }

    };
  }

  /**
   * A matcher that checks a relation contains single-value tuples that have the given values
   */
  public static Matcher<? super Relation> withTuples(List<Tuple> values) {
    Matcher<?> subMatcher = hasItems(values.toArray());
    Struct expectedStruct = values.size() == 0 ? Struct.of() : values.get(0).getStruct();
    return new TypeSafeMatcher<Relation>() {

      @Override
      public void describeTo(Description description) {
        description.appendText("Relation ").appendValue(expectedStruct).appendText(" with tuples ").appendValue(values);
      }

      @Override
      protected void describeMismatchSafely(Relation item, Description mismatchDescription) {

        if (!item.getType().equals(expectedStruct)) {
          mismatchDescription.appendText("Had type ").appendValue(item.getType());
        } else {
          List<Tuple> collected = item.stream().collect(Collectors.toList());
          mismatchDescription.appendText("Had tuples ");
          subMatcher.describeMismatch(collected, mismatchDescription);
        }
      }

      @Override
      protected boolean matchesSafely(Relation item) {
        if (!item.getType().equals(expectedStruct)) {
          return false;
        }
        List<Tuple> collected = item.stream().collect(Collectors.toList());
        return subMatcher.matches(collected);
      }

    };
  }

  public static <T extends Relation> Matcher<T> relationWithTuples(
      Matcher<? extends Iterable<? extends Tuple>> matcher
  ) {
    return new TypeSafeDiagnosingMatcher<T>(Relation.class) {

      @Override
      public void describeTo(Description description) {
        description.appendText("Relation with tuple ").appendDescriptionOf(matcher);
      }

      @Override
      protected boolean matchesSafely(Relation item, Description desc) {
        List<Tuple> collectedValues = item
            .stream()
            .collect(Collectors.toList());

        desc.appendText("tuples ").appendValue(collectedValues);

        return matcher.matches(collectedValues);
      }
    };
  }


  public static <T extends Relation> Matcher<T> relationWithTuples(Tuple... expectedTuples) {
    Stream<Tuple> tupleStream = Arrays.asList(expectedTuples).stream();
    return relationWithTuples(
      Matchers.contains(
        tupleStream.map(t -> Matchers.equalTo(t)).collect(Collectors.toList())
      )
    );
  }

  /**
   * Non-typesafe version of {@link #withValues(Object...)}
   */
  public static <T extends Object> Matcher<T> relationWithValues(Object... values) {
    Matcher<? super Relation> typedMatcher = withValues(values);
    return new BaseMatcher<T>() {

      @Override
      public boolean matches(Object item) {
        if (item instanceof Relation) {
          return typedMatcher.matches(item);
        } else {
          return false;
        }
      }

      @Override
      public void describeTo(Description description) {
        typedMatcher.describeTo(description);
      }
    };
  }

  public static Matcher<Relation> relationWithType(Struct expectedType) {
    return new TypeSafeMatcher<Relation>(Relation.class) {

      @Override
      public void describeTo(Description description) {
        description
            .appendText("relation with type ")
            .appendValue(expectedType);
      }

      @Override
      protected boolean matchesSafely(Relation item) {
        return item.getType().equals(expectedType);
      }

      @Override
      protected void describeMismatchSafely(Relation item, Description mismatchDescription) {
        mismatchDescription.appendText("Relation with type ").appendValue(item.getType());
      }
    };
  }


}
