/*
 * 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 java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import nz.org.riskscape.cpython.CPythonSpawner.CPythonProcess;
import nz.org.riskscape.engine.OsUtils;
import nz.org.riskscape.engine.resource.FileResource;
import nz.org.riskscape.problem.ProblemSink;

/**
 * Encapsulates some higher level logic around the configured python environment
 */
@Getter @ToString @EqualsAndHashCode @Slf4j
public class CPythonSettings {

  // path to serializing bridge
  public static final String DEFAULT_ADAPTOR_PATH = "rs2CPyAdaptor.py";

  public static final String DEFAULT_EXEC_ADAPTOR_PATH = "rs2CPyExecAdaptor.py";
  public static final String DEFAULT_PYTHON3_OPTIONS = "";
  // constant when python3-bin not set to simplify detection
  public static final String NOT_SET = "";

  // package scoped and non-final for test manipulation - to be otherwise treated as a constant!
  private static final String DEFAULT_LINUX_PYTHON_LOCATION = System.getenv()
  .getOrDefault("RS_PYTHON3_BIN", "/usr/bin/python3");


  private String python3Bin;
  private Path adaptorPath;
  private Path execAdaptorPath;

  private List<String> python3Options;
  private Path libDir;

  // NB see GL607 for future things
  private int maxProcessesPerFunction;

  /**
   * Returns default settings from just the plugin's library dir and the path to a python interpreter
   */
  public static CPythonSettings defaults(Path libDir, String python3bin) {
    Map<String, List<String>> settings = new HashMap<>();
    settings.put("cpython.python3-bin", Arrays.asList(python3bin));
    return fromIniSection(libDir, settings);
  }

  /**
   * Build settings from the given `iniSection` config
   * @param pluginInstallPath filesystem path to plugin's installed resources
   */
  public static CPythonSettings fromIniSection(Path pluginInstallPath, Map<String, List<String>> iniSection) {
    CPythonSettings settings = new CPythonSettings();

    settings.libDir = pluginInstallPath.resolve(getOrDefault("lib-dir", iniSection, "."));

    settings.python3Bin = getOrDefault("python3-bin", iniSection, NOT_SET);
    if (settings.python3Bin == NOT_SET && OsUtils.isLinux()) {
      if (new File(DEFAULT_LINUX_PYTHON_LOCATION).canExecute()) {
        log.info("Using default python3 install location of {}", DEFAULT_LINUX_PYTHON_LOCATION);
        settings.python3Bin = DEFAULT_LINUX_PYTHON_LOCATION;
      }
    }

    settings.adaptorPath = settings.libDir.resolve(getOrDefault("adaptor-script", iniSection, DEFAULT_ADAPTOR_PATH));
    settings.execAdaptorPath =
        settings.libDir.resolve(getOrDefault("exec-adaptor-script", iniSection, DEFAULT_EXEC_ADAPTOR_PATH));
    settings.python3Options = iniSection.getOrDefault("python3-add-option", Collections.emptyList());

    settings.maxProcessesPerFunction = Integer.parseInt(getOrDefault(
        "max-processes",
        iniSection,
        Integer.toString(Runtime.getRuntime().availableProcessors()))
    );

    return settings;
  }

  /**
   * @return true if the user has setup python3-bin or we've successfully found python at the default location.
   * Later on we do some more thorough checks that python is working, and it doesn't make sense to do those checks
   * if the user just has the CPython plugin installed because riskscape shipped with it on by default.
   */
  public boolean isPython3BinSet() {
    return python3Bin != NOT_SET;
  }

  /**
   * Runs a few checks to get some confidence that our cpython adaptor is going to work properly, logging errors to
   * problemSink
   */
  public boolean checkPython3Working(ProblemSink problemSink) {

    Path checkPythonScript = libDir.resolve("checkPython.py");

    List<String> checkCommand = newPython3Command();
    checkCommand.add(checkPythonScript.toString());
    CPythonProcess process;
    try {
      process = new CPythonSpawner(this, problemSink).spawn(
          new FileResource(checkPythonScript),
          checkCommand
      );
    } catch (IOException e) {
      problemSink.log(CPythonProblems.get().failedToStartPlugin(e.getMessage()));
      // send the error somewhere
      return false;
    }

    // this is blocking
    boolean exittedOk = process.exittedOK();
    if (!exittedOk) {
      String errorText = process.getErrorText();
      problemSink.log(CPythonProblems.get().failedToStartPlugin(errorText));
      return false;
    }

    if (!getAdaptorPath().toFile().canRead()) {
      problemSink.log(CPythonProblems.get().failedToStartPlugin("can not read " + getAdaptorPath()));
      return false;
    }

    return true;
  }

  /**
   * @return the beginning of a command that can be used to invoke python3, with options but without the adaptor script
   */
  public List<String> newPython3Command() {
    List<String> command = new LinkedList<>();
    command.add(python3Bin);
    command.addAll(python3Options);
    return command;
  }

  private static String getOrDefault(String key, Map<String, List<String>> section, String defaultValue) {
    List<String> values = section.get("cpython." + key);

    if (values == null || values.size() == 0) {
      return defaultValue;
    } else {
      return values.get(0);
    }
  }
}
