/*
 * 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.wizard.model2.analysis;

import static nz.org.riskscape.engine.function.RiskscapeFunction.*;

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

import java.util.Arrays;
import java.util.Locale;
import java.util.Optional;

import nz.org.riskscape.wizard.model2.smp.SamplePhase;
import org.junit.Before;
import org.junit.Test;

import lombok.Getter;

import nz.org.riskscape.engine.function.IdentifiedFunction;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.relation.EmptyRelation;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.wizard.Question;
import nz.org.riskscape.wizard.survey2.BasePhase;
import nz.org.riskscape.wizard.survey2.BasePhaseTest;
import nz.org.riskscape.wizard.Survey;

public class AnalysisPhaseTest  extends BasePhaseTest {


  // last question is hidden one to append reporting questions to
  public static final String LAST_QUESTION = "final";

  @Getter
  String startWith = "";

  Struct exposureType = Struct.of("name", Types.TEXT, "cost", Types.FLOATING, "year", Types.INTEGER);

  Struct complexHazardType = Struct.of("value", Types.FLOATING);

  IdentifiedFunction simpleHazardFunction = RiskscapeFunction.create(BUILT_IN,
      Arrays.asList(exposureType, Types.FLOATING),
      Types.FLOATING, (args) -> args.get(1))
      .identified("simpleHazard");

  IdentifiedFunction complexHazardFunction = RiskscapeFunction.create(BUILT_IN,
      Arrays.asList(exposureType, complexHazardType),
      Types.FLOATING, (args) -> args.get(1))
      .identified("complexHazard");

  @Before
  public void setupFixtures() {
    project.getFunctionSet().add(simpleHazardFunction);
    project.getFunctionSet().add(complexHazardFunction);
  }

  @Override
  protected BasePhase getPhaseUnderTest(Survey survey) {
    return new AnalysisPhase(survey);
  }

  public void setupSimpleHazardPipeline() {
    // create a basic runnable pipeline that will always produce hazard/consequence values
    startWith = ""
        + "input(relation: 'exposures',      name: 'exposure') as exposures -> "
        + "select({*, random_choice([0.0, 1.0, null_of('floating')]) as hazard}) as sampled";

    addPickledData("exposures", new EmptyRelation(exposureType));
  }

  public void setupComplexHazardPipeline() {
    // create a basic runnable pipeline that will always produce hazard/consequence values
    startWith = ""
        + "input(relation: 'exposures',      name: 'exposure') as exposures -> "
        + "select({*, random_choice([{value: 2.5}, {value: 3.5}]) as hazard}) as sampled";

    addPickledData("exposures", new EmptyRelation(exposureType));
  }

  @Test
  public void canCallAFunctionWithSimpleHazardType() {
    setupSimpleHazardPipeline();

    selectQuestionSet("analysis");
    answer("function", simpleHazardFunction);

    Question last = pick(LAST_QUESTION);
    assertThat(buildState.getInputStruct(last), equalTo(
        Struct.of("exposure", exposureType, "hazard", Nullable.FLOATING, "consequence", Nullable.FLOATING)
    ));
  }

  @Test
  public void canCallAFunctionWithComplexHazardType() {
    setupComplexHazardPipeline();

    selectQuestionSet("analysis");
    answer("map-hazard", Boolean.FALSE);
    answer("function", complexHazardFunction);

    Question last = pick(LAST_QUESTION);
    assertThat(buildState.getInputStruct(last), equalTo(
        Struct.of("exposure", exposureType, "hazard", complexHazardType, "consequence", Types.FLOATING)
    ));
  }

  @Test
  public void canMapVectorLayerHazardToRasterLayerFunction() {
    // we have a complex hazard but want to use our simple function
    setupComplexHazardPipeline();

    selectQuestionSet("analysis");
    answer("map-hazard", Boolean.TRUE);
    answer("map-hazard-intensity", expressionParser.parse("value"));
    answer("function", simpleHazardFunction);

    Question last = pick(LAST_QUESTION);
    assertThat(buildState.getInputStruct(last), equalTo(
        Struct.of("exposure", exposureType, "hazard", Types.FLOATING, "consequence", Types.FLOATING)
    ));
  }

  @Test
  public void exposedRatioListIsSummed() {
    setupSimpleHazardPipeline();
    startWith = startWith + " -> select({*, [0.1, 0.2] as exposed_ratio})";

    selectQuestionSet("analysis");
    answer("function", simpleHazardFunction);

    skip(LAST_QUESTION);
    assertThat(buildState.getRealizedStep().getProduces(), equalTo(
        Struct.of("exposure", exposureType,
            "hazard", Nullable.FLOATING,
            "exposed_ratio", Nullable.FLOATING,
            "consequence", Nullable.FLOATING)
        )
    );
  }

  @Test
  public void lastSelectDoesNotIncludeHazardSampled() {
    // See #1316

    setupSimpleHazardPipeline();

    // Simulate the sample step happening earlier in the pipeline
    startWith = startWith + " -> select({*, 1 as " + SamplePhase.SAMPLED_HAZARD + "})";

    selectQuestionSet("analysis");
    answer("function", simpleHazardFunction);

    Question last = pick(LAST_QUESTION);
    answer(last, Question.HIDDEN_VALUE);

    assertThat(
        buildState.getInputStruct(last).getMember(SamplePhase.SAMPLED_HAZARD),
        equalTo(Optional.empty()
    ));
  }


  @Test
  public void phaseHasExpectedName() {
    AnalysisPhase analysisPhase = survey.getPhaseOfType(AnalysisPhase.class).orElseThrow();
    assertThat(analysisPhase.getName(Locale.getDefault()).get(), is("Analysis"));
  }
}
