/*
 * 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 static org.junit.Assert.*;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.junit.Test;

import com.google.common.collect.Sets;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.rl.RealizationContext;
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.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.rl.ast.FunctionCall;

@SuppressWarnings("unchecked")
public class ListCollectingTest extends BaseAggregationFunctionTest {

  @RequiredArgsConstructor
  static class TestExample extends ListCollecting {

    private final Object identity;
    private final Type resultType;
    private final Object result;

    // remember values from process
    @Getter
    public Set<Object> seenValues = new HashSet<>();

    // remember function call from realization
    public FunctionCall seenFunctionCall;

    // set a problem to be thrown from #buildProcessor
    public Problem toThrow = null;

    @Override
    protected ListProcessor buildProcessor(RSList listType, RealizationContext context, Type inputType,
        FunctionCall fc) throws ProblemException {
      this.seenFunctionCall = fc;

      if (toThrow != null) {
        throw new ProblemException(toThrow);
      }
      return new ListProcessor(
          resultType,
          l -> {
            // we typically get called at least twice - the test does two lots of processing, one for a single
            // accumulator and the other does a combine
            seenValues.clear();
            seenValues.addAll(l);
            return result;
          },
          identity
      );
    }

    public void clear() {
      seenValues.clear();
    }
  }

  FunctionCall functionCall = functionCall("foo(value)");

  @Test
  public void aSimpleExample() throws Exception {
    TestExample subject = new TestExample(null, Types.TEXT, "foo");
    Struct inputType = Types.TEXT.asStruct();
    tuples = tuples(inputType, "'foo'", "'bar'", "'baz'");

    realized = subject.realize(realizationContext, inputType, functionCall).get();

    // accumulator with no values is empty
    assertTrue(realized.newAccumulator().isEmpty());

    // processors return type is expression's return type, but
    assertEquals(Types.TEXT, realized.getResultType());

    // result is returned from the processor verbatim
    assertEquals("foo", process());

    // value is extracted from each tuple using the value expression and given to the processor
    assertEquals(Sets.newHashSet("foo", "bar", "baz"), subject.getSeenValues());
  }

  @Test
  public void aSimpleExampleWithIdentity() throws Exception {
    TestExample subject = new TestExample("blah", Types.TEXT, "foo");
    Struct inputType = Types.TEXT.asStruct();
    tuples = tuples(inputType, "'foo'", "'bar'", "'baz'");

    realized = subject.realize(realizationContext, inputType, functionCall).get();

    // accumulator with no values is not empty - we have an identity
    assertFalse(realized.newAccumulator().isEmpty());
    assertEquals("blah", realized.newAccumulator().process());

    // processors return type is expression's return type
    assertEquals(Types.TEXT, realized.getResultType());

    // result is returned from the processor verbatim
    assertEquals("foo", process());

    // value is extracted from each tuple using the value expression and given to the processor
    assertEquals(Sets.newHashSet("foo", "bar", "baz"), subject.getSeenValues());
  }

  @Test
  public void aSimpleExampleWithNullableInput() throws Exception {
    TestExample subject = new TestExample(null, Types.TEXT, "foo");
    Struct inputType = Nullable.TEXT.asStruct();
    tuples = tuples(inputType, "'foo'", "'bar'", "[]", "'baz'");

    realized = subject.realize(realizationContext, inputType, functionCall).get();

    // accumulator with no values is empty
    assertTrue(realized.newAccumulator().isEmpty());

    // processors return type is list processors's return type - regardless of what the value expression says
    assertEquals(Types.TEXT, realized.getResultType());

    // result is returned from the processor verbatim
    assertEquals("foo", process());

    // value is extracted from each tuple using the value expression and given to the processor, nulls are omitted
    assertEquals(Sets.newHashSet("foo", "bar", "baz"), subject.getSeenValues());

    tuples = tuples(inputType, "[]");

    // clear previous collection
    subject.clear();

    // list processor not called, no list present
    assertNull(process());

    // no values were seen
    assertEquals(Collections.emptySet(), subject.getSeenValues());
  }

  @Test
  public void aSimpleExampleWithNullableInputAndIdentity() throws Exception {
    TestExample subject = new TestExample("yeah", Types.TEXT, "foo");
    Struct inputType = Nullable.TEXT.asStruct();
    tuples = tuples(inputType, "'foo'", "'bar'", "[]", "'baz'");

    realized = subject.realize(realizationContext, inputType, functionCall).get();

    // accumulator with no values is not empty due to identity
    assertFalse(realized.newAccumulator().isEmpty());

    // processors return type is list processors's return type - regardless of what the value expression says
    assertEquals(Types.TEXT, realized.getResultType());

    // result is returned from the processor verbatim
    assertEquals("foo", process());

    // value is extracted from each tuple using the value expression and given to the processor, nulls are omitted
    assertEquals(Sets.newHashSet("foo", "bar", "baz"), subject.getSeenValues());

    tuples = tuples(inputType, "[]");

    // list processor not called, no list present
    subject.clear();

    // identity is returned - no values collected
    assertEquals("yeah", process());

    // value is extracted from each tuple using the value expression and given to the processor, nulls are omitted
    assertEquals(Collections.emptySet(), subject.getSeenValues());
  }

  @Test
  public void aNullReturningExampleWithAndWithoutIdentity() throws Exception {
    TestExample nullReturningIdentity = new TestExample("yeah", Nullable.TEXT, null);
    TestExample nullReturning = new TestExample(null, Nullable.TEXT, null);
    Struct inputType = Types.TEXT.asStruct();
    tuples = tuples(inputType, "'foo'", "'bar'", "[]", "'baz'");

    RealizedAggregateExpression realizedIdentity =
        nullReturningIdentity.realize(realizationContext, inputType, functionCall).get();

    RealizedAggregateExpression realizedNoIdentity =
        nullReturning.realize(realizationContext, inputType, functionCall).get();

    assertFalse(realizedIdentity.newAccumulator().isEmpty());
    assertTrue(realizedNoIdentity.newAccumulator().isEmpty());

    // processors return type is list processors's return type - regardless of what the value expression says
    assertEquals(Nullable.TEXT, realizedNoIdentity.getResultType());
    // nullable is stripped - identity value means something is always returned
    assertEquals(Types.TEXT, realizedIdentity.getResultType());

    realized = realizedIdentity;
    // result is from identity
    assertEquals("yeah", process());

    realized = realizedNoIdentity;
    // identity crisis
    assertNull(process());
  }

  @Test
  public void extraArgumentsAreAlsoAvailableToTheListCollector() throws Exception {
    TestExample example = new TestExample(null, Types.TEXT, null);
    Struct inputType = Types.TEXT.asStruct();
    // the list collector only realizes the first expression
    functionCall = functionCall("foo(value, foo, carrot())");
    realized = example.realize(realizationContext, inputType, functionCall).get();
    // check that it was passed through as is
    assertSame(functionCall, example.seenFunctionCall);
  }

  @Test
  public void realizationFailsIfValueExpressionDoesNotRealize() throws Exception {
    TestExample example = new TestExample(null, Types.TEXT, null);
    Struct inputType = Types.TEXT.asStruct();
    // the list collector only realizes the first expression
    functionCall = functionCall("foo(valos)");
    assertThat(
      example.realize(realizationContext, inputType, functionCall),
      Matchers.failedResult(Matchers.hasAncestorProblem(
          Matchers.equalIgnoringChildren(Problems.foundWith(functionCall.getArguments().get(0)))
      ))
    );
  }

  @Test
  public void aProblemExceptionFromListProcessorCreationIsCaughtAndReturnedInRealizationResult() throws Exception {
    TestExample example = new TestExample(null, Types.TEXT, null);
    example.toThrow = Problem.error("cool custom");
    Struct inputType = Types.TEXT.asStruct();
    assertThat(
        example.realize(realizationContext, inputType, functionCall),
        Matchers.failedResult(equalTo(Problems.foundWith(functionCall, example.toThrow)))
      );
  }

  @Test
  public void atLeaseOneArgumentIsRequired() throws Exception {
    TestExample example = new TestExample(null, Types.TEXT, null);
    Struct inputType = Types.TEXT.asStruct();
    functionCall = functionCall("foo()");
    assertThat(
        example.realize(realizationContext, inputType, functionCall),
        Matchers.failedResult(equalTo(
          Problems.foundWith(functionCall, ArgsProblems.get().wrongNumber(1, 0))
        ))
    );

  }
}
