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

import static nz.org.riskscape.engine.Matchers.*;
import static nz.org.riskscape.engine.cli.tests.TableMatchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import org.junit.Test;

import groovy.lang.Category;
import nz.org.riskscape.engine.Project;
import nz.org.riskscape.engine.cli.CliIntegrationTest;
import nz.org.riskscape.engine.cli.ExpressionCommand;
import nz.org.riskscape.engine.cli.FunctionCommand.FunctionListCommand;
import nz.org.riskscape.engine.cli.Table;
import nz.org.riskscape.engine.function.InterestingKeywordFunction;
import nz.org.riskscape.engine.test.EngineCommandIntegrationTest;
import nz.org.riskscape.engine.util.Pair;

/**
 * Test various high level features of running functions, via the function run and expression eval commands
 * @author nickg
 *
 */
@Category(CliIntegrationTest.class)
public class FunctionEvalTest extends EngineCommandIntegrationTest {

  @Test
  public void canExpressionEvalAFunctionWithSomeFunkyKeywords() {
    populateProject(stdhome());
    project.getFunctionSet().add(new InterestingKeywordFunction().identified("dummy"));

    ExpressionCommand.Eval cmd = setupCommand(new ExpressionCommand.Eval());

    // everything supplied in-line
    cmd.expression = "dummy('foo', 'bar', 'baz', 'foo')";
    assertEquals("[foo, bar, baz, foo]", cmd.run());

    // extra optional arg
    cmd.expression = "dummy('foo', 'bar', 'baz')";
    assertEquals("[foo, bar, baz, null]", cmd.run());

    // passed out of order using keyword args
    cmd.expression = "dummy('foo', \"This is --|just|-- ridiculous!\": 'yes', foo-baz-bar: 'bar', foo_bar: 'baz')";
    assertEquals("[foo, baz, bar, yes]", cmd.run());
  }

  @Test
  public void canShowReturnTypeWithExpressionEval() throws Exception {
    populateProject(stdhome());
    ExpressionCommand.Eval cmd = setupCommand(new ExpressionCommand.Eval());

    // Test with a list expression
    cmd.expression = "[1, 2.0]";
    cmd.showReturnType = true;
    String result = (String) cmd.run();
    String[] lines = result.split("\\r?\\n");
    assertEquals(2, lines.length);
    assertEquals("[1.0, 2.0]", lines[0]);
    assertEquals("List[Floating]", lines[1]);
  }

  @Test
  public void canExpressionEvalAJythonFunction() throws Exception {

    assertThat(
        populateProject(stdhome()), result(any(Project.class)));

    ExpressionCommand.Eval cmd = setupCommand(new ExpressionCommand.Eval());

    // everything supplied in-line
    cmd.expression = "\"1-polynomial\"(3)";
    assertEquals("11", cmd.run());

    assertThat(errBytes.toString(), emptyString());
    assertThat(outBytes.toString(), emptyString());
  }

  @SuppressWarnings("unchecked")
  @Test
  public void canListAnIniDefinedFunction() throws Exception {
    populateProject(stdhome());
    FunctionListCommand cmd = setupCommand(new FunctionListCommand());

    Table table = (Table) cmd.run();
    assertThat(table, hasRow(
        Pair.of("id", "pow2_str"),
        Pair.of("description", equalTo("Squares a number and returns it as a text string")),
        Pair.of("arguments", equalTo("[{num=>Floating}]")),
        Pair.of("return-type", equalTo("Text")),
        Pair.of("category", equalTo("UNASSIGNED"))
    ));

    // check that we also load functions defined in a functions.ini
    assertThat(table, hasRow(
        Pair.of("id", "pow2_str_alias"),
        Pair.of("description", equalTo("Alias of another function with slightly different return type")),
        Pair.of("arguments", equalTo("[{num=>Floating}]")),
        Pair.of("return-type", equalTo("Anything")),
        Pair.of("category", equalTo("UNASSIGNED"))
    ));
  }

  @Test
  public void canRunAnIniDefinedFunction() throws Exception {
    populateProject(stdhome());
    ExpressionCommand.Eval cmd = setupCommand(new ExpressionCommand.Eval());

    cmd.expression = "pow2_str({num: 4.0})";
    assertEquals("16.0", cmd.run());
    assertThat(errBytes.toString(), emptyString());
    assertThat(outBytes.toString(), emptyString());

    // coercion from int to floating struct member
    cmd.expression = "pow2_str(3)";
    assertEquals("9.0", cmd.run());
    assertThat(errBytes.toString(), emptyString());
    assertThat(outBytes.toString(), emptyString());
  }

  @Test
  public void canRunFunctionDefinedInSeparateIniFile() throws Exception {
    // this time we call weighted_mean() defined in a separate functions.ini
    populateProject(stdhome());
    ExpressionCommand.Eval cmd = setupCommand(new ExpressionCommand.Eval());

    cmd.expression = "weighted_mean([2.0, 4.0, 6.0, 8.0], [0.1, 0.25, 0.15, 0.5])";
    assertEquals("6.1", cmd.run());
    assertThat(errBytes.toString(), emptyString());
    assertThat(outBytes.toString(), emptyString());
  }
}
