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

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

import java.util.Optional;

import org.junit.Before;
import org.junit.Test;
import org.locationtech.jts.geom.Polygon;
import org.mockito.Mockito;

import nz.org.riskscape.engine.Assert;
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.data.coverage.GridCoverageRelation;
import nz.org.riskscape.engine.defaults.Plugin;
import nz.org.riskscape.engine.defaults.function.LookupBookmark;
import nz.org.riskscape.engine.function.IdentifiedFunction;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.problem.ProblemMatchers;
import nz.org.riskscape.engine.relation.EmptyRelation;
import nz.org.riskscape.engine.relation.ListRelation;
import nz.org.riskscape.engine.relation.Relation;
import nz.org.riskscape.engine.rl.BaseExpressionRealizerTest;
import nz.org.riskscape.engine.rl.RealizableFunction;
import nz.org.riskscape.engine.types.CoverageType;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.RelationType;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.TypeProblems;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.engine.types.WithinRange;

public class ToRelationTest extends BaseExpressionRealizerTest {

  ToRelation function = new ToRelation();
  TypedCoverage coverage = Mockito.mock(TypedCoverage.class);
  Relation relation = Mockito.mock(Relation.class);
  CoverageType coverageType = new CoverageType(Types.FLOATING);
  Struct standardTupleType = GridCoverageRelation.createStructType(coverageType);
  Relation emptyRelation = new EmptyRelation(standardTupleType);

  @Before
  public void setup() {
    project.add(function.identified("to_relation"));

    when(coverage.getType()).thenReturn(Types.FLOATING);
    when(coverage.getScalarDataType()).thenReturn(coverageType);

    // for testing the constant case
    LookupBookmark lookupBookmark = new LookupBookmark();
    project.getFunctionSet().add(
        RealizableFunction.asFunction(lookupBookmark, lookupBookmark.getArguments(), Types.ANYTHING)
            .builtin("bookmark", IdentifiedFunction.Category.MISC),
        Plugin.DEFAULTS_SOURCE);

    addPickledData("coverage", coverage);
  }

  @Test
  public void willReturnRelationWhenCoverageSupportsAsRelation() throws Exception {
    when(coverage.asRelation()).thenReturn(Optional.of(emptyRelation));

    evaluate("to_relation(value)", Tuple.ofValues(coverageType.asStruct(), coverage));
    assertThat(evaluated, is(emptyRelation));

    assertThat(realized.getResultType(), allOf(
        instanceOf(RelationType.class),
        hasProperty("memberType", is(standardTupleType))
    ));
  }


  @Test
  public void willConvertAWeirdlyTypedRelationWhenCoverageSupportsAsRelation() throws Exception {
    Struct relationMemberType = Struct.of(
        "geom", Types.POLYGON, //broader than default
        "value", new WithinRange(Types.FLOATING, 0D, 100D), // extra wrapping type
        "foo", Types.TEXT // some extra information
    );
    Polygon poly1 = mock(Polygon.class);
    Relation weirdRelation = new ListRelation(Tuple.ofValues(relationMemberType, poly1, 20.5D, "bar"));
    when(coverage.asRelation()).thenReturn(Optional.of(weirdRelation));

    evaluate("to_relation(value)", Tuple.ofValues(coverageType.asStruct(), coverage));
    // the relation has been projected, so not the normal empty relation
    assertThat(evaluated, is(not(weirdRelation)));

    assertThat(realized.getResultType(), allOf(
        instanceOf(RelationType.class),
        hasProperty("memberType", is(standardTupleType))
    ));

    // confirm the tuple is mapped to the expected result type
    assertThat(((Relation)evaluated).iterator().next(), is(Tuple.ofValues(standardTupleType, 20.5D, poly1)));
  }

  @Test
  public void willConvertAWeirdlyTypedIntegerRelationWhenCoverageSupportsAsRelation() throws Exception {
    // bit of an edge case as all the real coverages will return a floating value.
    // but proves a point that to_relation will setup the right coercion to the expected type.
    Struct relationMemberType = Struct.of(
        "geom", Types.POLYGON, //broader than default
        "value", new WithinRange(Types.INTEGER, 0L, 100L), // extra wrapping type
        "foo", Types.TEXT // some extra information
    );
    Polygon poly1 = mock(Polygon.class);
    Relation weirdRelation = new ListRelation(Tuple.ofValues(relationMemberType, poly1, 20L, "bar"));
    when(coverage.asRelation()).thenReturn(Optional.of(weirdRelation));

    evaluate("to_relation(value)", Tuple.ofValues(coverageType.asStruct(), coverage));
    // the relation has been projected, so not the normal empty relation
    assertThat(evaluated, is(not(weirdRelation)));

    assertThat(realized.getResultType(), allOf(
        instanceOf(RelationType.class),
        hasProperty("memberType", is(standardTupleType))
    ));

    // confirm the tuple is mapped to the expected result type
    assertThat(((Relation)evaluated).iterator().next(), is(Tuple.ofValues(standardTupleType, 20.0D, poly1)));
  }

  @Test
  public void returnsNullIfCoverageIsNull() throws Exception {
    Struct inputType = Struct.of("value", Nullable.of(coverageType));
    assertThat(evaluate("to_relation(value)", Tuple.ofValues(inputType)), nullValue());
    assertThat(realized.getResultType(), is(Nullable.of(new RelationType(standardTupleType))));
  }

  @Test
  public void willThrowExceptionWhenCoverageDoesNotSupportAsRelation() throws Exception {
    when(coverage.asRelation()).thenReturn(Optional.empty());

    RiskscapeException ex = Assert.assertThrows(RiskscapeException.class, () -> {
      evaluate("to_relation(value)", Tuple.ofValues(coverageType.asStruct(), coverage));
    });

    assertThat(
        ex.getProblems(),
        contains(
            Matchers.hasAncestorProblem(
              ProblemMatchers.isProblem(GeneralProblems.class, (r, t) -> t.operationNotSupported(
                  r.eq("to_relation"),
                  r.any()
              ))
            )
        )
    );
  }

  @Test
  public void willThrowExceptionWhenCoverageHasNonNumericValue() throws Exception {
    // academic as only test coverages can be backed by non numeric coverages.
    // but shows that the function behaves well should that ever change.
    relation = new EmptyRelation(Struct.of(
        "geom", Types.POLYGON, //broader than default
        "value", Types.TEXT // some extra information
    ));
    when(coverage.asRelation()).thenReturn(Optional.of(relation));

    RiskscapeException ex = Assert.assertThrows(RiskscapeException.class, () -> {
      evaluate("to_relation(value)", Tuple.ofValues(coverageType.asStruct(), coverage));
    });

    assertThat(
        ex.getProblems(),
        contains(
            Matchers.hasAncestorProblem(
                is(TypeProblems.get().couldNotCoerce(relation.getProducedType(), standardTupleType))
            )
        )
    );
  }

  @Test
  public void failsToRealizeIfCoverageArgIsNotCoverage() throws Exception {
    assertThat(
        realizeOnly("to_relation(value)", Types.TEXT.asStruct()).getProblems(),
        contains(
            Matchers.hasAncestorProblem(
                is(TypeProblems.get().mismatch(function.getArguments().get(0), CoverageType.WILD, Types.TEXT))
            )
        )
    );
  }

  @Test
  public void constantCaseReturnsRelationDirectly() throws Exception {
    Relation complexRelation = new EmptyRelation(Struct.of("foo", Types.TEXT));
    // override the test default to return something that we wouldn't usually get - this test asserts that we use
    // the type from the constant type, not the assumed type (for dynamic)
    when(coverage.asRelation()).thenReturn(Optional.of(complexRelation));

    evaluate("to_relation(bookmark('coverage'))", Tuple.ofValues(coverageType.asStruct(), coverage));
    assertThat(evaluated, is(complexRelation));

    // not the value/geom type that is usually returned
    assertThat(realized.getResultType(), is(complexRelation.getScalarDataType()));
    assertThat(realized.getResultType(), allOf(
        instanceOf(RelationType.class),
        hasProperty("memberType", not(standardTupleType))
    ));
  }

  @Test
  public void constantCaseThrowsExceptionWhenCoverageDoesNotSupportAsRelation() throws Exception {
    when(coverage.asRelation()).thenReturn(Optional.empty());

    assertThat(
        realizeOnly("to_relation(bookmark('coverage'))", coverageType.asStruct()).getProblems(),
        contains(
            Matchers.hasAncestorProblem(
              ProblemMatchers.isProblem(GeneralProblems.class, (r, t) -> t.operationNotSupported(
                  r.eq("to_relation"),
                  r.any()
              ))
            )
        )
    );
  }
}
