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

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

import java.util.List;

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

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.rl.ast.ExpressionProblems;

public class MapStructTest extends BaseExpressionRealizerTest {

  @Before
  public void setup() {
    project.getFunctionSet().insertFirst(DefaultOperators.INSTANCE);
    project.getFunctionSet().addAll(LanguageFunctions.FUNCTIONS);
    // map_struct is added via the beta plugin for now.
    project.getFunctionSet().add(LanguageFunctions.MAP_STRUCT);
    // add round()
    project.getFunctionSet().addAll(MathsFunctions.FUNCTIONS);
  }

  @Test
  public void willMapAllAttributes() {
    assertThat(
        evaluate("map_struct({foo: 33, bar: 0.25}, (i) -> i * 2)", Tuple.EMPTY_TUPLE),
        is(tuple("{foo: 66, bar: 0.5}"))
    );
    assertThat(realized.getResultType(), is(Struct.of("foo", Types.INTEGER, "bar", Types.FLOATING)));
  }

  @Test
  public void canMapNestedStruct() {
    // NB we use round() in these tests because that will error if given a whole struct instead of
    // a struct member, whereas multiplication operations would still work on a struct
    assertThat(
        evaluate("map_struct({baz: {foo: 33, bar: 0.25}}, (x) -> map_struct(x, i -> round(i * 2, 1)))",
                 Tuple.EMPTY_TUPLE),
        is(tuple("{baz: {foo: 66.0, bar: 0.5}}"))
    );
    assertThat(realized.getResultType(),
        is(Struct.of("baz", Struct.of("foo", Types.FLOATING, "bar", Types.FLOATING)))
    );
  }

  @Test
  public void canMapNullableStruct() {
    Struct testStruct = Struct.of("foo", Types.FLOATING, "bar", Types.FLOATING);
    assertThat(
        evaluate("map_struct(nullable({foo: 44.0, bar: 0.75}), (i) -> round(i * 2, 1))", Tuple.EMPTY_TUPLE),
        is(tuple("{foo: 88.0, bar: 1.5}"))
    );
    assertThat(realized.getResultType(), is(Nullable.of(testStruct)));
  }

  @Test
  public void canMapNullStruct() {
    Struct testStruct = Struct.of("foo", Types.FLOATING, "bar", Types.FLOATING);
    assertThat(
        evaluateConstant("map_struct(null_of('struct(foo: floating, bar: floating)'), (i) -> round(i * 2, 1))"),
        nullValue()
    );
    assertThat(realized.getResultType(), is(Nullable.of(testStruct)));
  }

  @Test
  public void canMapNullableNestedStruct() {
    Struct nested = Struct.of("foo", Types.FLOATING, "bar", Types.FLOATING);
    Type nestedType = Nullable.of(Struct.of("nested",
        Struct.of("foo", Types.FLOATING, "bar", Types.FLOATING)
    ));
    Tuple input = Tuple.ofValues(Struct.of("data", nestedType),
        Tuple.ofValues(Struct.of("nested", nested),
            Tuple.ofValues(nested, 11L, 0.25D)
        )
    );
    assertThat(
        evaluate("map_struct(data, (x) -> map_struct(x, i -> round(i * 3, 1)))", input),
        is(tuple("{nested: {foo: 33.0, bar: 0.8}}"))
    );
    assertThat(realized.getResultType(), is(nestedType));
  }

  @Test
  public void willMapNonStructInput() {
    assertThat(
        evaluate("map_struct(33, (i) -> i * 2)", Tuple.EMPTY_TUPLE),
        is(66L)
    );
    assertThat(realized.getResultType(), is(Types.INTEGER));
  }

  @Test
  public void willMapNullNonStructInput() {
    assertThat(
        evaluate("map_struct(null_of('integer'), (i) -> i * 2)", Tuple.EMPTY_TUPLE),
        nullValue()
    );
    assertThat(realized.getResultType(), is(Nullable.INTEGER));

    // we currently take a 'null in, null out' approach, because that's simplest/most sensible for structs,
    // and it makes sense to handle non-structs in the same way. However, an alternative approach would be for
    // the lambda expression to handle nullability, in which case you'd end up with {foo: null_of('integer')} here.
    // This is a somewhat academic corner-case though - the main point of the test is that the code shouldn't explode
    assertThat(
        evaluate("map_struct(null_of('integer'), (i) -> {foo: i * 2})", Tuple.EMPTY_TUPLE),
        nullValue()
    );
    assertThat(realized.getResultType(), is(Nullable.of(Struct.of("foo", Types.INTEGER))));
  }

  @Test
  public void failsIfMapperCannotBeAppliedToAllAttributes() {
    assertThat(realizeOnly("map_struct({foo: 33, bar: 'bar'}, (i) -> i * 2)", Struct.EMPTY_STRUCT), failedResult(
        hasAncestorProblem(is(
            Problems.foundWith(Struct.StructMember.class, "bar").withChildren(
                ExpressionProblems.get().noSuchOperatorFunction("*", List.of(Types.TEXT, Types.INTEGER)),
                MapStruct.PROBLEMS.lambdaNotCompatibleAllAttributesHint(
                    Struct.of("foo", Types.INTEGER, "bar", Types.TEXT)
                )
            )
        ))
    ));
  }

  @Test
  public void failsIfMapperCannotBeAppliedToNonStructType() {
    assertThat(realizeOnly("map_struct('bar', (i) -> i * 2)", Struct.EMPTY_STRUCT), failedResult(
        hasAncestorProblem(is(
            ExpressionProblems.get().noSuchOperatorFunction("*", List.of(Types.TEXT, Types.INTEGER))
        ))
    ));
  }

  @Test
  public void failsIfWrongNumberOfArgs() {
    assertThat(realizeOnly("map_struct({foo: 33, bar: 0.25})", Struct.EMPTY_STRUCT), failedResult(
        hasAncestorProblem(is(ArgsProblems.get().wrongNumber(2, 1)))
    ));

    assertThat(realizeOnly("map_struct({foo: 33, bar: 0.25}, (i) -> i * 2, 'foo')", Struct.EMPTY_STRUCT), failedResult(
        hasAncestorProblem(is(ArgsProblems.get().wrongNumber(2, 3)))
    ));
  }

  @Test
  public void failsIfMapperNotLambda() {
    assertThat(realizeOnly("map_struct({foo: 33, bar: 0.25}, 'foo')", Struct.EMPTY_STRUCT), failedResult(
        hasAncestorProblem(is(ArgsProblems.mismatch(MapStruct.ARGUMENTS.get("mapper"), Types.TEXT)))
    ));
  }

  @Test
  public void failsIfLambdaWrongArity() {
    assertThat(realizeOnly("map_struct({foo: 33, bar: 0.25}, () -> 'foo')", Struct.EMPTY_STRUCT), failedResult(
        hasAncestorProblem(is(ExpressionProblems.get().lambdaArityError(parse("() -> 'foo'"), 0, 1)))
    ));

    assertThat(realizeOnly("map_struct({foo: 33, bar: 0.25}, (a, b) -> 'foo')", Struct.EMPTY_STRUCT), failedResult(
        hasAncestorProblem(is(ExpressionProblems.get().lambdaArityError(parse("(a, b) -> 'foo'"), 2, 1)))
    ));
  }
}
