/*
 * 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 nz.org.riskscape.engine.Assert.*;
import static nz.org.riskscape.engine.Matchers.*;
import static nz.org.riskscape.engine.cli.tests.TableMatchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.junit.Test;

import nz.org.riskscape.engine.Assert;
import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.cli.BookmarksCommand;
import nz.org.riskscape.engine.cli.ExitException;
import nz.org.riskscape.engine.cli.FunctionCommand.FunctionListCommand;
import nz.org.riskscape.engine.cli.PipelineCommand;
import nz.org.riskscape.engine.cli.Table;
import nz.org.riskscape.engine.cli.TypesCommand;
import nz.org.riskscape.engine.cli.TypesCommand.InfoCommand;
import nz.org.riskscape.engine.cli.model.ListCommand;
import nz.org.riskscape.engine.cli.model.RunCommand;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.test.EngineCommandIntegrationTest;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.engine.util.Pair;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.StandardCodes;

/**
 * Tests that the CLI handles the various good and bad cases of errors from projects, without getting stuck in to the
 * minutae of what makes a resource valid or otherwise (cover that off in unit tests)
 *
 * This test is trying a different approach - it builds the required pieces for testing 'in-process', which means
 * (in some cases) easier assertions and faster test times.  Next time I will try moving the static bits here in to a
 * special test runner that constructs the engine and plugins once for the entire test suite.
 */
@SuppressWarnings("unchecked")
public class ProjectErrorsAndValidationTest extends EngineCommandIntegrationTest {

  protected Path projectFiles() {
    return Paths.get(".", "src", "test", "homes", "project-errors-and-validation");
  }

  @Test
  public void testAValidProject() throws Exception {

    populateProject(projectFiles().resolve("everything-valid.ini"));
    // no other info should be logged
    assertThat(this.errBytes.toString(), equalTo(""));
    assertThat(this.outBytes.toString(), equalTo(""));

    Table bookmarks = (Table) setupCommand(new BookmarksCommand.BookmarkListCommand()).run();
    assertThat(
        bookmarks,
        hasRow(
            Pair.of("id", "good"),
            Pair.of("description", equalTo("nothing to see here")),
            Pair.of("location", containsString("file:/"))
        )
    );

    Table functions = (Table) setupCommand(new FunctionListCommand()).run();
    assertThat(
        functions,
        hasRow(
            Pair.of("id", "jython-good"),
            Pair.of("description", equalTo("no trouble"))
        )
    );

    Table types = (Table) setupCommand(new TypesCommand.ListCommand()).run();
    assertThat(
        types,
        allOf(
          hasRow(
              Pair.of("id", "good"),
              Pair.of("description", equalTo("{foo=>Text}"))
          )
        )
    );

    Table models = (Table) setupCommand(new ListCommand()).run();
    assertThat(
        models,
        hasRow(
            Pair.of("id", "good"),
            Pair.of("framework", containsString("pipeline"))
        )
    );

  }

  @Test
  public void duplicateIdsLogAWarning() throws Exception {
    List<Problem> problems = populateProject(projectFiles().resolve("duplicate-id.ini")).getProblems();

    Table bookmarks = (Table) setupCommand(new BookmarksCommand.BookmarkListCommand()).run();
    assertThat(
        bookmarks,
        hasRow(
            Pair.of("id", "foo"),
            Pair.of("description", containsString("first one"))
        )
    );

    assertThat(problems, hasSize(1));
    assertThat(render(problems.get(0)), allOf(
        // Not asserting the whole message here as the path is very environment specific, but doing enough to catch
        // that the line number is included
        containsString("Section 'bookmark foo' was already defined at line 4 of "),
        containsString("ignoring the duplicate definition from line 8 of "))
    );
  }

  @Test
  public void aProjectWithABunchOfErrorsIncludesSomeErrorsInTableOutput() throws Exception {

    cliRoot.setShowProjectErrors(true);
    List<Problem> problems = populateProject(projectFiles().resolve("range-of-broken-things.ini")).getProblems();
    // no other info should be logged

    String populationMessages =
      problems.stream().map(p -> render(p)).collect(Collectors.joining("\n"));

    assertThat(populationMessages, allOf(
        matchesPattern(Pattern.compile(
            ".*Failed to create function from /.*jython-no-id.py.*"
            + "Could not create Jython function.*"
            + "function is missing ID.*", Pattern.DOTALL))
    ));

    assertThat(populationMessages, allOf(
        matchesPattern(Pattern.compile(
            ".*Failed to create function from /.*jython-syntax-error.py.*"
            + "Could not create Jython function.*"
            + "SyntaxError: no viable alternative.*", Pattern.DOTALL))
    ));

    assertThat(populationMessages, allOf(
        matchesPattern(Pattern.compile(
            ".*Failed to validate function 'jython-missing-args' \\(from .*jython-missing-args.py\\).*"
            + "Could not create Jython function.*"
            + "function is missing ARGUMENT_TYPES.*", Pattern.DOTALL
            ))
    ));

    assertThat(populationMessages, allOf(
        matchesPattern(Pattern.compile(
            ".*project-errors-and-validation/missing-file.csv' does not exist.*", Pattern.DOTALL
            ))
    ));

    Table models = (Table) setupCommand(new ListCommand()).run();
    assertThat(
        models,
        allOf(
            hasRow(
                Pair.of("id", "bad"),
                Pair.of("details", containsString("Got '>', wanted one of ["))
            ),
            hasRow(
                Pair.of("id", "remote-missing"),
                Pair.of("details",
                    containsString("File not found at https://platform-test.ci.rsdev.nz/missing.txt"))
            )
        )
    );

    Table bookmarks = (Table) setupCommand(new BookmarksCommand.BookmarkListCommand()).run();
    assertThat(
        bookmarks,
        hasRow(
            Pair.of("id", "bad"),
            Pair.of("description", containsString("'location' parameter is required"))
        )
    );

    Table functions = (Table) setupCommand(new FunctionListCommand()).run();
    assertThat(
        functions,
        allOf(
          not(hasRow(Pair.of("id", "jython-syntax-error"))),
          hasRow(
              Pair.of("id", "jython-missing-args"),
              Pair.of("description", containsString("function is missing ARGUMENT_TYPES"))
          ),
          hasRow(
              Pair.of("id", "bad-unknown-remote-location"),
              Pair.of("description",
                  containsString("File not found at https://platform-test.ci.rsdev.nz/missing-file.py"))
          )
        )
    );

    // start a-fresh
    errBytes.reset();
    Table types = (Table) setupCommand(new TypesCommand.ListCommand()).run();
    assertThat(
        types,
        allOf(
          hasRow(
              Pair.of("id", "bad"),
              Pair.of("description", containsString("No simple type named 'tox'")))
          )
    );

    // and again
    errBytes.reset();

  }

  @Test
  public void aProjectWithABunchOfErrorsPointsToThemOnStderr() throws Exception {

    cliRoot.setShowProjectErrors(false);
    populateProject(projectFiles().resolve("range-of-broken-things.ini"));

    // we used to validate everything on start up, not so any more - only on --show-project-errors
    assertThat(
        this.errBytes.toString(),
        not(containsString("There were 5 problem"))
    );

    RunCommand graph = new RunCommand();
    graph.modelId = "bad";
    graph.graphPipeline = true;
    ExitException e = Assert.assertThrows(ExitException.class, () -> setupCommand(graph).run());
    assertThat(e.getProblem(), Matchers.isError(GeneralProblems.class, "failedResourceLookedUp"));

    InfoCommand infoCommand = new TypesCommand.InfoCommand();
    infoCommand.id = "bad";
    e = Assert.assertThrows(ExitException.class, () -> setupCommand(infoCommand).run());
    assertThat(e.getProblem(), Matchers.isError(GeneralProblems.class, "failedResourceLookedUp"));

    Table models = (Table) setupCommand(new ListCommand()).run();
    assertThat(
        models,
        hasRow(
            Pair.of("id", "bad"),
            Pair.of("details", containsString("Got '>', wanted one of ["))
        )
    );

    BookmarksCommand.Info bookmarkCommand = new BookmarksCommand.Info();
    bookmarkCommand.bookmarkId = "bad";
    e = Assert.assertThrows(ExitException.class, () -> setupCommand(bookmarkCommand).run());
    assertThat(e.getProblem(), Matchers.isError(GeneralProblems.class, "failedResourceLookedUp"));
  }

  @Test
  public void problemExceptionInPipelineBubblesUpIntoExitException() {
    // our test is tring to save a relation with no geometry to a shapefile which causes a problem exception.
    // That problem should bubble up into the exist exception.

    populateProject(projectFiles().resolve("everything-valid.ini"));

    PipelineCommand.Eval command = setupCommand(new PipelineCommand.Eval());
    command.runnerOptions.format = "shapefile";
    command.runnerOptions.output = getTempDirectory().toString();
    command.pipelineFile = "input(relation: 'good')";

    ExitException error = assertThrows(ExitException.class, () -> command.run());

    assertThat(error.getProblem(), hasAncestorProblem(
        is(Problem.error(StandardCodes.GEOMETRY_REQUIRED, Struct.of("no", Types.TEXT)))
    ));
  }

}
