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

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

import java.nio.file.Path;

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

import nz.org.riskscape.engine.cli.BaseCliIntegrationTest2;
import nz.org.riskscape.engine.cli.CommandResult;

/**
 * Checks how the cpython plugin and functions behave depending on settings.ini
 */
public class CPythonStartupTest extends BaseCliIntegrationTest2 {

  Path homes;

  @Before
  public void setupDirs() {
    homes = environment().sourceTree.resolve("src").resolve("test").resolve("homes");
  }

  @Test
  public void producesNoWarningIfNoPythonAndNoSettings() throws Exception {
    CommandResult result = execute(defaultCommand(homes.resolve("no-settings")).option("--version"));
    assertThat(result, hasInStdout("cpython.CPythonPlugin"));
    assertThat(result, not(hasInStderr("[ERROR] Failed to start CPython plugin")));
  }

  @Test
  public void canCallASimpleCPythonFunctionWhenEnabled() throws Exception {
    CommandResult result = execute(defaultCommand(homes.resolve("good-settings"))
        .option("-P", homes.resolve("hello-with-framework.ini"))
        .subcommands("expression", "eval").subcommand("hello('test-o')"));

    assertThat(result, hasInStdout("Hello, test-o [cpython]"));
    assertThat(result.stderr, empty());
  }

  @Test
  public void canRunASimplePipelineThatUsesACPythonFunction() throws Exception {
    CommandResult result = execute(defaultCommand(homes.resolve("good-settings"))
        .option("-P", homes.resolve("simple-pipeline.ini"))
        .subcommands("model", "run", "simple"));

    // for now, we just confirm that it runs successfully without any serialization problems and that our output
    // is written - there's a ticket for some proper model integration tests that will use the simpler
    // EngineCommandIntegrationTest base class that makes asserting file output a million times easier
    assertThat(result, hasInStdout("squares.csv"));
    assertThat(result.stderr, empty());
  }

  @Test
  public void startsWithAWarningIfPythonBinIsBad() throws Exception {
    CommandResult result = execute(defaultCommand(homes.resolve("bad-settings")).option("--version"));
    assertThat(result, hasInStdout("cpython.CPythonPlugin"));
    assertThat(result, hasInStderr("[ERROR] Failed to start CPython plugin"));
  }

  @Test
  public void startsWithAWarningWithBadPythonWindowsPath() throws Exception {
    CommandResult result = execute(defaultCommand(homes.resolve("bad-settings-windows")).option("--version"));
    assertThat(result, hasInStdout("cpython.CPythonPlugin"));
    assertThat(result, hasInStderr("[ERROR] Failed to start CPython plugin"));
    // check python path hasn't got mangled
    assertThat(result, hasInStderr("Cannot run program \"C:\\users\\foo\\bin\\python3.exe\""));
  }

  @Test
  public void canCallACPythonFunctionIfNoSettingsButDefaultGood() throws Exception {

    CommandResult result = execute(defaultCommand(homes.resolve("no-settings"))
        .option("-P", homes.resolve("hello-with-framework.ini"))
        .subcommands("expression", "eval").subcommand("hello('test-o')"));

        assertThat(result, hasInStdout("Hello, test-o [cpython]"));
        assertThat(result.stderr, empty());
  }

  @Test
  public void usingACPythonFunctionFailsIfNoSettingsAndDefaultBad() throws Exception {

    CommandResult result = execute(defaultCommand(homes.resolve("no-settings"))
        .environmentVariable("RS_PYTHON3_BIN", "/no/python/here")
        .option("-P", homes.resolve("hello-with-framework.ini"))
        .subcommands("expression", "eval").subcommand("hello('test-o')"));

    assertThat(result, not(hasInStdout("hello, test-o")));
    assertThat(result, not(hasInStderr("[ERROR] Failed to start CPython plugin")));

    assertThat(result, hasInStderr("function 'hello' (from line 1 of /home/riskscape/src/test/homes/"
        + "hello-with-framework.ini) is not valid"));
    assertThat(result, hasInStderr("CPython functions are not available.  Please follow the CPython set up "
        + "instructions and confirm that RiskScape starts without warnings and try again."));
  }


  @Test
  public void usingACPythonFunctionFailsIfBadSettings() throws Exception {
    CommandResult result = execute(defaultCommand(homes.resolve("bad-settings"))
        .option("-P", homes.resolve("hello-with-framework.ini"))
        .subcommands("expression", "eval").subcommand("hello('test-o')"));

    assertThat(result, not(hasInStdout("hello, test-o")));
    assertThat(result, hasInStderr("[ERROR] Failed to start CPython plugin"));

    assertThat(result, hasInStderr("function 'hello' (from line 1 of /home/riskscape/src/test/homes/"
        + "hello-with-framework.ini) is not valid"));
    assertThat(result, hasInStderr("CPython functions are not available.  Please follow the CPython set up "
        + "instructions and confirm that RiskScape starts without warnings and try again."));
  }

  @Test
  public void jythonWillClaimAFunctionIfNoFrameworkAndCPythonNotWorking() throws Exception {
    CommandResult result = execute(defaultCommand(homes.resolve("bad-settings"))
        .option("-P", homes.resolve("hello-no-framework.ini"))
        .subcommands("expression", "eval").subcommand("hello('test-o')"));

    assertThat(result, hasInStdout("Hello, test-o [jython]"));
    assertThat(result, hasInStderr("[ERROR] Failed to start CPython plugin"));
  }

  @Test
  public void cpythonWillClaimAFunctionIfNoFrameworkAndCPythonIsWorking() throws Exception {
    CommandResult result = execute(defaultCommand(homes.resolve("good-settings"))
        .option("-P", homes.resolve("hello-no-framework.ini"))
        .subcommands("expression", "eval").subcommand("hello('test-o')"));

    assertThat(result, hasInStdout("Hello, test-o [cpython]"));
    assertThat(result, not(hasInStderr("[ERROR] Failed to start CPython plugin")));
  }

}
