/*
 * 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 org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import nz.org.riskscape.engine.test.EngineTestPlugins;
import nz.org.riskscape.engine.test.EngineTestSettings;
import org.junit.Test;

import groovy.lang.Category;
import nz.org.riskscape.engine.cli.CliIntegrationTest;
import nz.org.riskscape.engine.cli.ExpressionCommand;
import nz.org.riskscape.engine.test.EngineCommandIntegrationTest;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Sanity-checks the exemplar functions by evaluating them in expressions
 */
@Category(CliIntegrationTest.class)
@EngineTestPlugins({"defaults", "cpython"})
@EngineTestSettings({"cpython.python3-bin=python3", "cpython.lib-dir=lib"})
public class ExemplarFunctionsTest extends EngineCommandIntegrationTest {

  public static final List<String> VOLCANO_FUNCTIONS = Arrays.asList(
    "Volcanic_Impact_State_Road",
    "Volcanic_Impact_State_Rail",
    "Volcanic_Impact_State_Substation",
    "Volcanic_Impact_State_Transmission_Line",
    "Volcanic_Impact_State_Electricity_Generation",
    "Volcanic_Impact_State_Wastewater_Plant",
    "Volcanic_Impact_State_Water_Plant"
  );

  public static final String TEPHRA_HAZARD = "tephra_HIM";

  public static final List<String> VOLCANO_HAZARDS = Arrays.asList(
    "tephra_HIM",
    "pdc_HIM",
    "lahar_HIM",
    "crater_HIM",
    "edifice_HIM",
    "lava_HIM"
  );

  public Path volcanoHome() {
    return Paths.get("..", "..", "exemplars", "functions", "volcano");
  }

  @Test
  public void noVolcanoHazardYieldsNoImpact() {
    populateProject(volcanoHome());

    String nullHazard = VOLCANO_HAZARDS.stream()
      .map(hazard -> hazard + ": null_of('floating')")
      .collect(Collectors.joining(", ", "{", "}"));
    String noDamage = "{pIS0=0.0, pIS1=0.0, pIS2=0.0, pIS3=0.0, impact_state=0}";

    ExpressionCommand.Eval cmd = setupCommand(new ExpressionCommand.Eval());

    for (String function : VOLCANO_FUNCTIONS) {
      // everything supplied in-line (exposure args can be anything)
      cmd.expression = String.format("%s('foo', %s)", function, nullHazard);
      assertEquals(noDamage, cmd.run());
    }
  }

  @Test
  public void volcanicNonTephraHazardYieldsBadImpactState() {
    populateProject(volcanoHome());

    // if an asset is exposed to anything besides tephra (i.e. lava, edifice, etc), it's basically written off
    String completeDamage = "{pIS0=1.0, pIS1=1.0, pIS2=1.0, pIS3=1.0, impact_state=3}";

    ExpressionCommand.Eval cmd = setupCommand(new ExpressionCommand.Eval());

    for (String hazard : VOLCANO_HAZARDS) {
      if (hazard.equals(TEPHRA_HAZARD)) {
        continue;
      }
      for (String function : VOLCANO_FUNCTIONS) {
        cmd.expression = String.format("%s('foo', { %s: 1.0 })", function, hazard);
        assertEquals(completeDamage, cmd.run());
      }
    }
  }

  @Test
  public void volcanicOneMetreTephraYieldsBadImpactState() {
    populateProject(volcanoHome());

    // if an asset is exposed to >= 1000mm tephra, it's basically written off
    String completeDamage = "{pIS0=1.0, pIS1=1.0, pIS2=1.0, pIS3=1.0, impact_state=3}";

    ExpressionCommand.Eval cmd = setupCommand(new ExpressionCommand.Eval());

    for (String function : VOLCANO_FUNCTIONS) {
      cmd.expression = String.format("%s('foo', { %s: 1000.0 })", function, TEPHRA_HAZARD);
      assertEquals(completeDamage, cmd.run());
    }
  }

  @Test
  public void volcanicTenCmTephraYieldsDifferentImpactStates() {
    populateProject(volcanoHome());

    // call the function with the same tephra value (10cm) and the results should vary because
    // different logic is being used by each of the different functions
    List<String> expectedDamage = Arrays.asList(
      "{pIS0=1.0, pIS1=0.804, pIS2=0.318, pIS3=0.054, impact_state=1}",              // road
      "{pIS0=1.0, pIS1=1.0, pIS2=0.681, pIS3=0.381, impact_state=2}",                // rail
      "{pIS0=1.0, pIS1=0.8190000000000001, pIS2=0.479, pIS3=0.179, impact_state=1}", //substation
      "{pIS0=1.0, pIS1=0.8099999999999999, pIS2=0.44899999999999995, pIS3=0.069, impact_state=1}", // transmission
      "{pIS0=1.0, pIS1=0.841, pIS2=0.515, pIS3=0.228, impact_state=1}",              // elec gen
      "{pIS0=1.0, pIS1=1.0, pIS2=0.835, pIS3=0.317, impact_state=2}",                // wwtp
      "{pIS0=1.0, pIS1=0.882, pIS2=0.5640000000000001, pIS3=0.232, impact_state=1}"  // wtp
    );

    ExpressionCommand.Eval cmd = setupCommand(new ExpressionCommand.Eval());

    for (int i = 0; i < VOLCANO_FUNCTIONS.size(); i++) {
      String function = VOLCANO_FUNCTIONS.get(i);
      cmd.expression = String.format("%s('foo', { %s: 100.0 }, random_seed: 12345)", function, TEPHRA_HAZARD);
      assertEquals(expectedDamage.get(i), cmd.run());
    }
  }

  @Test
  public void volcanicRandomSeedChangesImpactState() {
    populateProject(volcanoHome());

    // probabilities are the same as volcanicTenCmTephraYieldsDifferentImpactStates() but the
    // impact_state is different because we're using a different random seed
    List<String> expectedDamage = Arrays.asList(
      "{pIS0=1.0, pIS1=0.804, pIS2=0.318, pIS3=0.054, impact_state=2}",              // road
      "{pIS0=1.0, pIS1=1.0, pIS2=0.681, pIS3=0.381, impact_state=3}",                // rail
      "{pIS0=1.0, pIS1=0.8190000000000001, pIS2=0.479, pIS3=0.179, impact_state=2}", //substation
      "{pIS0=1.0, pIS1=0.8099999999999999, pIS2=0.44899999999999995, pIS3=0.069, impact_state=2}", // transmission
      "{pIS0=1.0, pIS1=0.841, pIS2=0.515, pIS3=0.228, impact_state=2}",              // elec gen
      "{pIS0=1.0, pIS1=1.0, pIS2=0.835, pIS3=0.317, impact_state=3}",                // wwtp
      "{pIS0=1.0, pIS1=0.882, pIS2=0.5640000000000001, pIS3=0.232, impact_state=2}"  // wtp
    );

    ExpressionCommand.Eval cmd = setupCommand(new ExpressionCommand.Eval());

    for (int i = 0; i < VOLCANO_FUNCTIONS.size(); i++) {
      String function = VOLCANO_FUNCTIONS.get(i);
      cmd.expression = String.format("%s('foo', { %s: 100.0 }, random_seed: 456)", function, TEPHRA_HAZARD);
      assertEquals(expectedDamage.get(i), cmd.run());
    }
  }

  @Test
  public void volcanicCanSanityCheckHazardLayer() {
    populateProject(volcanoHome());

    // check there's a way that users can check for typos/type mismatches in their multi-hazard layer
    ExpressionCommand.Eval cmd = setupCommand(new ExpressionCommand.Eval());
    cmd.expression = "Volcanic_Multihazard_Info({tephra_HIM: 99.0, lava_HIM: 1, "
          + "crater_HIM: null_of('floating'), PDC: 0.0 })";
    assertThat(cmd.run(), is("{hazards=[Tephra, Lava, Crater], "
              + "missing_attributes=[lahar_HIM, edifice_HIM, pdc_HIM], spurious_attributes=[PDC]}")
    );
  }
}
