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

import static nz.org.riskscape.engine.Assert.*;
import static nz.org.riskscape.engine.Matchers.*;

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

import org.junit.Test;

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.pipeline.Realized;
import nz.org.riskscape.engine.projection.FlatProjector;
import nz.org.riskscape.engine.relation.ListRelation;
import nz.org.riskscape.engine.types.CoercionException;
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.problem.ResultOrProblems;
import nz.org.riskscape.problem.Problem.Severity;

@SuppressWarnings("unchecked")
public class SegmentStepTest extends BaseStepTest<SegmentStep> {

  @Override
  protected SegmentStep createStep() {
    return new SegmentStep(engine);
  }

  Struct inputType = Struct.of("a1", Types.TEXT, "a2", Types.TEXT, "a3", Types.TEXT);
  ListRelation relation = new ListRelation(Tuple.ofValues(inputType));

  @Test
  public void canSegmentAndCoerceToIntegers() {
    addInput(relation);

    Struct s1Type = Struct.of("a1", Types.INTEGER);
    addParam("segmented", Struct.of("s1", s1Type));

    Struct expectedType = Struct.of("s1", s1Type);

    ResultOrProblems<? extends Realized> realized = step.realizeSimple(input());
    assertThat(realized, result(FlatProjector.class, flatProjecting(expectedType)));

    FlatProjector projector = (FlatProjector) realized.get();
    assertThat(projector.getSourceType(), is(inputType));

    assertThat(
        projector.apply(Tuple.ofValues(inputType, "1", "2", "3")),
        iteratorWithTuples(Tuple.ofValues(expectedType, Tuple.ofValues(s1Type, 1L))));

    CoercionException ex = assertThrows(CoercionException.class,
        () -> projector.apply(Tuple.ofValues(inputType, "dog", "2", "3")));
    assertThat(ex.getMessage(), is("Value 'dog' from source attribute a1 could not be converted to type Integer - "
        + "Can not convert value 'dog' (class java.lang.String) to riskscape type 'Integer'"));
  }

  @Test
  public void willSkipRowsThatFailCoercion() {
    addInput(relation);

    Struct s1Type = Struct.of("a1", Types.INTEGER);
    addParam("segmented", Struct.of("s1", s1Type));
    addParam("skip-invalid", true);

    Struct expectedType = Struct.of("s1", s1Type);

    ResultOrProblems<? extends Realized> realized = step.realizeSimple(input());
    assertThat(realized, result(FlatProjector.class, flatProjecting(expectedType)));

    FlatProjector projector = (FlatProjector) realized.get();
    assertThat(projector.getSourceType(), is(inputType));

    assertThat(
        projector.apply(Tuple.ofValues(inputType, "1", "2", "3")),
        iteratorWithTuples(Tuple.ofValues(expectedType, Tuple.ofValues(s1Type, 1L))));

    assertThat(
        projector.apply(Tuple.ofValues(inputType, "dog", "2", "3")),
        iteratorWithTuples());  //emtpy iterator
  }

  @Test
  public void canAllowMissingAttributes_ProducesNulls() {
    addInput(relation);

    Struct s1Type = Struct.of("a1", Types.INTEGER, "missing", Types.TEXT);
    addParam("segmented", Struct.of("s1", s1Type));
    addParam("allow-missing-attributes", true);

    Struct expectedType = Struct.of("s1", s1Type);

    ResultOrProblems<? extends Realized> realized = step.realizeSimple(input());
    assertThat(realized, result(FlatProjector.class, flatProjecting(expectedType)));

    FlatProjector projector = (FlatProjector) realized.get();
    assertThat(projector.getSourceType(), is(inputType));

    assertThat(
        projector.apply(Tuple.ofValues(inputType, "1", "2", "3")),
        iteratorWithTuples(Tuple.ofValues(expectedType, Tuple.ofValues(s1Type, 1L, null))));
  }

  @Test
  public void canSegmentAndCoerceToNullableIntegers() {
    addInput(relation);

    Struct s1Type = Struct.of("a1", Nullable.INTEGER);
    addParam("segmented", Struct.of("s1", s1Type));

    Struct expectedType = Struct.of("s1", s1Type);

    ResultOrProblems<? extends Realized> realized = step.realizeSimple(input());
    assertThat(realized, result(FlatProjector.class, flatProjecting(expectedType)));

    FlatProjector projector = (FlatProjector) realized.get();
    assertThat(projector.getSourceType(), is(inputType));

    assertThat(
        projector.apply(Tuple.ofValues(inputType, "1", "2", "3")),
        iteratorWithTuples(Tuple.ofValues(expectedType, Tuple.ofValues(s1Type, 1L))));

    //Empty string should coerce to null
    assertThat(
        projector.apply(Tuple.ofValues(inputType, "", "2", "3")),
        iteratorWithTuples(Tuple.ofValues(expectedType, Tuple.ofValues(s1Type))));
  }

  @Test
  public void canSegmentText() {
    addInput(relation);

    Struct s1Type = Struct.of("a1", Types.TEXT);
    addParam("segmented", Struct.of("s1", s1Type));

    Struct expectedType = Struct.of("s1", s1Type);

    ResultOrProblems<? extends Realized> realized = step.realizeSimple(input());
    assertThat(realized, result(FlatProjector.class, flatProjecting(expectedType)));

    FlatProjector projector = (FlatProjector) realized.get();
    assertThat(projector.getSourceType(), is(inputType));

    assertThat(
        projector.apply(Tuple.ofValues(inputType, "1", "2", "3")),
        iteratorWithTuples(Tuple.ofValues(expectedType, Tuple.ofValues(s1Type, "1"))));

    assertThat(
        projector.apply(Tuple.ofValues(inputType, "some text", "2", "3")),
        iteratorWithTuples(Tuple.ofValues(expectedType, Tuple.ofValues(s1Type, "some text"))));

    assertThat(
        projector.apply(Tuple.ofValues(inputType, "", "2", "3")),
        iteratorWithTuples(Tuple.ofValues(expectedType, Tuple.ofValues(s1Type, ""))));
  }

  @Test
  public void canSegmentManyThingsOfDifferenctTypes() {
    addInput(relation);

    Struct s1Type = Struct.of("a1", Types.TEXT);
    Struct s2Type = Struct.of("a2", Types.INTEGER);
    Struct s3Type = Struct.of("a3", Types.BOOLEAN);

    Struct expectedType = Struct.of("s1", s1Type, "s2", s2Type, "s3", s3Type);
    addParam("segmented", expectedType);

    ResultOrProblems<? extends Realized> realized = step.realizeSimple(input());
    assertThat(realized, result(FlatProjector.class, flatProjecting(expectedType)));

    FlatProjector projector = (FlatProjector) realized.get();
    assertThat(projector.getSourceType(), is(inputType));

    assertThat(
        projector.apply(Tuple.ofValues(inputType, "text", "2", "true")),
        iteratorWithTuples(Tuple.ofValues(expectedType,
            Tuple.ofValues(s1Type, "text"),
            Tuple.ofValues(s2Type, 2L),
            Tuple.ofValues(s3Type, true))));
  }

  @Test
  public void canSegmentManyThingsAndSkipInvalid() {
    addInput(relation);
    addParam("skip-invalid", true);

    Struct s1Type = Struct.of("a1", Types.TEXT);
    Struct s2Type = Struct.of("a2", Types.INTEGER);
    Struct s3Type = Struct.of("a3", Types.FLOATING);

    Struct expectedType = Struct.of("s1", s1Type, "s2", s2Type, "s3", s3Type);
    addParam("segmented", expectedType);

    ResultOrProblems<? extends Realized> realized = step.realizeSimple(input());
    assertThat(realized, result(FlatProjector.class, flatProjecting(expectedType)));

    FlatProjector projector = (FlatProjector) realized.get();
    assertThat(projector.getSourceType(), is(inputType));

    assertThat(
        projector.apply(Tuple.ofValues(inputType, "text", "2", "2.5")),
        iteratorWithTuples(Tuple.ofValues(expectedType,
            Tuple.ofValues(s1Type, "text"),
            Tuple.ofValues(s2Type, 2L),
            Tuple.ofValues(s3Type, 2.5D))));

    assertThat(
        projector.apply(Tuple.ofValues(inputType, "text", "two", "2.5")),
        iteratorWithTuples());

    assertThat(
        projector.apply(Tuple.ofValues(inputType, "text", "2", "two point five")),
        iteratorWithTuples());

    assertThat(
        projector.apply(Tuple.ofValues(inputType, "text", "two", "two point five")),
        iteratorWithTuples());
  }

  @Test
  public void failWhenRequiredAttributesDoNotExist() {
    addInput(relation);

    Struct s1Type = Struct.of("not_known", Types.INTEGER);
    addParam("segmented", Struct.of("s1", s1Type));

    assertThat(step.realizeSimple(input()),
        failedResult(isProblem(Severity.ERROR, is(
            "Segment 's1' requires attribute 'not_known' which does not exist in input {a1=>Text, a2=>Text, a3=>Text}"
        ))));

  }

  @Test
  public void failForNestedStructs_InputSide() {
    Struct nestedInputType = Struct.of("a1", Struct.of("value", Types.TEXT));
    ListRelation nestedRelation = new ListRelation(Tuple.ofValues(nestedInputType));

    addInput(nestedRelation);

    Struct s1Type = Struct.of("a1", Types.ANYTHING);
    addParam("segmented", Struct.of("s1", s1Type));

    assertThat(step.realizeSimple(input()),
        failedResult(isProblem(Severity.ERROR, is(
            "Source attribute 'a1' is a struct"
        ))));

  }

  @Test
  public void failForNestedStructs_ProducedSide() {
    Struct nestedInputType = Struct.of("a1", Types.TEXT);
    ListRelation nestedRelation = new ListRelation(Tuple.ofValues(nestedInputType));

    addInput(nestedRelation);

    Struct s1Type = Struct.of("a1", Struct.of("value", Types.ANYTHING));
    addParam("segmented", Struct.of("s1", s1Type));

    assertThat(step.realizeSimple(input()),
        failedResult(isProblem(Severity.ERROR, is(
            "Segment 's1' contains nested structs in 'a1'"
        ))));

  }
}
