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

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

import java.util.Arrays;

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

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.TupleMatchers;
import nz.org.riskscape.engine.function.StringFunctions;
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.PropertyAccess;

public class AggregateExpressionRealizerTest extends BaseAggregationFunctionTest {

  private Struct inputType;

  @Before
  public void before() {

    project.getFunctionSet().addAll(StringFunctions.FUNCTIONS);

    inputType = norm(Struct.of("foo", Types.INTEGER, "bar", Types.TEXT, "baz", Types.FLOATING));
    tuples = tuples(inputType, "[1, 'cool', 2.0]", "[2, 'story', 3.0]", "[3, 'bro', 4.0]");
  }

  @Test
  public void canAggregateUsingASimpleExpression() {
    realizeAggregate("sum(foo)");
    assertEquals(Types.INTEGER, realized.getResultType());
    assertEquals(6L, process());
  }

  private void realizeAggregate(String expression) {
    realizeAggregate(inputType, parse(expression));
  }

  @Test
  public void canAggregateUsingAFewDifferentFunctions() throws Exception {
    realizeAggregate("{sum(foo) as sum_foo, count(bar) as count_bar, min(baz) as min_baz}");

    assertEquals(tuple("{sum_foo: 6, count_bar: 3, min_baz: 2.0}"), process());
  }

  @Test
  public void canAggregateUsingAFewDifferentFunctionsWithoutAliases() throws Exception {
    realizeAggregate("{"
        + "sum(foo), "
        + "count(*), "
        + "str(min(baz)), "
        + "1, "
        + "[2.0]"
        + "}");

    assertThat(
      process(),
      instanceOfAnd(
        Tuple.class,
        allOf(
          TupleMatchers.tupleWithValue("sum_foo", equalTo(6L)),
          TupleMatchers.tupleWithValue("count", equalTo(3L)),
          TupleMatchers.tupleWithValue("str_min_baz", equalTo("2.0")),
          TupleMatchers.tupleWithValue("integer", equalTo(1L)),
          TupleMatchers.tupleWithValue("list_floating", equalTo(Arrays.asList(2.0D)))
        )
      )
    );
  }

  @Test
  public void canWrapAggregateFunctionsInArbitrarilyComplexExpressions() throws Exception {
    realizeAggregate("str(sum(foo) + count(bar) > max(baz))");

    assertEquals("true", process());
  }

  @Test
  public void referencingAPropertyOutsideOfAFunctionFails() throws Exception {
    realizeAggregate("sum(foo) + bar");

    assertThat(realizationProblems, contains(
      ExpressionProblems.get().propertyOutsideOfAggregationFunction((PropertyAccess) expressionParser.parse("bar"))
    ));
  }

  @Test
  public void aBadExpressionWithinFunctionCallFails() throws Exception {
    realizeAggregate("{count(*), sum(foos)}");

    assertThat(realizationProblems, contains(equalIgnoringChildren(
      ExpressionProblems.get().failedToRealize(expressionParser.parse("sum(foos)"), inputType)
    )));
  }

  @Test
  public void anAccumulatorIsEmptyIfFunctionsAccumulatorIsEmpty() throws Exception {
    // TODO this is a bit fraught where structs are concerned - hard to say if a struct with nullable members
    // is itself equivalent to null (for these purposes)
    // Given that the emptyness and nullability is mostly a concern for when there's a grouping that always
    // applies vs no grouping and we need to tell the difference between a non-empty bucket producing a null result
    // and an empty bucket having an identity value.  I suspect this will need to be massaged a bit when my thinking
    // evolves about the terminology and basis for identity values in aggregate expressions
    realizeAggregate("{sum(foo)}");
    assertTrue(realized.newAccumulator().isEmpty());

    realizeAggregate("{count(*)}");
    assertFalse(realized.newAccumulator().isEmpty());

    // the count has identity, which means the result as a whole will have some identity
    realizeAggregate("{count(*), sum(foo)}");
    assertFalse(realized.newAccumulator().isEmpty());

    // another case to consider here would be applying something like an if_null() around the result - or a further
    // struct expression - what does that do to the identity?
  }

}
