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

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import static nz.org.riskscape.engine.Matchers.*;

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

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Assert;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.rl.BaseExpressionRealizerTest;
import nz.org.riskscape.engine.rl.EvalException;
import nz.org.riskscape.engine.rl.LanguageFunctions;
import nz.org.riskscape.engine.types.CoercionException;
import nz.org.riskscape.engine.types.Enumeration;
import nz.org.riskscape.engine.types.Nullable;
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.engine.types.WithinRange;
import nz.org.riskscape.engine.types.WithinSet;
import nz.org.riskscape.rl.ast.ExpressionProblems;

public class CastTest extends BaseExpressionRealizerTest {

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

  @Test
  public void canCastSimpleTypes() {
    assertThat(evaluateConstant("cast('4', 'integer')"), is(4L));
    assertThat(realized.getResultType(), is(Types.INTEGER));

    assertThat(evaluateConstant("cast('4.2', 'floating')"), is(4.2D));
    assertThat(realized.getResultType(), is(Types.FLOATING));
  }

  @Test
  public void canCastToEnum() {
    assertThat(evaluateConstant("cast('wood', 'enum(\\'wood\\', \\'steel\\')')"), is("wood"));
    assertThat(realized.getResultType(), is(Enumeration.oneBased("wood", "steel")));

    assertCoercionFails("cast('plastic', 'enum(\\'wood\\', \\'steel\\')')");
  }

  @Test
  public void canCastToSet() {
    assertThat(evaluateConstant("cast('wood', 'set(text, \\'wood\\', \\'steel\\')')"), is("wood"));
    assertThat(realized.getResultType(), is(new WithinSet(Types.TEXT, "wood", "steel")));

    assertCoercionFails("cast('plastic', 'set(text, \\'wood\\', \\'steel\\')')");
  }

  @Test
  public void canCastToRange() {
    assertThat(evaluateConstant("cast('2', 'range(integer, 1, 10)')"), is(2L));
    assertThat(realized.getResultType(), is(new WithinRange(Types.INTEGER, 1L, 10L)));

    assertCoercionFails("cast('plastic', 'range(integer, 1, 10)')");
  }

  @Test
  public void canCastToIdentifiedType() {
    Type myType = new WithinRange(Types.FLOATING, 5.0D, 10.D);
    project.getTypeSet().add("my-type", myType);

    assertThat(evaluateConstant("cast('5.7', 'my-type')"), is(5.7D));
    assertThat(realized.getResultType(), is(myType));

    assertCoercionFails("cast('11', 'my-type')");
  }

  @Test
  public void handlesNullableValue() {
    Struct type = Struct.of("value", Nullable.INTEGER);
    assertThat(evaluate("cast(value, 'range(integer, 1, 10)')", Tuple.ofValues(type, 3L)), is(3L));
    assertThat(realized.getResultType(), is(new WithinRange(Types.INTEGER, 1, 10)));
    // NB: cast() can remove nullable, so the null-safe wrapper does not kick in
    EvalException ex = Assert.assertThrows(EvalException.class,
            () -> evaluate("cast(value, 'range(integer, 1, 10)')", Tuple.ofValues(type)));
  }

  @Test
  public void dealsWithBadArguments() {
    // not enough args
    assertThat(realizeOnly("cast('thing')", Struct.EMPTY_STRUCT), failedResult(
        hasAncestorProblem(is(ArgsProblems.get().wrongNumber(Cast.ARGUMENTS.getArity(), 1)))
    ));

    // too many
    assertThat(realizeOnly("cast('thing', 'integer', 'foo')", Struct.EMPTY_STRUCT), failedResult(
        hasAncestorProblem(is(ArgsProblems.get().wrongNumber(Cast.ARGUMENTS.getArity(), 3)))
    ));

    // typedef not text
    assertThat(realizeOnly("cast('thing', 33.3)", Struct.EMPTY_STRUCT), failedResult(
        hasAncestorProblem(is(ArgsProblems.mismatch(Cast.ARGUMENTS.get("typedef"), Types.FLOATING)))
    ));

    // typedef not constant
    assertThat(realizeOnly("cast('thing', value)", Struct.of("value", Types.TEXT)), failedResult(
        hasAncestorProblem(is(ExpressionProblems.get().constantRequired(parse("value"))))
    ));

    // typedef not good
    assertThat(realizeOnly("cast('thing', 'unknown')", Struct.EMPTY_STRUCT), failedResult(
        hasAncestorProblem(equalIgnoringChildren(ExpressionProblems.get().notAValid(Type.class, "unknown")))
    ));
  }

  void assertCoercionFails(String expr) {
    EvalException ex = Assert.assertThrows(EvalException.class, () -> evaluateConstant(expr));
    assertThat(ex.getCause(), instanceOf(CoercionException.class));
  }

}
