/*
 * 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.ArrayList;
import java.util.Arrays;
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.rl.agg.BaseAggregationFunctionTest;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.RSList;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.rl.ast.ExpressionProblems;
import nz.org.riskscape.rl.ast.Lambda;

public class MapStructAggregationTest extends BaseAggregationFunctionTest {

  Struct itemType = Struct.of("v1", Types.INTEGER, "v2", Types.FLOATING);
  Struct inputType = Struct.of("value", itemType);

  @Before
  public void setup() {
    project.getFunctionSet().add(LanguageFunctions.MAP_STRUCT);
  }

  @Test
  public void willAggregateStructWhereAggregationRetainsItemType() {
    inputType = Struct.of("foo", itemType);
    realized = realizeAggregate(inputType, parse("map_struct(foo, v -> sum(v))")).get();

    assertThat(realized.getResultType(), is(itemType));

    tuples = List.of(
        Tuple.ofValues(inputType, Tuple.ofValues(itemType, 1L, 0.25D)),
        Tuple.ofValues(inputType, Tuple.ofValues(itemType, 2L, 0.5D))
    );
    assertThat(process(), is(Tuple.ofValues(itemType, 3L, 0.75D)));
  }

  @Test
  public void willAggregateStructWhereAggregationChangesItemType() {
    realized = realizeAggregate(inputType, parse("map_struct(value, v -> ceil(sum(v)))")).get();

    Struct returnType = Struct.of("v1", Types.INTEGER, "v2", Types.INTEGER);
    assertThat(realized.getResultType(), is(returnType));

    tuples = List.of(
        Tuple.ofValues(inputType, Tuple.ofValues(itemType, 1L, 0.25D)),
        Tuple.ofValues(inputType, Tuple.ofValues(itemType, 2L, 0.5D))
    );
    assertThat(process(), is(Tuple.ofValues(returnType, 3L, 1L)));
  }

  @Test
  public void willAggregateStructWhenItemIsNullable() {
    inputType = Struct.of("value", Nullable.of(itemType));

    realized = realizeAggregate(inputType, parse("map_struct(value, v -> sum(v))")).get();

    Struct returnType = Struct.of("v1", Types.INTEGER, "v2", Types.FLOATING);
    assertThat(realized.getResultType(), is(returnType));

    tuples = new ArrayList<>();
    tuples.add(Tuple.ofValues(inputType, Tuple.ofValues(itemType, 1L)));
    tuples.add(null);
    tuples.add(Tuple.ofValues(inputType, Tuple.ofValues(itemType, 2L, 0.5D)));
    assertThat(process(), is(Tuple.ofValues(returnType, 3L, 0.5D)));
  }

  @Test
  public void willAggregateStructWhenOneMemberIsNullable() {
    itemType = Struct.of("v1", Types.INTEGER, "v2", Nullable.FLOATING);
    inputType = Struct.of("value", itemType);

    realized = realizeAggregate(inputType, parse("map_struct(value, v -> sum(v))")).get();

    Struct returnType = Struct.of("v1", Types.INTEGER, "v2", Nullable.FLOATING);
    assertThat(realized.getResultType(), is(returnType));

    tuples = List.of(
        Tuple.ofValues(inputType, Tuple.ofValues(itemType, 1L)),
        Tuple.ofValues(inputType, Tuple.ofValues(itemType, 2L, 0.5D))
    );
    assertThat(process(), is(Tuple.ofValues(returnType, 3L, 0.5D)));
  }

  @Test
  public void willAggregateStructWhenOneMemberIsNullableAndHasNoValues() {
    itemType = Struct.of("v1", Types.INTEGER, "v2", Nullable.FLOATING);
    inputType = Struct.of("value", itemType);

    realized = realizeAggregate(inputType, parse("map_struct(value, v -> sum(v))")).get();

    Struct returnType = Struct.of("v1", Types.INTEGER, "v2", Nullable.FLOATING);
    assertThat(realized.getResultType(), is(returnType));

    tuples = List.of(
        Tuple.ofValues(inputType, Tuple.ofValues(itemType, 1L)),
        Tuple.ofValues(inputType, Tuple.ofValues(itemType, 2L))
    );
    assertThat(process(), is(Tuple.ofValues(returnType, 3L)));
  }

  @Test
  public void willAggregateList() {
    inputType = Struct.of("values", RSList.create(itemType));
    RealizedExpression rExpr = realizationContext.getExpressionRealizer().realize(inputType,
        parse("map_struct(values, v -> sum(v))")).get();

    Struct resultType = Struct.of("v1", Types.INTEGER, "v2", Types.FLOATING);
    assertThat(rExpr.getResultType(), is(Nullable.of(resultType)));

    tuples = List.of(
        Tuple.ofValues(itemType, 1L, 0.5D),
        Tuple.ofValues(itemType, 2L, 0.25D)
    );

    assertThat(rExpr.evaluate(Tuple.ofValues(inputType, tuples)), is(Tuple.ofValues(resultType, 3L, 0.75D)));
  }

  @Test
  public void willAggregateListWithNullableItem() {
    inputType = Struct.of("values", RSList.create(Nullable.of(itemType)));
    RealizedExpression rExpr = realizationContext.getExpressionRealizer().realize(inputType,
        parse("map_struct(values, v -> sum(v))")).get();

    Struct resultType = Struct.of("v1", Types.INTEGER, "v2", Types.FLOATING);
    assertThat(rExpr.getResultType(), is(Nullable.of(resultType)));

    tuples = new ArrayList<>();
    tuples.add(Tuple.ofValues(itemType, 1L, 0.5D));
    tuples.add(null);
    tuples.add(Tuple.ofValues(itemType, 2L, 0.25D));

    assertThat(rExpr.evaluate(Tuple.ofValues(inputType, tuples)), is(Tuple.ofValues(resultType, 3L, 0.75D)));
  }

  @Test
  public void errorIfLambdaCannotRealizeAgainstAllAttributes() {
    itemType = Struct.of("v1", Types.INTEGER, "v2", Types.TEXT, "v3", Types.FLOATING);
    inputType = Struct.of("value", itemType);
    assertThat(realizeAggregate(inputType, parse("map_struct(value, v -> mean(v))")), failedResult(hasAncestorProblem(
        equalIgnoringChildren(ExpressionProblems.get().failedToRealize(parse("mean(v)"), Struct.of("v", Types.TEXT)))
    )));
    List<String> renderedProblems = Arrays.stream(render(realizationProblems).split("\n"))
        .toList();
    // we go though checking each line of the rendered message to ensure there is no mention of the defered
    // expression to aggregate_struct (that could be confusing to users).
    assertThat(renderedProblems, contains(
        startsWith("Failed to validate expression 'map_struct(value, v -> mean(v))' against "
            + "input type {value=>{v1=>Integer, v2=>Text, v3=>Floating}}"),
        startsWith("  - Problems found with 'v2' struct member"),
        startsWith("    - Failed to validate expression 'mean(v)' against input type {v=>Text}"),
        startsWith("      - The 'Text' type is not supported with this aggregation function"),
        startsWith("        - This aggregation function is comprised of simple expressions"),
        startsWith("          - Operator '/' is not supported for types '[Text, Integer]'"),
        // we get lambdaNotCompatibleAllAttributesHint
        startsWith("    - Please check that the lambda expression is compatible with all the attribute "
            + "types in this struct: '{v1=>Integer, v2=>Text, v3=>Floating}'")
    ));
  }

  @Test
  public void errorIfValueNotStruct() {
    inputType = Struct.of("value", Types.INTEGER);
    assertThat(realizeAggregate(inputType, parse("map_struct(value, v -> sum(v))")), failedResult(is(
        ExpressionProblems.get().failedToRealize(parse("map_struct(value, v -> sum(v))"), inputType).withChildren(
            ArgsProblems.mismatch(MapStruct.ARGUMENTS.get("struct"), Types.INTEGER)
        )
    )));
  }

  @Test
  public void errorIfMapperNotLambda() {
    assertThat(realizeAggregate(inputType, parse("map_struct(value, 'foo')")), failedResult(is(
        ExpressionProblems.get().failedToRealize(parse("map_struct(value, 'foo')"), inputType).withChildren(
            ExpressionProblems.get().mismatch(parse("'foo'"), Lambda.class, "v -> sum(v)")
        )
    )));
  }

  @Test
  public void errorIfLambdaHasBadArity() {
    assertThat(realizeAggregate(inputType, parse("map_struct(value, () -> 'foo')")), failedResult(is(
        ExpressionProblems.get().failedToRealize(parse("map_struct(value, () -> 'foo')"), inputType).withChildren(
            ExpressionProblems.get().lambdaArityError(parse("() -> 'foo'"), 0, 1)
        )
    )));

    assertThat(realizeAggregate(inputType, parse("map_struct(value, (x, y) -> 'foo')")), failedResult(is(
        ExpressionProblems.get().failedToRealize(parse("map_struct(value, (x, y) -> 'foo')"), inputType).withChildren(
            ExpressionProblems.get().lambdaArityError(parse("(x, y) -> 'foo'"), 2, 1)
        )
    )));
  }

  @Test
  public void errorWrongNumberOfArgs() {
    assertThat(realizeAggregate(inputType, parse("map_struct(value)")), failedResult(is(
        ExpressionProblems.get().failedToRealize(parse("map_struct(value)"), inputType).withChildren(
            ArgsProblems.get().wrongNumber(2, 1)
        )
    )));

    assertThat(realizeAggregate(inputType, parse("map_struct(value, v -> sum(v), 3)")), failedResult(is(
        ExpressionProblems.get().failedToRealize(parse("map_struct(value, v -> sum(v), 3)"), inputType).withChildren(
            ArgsProblems.get().wrongNumber(2, 3)
        )
    )));
  }

  @Test
  public void canHandleStructMembersRequiringQuoting() {
    // Test that struct members with names requiring quoting (spaces, keywords, special chars)
    // are properly handled. Without proper quoting, this would fail during realization.
    itemType = Struct.of("damage state", Types.INTEGER, "if", Types.FLOATING, "total-cost", Types.INTEGER);
    inputType = Struct.of("value", itemType);

    realized = realizeAggregate(inputType, parse("map_struct(value, v -> sum(v))")).get();

    Struct returnType = Struct.of("damage state", Types.INTEGER, "if", Types.FLOATING, "total-cost", Types.INTEGER);
    assertThat(realized.getResultType(), is(returnType));

    tuples = List.of(
        Tuple.ofValues(inputType, Tuple.ofValues(itemType, 1L, 0.5D, 10L)),
        Tuple.ofValues(inputType, Tuple.ofValues(itemType, 2L, 1.5D, 20L))
    );
    assertThat(process(), is(Tuple.ofValues(returnType, 3L, 2.0D, 30L)));
  }

  @Test
  public void canAggregateAnEmptyStruct() throws Exception {
    inputType = Struct.of("value", Struct.EMPTY_STRUCT);
    realizeAggregate(inputType, parse("map_struct(value, v -> sum(v))")).get();

    assertThat(realized.getResultType(), is(Struct.EMPTY_STRUCT));

    tuples = tuples("[{}, {}, {}]");
    assertThat(process(), is(tuple("{}")));
  }
}
