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

import static nz.org.riskscape.engine.Assert.*;
import static nz.org.riskscape.engine.Matchers.*;
import static nz.org.riskscape.engine.cli.tests.TableMatchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.junit.Test;

import nz.org.riskscape.engine.cli.BookmarksCommand;
import nz.org.riskscape.engine.cli.ExitException;
import nz.org.riskscape.engine.cli.Table;
import nz.org.riskscape.engine.cli.model.ListCommand;
import nz.org.riskscape.engine.data.InputDataProblems;
import nz.org.riskscape.engine.util.Pair;
import nz.org.riskscape.problem.Problem;

/**
 * Try to run models using invalid input data and check that RiskScape provides
 * the user with an appropriate level of constructive criticism.
 */
@SuppressWarnings("unchecked")
public class InvalidInputDataTest extends BaseModelRunCommandTest {

  @Test
  public void getSensibleErrorForNullExposureGeometry() throws Exception {
    runCommand.modelId = "exposure_has_null_geom";

    ExitException ex = assertThrows(ExitException.class, () -> runCommand.run());
    assertThat(ex.getProblem(), hasAncestorProblem(equalTo(
        InputDataProblems.get().invalidTupleError().withChildren(
            InputDataProblems.get().nullGeometry("the_geom", "null_geom.1")
        ))));
  }

  @Test
  public void getSensibleErrorForNullHazardGeometry() throws Exception {
    runCommand.modelId = "hazard_has_null_geom";

    ExitException ex = assertThrows(ExitException.class, () -> runCommand.run());
    assertThat(ex.getProblem(), hasAncestorProblem(equalTo(
        InputDataProblems.get().invalidTupleError().withChildren(
            InputDataProblems.get().nullGeometry("the_geom", "null_geom.1")
        ))));
  }

  private Problem skippedTuple(Problem reason) {
    return InputDataProblems.get().invalidTupleSkipped().withChildren(reason);
  }

  @Test
  public void canSkipNullExposureGeometryAndStillRunModel() throws Exception {
    runCommand.modelId = "exposure_has_null_geom";
    // this is essentially the same model except the bookmark has skip-invalid=true
    runCommand.parameters = Arrays.asList("input-exposures.layer=null_geom_skip_invalid");
    runCommand.run();

    // check model outputs the expected results for the non-null geometry present
    List<List<String>> rows = openCsv("event-impact.csv", "id", "exposed", "text");
    assertThat(rows,
        containsInAnyOrder(
            contains(equalTo("2"), equalTo("1"), equalTo("not null")),
            contains(equalTo("4"), equalTo("1"), equalTo("not null also"))
    ));

    // check that warnings were emitted for the invalid tuples we skipped
    assertThat(collectedSinkProblems, contains(
        equalTo(skippedTuple(
            InputDataProblems.get().nullGeometry("the_geom", "null_geom.1")
        )),
        equalTo(skippedTuple(
            InputDataProblems.get().nullGeometry("the_geom", "null_geom.3")
        ))
    ));
  }

  @Test
  public void canSkipNullHazardGeometryAndStillRunModel() throws Exception {
    runCommand.modelId = "hazard_has_null_geom";
    // this is essentially the same model except the bookmark has skip-invalid=true
    runCommand.parameters = Arrays.asList("input-hazards.layer=null_geom_skip_invalid");
    runCommand.run();

    // check model outputs the expected results for the non-null geometry present
    List<List<String>> rows = openCsv("event-impact.csv", "id", "exposed", "hazard");
    assertThat(rows,
        containsInAnyOrder(
            contains(equalTo("1"), equalTo("1"), equalTo("6"))
    ));

    // check that warnings were emitted for the invalid tuples we skipped
    assertThat(collectedSinkProblems, contains(
        equalTo(skippedTuple(
            InputDataProblems.get().nullGeometry("the_geom", "null_geom.1")
        )),
        equalTo(skippedTuple(
            InputDataProblems.get().nullGeometry("the_geom", "null_geom.3")
        ))
    ));
  }

  @Test
  public void canListModelsThatUseInputDataNullGeom() throws Exception {
    // bad input data shouldn't affect our ability to display the models that are present
    ListCommand cmd = setupCommand(new ListCommand());
    Table models = (Table) cmd.run();

    assertThat(models, hasRow(
        Pair.of("id", "exposure_has_null_geom"),
        Pair.of("framework", equalTo("wizard"))));
    assertThat(models, hasRow(
        Pair.of("id", "hazard_has_null_geom"),
        Pair.of("framework", equalTo("wizard"))));
  }

  @Test
  public void getSensibleErrorMeasuringBookmarksThatHaveNullGeom() throws Exception {
    // measuring a bookmark with null geometry should throw up InvalidTupleExceptions
    BookmarksCommand.Info cmd = setupCommand(new BookmarksCommand.Info());
    cmd.bookmarkId = "null_geom";

    ExitException ex = assertThrows(ExitException.class, () -> cmd.run());
    assertThat(ex.getProblem(), hasAncestorProblem(equalTo(
        InputDataProblems.get().invalidTupleError().withChildren(
            InputDataProblems.get().nullGeometry("the_geom", "null_geom.1")
        ))));
  }

  @Test
  public void canMeasureBookmarkBySkipInvalidNullGeom() throws Exception {
    BookmarksCommand.Info cmd = setupCommand(new BookmarksCommand.Info());
    cmd.bookmarkId = "null_geom_skip_invalid";
    cmd.run();

    // we should've skipped the 2 invalid rows and read the 2 valid ones
    assertThat(this.outBytes.toString(), containsString("Row count   : 2"));

    // check that warnings were emitted for the invalid tuples we skipped
    assertThat(collectedSinkProblems, contains(
        equalTo(skippedTuple(
            InputDataProblems.get().nullGeometry("the_geom", "null_geom.1")
        )),
        equalTo(skippedTuple(
            InputDataProblems.get().nullGeometry("the_geom", "null_geom.3")
        ))
    ));
  }

  @Test
  public void canListBookmarksThatHaveNullGeom() throws Exception {
    // listing bookmarks should be fine as we don't iterate through the tuples
    BookmarksCommand.BookmarkListCommand cmd = setupCommand(new BookmarksCommand.BookmarkListCommand());
    Table bookmarks = (Table) cmd.run();

    assertThat(bookmarks, hasRow(Pair.of("id", "null_geom")));
    assertThat(bookmarks, hasRow(Pair.of("id", "null_geom_skip_invalid")));
    assertThat(collectedSinkProblems, equalTo(Collections.emptyList()));
  }
}
