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

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

import java.util.Arrays;

import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Point;
import org.mockito.Mockito;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;

import com.google.common.collect.Range;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Assert;
import nz.org.riskscape.engine.CrsHelper;
import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.coverage.TypedCoverage;
import nz.org.riskscape.engine.function.FunctionArgument;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.rl.BaseExpressionRealizerTest;
import nz.org.riskscape.engine.rl.EvalException;
import nz.org.riskscape.engine.types.CoverageType;
import nz.org.riskscape.engine.types.MultiGeom;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Referenced;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.engine.types.Type;
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.Problems;

public class CombineCoveragesTest extends BaseExpressionRealizerTest implements CrsHelper {

  @Before
  public void setup() {
    project.getFunctionSet().add(new CombineCoverages().identified("combine_coverages"));
    inputStruct = Struct.EMPTY_STRUCT;
  }

  Point point = project.getSridSet().getGeometryFactory(nzTransverseMercator()).createPoint(new Coordinate(1, 1));
  Tuple inputTuple= Tuple.EMPTY_TUPLE;

  private MultiCoverage coverageResult;

  @Test
  public void canCombineTwoTypedCoverages() throws Exception {
    TypedCoverage cov1 = addCoverage("foo", Types.INTEGER, nzTransverseMercator());
    TypedCoverage cov2 = addCoverage("bar", Types.FLOATING, nzTransverseMercator());

    evaluate("combine_coverages({foo, bar}, 1)");
    assertSuccessful();

    assertThat(
      coverageResult.getType(),
      equalTo(Struct.of("foo", Nullable.of(Types.INTEGER), "bar", Nullable.of(Types.FLOATING)))
    );
    assertThat(
      coverageResult.getCoveragesAsMap(),
      allOf(hasEntry("foo", cov1), hasEntry("bar", cov2))
    );
  }

  @Test
  public void flattensNestedTypes() throws Exception {
    TypedCoverage cov1 = addCoverage("foo", Struct.of("value", Types.INTEGER), nzTransverseMercator());
    TypedCoverage cov2 = addCoverage("bar", Struct.of("value", Types.FLOATING), nzTransverseMercator());

    evaluate("combine_coverages({foo, bar}, 1)");
    assertSuccessful();

    assertThat(
      coverageResult.getType(),
      equalTo(Struct.of("foo_value", Nullable.of(Types.INTEGER), "bar_value", Nullable.of(Types.FLOATING)))
    );

    assertThat(
      coverageResult.getCoveragesAsMap(),
      allOf(hasEntry("foo_value", cov1), hasEntry("bar_value", cov2))
    );
  }

  @Test
  public void flattensNestedTypesRemovingAnyGeometryMembers() throws Exception {
    TypedCoverage cov1 = addCoverage("foo",
        Struct.of("value", Types.INTEGER, "the_geom", Referenced.of(Types.POLYGON, nzTransverseMercator())),
        nzTransverseMercator());
    TypedCoverage cov2 = addCoverage("bar",
        Struct.of("geometry", MultiGeom.MULTI_POLYGON, "value", Types.FLOATING),
        nzTransverseMercator());

    evaluate("combine_coverages({foo, bar}, 1)");
    assertSuccessful();

    assertThat(
      coverageResult.getType(),
      equalTo(Struct.of("foo_value", Nullable.of(Types.INTEGER), "bar_value", Nullable.of(Types.FLOATING)))
    );

    assertThat(
      coverageResult.getCoveragesAsMap(),
      allOf(hasEntry("foo_value", cov1), hasEntry("bar_value", cov2))
    );
  }

  @Test
  public void failsIfNoCoveragesGiven() throws Exception {
    evaluate("combine_coverages({}, 1)");
    assertFailed(Matchers.hasAncestorProblem(equalTo(TypeProblems.get().structMustBeNonEmpty("coverages"))));
  }

  @Test
  public void failsIfSomeOfTheArgumentsAreNotCoverages() throws Exception {
    evaluate("combine_coverages({foo: 'bar'}, 1)");
    assertFailed(Matchers.hasAncestorProblem(equalTo(Problems.foundWith(functionArg(0),
        TypeProblems.get().mismatch(
          new StructMember("foo", Types.TEXT, 0),
          CoverageType.WILD,
          Types.TEXT
    )))));
  }

  @Test
  public void failsIfGridDistanceNotAPositiveNonZeroNumber() throws Exception {
    addCoverage("foo", Types.INTEGER, nzTransverseMercator());

    EvalException ex = Assert.assertThrows(EvalException.class, () -> evaluate("combine_coverages({foo}, 0)"));
    Throwable throwable = ex.getRootCause();
    assertThat(throwable, instanceOf(RiskscapeException.class));
    assertThat(
      ((RiskscapeException) ex).getProblem(),
      Matchers.hasAncestorProblem(
        equalTo(
          GeneralProblems.get().valueOutOfRange(
            functionArg(1),
            0D,
            Range.greaterThan(0.0D)
          )
        )
      )
    );
  }

  @Test
  public void failsIfGridDistanceMissing() throws Exception {
    addCoverage("foo", Types.INTEGER, nzTransverseMercator());

    evaluate("combine_coverages({foo})");
    assertFailed(hasAncestorProblem(equalTo(
      ArgsProblems.get().required("grid-resolution")
    )));
  }

  @Test
  public void failsIfCoveragesMissing() throws Exception {
    evaluate("combine_coverages()");
    assertFailed(hasAncestorProblem(equalTo(
        ArgsProblems.get().required("coverages")
      )));
  }

  @Test
  public void failsIfGridDistanceWrongType() throws Exception {
    addCoverage("foo", Types.INTEGER, nzTransverseMercator());

    evaluate("combine_coverages({foo}, '1')");
    assertFailed(hasAncestorProblem(equalTo(TypeProblems.get().requiresOneOf(
        functionArg(1),
        Arrays.asList(Types.INTEGER, Types.FLOATING),
        Types.TEXT
    ))));
  }

  private void assertFailed(Matcher<Problem> problemMatcher) {
    assertThat(realizationProblems, contains(problemMatcher));
  }

  private void assertSuccessful() {
    if (!realizationProblems.isEmpty()) {
      fail(Problem.debugString(realizationProblems));
    }
    assertThat(evaluated, instanceOf(MultiCoverage.class));
    coverageResult = (MultiCoverage) evaluated;
  }

  private void evaluate(String expr) {
    evaluate(expr, inputTuple);
  }

  private TypedCoverage mockCoverage(String name, Type elementType, CoordinateReferenceSystem crs) {
    TypedCoverage coverage = Mockito.mock(TypedCoverage.class, name);
    Mockito.when(coverage.getType()).thenReturn(elementType);
    Mockito.when(coverage.getCoordinateReferenceSystem()).thenReturn(crs);

    return coverage;
  }

  private TypedCoverage addCoverage(String name, Type memberType, CoordinateReferenceSystem crs) {
    TypedCoverage mock = mockCoverage(name, memberType, crs);

    inputStruct = inputStruct.asStruct().add(name, new CoverageType(memberType));
    Object[] newArray = new Object[inputTuple.size() + 1];
    System.arraycopy(inputTuple.toArray(), 0, newArray, 0, inputTuple.size());
    newArray[inputTuple.size()] = mock;
    inputTuple = Tuple.ofValues(inputStruct.asStruct(), newArray);
    return mock;
  }

  private FunctionArgument functionArg(int index) {
    return project.getFunctionSet().get("combine_coverages").getArguments().get(index);
  }
}
