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

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

import java.util.Locale;
import java.util.Set;

import org.junit.Test;

import lombok.Getter;

import nz.org.riskscape.engine.CrsHelper;
import nz.org.riskscape.engine.PipelineMatchers;
import nz.org.riskscape.engine.coverage.TypedCoverage;
import nz.org.riskscape.engine.i18n.MutableMessageSource;
import nz.org.riskscape.engine.pipeline.RealizedStep;
import nz.org.riskscape.engine.relation.EmptyRelation;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.RSList;
import nz.org.riskscape.engine.types.Referenced;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.rl.ExpressionParser;
import nz.org.riskscape.wizard.Question;
import nz.org.riskscape.wizard.model2.input.InputDataPhase;
import nz.org.riskscape.wizard.survey2.BasePhase;
import nz.org.riskscape.wizard.survey2.BasePhaseTest;
import nz.org.riskscape.wizard.Survey;

public class SamplePhaseTest extends BasePhaseTest implements CrsHelper {

  // last question is hidden one to append 'sampled' step name
  public static final String LAST_QUESTION = "append-name";

  @Getter
  String startWith = "";

  Struct exposureType = Struct.of("id", Types.INTEGER, "name", Types.TEXT, "geom", Types.POLYGON);

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

  @Test
  public void canInterrogateInputScopeStructForNextQuestion() throws Exception {
    // this is really a general-purpose test for IncrementalBuildState.getInputStruct(),
    // but it's a bit easier to prove it's working when we're adding real pipeline
    // changes rather than trying to mock everything
    startWith = inputRelation("exposures", exposureType)
        + inputCoverage("hazards", Types.FLOATING)
        + inputCoverage("resources", Types.TEXT);

    selectQuestionSet("sample");
    Question sampleHazard = pick("hazards-by");

    // haven't answered the question yet, so input type is just the exposure-layer
    assertThat(buildState.getInputStruct(sampleHazard), equalTo(
        Struct.of("exposure", exposureType)
    ));

    // once we answer it, we should see the sampled result present for the next question
    answer(sampleHazard, SampleType.CENTROID);
    Question resourcesBuffer = pick("resources-buffer");

    assertThat(buildState.getInputStruct(resourcesBuffer), equalTo(
        Struct.of("exposure", exposureType, "hazard", Nullable.FLOATING)
    ));

    answer(resourcesBuffer, ExpressionParser.INSTANCE.parse("10.0"));
    Question last = pick(LAST_QUESTION);

    assertThat(buildState.getInputStruct(last), equalTo(
        Struct.of("exposure", exposureType, "hazard", Nullable.FLOATING, "resource", Nullable.TEXT)
    ));
  }

  @Test
  public void canDoCentroidSampleOnASingleCoverage() throws Exception {
    startWith = inputRelation("exposures", exposureType) + inputCoverage("hazards", Types.FLOATING);

    selectQuestionSet("sample");
    answer("hazards-by", SampleType.CENTROID);
    skipRemainingQuestions();

    assertNoMoreQuestions();

    Set<RealizedStep> endSteps = buildState.getRealizedPipeline().getEndSteps();
    assertThat(
      endSteps,
      contains(
        PipelineMatchers.realizedStepWithType(equalTo(Struct.of(
          "exposure", exposureType,
          "hazard", Nullable.FLOATING
        )))
      )
    );
  }

  @Test
  public void canDoClosestSampleOnASingleCoverage() throws Exception {
    startWith = inputRelation("exposures", exposureType)
        + inputCoverage("hazards", Types.FLOATING);

    selectQuestionSet("sample");
    answer("hazards-by", SampleType.CLOSEST);
    skip("hazards-buffer");
    skipRemainingQuestions();

    assertNoMoreQuestions();

    Set<RealizedStep> endSteps = buildState.getRealizedPipeline().getEndSteps();
    assertThat(
      endSteps,
      contains(
        PipelineMatchers.realizedStepWithType(equalTo(Struct.of(
          "exposure", exposureType,
          "hazard", Nullable.FLOATING
        )))
      )
    );
  }

  @Test
  public void canDoAllIntersectionsSampleOnASingleCoverage() throws Exception {
    startWith = inputRelation("exposures", exposureType)
        + inputCoverage("hazards", Types.FLOATING);

    selectQuestionSet("sample");
    answer("hazards-by", SampleType.ALL_INTERSECTIONS);
    skip("hazards-buffer");
    skipRemainingQuestions();

    assertNoMoreQuestions();

    Set<RealizedStep> endSteps = buildState.getRealizedPipeline().getEndSteps();
    assertThat(
      endSteps,
      contains(
        PipelineMatchers.realizedStepWithType(equalTo(Struct.of(
          "exposure", exposureType,
          // note the hazard should be a list of the type that the coverage contains
          "hazard", RSList.create(Types.FLOATING),
          SamplePhase.SAMPLED_HAZARD, RSList.create(Struct.of("geometry", Types.GEOMETRY, "sampled", Types.FLOATING)),
          SamplePhase.EXPOSED_RATIO, RSList.create(Types.FLOATING)
        )))
      )
    );
  }

  @Test
  public void canDoBufferAllIntersectionsSampling() throws Exception {
    startWith = inputRelation("exposures", exposureType)
        + inputCoverage("hazards", Types.FLOATING);

    selectQuestionSet("sample");
    answer("hazards-by", SampleType.ALL_INTERSECTIONS);
    answer("hazards-buffer", ExpressionParser.INSTANCE.parse("10.0"));
    skipRemainingQuestions();

    assertNoMoreQuestions();

    Set<RealizedStep> endSteps = buildState.getRealizedPipeline().getEndSteps();
    assertThat(
      endSteps,
      contains(
        PipelineMatchers.realizedStepWithType(equalTo(Struct.of(
          "exposure", exposureType,
          "hazard", RSList.create(Types.FLOATING),
          // note we don't support 'exposed_ratio' here because we buffered the original geometry
          SamplePhase.SAMPLED_HAZARD, RSList.create(Struct.of("geometry", Types.GEOMETRY, "sampled", Types.FLOATING))
        )))
      )
    );
  }

  @Test
  public void canSampleManyLayers() throws Exception {
    Struct hazardFeatureType = Struct.of(
        "depth", Types.FLOATING,
        "area",  Referenced.of(Types.POLYGON, nzTransverseMercator())
      );
    startWith = inputRelation("exposures", exposureType)
        + inputCoverage("hazards", hazardFeatureType)
        + inputCoverage("carrots", Types.TEXT)
        + inputCoverage("canines", RSList.create(Types.TEXT));

    selectQuestionSet("sample");
    // sampling the hazard-layer is the only mandatory question
    answer("hazards-by", SampleType.CENTROID);

    skipRemainingQuestions();

    assertNoMoreQuestions();
    assertSuccessful();

    Set<RealizedStep> endSteps = buildState.getRealizedPipeline().getEndSteps();
    assertThat(
      endSteps,
      contains(
        PipelineMatchers.realizedStepWithType(equalTo(Struct.of(
          "exposure", exposureType,
          "hazard", Nullable.of(hazardFeatureType),
          "carrot", Nullable.of(Types.TEXT),
          "canine", Nullable.of(RSList.create(Types.TEXT))
        )))
      )
    );
  }

  @Test
  public void canSkipSamplingBufferQuestions() throws Exception {
    Struct hazardFeatureType = Struct.of(
        "depth", Types.FLOATING,
        "area",  Referenced.of(Types.POLYGON, nzTransverseMercator())
      );
    startWith = inputRelation("exposures", exposureType)
        + inputCoverage("hazards", hazardFeatureType)
        + inputCoverage("carrots", Types.TEXT)
        + inputCoverage("canines", RSList.create(Types.TEXT));

    selectQuestionSet("sample");
    assertThat(choices("hazards-by", SampleType.class), contains(
        // polygons see all_intersections
        SampleType.CENTROID, SampleType.CLOSEST, SampleType.ALL_INTERSECTIONS
    ));
    answer("hazards-by", SampleType.CLOSEST);

    // specifying a buffer for these other layers are optional
    skip("hazards-buffer");
    skip("canines-buffer");
    skipRemainingQuestions();

    assertNoMoreQuestions();
    assertSuccessful();

    Set<RealizedStep> endSteps = buildState.getRealizedPipeline().getEndSteps();
    assertThat(
      endSteps,
      contains(
        PipelineMatchers.realizedStepWithType(equalTo(Struct.of(
          "exposure", exposureType,
          "hazard", Nullable.of(hazardFeatureType),
          "carrot", Nullable.of(Types.TEXT),
          "canine", Nullable.of(RSList.create(Types.TEXT))
        )))
      )
    );
  }


  @Test
  public void pointHazardLayersNotOfferedAllIntersections() throws Exception {
    exposureType = Struct.of("id", Types.INTEGER, "geom", Types.POINT);
    Struct hazardFeatureType = Struct.of(
        "depth", Types.FLOATING,
        "area",  Referenced.of(Types.POLYGON, nzTransverseMercator())
      );
    startWith = inputRelation("exposures", exposureType)
        + inputCoverage("hazards", hazardFeatureType);

    selectQuestionSet("sample");
    assertThat(choices("hazards-by", SampleType.class), contains(
        // smaller set of options - this is point exposures
        SampleType.CENTROID, SampleType.CLOSEST
    ));
    answer("hazards-by", SampleType.CLOSEST);

    skip("hazards-buffer");
    // specifying a sample type for carrots/canines is optional
    skipRemainingQuestions();

    assertNoMoreQuestions();
    assertSuccessful();

    Set<RealizedStep> endSteps = buildState.getRealizedPipeline().getEndSteps();
    assertThat(
      endSteps,
      contains(
        PipelineMatchers.realizedStepWithType(equalTo(Struct.of(
          "exposure", exposureType,
          "hazard", Nullable.of(hazardFeatureType)
        )))
      )
    );
  }

  @Test
  public void phaseHasExpectedName() {
    SamplePhase samplePhase = survey.getPhaseOfType(SamplePhase.class).orElseThrow();
    assertThat(samplePhase.getName(Locale.getDefault()).get(), is("Sample"));

    if (survey.getMessageSource() instanceof MutableMessageSource mms) {
      mms.addMessage(Locale.getDefault(), "phase.Sample.name", "my sample phase");
      assertThat(samplePhase.getName(Locale.getDefault()).get(), is("my sample phase"));
    } else {
      fail("message source not mutable");
    }
  }

  private void skipRemainingQuestions() {
    skip(LAST_QUESTION);
  }

  private String inputCoverage(String datasetName, Type type) {
    // note that the SamplePhase code expects the pipeline to have start and end
    // steps that follow an expected naming format
    addPickledData(datasetName, TypedCoverage.empty(type));
    String template = String.format(""
        + " input(value: bookmark('LAYER'), name: '%s') as LAYER_input"
        + " -> select({*}) as LAYER ",
        InputDataPhase.getAttributeName(datasetName));
    return template.replaceAll("LAYER", datasetName);
  }

  private String inputRelation(String datasetName, Struct type) {
    addPickledData(datasetName, new EmptyRelation(type));
    String template = String.format(""
        + " input(relation: 'LAYER', name: '%s') as LAYER_input"
        + " -> select({*}) as LAYER ",
        InputDataPhase.getAttributeName(datasetName));
    return template.replaceAll("LAYER", datasetName);
  }
}
