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

import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Optional;

import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;

import lombok.Getter;
import lombok.Setter;

import nz.org.riskscape.engine.cli.BaseCliIntegrationTest.ExecResult;

/**
 * Runs riskscape in a docker container
 */
public class DockerRunner extends ProcessRunner implements CommandRunner {

  /**
   * Environment variable that can be set with the docker image to use, else default image
   * "riskscape-cli" will be used.
   */
  public static final String RISKSCAPE_CLI_IMAGE = "RISKSCAPE_CLI_IMAGE";

  /**
   * Environment variable that can be set with the local directory to be volume mounted
   * into the docker container. Default to: current working directory
   */
  public static final String RISKSCAPE_DOCKER_DIRECTORY_SOURCE = "RISKSCAPE_DOCKER_DIRECTORY_SOURCE";

  /**
   * Environment variable that can be set with the directory in the docker container that will be
   * volume mounted to. Defaults to: /home/riskscape
   */
  public static final String RISKSCAPE_DOCKER_DIRECTORY_TARGET = "RISKSCAPE_DOCKER_DIRECTORY_TARGET";

  /**
   * Environment variable that will override the default docker image entry point, when set.
   */
  public static final String RISKSCAPE_DOCKER_ENTRY_POINT = "RISKSCAPE_DOCKER_ENTRY_POINT";

  /**
   * Environment variable containing the docker network to use. Defaults to riskscape-test
   *
   * If set to empty string then networking is not configured.
   */
  public static final String RISKSCAPE_DOCKER_NETWORK = "RISKSCAPE_DOCKER_NETWORK";

  @Setter @Getter
  private String imageTag = System.getenv().getOrDefault(RISKSCAPE_CLI_IMAGE, "riskscape-cli");
  @Setter @Getter
  private String networkName = System.getenv().getOrDefault(RISKSCAPE_DOCKER_NETWORK, "riskscape-test");

  private final String dockerDirectory = System.getenv()
      .getOrDefault(RISKSCAPE_DOCKER_DIRECTORY_TARGET, "/home/riskscape");

  @Override
  public CommandResult execute(CommandInput input) {
    String dockerUser = String.format("%s:%s", fetchUid(), fetchGid());

    ImmutableList.Builder<String> prefix = ImmutableList.builder();

    prefix.add("docker", "run", "--rm")
      .add("--user", dockerUser)
      .add("-v", String.format("%s:%s",
          Paths.get(System.getenv().getOrDefault(RISKSCAPE_DOCKER_DIRECTORY_SOURCE, ".")).toAbsolutePath().normalize(),
         dockerDirectory))
      .add("-w", "/home/riskscape")
      //Set user.home with JVM_OPTS because we don't expect the docker image to recognise our UID
      .add("--env", "JVM_OPTS=-Duser.home=" + dockerDirectory);

    if (! Strings.isNullOrEmpty(networkName)) {
      prefix.add("--network", networkName);
    }

    input.environmentVariables.entrySet().stream()
        .forEach(entry -> prefix.add("--env", entry.getKey() + "=" + entry.getValue()));

    String entryPoint =  System.getenv().get(RISKSCAPE_DOCKER_ENTRY_POINT);
    if (Strings.isNullOrEmpty(entryPoint)) {
      // run riskscape as the default entry-point
      prefix.add("--entrypoint", "/opt/riskscape-cli/bin/riskscape");
    } else {
      prefix.add("--entrypoint", entryPoint);
    }

//      inputter.ifPresent(i -> prefix.add("--interactive"));

    prefix.add(imageTag);
    Iterator<String> inputIterator = input.toStream().iterator();
    String next = inputIterator.next();
    if (!next.equals("riskscape")) {
      prefix.add(next);
    }

    prefix.addAll(inputIterator);

    ExecResult result =  exec(Paths.get(".."), prefix.build(), Optional.empty());

    return CommandResult.builder().exitCode(result.retCode).stderr(result.stderr).stdout(result.stdout).build();
  }

  private String fetchUid() {
    ExecResult result = exec(Paths.get("."), Arrays.asList("id", "-u"), Optional.empty());
    return result.stdout.get(0).trim();
  }

  private String fetchGid() {
    ExecResult result = exec(Paths.get("."), Arrays.asList("id", "-g"), Optional.empty());
    return result.stdout.get(0).trim();
  }

  @Override
  public CommandEnv environment() {
    return new CommandEnv(Paths.get(dockerDirectory), Paths.get(".").toAbsolutePath());
  }

}
