/*
 * 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.io.PrintStream;
import java.util.Collections;
import java.util.Locale;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.cli.InterruptHandler;
import nz.org.riskscape.cli.Terminal;
import nz.org.riskscape.engine.i18n.Messages;
import nz.org.riskscape.picocli.CommandLine.Help.Ansi;
import nz.org.riskscape.picocli.CommandLine.Help.Ansi.Text;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemSink;
import nz.org.riskscape.problem.Problem.Severity;

/**
 * Wraps all of the user-facing parts of the CLI
 */
@RequiredArgsConstructor
public abstract class BaseTerminal implements ProblemSink, Terminal {

  public static final int DEFAULT_TTY_WIDTH = 80;
  public static final int TERMINAL_HEIGHT_UNLIMITED = Integer.MAX_VALUE;

  /**
   * A default {@link Ansi} object to use when building {@link Text} objects from {@link String}s.
   */
  public static Ansi defaultAnsi = Ansi.AUTO;

  /**
   * Wraps a PrintStream in one that will inhibit the auto closing of the underlying output stream.
   * @param toWrap
   * @return a print stream wrapping toWrap
   */
  public static PrintStream wrapAsUncloseable(PrintStream toWrap) {
    return new PrintStream(toWrap) {
      @Override
      public void close() {
        //Don't call super.close() as that will close the underlying stream
        flush();
      }
    };
  }

  // this class uses a problem renderer to format problems before printing them out for the ProblemSink interface, but
  // it *should not* be exposed as part of this classes API - I'm trying to slim the terminal interface down
  private final Messages messages;

  /**
   * The locale for this terminal.  Note that while the terminal has a locale (typically read/setup from an environment
   * variable), the terminal itself does not want to deal with internationalization issues, so don't start adding i18n
   * code in here, please!
   */
  @Getter
  private final Locale locale;

  @Getter
  private InterruptHandler fallbackHandler = () -> doExit();

  /**
   * Whether to include stack traces in problems when printed
   * XXX this is currently broken, as the stack traces get filled lazily
   */
  public boolean showStackTrace = true;

  public BaseTerminal(Messages messages) {
    this(messages, messages.getDefaultLocale());
  }

  /**
   * Allows this {@link Terminal} to act as a {@link ProblemSink} - dumps any messages out to stderr along with some
   * basic formatting to make them stick out a bit
   */
  @Override
  public void log(Problem problem) {
    formatToErrorStream("[%s] %s%n", formatLevel(problem), messages.renderProblem(problem, getLocale()));
  }

  /**
   * Writes the formatted string to {@link #getErr() }. The actual write is synchronized on the terminal to
   * prevent concurrent writes.
   *
   * @param format a format string
   * @param args arguments required by format string
   */
  private void formatToErrorStream(String format, Object... args) {
    synchronized (this) {
      getErr().format(format, args);
    }
  }

  @Override
  public InterruptHandler setFallbackHandler(InterruptHandler newFallbackHandler) {
    InterruptHandler prev = this.fallbackHandler;
    this.fallbackHandler = newFallbackHandler;
    return prev;
  }

  /**
   * The default {@link #fallbackHandler} that is called when the user presses ctrl-c.
   */
  void doExit() {
    // ExitException won't work outside the main thread, so System.exit it must be
    System.exit(1);
  }

  /**
   * @return true if this terminal is connected to a TTY.
   */
  @Override
  public boolean isTTY() {
    return false;
  }

  private String formatLevel(Problem p) {
    Ansi.Style problemStyle;
    if (p.getSeverity() == Severity.INFO) {
      problemStyle = Ansi.Style.fg_green;
    } else if (p.getSeverity() == Severity.ERROR) {
      problemStyle = Ansi.Style.fg_red;
    } else if (p.getSeverity() == Severity.WARNING) {
      problemStyle = Ansi.Style.fg_yellow;
    } else {
      problemStyle = Ansi.Style.fg_blue;
    }

    return getAnsi().apply(p.getSeverity().name(), Collections.singletonList(problemStyle)).toString();
  }

  @Override
  public Ansi getAnsi() {
    return defaultAnsi;
  }

}
