/*
 * 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.regex.Pattern;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Before;
import org.junit.experimental.categories.Category;

/**
 * Second attempt at a clean api for running cli tests, builder for commands plus abstracting away the
 * way the cli is actually invoked and its environment
 */
@Category(CliIntegrationTest.class)
public class BaseCliIntegrationTest2 {

  /**
   * Environment variable that decides what implementation of {@link CommandRunner} to use.
   */
  public static final String ENV_TEST_RUNNER_CLASS = "RISKSCAPE_CLI_TEST_RUNNER_CLASS";

  protected CommandRunner runner;

  /**
   * Sets up the {@link CommandRunner} that will be used for testing.
   *
   * This method is called before each test is run to setup a new runner.
   *
   * The runner created is set from {@link #getRunnerClassName() }
   *
   * @throws Exception
   */
  @Before
  public final void setupRunner() throws Exception {
    String className = getRunnerClassName();
    this.runner = (CommandRunner) Class.forName(className).newInstance();
  }

  /**
   * Get the class name of the runner that will be used for testing.
   *
   * This implementation will return:
   * - content of "RISKSCAPE_CLI_TEST_RUNNER_CLASS" environment variable if that exists
   * - else "nz.org.riskscape.engine.cli.DockerRunner"
   *
   * @return String, runner class name.
   */
  protected String getRunnerClassName() {
    return System.getenv().getOrDefault(ENV_TEST_RUNNER_CLASS, "nz.org.riskscape.engine.cli.DockerRunner");
  }

  public CommandResult execute(CommandInput input) {
    return runner.execute(input);
  }

  /**
   * @param project file, will be resolved from homeDir()
   * @return default command with project file added to options
   */
  public CommandInput defaultCommand(String project) {
    return defaultCommand().option("--project", homeDir().resolve(project));
  }

  /**
   * @return the default command for running riskscape for test purposes
   */
  public CommandInput defaultCommand() {
    return defaultCommand(homeDir());
  }

  public CommandInput defaultCommand(Path homeDirectory) {

    return CommandInput.command("riskscape")
        .option("-H", homeDirectory)
        .option("--show-stacktrace")
        .option("--pipeline-threads=1");
  }

  public CommandInput defaultCommandNoHomeDir() {
    return CommandInput.command("riskscape")
        .option("--show-stacktrace")
        .option("--pipeline-threads=1");
  }

  /**
   * @return the directory, based on the environment's source tree, that points to the riskscape home directory
   * to use for the test cases
   */
  protected Path homeDir() {
    return environment().sourceTree.resolve("src").resolve("test").resolve("homes").resolve(getClass().getSimpleName());
  }

  protected CommandEnv environment() {
    return runner.environment();
  }

  public CommandInput modelRunCommand(String template) {
    return defaultCommand().subcommands("model", "run").option(template);
  }

  protected Matcher<CommandResult> exitsWith(int exitstatus) {
    return new TypeSafeMatcher<CommandResult>(CommandResult.class) {

      @Override
      public void describeTo(Description description) {
        description.appendText("Exits with ").appendValue(exitstatus);
      }

      @Override
      protected boolean matchesSafely(CommandResult item) {
        return item.exitCode.equals(exitstatus);
      }

      @Override
      protected void describeMismatchSafely(CommandResult item, Description mismatchDescription) {
        mismatchDescription.appendText("Exited with ").appendValue(item.exitCode);
      }
    };
  }

  protected Matcher<CommandResult> hasInOutput(CommandResult.Stream stream, Matcher<String> matcher) {
    return new TypeSafeDiagnosingMatcher<CommandResult>(CommandResult.class) {



      @Override
      public void describeTo(Description description) {
        description.appendValue(stream).appendText(" includes ").appendDescriptionOf(matcher);
      }


      @Override
      protected boolean matchesSafely(CommandResult item, Description mismatchDescription) {

        for (String line : stream.get(item)) {
          if (matcher.matches(line)) {
            return true;
          }
        }

        mismatchDescription.appendValue(stream.get(item));
        return false;
      }
    };
  }

  protected Matcher<CommandResult> hasInStdout(String toMatch) {
    return hasInOutput(CommandResult.Stream.OUT, Matchers.containsString(toMatch));
  }

  protected Matcher<CommandResult> hasInStdout(Pattern toMatch) {
    return hasInOutput(CommandResult.Stream.OUT, Matchers.matchesPattern(toMatch));
  }

  protected Matcher<CommandResult> hasInStderr(String toMatch) {
    return hasInOutput(CommandResult.Stream.ERR, Matchers.containsString(toMatch));
  }

  protected Matcher<CommandResult> hasInStderr(Pattern toMatch) {
    return hasInOutput(CommandResult.Stream.ERR, Matchers.matchesPattern(toMatch));
  }

}
