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

import org.hamcrest.Matchers;
import org.junit.Test;

import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.FunctionArgument;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.rl.ExpressionRealizer.ProblemCodes;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.problem.Problem.Severity;
import nz.org.riskscape.rl.ast.ExpressionProblems;

@SuppressWarnings("unchecked")
public class ErrorHandlingTest extends BaseExpressionRealizerTest {


  @Test
  public void aParseExceptionIsCaughtAndReturned() throws Exception {
    assertThat(
        realizer.realize(inputStruct, "foo bar baz"),
        failedResult(equalIgnoringChildren(ExpressionProblems.get().malformedExpression("foo bar baz"))));
  }

  @Test
  public void unknownStructMemberErrorsAreReturned() throws Exception {
    assertThat(
        realizer.realize(inputStruct, "foo"),
        failedResult(
            equalTo(ExpressionProblems.get().noSuchStructMember("foo", Arrays.asList()))
        ));
  }

  @Test
  public void functionBindingErrorsAreReturned() throws Exception {
    assertThat(
        realizer.realize(inputStruct, "foo()"),
        failedResult(isProblem(MissingFunctionException.class)));
  }

  @Test
  public void missingOperatorProblemsAreReturned() throws Exception {
    assertThat(
        realizer.realize(inputStruct, "[] + 12"),
        failedResult(isError(ExpressionProblems.class, "noSuchOperatorFunction")));
  }

  @Test
  public void multipleProblemsAreReturned() throws Exception {
    ResultOrProblems<RealizedExpression> eOr = realizer.realize(inputStruct, "[foo(), [] + 12]");
    assertThat(
        eOr.getProblems(),
        Matchers.contains(
            isProblem(MissingFunctionException.class),
            isError(ExpressionProblems.class, "noSuchOperatorFunction")
        )
    );
  }


  @Test
  public void expressionWithUnknownKeywordArgumentsFail() throws Exception {
    RiskscapeFunction function = keywordArgFunction(ArgumentList.fromArray(
        new FunctionArgument("fooarg", Types.FLOATING)
    ));

    project.getFunctionSet().add(function.identified("my_function", null, null, null));

    realize(inputStruct, parse("my_function(bararg: 1, fooarg: 'foo')"));
    assertThat(
        realizationProblems,
        Matchers.contains(
            isError(ProblemCodes.KEYWORD_DOES_NOT_EXIST)
        )
    );
  }

  @Test
  public void expressionWithPlainWrongKeywordArgumentsFail() throws Exception {
    RiskscapeFunction function = keywordArgFunction(ArgumentList.fromArray(
        new FunctionArgument("fooarg", Types.FLOATING),
        new FunctionArgument("bararg", Types.FLOATING)
    ));

    project.getFunctionSet().add(function.identified("my_function", null, null, null));


    realize(inputStruct, parse("my_function(bazarg: 1)"));
    assertThat(
        realizationProblems,
        Matchers.contains(
            isError(ProblemCodes.KEYWORD_DOES_NOT_EXIST)
        )
    );
  }

  @Test
  public void expressionWithRepeatedKeywordArgumentsFails() throws Exception {
    RiskscapeFunction function = keywordArgFunction(ArgumentList
        .fromArray(new FunctionArgument("fooarg", Types.FLOATING),
            new FunctionArgument("bararg", Types.FLOATING)));

    project.getFunctionSet().add(function.identified("my_function", null, null, null));

    realize(inputStruct, parse("my_function(fooarg: 1, fooarg: 2)"));
    assertThat(realizationProblems, Matchers.contains(isError(ProblemCodes.KEYWORD_OUT_OF_ORDER)));
  }

  @Test
  public void expressionWithMissingArgumentsFails() throws Exception {
    RiskscapeFunction function = keywordArgFunction(ArgumentList
        .fromArray(new FunctionArgument("fooarg", Types.FLOATING),
            new FunctionArgument("bararg", Types.FLOATING)));

    project.getFunctionSet().add(function.identified("my_function", null, null, null));

    realize(inputStruct, parse("my_function(fooarg: 1)"));
    assertThat(realizationProblems, Matchers.contains(
        isProblem(Severity.ERROR,
            Matchers.containsString("Could not find function my_function with arguments [Integer]"))));
  }

  @Test
  public void keywordArgsMustNotReferToEarlierKeywords() throws Exception {
    RiskscapeFunction function = keywordArgFunction(ArgumentList.fromArray(
        new FunctionArgument("fooarg", Types.TEXT),
        new FunctionArgument("bararg", Types.INTEGER),
        new FunctionArgument("bazarg", Types.FLOATING)
    ));

    project.getFunctionSet().add(function.identified("my_function", null, null, null));

    realize(inputStruct, parse("my_function('foo', bararg: 1, fooarg: 'more foo')"));
    assertThat(
        realizationProblems,
        Matchers.contains(
            isError(ProblemCodes.KEYWORD_OUT_OF_ORDER)
        )
    );
  }

  @Test
  public void positionalArgsNotAllowedAfterKeywordArgs() throws Exception {
    RiskscapeFunction function = keywordArgFunction(ArgumentList.fromArray(
        new FunctionArgument("fooarg", Types.TEXT),
        new FunctionArgument("bararg", Types.INTEGER),
        new FunctionArgument("bazarg", Types.FLOATING)
    ));

    project.getFunctionSet().add(function.identified("my_function", null, null, null));

    realize(inputStruct, parse("my_function('foo', bararg: 1, 'more foo')"));
    assertThat(
        realizationProblems,
        Matchers.contains(
            isError(ProblemCodes.KEYWORD_REQUIRED)
        )
    );
  }

  @Test
  public void wrongArgumentTypeWhenOptionalArgumentsPresentFails() throws Exception {
    RiskscapeFunction function = keywordArgFunction(ArgumentList.fromArray(
        new FunctionArgument("fooarg", Types.TEXT),
        new FunctionArgument("bararg", Types.INTEGER),
        new FunctionArgument("bazarg", Nullable.of(Types.FLOATING))
    ));

    project.getFunctionSet().add(function.identified("my_function", null, null, null));

    realize(inputStruct, parse("my_function('foo', 43.0, 42)"));
    assertThat(realizationProblems, Matchers.contains(isProblem(Severity.ERROR,
        Matchers.containsString("Could not find function my_function with arguments [Text, Floating, Integer]"))));

    realize(inputStruct, parse("my_function('foo', 43.0)"));
    assertThat(realizationProblems, Matchers.contains(isProblem(Severity.ERROR,
        Matchers.containsString("Could not find function my_function with arguments [Text, Floating]"))));
  }
}
