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

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.collection.IsIterableContainingInOrder.*;
import static org.junit.Assert.*;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.junit.Test;

import com.google.common.collect.Lists;

import nz.org.riskscape.engine.Identified;
import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.engine.pipeline.Pipeline;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.problem.ProblemPlaceholder;
import nz.org.riskscape.engine.typeset.IdentifiedType;
import nz.org.riskscape.problem.Problem.Severity;

public class ProblemTest {

  @Test
  public void canCreateAProblemWithAMessageThatHasPotentialMessageFormatCharactersInIt() throws Exception {
    assertEquals(
        "this %s is a problem",
        new Problem(Severity.ERROR, "this %s is a problem").getMessage()
    );
  }

  @Test
  public void canCreateCompositeProblemWithOneError() {
    Problem problem = Problem.composite(Lists.newArrayList(Problem.error("just an error")),
        "problem is: %s", "mock-problem");
    assertThat(problem.getSeverity(), is(Severity.ERROR));
    assertThat(problem.getMessage(), is("problem is: mock-problem"));
    assertThat(problem.getChildren(), contains(Problem.error("just an error")));
  }

  @Test
  public void canCreateCompositeProblemWithOneWarning() {
    Problem problem = Problem.composite(Lists.newArrayList(Problem.warning("just a warning")),
        "problem is: %s", "mock-problem");
    assertThat(problem.getSeverity(), is(Severity.WARNING));
    assertThat(problem.getMessage(), is("problem is: mock-problem"));
    assertThat(problem.getChildren(), contains(Problem.warning("just a warning")));
  }

  @Test
  public void canCreateCompositeProblemWithWarningAndProblem() {
    Problem problem = Problem.composite(Lists.newArrayList(
        Problem.warning("just a warning"),
        Problem.error("just an error")
    ),
        "problem is: %s", "mock-problem");
    assertThat(problem.getSeverity(), is(Severity.ERROR));
    assertThat(problem.getMessage(), is("problem is: mock-problem"));
    assertThat(problem.getChildren(), contains(
        Problem.warning("just a warning"),
        Problem.error("just an error")));
  }

  private Problem makeProblemWithContext(Class<?> thing, String name) {
    Identified context = ProblemPlaceholder.of(thing, name);
    return GeneralProblems.get().badValue("foo", context, "bar").affecting(context);
  }

  @Test
  public void canFilterbyContext() {
    Problem problem = Problems.foundWith(IdentifiedType.class, "parent-type", Lists.newArrayList(
        makeProblemWithContext(Pipeline.class, "child-pipeline"),
        Problems.foundWith(IdentifiedType.class, "child-type", Arrays.asList(
            makeProblemWithContext(IdentifiedType.class, "grandchild-type")))
    ));

    // first, look for something that returns no match
    List<Problem> filtered = Problem.filterAffected(Arrays.asList(problem), Parameter.class);
    assertEquals(0, filtered.size());

    // now, look for something that returns multiple matches
    filtered = Problem.filterAffected(Arrays.asList(problem), IdentifiedType.class);
    assertEquals(3, filtered.size());

    List<String> contextNames = filtered.stream().map(Problem::getAffectedName).collect(Collectors.toList());
    assertThat(contextNames, hasItems("parent-type", "child-type", "grandchild-type"));
        //hasItem("parent-type"), hasItem("child-type"), hasItem("grandchild-type"))));
  }


  @Test
  public void canFilterGrandchildByContext() {
    Problem problem = Problems.foundWith(IdentifiedType.class, "parent-type", Lists.newArrayList(
        makeProblemWithContext(Pipeline.class, "child-pipeline"),
        Problems.foundWith(IdentifiedType.class, "child-type", Arrays.asList(
            makeProblemWithContext(Parameter.class, "grandchild-parameter")))
    ));

    List<Problem> filtered = Problem.filterAffected(Arrays.asList(problem), Parameter.class);
    assertEquals(1, filtered.size());
    Problem paramProblem = filtered.get(0);
    assertEquals("grandchild-parameter", paramProblem.getAffectedName());
  }

  @Test
  public void cannotModifyChildrenIndirectly() throws Exception {
    Problem problem = Problem.error("foo").withChildren(Problem.error("bar"));
    List<Problem> children = problem.getChildren();
    // trying to modify the child list should not alter the original Problem
    try {
      children.clear();
      fail();
    } catch (UnsupportedOperationException ex) {
    }

    assertEquals(1, problem.getChildren().size());
  }

  @Test
  public void canOutputMessageForSimpleProblem() {
    Problem problem = Problem.warning("This is my problem");
    assertThat(problem.getMessage(), is("This is my problem"));
  }

  @Test
  public void testThrowIfErrors() throws Exception {
    Problem.throwIfErrors(Collections.emptyList(), p -> new RuntimeException());
    Problem.throwIfErrors(Arrays.asList(Problem.warning("don't panic")), p -> new RuntimeException());

    try {
      Problem.throwIfErrors(Arrays.asList(Problem.error("panic")), p -> new RuntimeException());
      fail();
    } catch (RuntimeException ex) {}

    try {
      Problem.throwIfErrors(Arrays.asList(Problem.warning("don't panic"), Problem.error("panic")),
          p -> new RuntimeException());
      fail();
    } catch (RuntimeException ex) {}

  }
  private String joinLines(String... lines) {
    return Arrays.asList(lines).stream().collect(Collectors.joining(String.format("%n")));
  }

  @Test
  public void canAccessProblemMetadata() throws Exception {
    File file = new File("/tmp/foo.txt");
    Problem problem = Problem.error("foo").affecting(file);
    assertEquals(Optional.of(file), problem.getAffected(File.class));

    // placeholders are faux objects for display/construction convenience.
    // we can still use them to determine the name/class of the thing affected,
    // but we shouldn't actually get an object back because there isn't really one
    ProblemPlaceholder fauxFile = ProblemPlaceholder.of(File.class, "/tmp/foo.txt");
    problem = Problem.error("bar").affecting(fauxFile);
    assertTrue(problem.affects(File.class));
    assertEquals("/tmp/foo.txt", problem.getAffectedName());
    assertEquals(Optional.empty(), problem.getAffected(File.class));
  }

  @Test
  public void twoIdenticalProblemsAreEqual() throws Exception {
    // there was a bug with the AffectedMetadata breaking equals on factory-constructed problems
    Problem problem0 = GeneralProblems.get().badValue("foo", "bar", "baz").affecting("foo");
    Problem problem1 = GeneralProblems.get().badValue("foo", "bar", "baz").affecting("foo");

    assertEquals(problem0, problem1);
  }


  @Test
  public void twoNonIdenticalProblemsAreEqual() throws Exception {
    Problem problem0 = GeneralProblems.get().badValue("foo", "bar", "baz").affecting("foo");
    Problem problem1 = GeneralProblems.get().badValue("foo", "baz", "bar").affecting("foo");

    assertNotEquals(problem0, problem1);
  }

  @Test
  public void canToStringProblemWithNullArguments() {
    Problem problem = GeneralProblems.get().badValue(null, "foo", "bar");
    assertEquals("Problem(ERROR: BAD_VALUE[null, 'foo', 'bar'])", problem.toString());
  }

  @Test
  public void canAccessProblemStackTrace() throws Exception {
    Throwable cause = new RuntimeException("Whoops");
    Problem caughtException = Problem.error("Caught it!").withException(cause);
    assertThat(caughtException.getException(), is(cause));
    assertThat(caughtException.findAnyException(), is(cause));

    // should be able to check if any children have exceptions
    Problem parent = Problem.error("Nested it").withChildren(caughtException);
    assertThat(parent.getException(), nullValue());
    assertThat(parent.findAnyException(), is(cause));

    Problem twiceRemoved = Problem.error("Nested it again").withChildren(parent);
    assertThat(twiceRemoved.getException(), nullValue());
    assertThat(twiceRemoved.findAnyException(), is(cause));
  }

  @Test
  public void wrapAffectedMetadataListTypesEqual() throws Exception {
    Problem.AffectedMetadata affectedObjectOne = Problem.wrapAffectedObject(List.of("foo"));
    Problem.AffectedMetadata affectedObjectTwo = Problem.wrapAffectedObject(Lists.newArrayList("foo"));

    assertThat(affectedObjectOne, equalTo(affectedObjectTwo));
    assertThat(affectedObjectOne.getUnderlyingClass(), equalTo(List.class));
    assertThat(affectedObjectTwo.getUnderlyingClass(), equalTo(List.class));
  }
}
