/*
 * 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 org.hamcrest.Matchers.*;

import org.junit.Test;

import static org.junit.Assert.*;

import java.util.Arrays;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.rl.RealizedExpression;
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;

public class StandardDeviationAggregationFunctionTest extends BaseAggregationFunctionTest {

  @Test
  public void stddevAggregation() {
    Struct inputType = norm(Types.INTEGER.asStruct());
    realized = realizeAggregate(inputType, parse("stddev(value)")).get();

    assertThat(realized.getResultType(), is(Nullable.of(StandardDeviationAggregationFunction.RESULT_TYPE)));

    // not enough items to produce output
    tuples = tuples(inputType, "[20]");
    assertThat(process(), is(nullValue()));

    tuples = tuples(inputType, "[10]", "[15]", "[20]");
    assertThat((Tuple)process(), stddevMatcher(15D, 5D));
  }

  @Test
  public void stddevAggregationOnNullableInputs() {
    Struct inputType = norm(Struct.of("value", Nullable.INTEGER));
    realized = realizeAggregate(inputType, parse("stddev(value)")).get();

    assertThat(realized.getResultType(), is(Nullable.of(StandardDeviationAggregationFunction.RESULT_TYPE)));

    // not enough items to produce output
    tuples = tuples(inputType, "[20]");
    assertThat(process(), is(nullValue()));

    tuples = tuples(inputType, "[10]", "[15]", "[20]");
    assertThat((Tuple)process(), stddevMatcher(15D, 5D));
  }


  @Test
  public void stddevCalledAsFunction() {
    RSList listType = RSList.create(Types.INTEGER);
    Struct inputType = Struct.of("items", listType);
    RealizedExpression rExpr = realizationContext.getExpressionRealizer()
        .realize(inputType, parse("stddev(items)")).get();

    assertThat(rExpr.getResultType(), is(Nullable.of(StandardDeviationAggregationFunction.RESULT_TYPE)));

    // we expect a null result if input list is empty
    assertThat(rExpr.evaluate(Tuple.ofValues(inputType, Arrays.asList())), is(nullValue()));

    // we expect a null result if input list does not have enough items
    assertThat(rExpr.evaluate(Tuple.ofValues(inputType, Arrays.asList(15L))), is(nullValue()));

    assertThat((Tuple) rExpr.evaluate(Tuple.ofValues(inputType, Arrays.asList(10L, 15L, 20L))),
        stddevMatcher(15D, 5D));

    assertThat((Tuple) rExpr.evaluate(Tuple.ofValues(inputType,
        Arrays.asList(-32L, 9L, -21L, -12L, -26L, -25L, 37L, -48L, -32L, 49L))),
        stddevMatcher(-10.1D, 31.743590779172347D));
  }

  Matcher<Tuple> stddevMatcher(Double mean, Double stddev) {
    Matcher<Double> meanMatcher = closeTo(mean, TOLERANCE);
    Matcher<Double> stddevMatcher = closeTo(stddev, TOLERANCE);
    return new TypeSafeMatcher<Tuple>() {
      @Override
      public boolean matchesSafely(Tuple number) {
        return number.toMap().containsKey("mean") && meanMatcher.matches(number.fetch("mean"))
            && number.toMap().containsKey("stddev") && stddevMatcher.matches(number.fetch("stddev"));
      }

      @Override
      public void describeTo(Description description) {
        description.appendText(String.format("does not match mean: %f, stddev: %f", mean, stddev));
      }

    };
  }

}
