/*
 * 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 java.util.List;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;

import java.util.Arrays;

import org.junit.Before;
import org.junit.Test;

public class RM003_AssetModel_MultiHazards extends ModelPipelineIntegrationCliTest {

  Struct building = Struct.of("id", Types.INTEGER).and("type", Types.TEXT).and("value", Types.INTEGER).build();
  Struct nullableHazard = Struct.of("value", Nullable.INTEGER).build();

  @Before
  public void setup() throws Exception {
    this.riskscapeDir = expand("src/test/homes/rm003-multi-hazards");
    setupOutputDir();
  }

  @Test
  public void canRunAFunctionWithOneHazard() {
    doRunAFunctionWithOneHazard("buildings_2193.shp", "hazard1-asc");
    doRunAFunctionWithOneHazard("buildings_4326.shp", "hazard1-asc");
    doRunAFunctionWithOneHazard("buildings_2193.shp", "hazard1");
    doRunAFunctionWithOneHazard("buildings_4326.shp", "hazard1");
  }

  public void doRunAFunctionWithOneHazard(String assetFile, String hazardBookmark) {
    ExecResult result = execute(params.clear()
        .add("--project=project.ini")
        .add("model")
        .add("run")
        .add("onehazard")
        .add("-p=input-exposures.layer=data/" + assetFile)
        .add("-p=input-hazards.layer=" + hazardBookmark)
        .add("-p").add("report-event-impact.select[0]=consequence as output")
        .add("-p").add("report-event-impact.select[1]=exposure as asset")
        .add("-p").add("report-event-impact.select[2]=hazard as hazard")
        .add("--output=" + mappedOutputDir.toString())
        .add("--replace")
        .add("--format=csv"));

    assertEquals(0, result.retCode.intValue());

    List<List<String>> results = readColumnsFromCsv(outputDir.resolve("event-impact.csv"), "output", "asset.id",
        "hazard");
    assertThat(results, hasItems(
        Arrays.asList("-1", "1", ""),
        Arrays.asList("2600", "8", "4.0")
    ));
  }

  @Test
  public void canRunAFunctionWithOneHazardAndAggregateOnHazard() {
    doRunAFunctionWithOneHazardAndAggregateOnHazard("buildings_2193.shp", "hazard1-asc");
    doRunAFunctionWithOneHazardAndAggregateOnHazard("buildings_4326.shp", "hazard1-asc");
    doRunAFunctionWithOneHazardAndAggregateOnHazard("buildings_2193.shp", "hazard1");
    doRunAFunctionWithOneHazardAndAggregateOnHazard("buildings_4326.shp", "hazard1");
  }

  public void doRunAFunctionWithOneHazardAndAggregateOnHazard(String assetFile, String hazardBookmark) {
    ExecResult result = execute(params.clear()
        .add("--project=project.ini")
        .add("model")
        .add("run")
        .add("onehazard")
        .add("-p=input-exposures.layer=data/" + assetFile)
        .add("-p=input-hazards.layer=" + hazardBookmark)
        .add("-p").add("report-event-impact.group-by[0]=hazard as hazard")
        .add("-p").add("report-event-impact.aggregate[0]=count(exposure.id) as count")
        .add("--output=" + mappedOutputDir.toString())
        .add("--replace")
        .add("--format=csv"));

    assertEquals(0, result.retCode.intValue());

    List<List<String>> results = readColumnsFromCsv(outputDir.resolve("event-impact.csv"), "hazard", "count");
    assertThat(results, containsInAnyOrder(
        Arrays.asList("", "3"),
        Arrays.asList("3.0", "1"),
        Arrays.asList("4.0", "3"),
        Arrays.asList("6.0", "1"),
        Arrays.asList("8.0", "3")
    ));
  }

  @Test
  public void canRunAFunctionWithOneHazardAndAggregateOnAssetAndHazard() {
    doRunAFunctionWithOneHazardAndAggregateOnAssetAndHazard("buildings_2193.shp", "hazard1-asc");
    doRunAFunctionWithOneHazardAndAggregateOnAssetAndHazard("buildings_4326.shp", "hazard1-asc");
    doRunAFunctionWithOneHazardAndAggregateOnAssetAndHazard("buildings_4326.shp", "hazard1");
  }

  public void doRunAFunctionWithOneHazardAndAggregateOnAssetAndHazard(String assetFile, String hazardBookmark) {

    ExecResult result = execute(params.clear()
        .add("--project=project.ini")
        .add("model")
        .add("run")
        .add("onehazard")
        .add("-p=input-exposures.layer=data/" + assetFile)
        .add("-p=input-hazards.layer=" + hazardBookmark)
        .add("-p").add("report-event-impact.group-by[0]=exposure.type as asset_type")
        .add("-p").add("report-event-impact.group-by[1]=hazard as hazard")
        .add("-p").add("report-event-impact.aggregate[0]=count(exposure.id) as count")
        .add("--output=" + mappedOutputDir.toString())
        .add("--replace")
        .add("--format=csv"));

    assertEquals(0, result.retCode.intValue());

    List<List<String>> results = readColumnsFromCsv(outputDir.resolve("event-impact.csv"),
        "asset_type", "hazard", "count");
    assertThat(results, containsInAnyOrder(
        Arrays.asList("house", "", "2"),
        Arrays.asList("house", "4.0", "2"),
        Arrays.asList("house", "6.0", "1"),
        Arrays.asList("house", "8.0", "2"),
        Arrays.asList("shed", "", "1"),
        Arrays.asList("shed", "3.0", "1"),
        Arrays.asList("shed", "4.0", "1"),
        Arrays.asList("shed", "8.0", "1")
    ));
  }

  @Test
  public void canRunAFunctionWithTwoHazards() {
    doRunAFunctionWithTwoHazards("buildings_2193.shp", "hazard1-asc", "hazard2-asc");
    doRunAFunctionWithTwoHazards("buildings_4326.shp", "hazard1-asc", "hazard2-asc");
    doRunAFunctionWithTwoHazards("buildings_2193.shp", "hazard1", "hazard2");
    doRunAFunctionWithTwoHazards("buildings_4326.shp", "hazard1", "hazard2");
    doRunAFunctionWithTwoHazards("buildings_2193.shp", "hazard1-asc", "hazard2");
    doRunAFunctionWithTwoHazards("buildings_4326.shp", "hazard1", "hazard2-asc");
  }

  public void doRunAFunctionWithTwoHazards(String assetFile, String hazardFile1, String hazardFile2) {
    ExecResult result = execute(params.clear()
        .add("--project=project.ini")
        .add("model")
        .add("run")
        .add("twohazards")
        .add("-p=input-exposures.layer=data/" + assetFile)
        .add("-p=input-hazards_1.layer=" + hazardFile1)
        .add("-p=input-hazards_2.layer=" + hazardFile2)
        .add("-p").add("report-event-impact.select[0]=consequence as output")
        .add("-p").add("report-event-impact.select[1]=exposure as asset")
        .add("-p").add("report-event-impact.select[2]=hazard.hazard1 as hazard1")
        .add("-p").add("report-event-impact.select[3]=hazard.hazard2 as hazard2")
        .add("--output=" + mappedOutputDir.toString())
        .add("--replace")
        .add("--format=csv"));

    assertEquals(0, result.retCode.intValue());
    List<List<String>> results = readColumnsFromCsv(outputDir.resolve("event-impact.csv"), "output", "asset.id",
        "hazard1", "hazard2");
    assertThat(results, hasSize(11));
    assertThat(results, hasItems(
        Arrays.asList("100", "1", "", ""),
        Arrays.asList("26000", "8", "4.0", "10.0")
    ));
  }

  @Test
  public void canRunAFunctionWithTwoHazardsWithFiltering() {
    doRunAFunctionWithTwoHazardsWithFiltering("buildings_2193.shp", "hazard1-asc", "hazard2-asc");
    doRunAFunctionWithTwoHazardsWithFiltering("buildings_4326.shp", "hazard1-asc", "hazard2-asc");
    doRunAFunctionWithTwoHazardsWithFiltering("buildings_2193.shp", "hazard1", "hazard2");
    doRunAFunctionWithTwoHazardsWithFiltering("buildings_4326.shp", "hazard1", "hazard2");
    doRunAFunctionWithTwoHazardsWithFiltering("buildings_2193.shp", "hazard1-asc", "hazard2");
    doRunAFunctionWithTwoHazardsWithFiltering("buildings_4326.shp", "hazard1", "hazard2-asc");
  }

  public void doRunAFunctionWithTwoHazardsWithFiltering(String assetFile, String hazardFile1, String hazardFile2) {
    ExecResult result = execute(params.clear()
        .add("--project=project.ini")
        .add("model")
        .add("run")
        .add("twohazards")
        .add("-p=input-exposures.layer=data/" + assetFile)
        .add("-p=input-hazards_1.layer=" + hazardFile1)
        .add("-p=input-hazards_2.layer=" + hazardFile2)
        .add("-p").add("report-event-impact.select[0]=consequence as output")
        .add("-p").add("report-event-impact.select[1]=exposure as asset")
        .add("-p").add("report-event-impact.select[2]=hazard.hazard1 as hazard1")
        .add("-p").add("report-event-impact.select[3]=hazard.hazard2 as hazard2")
        .add("-p").add("report-event-impact.filter=hazard.hazard2 = 10.0 and exposure.type=\'shed\'")
        .add("--output=" + mappedOutputDir.toString())
        .add("--replace")
        .add("--format=csv"));

    assertEquals(0, result.retCode.intValue());
    List<List<String>> results = readColumnsFromCsv(outputDir.resolve("event-impact.csv"), "output", "asset.id",
        "hazard1", "hazard2");
    assertThat(results, hasItems(
        Arrays.asList("4800", "3", "4.0", "10.0")
    ));
  }

  @Test
  public void canRunAFunctionWithTwoHazardsAndAggregateOnHazards() {
    doRunAFunctionWithTwoHazardsAndAggregateOnHazards("buildings_2193.shp", "hazard1-asc", "hazard2-asc");
    doRunAFunctionWithTwoHazardsAndAggregateOnHazards("buildings_4326.shp", "hazard1-asc", "hazard2-asc");
    doRunAFunctionWithTwoHazardsAndAggregateOnHazards("buildings_2193.shp", "hazard1", "hazard2");
    doRunAFunctionWithTwoHazardsAndAggregateOnHazards("buildings_4326.shp", "hazard1", "hazard2");
    doRunAFunctionWithTwoHazardsAndAggregateOnHazards("buildings_2193.shp", "hazard1-asc", "hazard2");
    doRunAFunctionWithTwoHazardsAndAggregateOnHazards("buildings_4326.shp", "hazard1", "hazard2-asc");
  }

  public void doRunAFunctionWithTwoHazardsAndAggregateOnHazards(String assetFile, String hazardFile1,
      String hazardFile2) {
    ExecResult result = execute(params.clear()
        .add("--project=project.ini")
        .add("model")
        .add("run")
        .add("twohazards")
        .add("-p=input-exposures.layer=data/" + assetFile)
        .add("-p=input-hazards_1.layer=" + hazardFile1)
        .add("-p=input-hazards_2.layer=" + hazardFile2)
        .add("-p").add("report-event-impact.group-by[0]=hazard.hazard1 as hazard1")
        .add("-p").add("report-event-impact.group-by[1]=hazard.hazard2 as hazard2")
        .add("-p").add("report-event-impact.aggregate[0]=count(exposure.id) as count")
        .add("--output=" + mappedOutputDir.toString())
        .add("--replace")
        .add("--format=csv"));

    assertEquals(0, result.retCode.intValue());
    List<List<String>> results = readColumnsFromCsv(outputDir.resolve("event-impact.csv"),
        "hazard1", "hazard2", "count");
    assertThat(results, containsInAnyOrder(
        Arrays.asList("", "", "3"),
        Arrays.asList("3.0", "", "1"),
        Arrays.asList("4.0", "10.0", "3"),
        Arrays.asList("6.0", "100.0", "1"),
        Arrays.asList("8.0", "", "1"),
        Arrays.asList("8.0", "100.0", "2")
    ));
  }

}
