/*
 * 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 java.util.concurrent.atomic.AtomicInteger;

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.function.RiskscapeFunction;
import nz.org.riskscape.engine.function.StringFunctions;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.engine.types.WithinSet;
import nz.org.riskscape.rl.ast.ExpressionProblems;

public class IfThenElseTest extends BaseExpressionRealizerTest {

  Struct type;

  @Before
  public void setup() {
    project.getFunctionSet().insertFirst(DefaultOperators.INSTANCE);
    project.getFunctionSet().addAll(LogicFunctions.LOGIC_FUNCTIONS);
    project.getFunctionSet().addAll(LanguageFunctions.FUNCTIONS);
  }

  @Test
  public void testBasicBehaviour() {
    type = Struct.of("foo", Types.BOOLEAN, "bar", Types.TEXT, "baz", Types.TEXT);
    assertEquals("yes", evaluate("if_then_else(foo, bar, baz)", Tuple.ofValues(type, true, "yes", "no")));
    assertEquals("no", evaluate("if_then_else(foo, bar, baz)", Tuple.ofValues(type, false, "yes", "no")));
    assertEquals(Types.TEXT, realized.getResultType());
  }

  @Test
  public void argsCanBeNamed() {
    type = Struct.of("foo", Types.BOOLEAN, "bar", Types.TEXT, "baz", Types.TEXT);
    assertEquals("yes", evaluate("if_then_else(else: baz, then: bar, condition: foo)",
        Tuple.ofValues(type, true, "yes", "no")));
    assertEquals("no", evaluate("if_then_else(then: bar, else: baz, condition: foo)",
        Tuple.ofValues(type, false, "yes", "no")));
    assertEquals(Types.TEXT, realized.getResultType());
  }

  @Test
  public void canPassLambdas() {
    type = Struct.of("foo", Types.BOOLEAN, "bar", Types.TEXT, "baz", Types.TEXT);
    assertEquals("foo", evaluate("if_then_else(foo, () -> 'foo', () -> 'baz')",
        Tuple.ofValues(type, true, "yes", "no")));
    assertEquals(Types.TEXT, realized.getResultType());
    assertEquals("baz", evaluate("if_then_else(foo, () -> 'foo', () -> 'baz')",
        Tuple.ofValues(type, false, "yes", "no")));
    assertEquals("yes", evaluate("if_then_else(foo, () -> bar, () -> baz)",
        Tuple.ofValues(type, true, "yes", "no")));

    // can mix and match lambda and non lambda expressions
    assertEquals("yes", evaluate("if_then_else(foo, () -> bar, baz)", Tuple.ofValues(type, true, "yes", "no")));
    assertEquals("no", evaluate("if_then_else(foo, () -> bar, baz)", Tuple.ofValues(type, false, "yes", "no")));
    assertEquals("yes", evaluate("if_then_else(foo, bar, () -> baz)", Tuple.ofValues(type, true, "yes", "no")));
    assertEquals(Types.TEXT, realized.getResultType());
  }

  @Test
  public void elseIsOptional() {
    type = Struct.of("foo", Types.BOOLEAN, "bar", Types.TEXT, "baz", Types.TEXT);
    assertEquals("foo", evaluate("if(foo, 'foo')",
        Tuple.ofValues(type, true, "yes", "no")));
    // null is returned in the else case
    assertNull(evaluate("if(foo, 'foo')",
        Tuple.ofValues(type, false, "yes", "no")));
    // return type is the then type, but nullable
    assertEquals(Nullable.TEXT, realized.getResultType());

    assertEquals("foo", evaluate("if(foo, () -> 'foo')",
        Tuple.ofValues(type, true, "yes", "no")));
    assertNull(evaluate("if(foo, () -> 'foo')",
        Tuple.ofValues(type, false, "yes", "no")));
    assertEquals(Nullable.TEXT, realized.getResultType());
  }

  @Test
  public void argsCanBeSingleAttributeTuples() {
    Struct itemType = Struct.of("item", Types.INTEGER);
    type = Struct.of("foo", itemType, "bar", itemType, "baz", itemType);
    Tuple one = Tuple.ofValues(itemType, 1L);
    Tuple two = Tuple.ofValues(itemType, 2L);
    Tuple three = Tuple.ofValues(itemType, 3L);

    assertEquals(three, evaluate("if_then_else(foo < bar, baz, bar)", Tuple.ofValues(type, one, two, three)));
  }

  @Test
  public void noTypeInCommonYieldsAnything() throws Exception {
    type = Struct.of("foo", Types.BOOLEAN, "bar", Types.TEXT, "baz", Types.INTEGER);
    assertEquals("yes", evaluate("if_then_else(foo, bar, baz)", Tuple.ofValues(type, true, "yes", 4L)));
    assertEquals(4L, evaluate("if_then_else(foo, bar, baz)", Tuple.ofValues(type, false, "yes", 4L)));
    assertEquals(Types.ANYTHING, realized.getResultType());
  }

  @Test
  public void testWrappedTypesGiveBestReturnType() {
    type = Struct.of("foo", Types.BOOLEAN, "bar", new WithinSet(Types.TEXT, "yes", "no"), "baz", Types.TEXT);
    assertEquals("yes", evaluate("if_then_else(foo, bar, baz)", Tuple.ofValues(type, true, "yes", "no")));
    assertEquals("no", evaluate("if_then_else(foo, bar, baz)", Tuple.ofValues(type, false, "yes", "no")));
  }

  @Test
  public void nullIfConditionReturnsElse() throws Exception {
    // a nullable condition does not affect the nullability of the return type
    assertThat(evaluate("if(null_of('boolean'), 'foo', 'bar')", Tuple.EMPTY_TUPLE), is("bar"));
    // return type is not nullable because the result will be 'foo' or 'bar'
    assertEquals(Types.TEXT, realized.getResultType());

    // a nullable then makes the return type nullable
    type = Struct.of("cond", Nullable.BOOLEAN);
    assertThat(evaluate("if(cond, null, 'bar')", Tuple.ofValues(type)), is("bar"));
    assertEquals(Nullable.TEXT, realized.getResultType());

    // as does a nullable else
    assertThat(evaluate("if(null_of('boolean'), 'foo', null)", Tuple.EMPTY_TUPLE), nullValue());
    assertEquals(Nullable.TEXT, realized.getResultType());

    // so does a missing else
    assertThat(evaluate("if(null_of('boolean'), 'foo')", Tuple.EMPTY_TUPLE), nullValue());
    assertEquals(Nullable.TEXT, realized.getResultType());
  }

  @Test
  public void nullableThenOrElseMakesReturnTypeNullable() {
    type = Struct.of("condition", Types.BOOLEAN);
    Tuple input = Tuple.ofValues(type, true);
    assertThat(evaluate("if(condition, 'foo', null_of('text'))", input), is("foo"));
    assertEquals(Nullable.TEXT, realized.getResultType());

    assertThat(evaluate("if(condition, null_of('text'), 'bar')", input), nullValue());
    assertEquals(Nullable.TEXT, realized.getResultType());

    assertThat(evaluate("if(condition, null_of('text'), null_of('text'))", input), nullValue());
    assertEquals(Nullable.TEXT, realized.getResultType());
  }

  @Test
  public void constantTrueConditionUsesThenReturnType() {
    assertThat((Tuple)evaluate("if(true, then: {foo: 'foo'}, else: {bar: 'bar'})", Tuple.EMPTY_TUPLE),
        is(tuple("{foo: 'foo'}"))
    );
    assertThat(realized.getResultType(), is(Struct.of("foo", Types.TEXT)));

    // works the same if then/else are lambdas
    assertThat((Tuple)evaluate("if(true, then: () -> {foo: 'foo'}, else: () -> {bar: 'bar'})", Tuple.EMPTY_TUPLE),
        is(tuple("{foo: 'foo'}"))
    );
    assertThat(realized.getResultType(), is(Struct.of("foo", Types.TEXT)));

    assertThat((Tuple)evaluate("if({foo: true}, then: {foo: 'foo'}, else: {bar: 'bar'})", Tuple.EMPTY_TUPLE),
        is(tuple("{foo: 'foo'}"))
    );
    assertThat(realized.getResultType(), is(Struct.of("foo", Types.TEXT)));
  }

  @Test
  public void constantFalseConditionUsesElseReturnType() {
    assertThat((Tuple)evaluate("if(false, then: {foo: 'foo'}, else: {bar: 'bar'})", Tuple.EMPTY_TUPLE),
        is(tuple("{bar: 'bar'}"))
    );
    assertThat(realized.getResultType(), is(Struct.of("bar", Types.TEXT)));

    // works the same if then/else are lambdas
    assertThat((Tuple)evaluate("if(false, then: () -> {foo: 'foo'}, else: () -> {bar: 'bar'})", Tuple.EMPTY_TUPLE),
        is(tuple("{bar: 'bar'}"))
    );
    assertThat(realized.getResultType(), is(Struct.of("bar", Types.TEXT)));

    assertThat((Tuple)evaluate("if({foo: false}, then: {foo: 'foo'}, else: {bar: 'bar'})", Tuple.EMPTY_TUPLE),
        is(tuple("{bar: 'bar'}"))
    );
    assertThat(realized.getResultType(), is(Struct.of("bar", Types.TEXT)));
  }

  @Test
  public void constantFalseConditionReturnsNullableThenWhenElseIsMissing() {
    assertThat((Tuple)evaluate("if(false, then: 'foo')", Tuple.EMPTY_TUPLE),
        nullValue()
    );
    assertThat(realized.getResultType(), is(Nullable.TEXT));
  }


  @Test
  public void constantFalseConditionReturnsNothingThenWhenElseMissingAndThenIsBad() {
    assertThat((Tuple)evaluate("if(false, then: () -> missing_struct_attribute)", Tuple.EMPTY_TUPLE),
        nullValue()
    );
    assertThat(realized.getResultType(), is(Types.NOTHING));
  }

//  @Test - enable once we fix https://gitlab.catalyst.net.nz/riskscape/riskscape/-/issues/1568
  public void constantConditionOnlyEvaluatedOnce() throws Exception {
    Tuple input = tuple("{foo: 'yes', bar: 'no'}");
    AtomicInteger counter = new AtomicInteger();
    RiskscapeFunction sentinel = RiskscapeFunction.create(this, List.of(), Types.INTEGER, (args) -> {
      return (long) counter.incrementAndGet();
    });

    project.getFunctionSet().add(sentinel.identified("sentinel"));

    assertThat(counter.get(), is(0));

    realize(input.getStruct(), parse("if(sentinel() = 1, then: foo, else: bar)"));

    // realization executes the condition
    assertThat(counter.get(), is(1));

    // Evaluate it a couple of times
    assertThat(realized.evaluate(input), equalTo("yes"));
    // note that the condition is constant, but the results are not
    assertThat(realized.evaluate(tuple("{foo: 'Correct', bar: 'Negative'}")), equalTo("Correct"));

    // This isn't really a something we care about testing, but is an interesting thing to note - the condition is
    // always going to be evaluated over and over again, because of how expressions are evaluated - regardless, the
    // result is ignored and we use the static version
    assertThat(counter.get(), not(is(1)));

    // for good measure, we will manually bump the counter and confirm it still returns yes - it's been 'statically'
    // compiled.
    counter.incrementAndGet();
    assertThat(realized.evaluate(input), equalTo("yes"));

    // realize it again, should now return the no type
    realize(input.getStruct(), parse("if(sentinel() = 1, then: foo, else: bar)"));
    assertThat(realized.evaluate(input), equalTo("no"));
  }

  @Test
  public void conditionCanNotBeConstantIfContainsAFunctionCall() {
    project.getFunctionSet().addAll(StringFunctions.FUNCTIONS);
    Tuple input = tuple("{foo: 'yes', bar: 2}");

    assertThat(
        evaluate("if(str(1) = '1', then: foo, else: bar)", input),
        is("yes")
    );

    // This is probably going to fail when we address #1568
    assertThat(realized.getResultType(), is(Types.ANYTHING));
  }

//  @Test - disabled until we sort GL1568 - Isn't possible, as there are no literals that will return a null
  public void constantNullConditionReturnsThenElseAncestorType() {
    // We can't distinguish between a constant null and not constant due to technical reasons. EvalConstant
    // returns a ResultOrProblems which itself cannot contain a null.
    // So if the condition is a constant null then the result type will be the ancestor type. But maybe this is
    // a red herring because why would anyone make the condition a constant null.
    assertThat((Tuple)evaluate("if(null_of('boolean'), then: {foo: 'foo'}, else: {bar: 'bar'})", Tuple.EMPTY_TUPLE),
        is(tuple("{bar: 'bar'}"))
    );
    assertThat(realized.getResultType(), is(Struct.of("bar", Types.TEXT)));
  }

  @Test
  public void constant_else_CanHaveErrorsIfConditionIsTrue_1595() throws Exception {
    // bar doesn't exist, it doesn't matter because the else case is statically determined to never be executed
    assertThat(
        evaluateConstant("if(true, then: 'foo', else: () -> bar)"),
        equalTo("foo")
    );
  }

  @Test
  public void constant_then_CanHaveErrorsIfConditionIsFalse_1595() throws Exception {
    // slight variation on above - missing_function() doesn't exist either
    assertThat(
        evaluateConstant("if(false, then: () -> missing_function(), else: 'foo')"),
        equalTo("foo")
    );
  }

  @Test
  public void errorsWhenArgumentsAreBad() {
    type = Struct.of("foo", Types.BOOLEAN, "bar", Types.TEXT, "baz", Types.TEXT);
    // not enough arguments
    assertThat(realizeOnly("if_then_else(foo)", type), failedResult(
        hasAncestorProblem(is(ArgsProblems.get().wrongNumberRange(2, 3, 1)))
    ));

    // too many arguments
    assertThat(realizeOnly("if_then_else(foo, bar, foo, bar)", type), failedResult(
        hasAncestorProblem(is(ArgsProblems.get().wrongNumberRange(2, 3, 4)))
    ));

    // test argument not a boolean
    assertThat(realizeOnly("if_then_else('true', bar, foo)", type), failedResult(
        hasAncestorProblem(is(ArgsProblems.mismatch(IfThenElse.ARGUMENTS.get("condition"), Types.TEXT)))
    ));

    // bad then lambda
    assertThat(realizeOnly("if_then_else(foo, (t) -> 'what', foo)", type), failedResult(
        hasAncestorProblem(
            is(ExpressionProblems.get().lambdaArityError(parse("(t) -> 'what'"), 1, 0)))
    ));

    // bad then lambda
    assertThat(realizeOnly("if_then_else(foo, bar, (w) -> 'what')", type), failedResult(
        hasAncestorProblem(is(
            ExpressionProblems.get().lambdaArityError(parse("(w) -> 'what'"), 1, 0)))
    ));

    // missing the condition arg
    assertThat(realizeOnly("if_then_else(then: 'foo', else: 'what')", type), failedResult(
        hasAncestorProblem(is(
            ArgsProblems.get().required("condition")
        ))
    ));

    // missing the then arg
    assertThat(realizeOnly("if_then_else(true, else: 'what')", type), failedResult(
        hasAncestorProblem(is(
            ArgsProblems.get().required("then")
        ))
    ));
  }

  @Test
  public void ifSmokeTest() {
    // if is aliased to if_then_else. so we only need a quick smoke test that it works
    type = Struct.of("foo", Types.BOOLEAN, "bar", Types.TEXT, "baz", Types.TEXT);
    assertEquals("foo", evaluate("if(foo, () -> 'foo', () -> 'baz')",
        Tuple.ofValues(type, true, "yes", "no")));
    assertEquals(Types.TEXT, realized.getResultType());
    assertEquals("baz", evaluate("if(foo, () -> 'foo', () -> 'baz')",
        Tuple.ofValues(type, false, "yes", "no")));
    assertEquals("yes", evaluate("if(foo, () -> bar, () -> baz)",
        Tuple.ofValues(type, true, "yes", "no")));
  }

}
