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

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.junit.Test;

import nz.org.riskscape.engine.cli.BaseCliIntegrationTest2;
import nz.org.riskscape.engine.cli.CommandResult;

// this only tests that the cli is reporting objects are failed - it doesn't go as far as creating a pipeline with
// failed dependendent objects and confirming they come out - that's too many things to test here
public class GL169_ProjectErrors extends BaseCliIntegrationTest2 {

  @Test
  public void testAProjectWithVariousInitErrors() throws Exception {
    CommandResult result1 = runner.execute(defaultCommand("project.ini")
        .subcommands("--show-project-errors", "model", "list"));

    // no id - could not be registered
    assertThat(result1.stderr, hasItems(
        matchesPattern(".+Failed to create function from .+/no-id.py"),
        matchesPattern(".+function is missing ID")
    ));

    assertThat(result1.stderr, hasItems(
        matchesPattern(".+Failed to validate identified type 'empty' \\(from line 7 of /.*project.ini\\)"),
        matchesPattern(".+- requires either a type or type.<ATTR_NAME> entry\\(s\\)")
    ));

    // has in id, but failed to validate
    assertThat(result1.stderr, hasItems(
        containsString("Failed to validate function 'has-an-id'"),
        containsString("Needs either a function or FUNCTION constant")
    ));

    // trying to load a thing that doesn't exist
    assertThat(result1.stderr, hasItems(
        containsString("Problems found with INI file section"),
        // nb this isn't an ideal message, but we're phasing out importing functions via `functions  =` so never mind
        containsString("File not found at /home/riskscape/src/test/homes/GL169_ProjectErrors/does-not-exist.py")
    ));

    //
    CommandResult result2 = runner.execute(defaultCommand("project.ini")
        .subcommands("model", "list"));

    // not all things trigger warnings now, so there's less warnings than when --show-project-errors is shown
    assertThat(result2.stderr, contains(containsString("There were problems during engine initialization")));

  }

  @Test
  public void testAFailedPipeline() throws Exception {
    assertThat(
        exec("model", "run", "empty", "--graph"),
        hasErrors(
            hasItems(
                allOf(
                    containsString("model 'empty' (from line 12 of /home/riskscape"),
                    containsString("is not valid")
                )
            ))
    );
  }

  @Test
  public void testAFailedType() throws Exception {
    assertThat(
        exec("type", "info", "empty"),
        hasErrors(
            hasItems(
                allOf(
                    containsString("type 'empty' (from line 7 of /home/riskscape"),
                    containsString("is not valid")
                )
            ))
    );
  }

  @Test
  public void testAFailedBookmark() throws Exception {
    assertThat(
        exec("bookmark", "info", "empty"),
        hasErrors(hasItems(
                allOf(
                    containsString("bookmark 'empty' (from line 9 of /home/riskscape"),
                    containsString("is not valid")
                )
            ))
    );
  }

  private Matcher<CommandResult> hasErrors(Matcher<Iterable<String>> errMatcher) {

    return new TypeSafeDiagnosingMatcher<CommandResult>(CommandResult.class) {

      @Override
      public void describeTo(Description description) {
        description.appendText("Command result with errors").appendDescriptionOf(errMatcher);
      }
      @Override
      protected boolean matchesSafely(CommandResult item, Description mismatchDescription) {
        mismatchDescription.appendText("result with errors ").appendValue(item.stderr);
        return errMatcher.matches(item.stderr);
      }
    };
  }

  private CommandResult exec(String... args) {
    return runner.execute(defaultCommand("project.ini")
        .subcommands(args));
  }



}
