/*
 * 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 nz.org.riskscape.engine.Assert.assertThrows;

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

import java.util.Optional;

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

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.FunctionCallException;
import nz.org.riskscape.engine.pipeline.Sink;
import nz.org.riskscape.engine.pipeline.SinkConstructor;
import nz.org.riskscape.engine.pipeline.TupleInput;
import nz.org.riskscape.engine.resource.Resource;
import nz.org.riskscape.engine.resource.StringResource;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.ProblemException;

public class CPythonExecTest extends CPythonBaseTest {

  Struct inputType = Struct.of("number", Types.INTEGER);
  Struct producedType;
  TupleInput tupleInput;
  Sink sink;
  CPythonAsyncProjector projector;

  @Before
  public void resetForRetry() {
    producedType = inputType;
  }

  @Test
  public void canCreateAVeryBasicAsyncFunction() throws Exception {
    createProjector("""
        def function(rows):
          for row in rows:
            yield {'number': row['number'] + 1}
        """);

    sink.accept(Tuple.ofValues(inputType, 1L));
    sink.finish();

    assertThat(readFromPython(), equalTo(Tuple.ofValues(producedType, 2L)));

    // process should exit 'naturally'
    projector.getProcess().join();
  }

  @Test
  public void canCreateFunctionWithRequiredParameters() throws Exception {
    producedType = producedType.add("message", Types.TEXT);
    Struct parameterType = Struct.of("message", Types.TEXT);
    createProjector("""
        def function(rows, parameters):
          for row in rows:
            yield {'number': row['number'] + 1, 'message': parameters['message']}
        """,
        Optional.of(Tuple.ofValues(parameterType, "foo"))
    );

    sink.accept(Tuple.ofValues(inputType, 1L));
    sink.finish();

    assertThat(readFromPython(), equalTo(Tuple.ofValues(producedType, 2L, "foo")));

    // process should exit 'naturally'
    projector.getProcess().join();
  }

  @Test
  public void canCreateFunctionWithDefaultParameters() throws Exception {
    // if function has default parameters you don't need to supply any at all
    producedType = producedType.add("message", Types.TEXT);
    createProjector("""
        def function(rows, parameters={'message': 'default'}):
          for row in rows:
            yield {'number': row['number'] + 1, 'message': parameters['message']}
        """,
        Optional.empty()
    );

    sink.accept(Tuple.ofValues(inputType, 1L));
    sink.finish();

    assertThat(readFromPython(), equalTo(Tuple.ofValues(producedType, 2L, "default")));

    // process should exit 'naturally'
    projector.getProcess().join();
  }

  @Test
  public void canCreateFunctionAndOverrideDefaultParameters() throws Exception {
    // you can change the default parameters
    producedType = producedType.add("message", Types.TEXT);
    Struct parameterType = Struct.of("message", Types.TEXT);
    createProjector("""
        def function(rows, parameters={'message': 'default'}):
          for row in rows:
            yield {'number': row['number'] + 1, 'message': parameters['message']}
        """,
        Optional.of(Tuple.ofValues(parameterType, "foobarbaz"))
    );

    sink.accept(Tuple.ofValues(inputType, 1L));
    sink.finish();

    assertThat(readFromPython(), equalTo(Tuple.ofValues(producedType, 2L, "foobarbaz")));

    // process should exit 'naturally'
    projector.getProcess().join();
  }

  @Test
  public void exceptionsFromThePythonFunctionComeOutViaInput() throws Exception {
    // Checks that any kind of exception within the body of the function is 'handled' to the extent that riskscape
    // sees if and fails some-what gracefully
    FunctionCallException ex = checkFunctionCallException("""
        def function(rows):
          yield foo # foo doesn't exist
        """);

    assertThat(render(ex), allOf(
        containsString("Your CPython function raised an error"),
        containsString("NameError: name 'foo' is not defined")
    ));
  }

  @Test
  public void incorrectTypeThrowsNiceException() throws Exception {
    FunctionCallException ex = checkFunctionCallException("""
        def function(rows):
          for row in rows:
            yield {'number': "hello"}
        """);

    assertThat(render(ex), allOf(
        containsString("An error occurred reading the result"),
        containsString("the type yielded by the Python code may not match the result-type specified"),
        containsString("Could not return value 'hello' as a 'Integer'")
    ));
  }

  @Test
  public void yieldedStructHasWrongAttributes() throws Exception {
    FunctionCallException ex = checkFunctionCallException("""
        def function(rows):
          for row in rows:
            yield {'numeric': 1}  # This should be 'number'
        """);

    assertThat(render(ex), allOf(
        containsString("An error occurred reading the result"),
        containsString("the type yielded by the Python code may not match the result-type specified"),
        containsString(
            "attribute 'number' was missing from the Python dictionary returned by your function. " +
                "The function return-type in your INI file may not match your python code"
        )
    ));
  }

  @Test
  public void aDodgyFunctionThrowsAnException() throws Exception {
    // this is the case where the pipeline will realize, but is going to choke when it gets ready for execution as
    // the script is missing its entry point

    ProblemException ex = assertThrows(ProblemException.class, () ->
      createProjector("""
          def funktion(rows):
            for row in rows:
              yield {'number': row['number'] + 1}
          """)
    );

    assertThat(render(ex), allOf(
        // in a pipeline, error-context should be the step definition
      containsString("Failed to load your CPython script for error-context."),
      containsString("Error: No 'def function' present")
    ));
  }

  private void createProjector(String scriptContent) throws Exception {
    createProjector(scriptContent, Optional.empty());
  }

  private void createProjector(String scriptContent, Optional<Tuple> parameters) throws Exception {
    Resource asyncScript = new StringResource("foo:/bar.py", scriptContent);
    projector = new CPythonAsyncProjector("error-context", inputType, producedType, parameters, asyncScript, runner);

    tupleInput = projector.getInput();
    SinkConstructor sinkConstructor = projector.getOutput();
    sink = sinkConstructor.newInstance(null).getOrThrow();
  }

  private FunctionCallException checkFunctionCallException(String pythonScript) throws Exception {
    createProjector(pythonScript);

    sink.accept(Tuple.ofValues(inputType, 1L));
    sink.finish();

    FunctionCallException exceptionCaught = assertThrows(FunctionCallException.class, () -> {
      Tuple result = null;
      while (result == null) {
        result = tupleInput.poll();
      }
    });

    // process should exit 'naturally'
    projector.getProcess().join();
    return exceptionCaught;
  }

  private Tuple readFromPython() {
    while (true) {
      Tuple fromPython = tupleInput.poll();

      if (fromPython != null) {
        return fromPython;
      }

      try {
        Thread.sleep(10);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }
  }
}
