/*
 * 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.GeoHelper.*;
import static nz.org.riskscape.engine.Matchers.*;
import static nz.org.riskscape.engine.TupleMatchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

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

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.gt.GeometryHelper;
import nz.org.riskscape.engine.projection.Projector;
import nz.org.riskscape.engine.steps.EnlargeStep.AccumInstance;
import nz.org.riskscape.engine.steps.EnlargeStep.EnlargingCollector;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.engine.types.TypeProblems;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.problem.StandardCodes;
import nz.org.riskscape.rl.ast.Expression;

@SuppressWarnings("unchecked")
public class EnlargeStepTest extends BaseStepTest<EnlargeStep> {

  GeometryHelper nzmgGeomHelper = GeometryHelper.nzMapGridWithOriginShift(project.getSridSet());

  ResultOrProblems<?> realized;
  Struct produced;

  @Before
  public void reset() {
    produced = null;
  }

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

  @Test
  public void canEnlargeLinesByAttributeMitredFlat() {
    Struct inputType = Struct.of("my-geom", Types.LINE, "value", Types.INTEGER);

    addParam("distance", expressionParser.parse("value"));
    addParam("mode", EnlargeStep.EnlargeMode.MITRED_FLAT);

    addStubInput(inputType);

    Tuple t1 = Tuple.ofValues(inputType, nzmgGeomHelper.line(10, 100, 100, 100), 1L);
    Tuple t2 = Tuple.ofValues(inputType, nzmgGeomHelper.line(10, 200, 100, 200), 2L);

    assertThat(run(inputType, t1, t2), contains(
        tupleWithValue("my-geom", geometryTopoMatch(nzmgGeomHelper.box(10, 99, 100, 101))),
        tupleWithValue("my-geom", geometryTopoMatch(nzmgGeomHelper.box(10, 198, 100, 202)))
    ));
  }

  @Test
  public void canEnlargeLinesByAttributeMitredSquare() {
    Struct inputType = Struct.of("geom", Types.LINE, "value", Types.INTEGER);

    addParam("distance", expressionParser.parse("value"));
    addParam("mode", EnlargeStep.EnlargeMode.MITRED_SQUARE);

    addStubInput(inputType);

    Tuple t1 = Tuple.ofValues(inputType, nzmgGeomHelper.line(10, 100, 100, 100), 1L);
    Tuple t2 = Tuple.ofValues(inputType, nzmgGeomHelper.line(10, 200, 100, 200), 2L);

    assertThat(run(inputType, t1, t2), contains(
        tupleWithValue("geom", geometryTopoMatch(nzmgGeomHelper.box(9, 99, 101, 101))),
        tupleWithValue("geom", geometryTopoMatch(nzmgGeomHelper.box(8, 198, 102, 202)))
    ));
  }

  @Test
  public void canEnlargeGeomInNestedTuple() {
    Struct itemType = Struct.of("geom", Types.LINE, "value", Types.INTEGER);
    Struct inputType = Struct.of("value", itemType);

    addParam("distance", expressionParser.parse("1"));
    addParam("mode", EnlargeStep.EnlargeMode.MITRED_FLAT);

    addStubInput(inputType);

    Tuple t1 = Tuple.ofValues(inputType, Tuple.ofValues(itemType, nzmgGeomHelper.line(10, 100, 100, 100), 1L));
    Tuple t2 = Tuple.ofValues(inputType, Tuple.ofValues(itemType, nzmgGeomHelper.line(10, 200, 100, 200), 2L));

    assertThat(run(inputType, t1, t2), contains(
        tupleWithValue("value", tupleWithValue("geom", geometryTopoMatch(nzmgGeomHelper.box(10, 99, 100, 101)))),
        tupleWithValue("value", tupleWithValue("geom", geometryTopoMatch(nzmgGeomHelper.box(10, 199, 100, 201))))
    ));
  }

  @Test
  public void canEnlargeGeomInNullableNestedTuple() {
    Struct itemType = Struct.of("geom", Types.LINE, "value", Types.INTEGER);
    Struct inputType = Struct.of("value", Nullable.of(itemType));

    addParam("distance", expressionParser.parse("1"));
    addParam("mode", EnlargeStep.EnlargeMode.MITRED_FLAT);

    addStubInput(inputType);

    Tuple t1 = Tuple.ofValues(inputType, Tuple.ofValues(itemType, nzmgGeomHelper.line(10, 100, 100, 100), 1L));
    Tuple t2 = Tuple.ofValues(inputType);

    assertThat(run(inputType, t1, t2), contains(
        tupleWithValue("value", tupleWithValue("geom", geometryTopoMatch(nzmgGeomHelper.box(10, 99, 100, 101)))),
        tupleWithValue("value", nullValue())
    ));
  }

  @Test
  public void canSpecifyWhichGeomToEnlarge() {
    Struct inputType = Struct.of("geom", Types.LINE, "value", Types.INTEGER, "geom2", Types.LINE);

    addParam("geom-expression", expressionParser.parse("geom2"));
    addParam("distance", expressionParser.parse("value"));
    addParam("mode", EnlargeStep.EnlargeMode.MITRED_SQUARE);

    addStubInput(inputType);

    Tuple t1 = Tuple.ofValues(inputType,
        nzmgGeomHelper.line(10, 100, 100, 100),
        2L,
        nzmgGeomHelper.line(10, 200, 100, 200));

    Tuple enlarged = run(inputType, t1).get(0);
    StructMember geomMember = produced.getEntry("geom");
    StructMember geom2Member = produced.getEntry("geom2");
    assertThat(enlarged.fetch(geomMember), is(nzmgGeomHelper.line(10, 100, 100, 100)));
    assertThat(enlarged.fetch(geom2Member), geometryTopoMatch(nzmgGeomHelper.box(8, 198, 102, 202)));
  }

  @Test
  public void canEnlargeLinesWithNoResultingOverlaps() {
    Struct inputType = Struct.of("geom", Types.LINE, "value", Types.TEXT);

    addParam("distance", expressionParser.parse("1"));
    addParam("mode", EnlargeStep.EnlargeMode.MITRED_FLAT);
    addParam("remove-overlaps", true);

    addStubInput(inputType);

    Tuple t1 = Tuple.ofValues(inputType, nzmgGeomHelper.line(0, 10, 20, 10), "1");
    Tuple t2 = Tuple.ofValues(inputType, nzmgGeomHelper.line(0, 20, 20, 20), "2");
    Tuple t3 = Tuple.ofValues(inputType, nzmgGeomHelper.line(0, 30, 20, 30), "3");

    List<Tuple> enlarged = run(inputType, t1, t2, t3);
    assertThat(enlarged,  contains(
        tupleWithValue("geom", geometryTopoMatch(nzmgGeomHelper.multiBox(nzmgGeomHelper.box(0, 9, 20, 11)))),
        tupleWithValue("geom", geometryTopoMatch(nzmgGeomHelper.multiBox(nzmgGeomHelper.box(0, 19, 20, 21)))),
        tupleWithValue("geom", geometryTopoMatch(nzmgGeomHelper.multiBox(nzmgGeomHelper.box(0, 29, 20, 31))))
    ));

    // ensure no not member exceptions when accessing tuple by struct member
    StructMember geomMember = produced.getEntry("geom");
    enlarged.get(0).fetch(geomMember);
  }

  @Test
  public void canEnlargeLinesAndRemoveResultingOverlaps() {
    Struct inputType = Struct.of("geom", Types.LINE, "value", Types.TEXT);

    addParam("distance", expressionParser.parse("1"));
    addParam("mode", EnlargeStep.EnlargeMode.MITRED_FLAT);
    addParam("remove-overlaps", true);

    addStubInput(inputType);

    Tuple t1 = Tuple.ofValues(inputType, nzmgGeomHelper.line(0, 100, 100, 100), "1");
    Tuple t2 = Tuple.ofValues(inputType, nzmgGeomHelper.line(50, 0, 50, 100), "2");
    Tuple t3 = Tuple.ofValues(inputType, nzmgGeomHelper.line(80, 0, 80, 100), "3");

    assertThat(run(inputType, t1, t2, t3), contains(
        // t1 should have overlap with t2 removed from it
        tupleWithValue("geom", geometryTopoMatch(nzmgGeomHelper.multiBox(nzmgGeomHelper.box(
            nzmgGeomHelper.toCoordinate(0, 101),
            nzmgGeomHelper.toCoordinate(100, 101),
            nzmgGeomHelper.toCoordinate(100, 99),
            nzmgGeomHelper.toCoordinate(51, 99),
            nzmgGeomHelper.toCoordinate(51, 100),
            nzmgGeomHelper.toCoordinate(49, 100),
            nzmgGeomHelper.toCoordinate(49, 99),
            nzmgGeomHelper.toCoordinate(0, 99),
            nzmgGeomHelper.toCoordinate(0, 101)
        )))),
        // t2 is it's whole enlarged self
        tupleWithValue("geom", geometryTopoMatch(nzmgGeomHelper.multiBox(nzmgGeomHelper.box(49, 0, 51, 100)))),
        // t3 has the overlap with t1 removed from it
        tupleWithValue("geom", geometryTopoMatch(nzmgGeomHelper.multiBox(nzmgGeomHelper.box(79, 0, 81, 99))))
    ));
  }


  @Test
  public void failsWhenNoGeometry() {
    Struct inputType = Struct.of("geom", Types.TEXT, "value", Types.INTEGER);

    addParam("distance", expressionParser.parse("value"));
    addParam("mode", EnlargeStep.EnlargeMode.MITRED_SQUARE);
    addStubInput(inputType);

    assertThat(step.realizeSimple(input()), failedResult(hasAncestorProblem(
        is(new Problem(Problem.Severity.ERROR, StandardCodes.GEOMETRY_REQUIRED, inputType))
    )));
  }

  @Test
  public void failsWhenGeometryExpressionWrongType() {
    Struct inputType = Struct.of("geom", Types.TEXT, "value", Types.INTEGER);

    Expression geomExpr = expressionParser.parse("geom");
    addParam("geom-expression", geomExpr);
    addParam("distance", expressionParser.parse("value"));
    addParam("mode", EnlargeStep.EnlargeMode.MITRED_SQUARE);
    addStubInput(inputType);

    assertThat(step.realizeSimple(input()), failedResult(hasAncestorProblem(
        is(TypeProblems.get().mismatch(geomExpr, Types.GEOMETRY, Types.TEXT))
    )));
  }

  List<Tuple> run(Struct inputType, Tuple... tuples) {
    realized = step.realizeSimple(input());
    assertThat(realized.hasProblems(), is(false));

    if (realized.get() instanceof Projector) {
      Projector projector = (Projector)realized.get();
      produced = projector.getProjectedType();
      return Arrays.asList(tuples).stream()
          .map(t -> projector.apply(t))
          .collect(Collectors.toList());
    }

    // it must be the enlarging collector
    EnlargingCollector c = (EnlargingCollector)realized.get();
    assertThat(c.getSourceType(), is(inputType));
    produced = c.getTargetType();

    AccumInstance acc1 = c.newAccumulator();
    AccumInstance acc2 = c.newAccumulator();
    int i = 0;
    for (Tuple tuple: tuples) {
      // put the first two tuple in acc1, then acc2 for everything after that. This way we can test
      // accumulator combination but not change the ordering
      AccumInstance acc = i++ < 2 ? acc1 : acc2;
      acc.accumulate(tuple);
    }
    AccumInstance combined = acc1.combine(acc2);
    return c.process(combined).collect(Collectors.toList());
  }


}
