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

import static org.junit.Assert.*;

import java.io.FileReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Test;

import com.csvreader.CsvReader;

import nz.org.riskscape.engine.cli.BaseCliIntegrationTest2;
import nz.org.riskscape.engine.cli.CommandResult;

public class GL95_BetterHandlingNonPointAssets extends BaseCliIntegrationTest2 {

  List<String> header;
  private LinkedList<List<String>> rows;
  private String idColumn = "id";

  @Test
  public void testSamplingInAPipeline1() throws Exception {
    // sampling1 is defined in a external pipeline file
    doSamplingPipelineTest("sampling1");
  }

  @Test
  public void testSamplingInAPipeline2() throws Exception {
    // sampling2 is defining inline in the ini file
    doSamplingPipelineTest("sampling2");
  }

  private void doSamplingPipelineTest(String pipeline) throws Exception {

    CommandResult result = runner.execute(defaultCommand()
      .option("--project", homeDir().resolve("project.ini"))
      .subcommands("model", "run", pipeline)
      .option("--parameters", homeDir().resolve("params.ini"))
      .option("--output", "output")
      .option("--replace"));

    assertThat(result, exitsWith(0));

    Path outputDir = environment().localSourceTree.resolve("output");
    assertTrue(outputDir.toFile().isDirectory());

    readCsv(outputDir.resolve("stats.csv"));

    assertEquals(
        Arrays.asList("id", "count", "stddev.mean", "stddev.stddev", "max", "min"),
        header
    );

    // check the number of intersections
    assertValueInRowById("1", "count", Matchers.equalTo("6"));
    assertValueInRowById("1", "stddev.mean", Matchers.equalTo("78.0"));
    assertValueInRowById("2", "count", Matchers.equalTo("11"));
    assertValueInRowById("2", "max", Matchers.equalTo("45.0"));
    assertValueInRowById("3", "count", Matchers.equalTo("28"));
    assertValueInRowById("3", "min", Matchers.equalTo("37.0"));

    readCsv(outputDir.resolve("losses.csv"));

    assertEquals(
        Arrays.asList("id", "area_affected_pc", "damage_ratio", "replacement_cost", "total_loss"),
        header
    );

    assertValueInRowById("1", "area_affected_pc", rounded(1.00, 2));
    // note that this is higher than the mean hazard intensity - it's because this value is weighted by the amount of
    // the asset that is exposed to each hazard value
    assertValueInRowById("1", "damage_ratio", rounded(0.81, 2));
    assertValueInRowById("1", "total_loss", rounded(9.72, 2));

    assertValueInRowById("2", "area_affected_pc", rounded(0.644, 3));
    assertValueInRowById("2", "total_loss", rounded(18.13, 2));

    assertValueInRowById("3", "area_affected_pc", rounded(0.829, 3));
    assertValueInRowById("3", "total_loss", rounded(42.83, 2));

    readCsv(outputDir.resolve("losses_by_region.csv"));

    assertEquals(
        Arrays.asList("region_id", "assets_affected", "regional_loss"),
        header
    );

    idColumn = "region_id";

    // note that the total regional losses are slightly less than the non-regionally aggregated losses - some losses
    // fall outside of any regions
    assertValueInRowById("1", "assets_affected", Matchers.equalTo("2"));
    assertValueInRowById("1", "regional_loss", rounded(16.86, 2));
    assertValueInRowById("2", "assets_affected", Matchers.equalTo("1"));
    assertValueInRowById("2", "regional_loss", rounded(15.42, 2));
    assertValueInRowById("3", "assets_affected", Matchers.equalTo("2"));
    assertValueInRowById("3", "regional_loss", rounded(33.05, 2));
  }

  private Matcher<String> rounded(double match, int dp) {
    return new TypeSafeMatcher<String>() {

      @Override
      public void describeTo(Description description) {
        description.appendText(" the number ").appendValue(match)
        .appendText(" to ").appendValue(dp).appendText(" decimal places");
      }

      @Override
      protected boolean matchesSafely(String item) {
        try {
          BigDecimal given = new BigDecimal(item).setScale(dp, RoundingMode.HALF_EVEN);
          BigDecimal toMatch = new BigDecimal(match).setScale(dp, RoundingMode.HALF_EVEN);

          return given.equals(toMatch);
        } catch (NumberFormatException ex) {
          return false;
        }
      }
    };
  }

  private void assertValueInRowById(String rowId, String field, Matcher<String> valueMatcher) {
    for (List<String> row : rows) {
      if (row.get(header.indexOf(idColumn)).equals(rowId)) {
        int columnIndex = header.indexOf(field);
        assertTrue("no such field " + field, columnIndex >= 0);
        assertThat(row.get(columnIndex), valueMatcher);
      }
    }
  }

  private void readCsv(Path csvPath) throws Exception {
    CsvReader reader = new CsvReader(new FileReader(csvPath.toFile()));
    reader.readHeaders();
    this.header = Arrays.asList(reader.getHeaders());
    this.rows = new LinkedList<>();
    while (reader.readRecord()) {
      rows.add(Arrays.asList(reader.getValues()));
    }
  }

}
