/*
 * 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.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;

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

import ch.qos.logback.classic.Level;
import lombok.Getter;
import lombok.Setter;
import nz.org.riskscape.picocli.CommandLine.Command;
import nz.org.riskscape.picocli.CommandLine.Option;

/**
 * The root of the riskscape cli command hierarchy.
 *
 * TODO move this (or an interface from it) in to engine-api
 */
@Command(
    name = "riskscape", versionProvider = Main.class
)
public class CliRoot extends StubCommand {

  public static final String RISKSCAPE_PROJECT_ENV = "RISKSCAPE_PROJECT";

  public static final String RISKSCAPE_HOME_ENV = "RISKSCAPE_HOME";

  private final Map<String, String> env;

  @Option(names = { "-V", "--version" }, versionHelp = true)
  boolean versionRequested;

  @Option(names = { "--license" })
  boolean licenseRequested;

  @Getter @Setter
  @Option(names = {"-e", "--show-stacktrace"})
  private boolean showStackTrace;

  @Deprecated
  @Option(names = {"--no-core-plugins"}, hidden = true)
  @Getter @Setter
  private boolean disableLoadingCorePlugins;

  @Deprecated
  @Option(names = {"-l", "--load-plugin"}, hidden = true)
  @Getter @Setter
  private List<Path> pluginPaths = Lists.newArrayList();

  @Deprecated
  @Option(names = {"-b", "--home", "-H"}, hidden = true)
  @Setter
  private String homeDir = null;

  @Option(
      names = {"--project", "-P"})
  @Setter
  String projectIni; // package level for testing

  @Option(names = {"--log-level"})
  @Setter
  private String logLevel;

  @Getter @Setter
  @Option(names = "--random-seed")
  private Long randomSeed;

  public Level getLogLevel() {
    return logLevel == null ? null : Level.toLevel(logLevel.toUpperCase());
  }

  @Getter @Setter
  @Option(names = "--pipeline-threads")
  private Integer pipelineThreads = Runtime.getRuntime().availableProcessors();

  // we leave this one here for now for backwards compatibility for any scripts that are setting it
  @Getter @Setter
  @Option(names = "--experimental-execution", hidden = true)
  private boolean experimentalExecution;

  @Getter @Setter
  @Option(names = {"--show-project-errors"})
  private boolean showProjectErrors;

  @Getter @Setter
  @Option(names = {"--beta"}, negatable = true)
  private Boolean betaFeaturesEnabled;

  public CliRoot() {
    env = System.getenv();
  }

  // testing constructor
  CliRoot(Map<String, String> env) {
    this.env = env;
  }

  /**
   * @return true if a RISKSCAPE_HOME directory was specified by the user,
   * either as a CLI option or as an environment variable.
   */
  public boolean isHomeDirSpecified() {
    return homeDir != null || env != null;
  }

  public Optional<String> getHomeDir() {
    String homeDirValue = homeDir;
    if (Strings.isNullOrEmpty(homeDirValue)) {
      homeDirValue = env.get(RISKSCAPE_HOME_ENV);
    }
    return Optional.ofNullable(homeDirValue);
  }

  public Optional<String> getProjectIni() {
    if (Strings.isNullOrEmpty(projectIni)) {
      return Optional.ofNullable(env.get(RISKSCAPE_PROJECT_ENV));
    } else {
      return Optional.of(projectIni);
    }
  }
}
