/*
 * 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 java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertEquals;

public class Assert {

  public interface Thrower {
    void run() throws Exception;
  }

  public static <T extends Throwable> T assertThrows(Class<T> clazz, Thrower thrower) {
    try {
      thrower.run();
    } catch (Throwable ex) {
      if (clazz.isInstance(ex)) {
        return clazz.cast(ex);
      } else {
        throw new RuntimeException("Should have raised exception of type " + clazz + " but was " + ex.getClass(), ex);
      }
    }
    fail("Should have raised an exception");
    return null;
  }


  public static <T> void assertInstanceOf(Class<T> desiredType, Object actual, Consumer<T> callback) {
    if (desiredType.isInstance(actual)) {
      callback.accept(desiredType.cast(actual));
    } else {
      Class<?> actualType = actual == null ? null : actual.getClass();
      fail("Expected "  + actual + " to be of type " + desiredType + " but was " + actualType);
    }
  }


  public static void assertContains(List<String> output, String toMatch) {
    assertTrue(
        String.format("Expected output to contain string '%s'\n%s", toMatch, output),
        output.stream().filter(line -> line.contains(toMatch)).findAny().isPresent());
  }

  public static void assertContains(List<Tuple> results, Tuple expected) {
    Optional<Tuple> found = results.stream().filter(t -> t.equals(expected)).findFirst();
    if (!found.isPresent()) {
      fail(String.format("Expected list to contain %s:\n%s", expected, results));
    }
  }

  public static void refuteContains(List<String> output, String toMatch) {
    assertFalse(
        String.format("Did not expect output to contain string '%s'\n%s", toMatch, output),
        output.stream().filter(line -> line.contains(toMatch)).findAny().isPresent());
  }

  /**
   * Assert that any single line in the output matches.
   *
   * @param output
   * @param regexToMatch
   */
  public static void assertMatchesSomewhere(List<String> output, String regexToMatch) {
    Pattern regex = Pattern.compile(regexToMatch);
    assertTrue(
        String.format("Expected to find %s among output:\n%s", regexToMatch,
            output.stream().collect(Collectors.joining("\n"))),
        output.stream().filter(line -> regex.matcher(line).find()).findAny().isPresent());
  }

  /**
   * Assert that any single line in the output matches.
   *
   * @param output
   * @param regexToMatch
   */
  public static void assertMatches(List<String> output, String regexToMatch) {
    assertTrue(
        String.format("Expected to find %s among output:\n%s", regexToMatch,
            output.stream().collect(Collectors.joining("\n"))),
        output.stream().filter(line -> line.matches(regexToMatch)).findAny().isPresent());
  }

  /**
   * Assert that no lines in the output matches.
   *
   * @param output
   * @param regexToMatch
   */
  public static void assertNoMatches(List<String> output, String regexToMatch) {
    assertFalse(output.stream().filter(line -> line.matches(regexToMatch)).findAny().isPresent());
  }


  /**
   * Assert that the given expected string appears in entireString
   */
  public static void assertStringContains(String expected, String entireString) {
    assertTrue(
        String.format("Expected '%s' to contain '%s'", entireString, expected),
        entireString.contains(expected));
  }

  /**
   * Assert that each list has the same content.
   *
   * Comparison is done per element and will fail on the first element with unexpected content.
   */
  public static void assertListEquals(List expected, List found) {
    assertEquals("Lists are not the same size", expected.size(), found.size());
    for (int i = 0; i < expected.size(); i++) {
      assertEquals(String.format("List element at index %d is not as expected", i), expected.get(i), found.get(i));
    }
  }

}
