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

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ProcessBuilder.Redirect;
import java.util.Optional;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

/**
 * Various utilities for interacting with the OS
 */
@Slf4j
public class OsUtils {

  @Getter
  private static final String OS = System.getProperty("os.name").toLowerCase();
  /**
   * For determining the code page (output encoding that the Windows terminal uses)
   */
  private static final String[] WINDOWS_CODE_PAGE_COMMAND =
      new String[] {"PowerShell", "-Command", "& {[console]::OutputEncoding.CodePage}"};

  private static final int WINDOWS_UTF8_CODE_PAGE = 65001;

  public static final String LINE_SEPARATOR = String.format("%n");

  /**
   * @return true if it looks like the system's os name is a Linux variant.
   * Note that other Unix variants (like AIX) are also included here, but Mac OS is not
   * (even though Mac is technically a Unix system).
   */
  public static boolean isLinux() {
    return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0);
  }

  /**
   * @return true if it looks like the system's os name is a Mac OS variant
   */
  public static boolean isMac() {
    // TODO this will probably work, but currently we don't actively test on Mac
    return OS.indexOf("mac") >= 0;
  }

  /**
   * @return true if it looks like the system's os name is a windows variant
   */
  public static boolean isWindows() {
    return OS.startsWith("win");
  }

  private static Optional<Integer> getCmdOutputAsInt(String[] cmd) {
    try {
      Process p = new ProcessBuilder(cmd).redirectInput(Redirect.INHERIT).start();
      int exitCode = p.waitFor();
      if (exitCode == 0) {
        // I hope you feel good about yourself, java
        return Optional.of(Integer.parseInt(new BufferedReader(new InputStreamReader(p.getInputStream())).readLine()));
      }
    } catch (IOException| RuntimeException | InterruptedException ex) {
    }
    return Optional.empty();
  }

  /**
   * for strings that have file separators in them, make them correct for
   * the env.
   *
   * @param path
   * @return String
   */
  public static String fixPathSep(String path) {
    return path.replace("/", File.separator);
  }

  public static String fps(String path) {
    return fixPathSep(path);
  }

  /**
   * Changes the code page (i.e. terminal encoding) for a Windows console
   */
  private static boolean setWindowsCodePage(int codePage) {
    String[] cmd = new String[] {"cmd", "/c", "chcp", String.valueOf(codePage)};
    try {
      Process p = new ProcessBuilder(cmd).redirectInput(Redirect.INHERIT).start();
      int exitCode = p.waitFor();
      return exitCode == 0;
    } catch (IOException | RuntimeException | InterruptedException ex) {
    }
    return false;
  }

  /**
   * Checks the current console for any compatibility problems that might cause
   * the user headaches when running RiskScape. In particular, the default
   * terminal encoding on Windows can result in some truly awful display issues.
   */
  public static void checkConsoleCompatibility() {
    // RiskScape output defaults to UTF8-encoded, but the default code page on
    // Windows doesn't support UTF8 and so renders things very messily.
    // The simple fix is to update the console code page to use UTF8-encoding
    if (isWindows() && System.getProperty("file.encoding").equals("UTF-8")) {
      int codePage = getCmdOutputAsInt(WINDOWS_CODE_PAGE_COMMAND).orElse(WINDOWS_UTF8_CODE_PAGE);
      if (codePage != WINDOWS_UTF8_CODE_PAGE) {
        if (setWindowsCodePage(WINDOWS_UTF8_CODE_PAGE)) {
          log.warn("Changed console to use UTF-8 encoding (was chcp {})", codePage);
        } else {
          log.warn("Could not change console code page. For best results when rendering output, run: chcp 65001");
        }
      }
    }
  }
}
