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

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

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

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

import lombok.Getter;

import nz.org.riskscape.engine.CrsHelper;
import nz.org.riskscape.engine.PipelineMatchers;
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.Struct;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.wizard.model2.analysis.AnalysisPhase;
import nz.org.riskscape.wizard.survey2.BasePhase;
import nz.org.riskscape.wizard.survey2.BasePhaseTest;
import nz.org.riskscape.wizard.Survey;

public class ReportPhaseTest extends BasePhaseTest implements CrsHelper {

  @Getter
  String startWith = "";

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

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

  @Before
  public void setupPipeline() {
    // 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 ->"
        + "select({*, { hazard * exposure.cost as loss, random_uniform(0, 10) as damage} as consequence})"
        + " as " + AnalysisPhase.LAST_STEP_NAME;

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

  @Test
  public void canSelectAttributesToIncludeInOutput() throws Exception {
    selectQuestionSet("report-event-impact");
    answers("select", "exposure.name as Building_name", "consequence.loss as Loss");
    skipRemainingQuestions();

    assertThat(getEndSteps(), contains(
        PipelineMatchers.realizedStepWithType(equalTo(Struct.of(
          "Building_name", Types.TEXT,
          "Loss", Nullable.FLOATING
        )))
    ));
  }

  @Test
  public void canProduceMultipleReports() throws Exception {
    selectQuestionSet("report-event-impact");
    answers("select", "exposure.name as Building_name", "consequence.loss as Loss");
    skipRemainingQuestions();

    selectQuestionSet("reports");
    answers("name", "foo");

    selectQuestionSet("report-foo");
    answers("select", "hazard as Flood_depth", "consequence.damage as Damage");
    skipRemainingQuestions();

    assertThat(getEndSteps(), containsInAnyOrder(
        PipelineMatchers.realizedStepWithType(equalTo(Struct.of(
          "Building_name", Types.TEXT,
          "Loss", Nullable.FLOATING
        ))),
        PipelineMatchers.realizedStepWithType(equalTo(Struct.of(
          "Flood_depth", Nullable.FLOATING,
          "Damage", Types.FLOATING
        )))
    ));
  }

  @Test
  public void canDoSimpleAggregation() {
    selectQuestionSet("report-event-impact");
    answers("group-by", "exposure.year");
    answers("aggregate", "max(hazard) as maxHazard");

    skip("finish-aggregate");

    assertSuccessful();

    skipRemainingQuestions();



    assertThat(getEndSteps(), contains(
      PipelineMatchers.realizedStepWithType(equalTo(Struct.of(
              "year", Types.INTEGER,
              "maxHazard", Nullable.FLOATING
              )
      ))
    ));
  }

  @Test
  public void canDoBucketAggregation() {
    selectQuestionSet("report-event-impact");

    answers("group-by", "exposure.year");
    answer("bucket-by", expressionParser.parse("hazard"));
    answers("bucket-range", 1);
    answers("bucket-aggregation", "max(hazard) as maxHazard");
    answer("bucket-name", "buckets");

    skip("finish-aggregate");

    skipRemainingQuestions();

    getEndSteps();

    assertThat(getEndSteps(), contains(
            PipelineMatchers.realizedStepWithType(equalTo(
                    Struct.of(
                            "year", Types.INTEGER,
                            "buckets", makeBuckets(Struct.of("maxHazard", Nullable.FLOATING))
                    )
            ))
    ));
  }

  @Test
  public void canDoBothSimpleAndBucketAggregation() {

    selectQuestionSet("report-event-impact");
    answers("group-by", "exposure.year");

    answers("aggregate", "max(hazard) as maxHazard");

    answer("bucket-by", expressionParser.parse("hazard"));
    answers("bucket-range", 1);
    answers("bucket-aggregation", "sum(hazard) as sumHazard");
    answer("bucket-name", "buckets");

    skip("finish-aggregate");

    skipRemainingQuestions();

    getEndSteps();

    assertThat(getEndSteps(), contains(
            PipelineMatchers.realizedStepWithType(equalTo(
                    Struct.of(
                            "year", Types.INTEGER,
                            "maxHazard", Nullable.FLOATING,
                            "buckets", makeBuckets(Struct.of("sumHazard", Nullable.FLOATING))
                    )
            ))
    ));
  }

  @Test
  public void groupByWithoutAnyAggregation() {
    // This one is a bit of an odd case, but Tim says he uses it sometimes, so let's support it

    selectQuestionSet("report-event-impact");

    answers("group-by", "exposure.year");
    skip("finish-aggregate");

    skipRemainingQuestions();

    assertThat(getEndSteps(), contains(
            PipelineMatchers.realizedStepWithType(equalTo(
                    Struct.of("year", Types.INTEGER)
            ))
    ));



  }



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

  private void skipRemainingQuestions() {
    skip("format"); // skip to the last optional question
    skip("finish"); // then skip the hidden question at the end
  }

  private Set<RealizedStep> getEndSteps() {
    // the end steps are actually the 'save' steps, which have no produced type
    Set<RealizedStep> saveSteps = buildState.getRealizedPipeline().getEndSteps();
    Set<RealizedStep> lastSteps = new HashSet<>();

    // get the step prior the save so we can see what it produces
    for (RealizedStep step : saveSteps) {
      assertEquals(1, step.getDependencies().size());
      lastSteps.add(step.getDependencies().get(0));
    }
    return lastSteps;
  }

  private Struct makeBuckets(Struct inner) {
    return Struct.of(
            "range_<_1", Nullable.of(inner),
            "range_1_+", Nullable.of(inner)
    );
  }
}
