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

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

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.junit.Before;
import org.junit.Test;

import com.google.common.collect.ImmutableMap;

import nz.org.riskscape.config.ConfigProblems;
import nz.org.riskscape.config.ConfigSection;
import nz.org.riskscape.engine.resource.CustomProtocolTestingResourceLoader;
import nz.org.riskscape.engine.resource.DefaultResourceFactory;
import nz.org.riskscape.engine.resource.FileResourceLoader;
import nz.org.riskscape.engine.resource.ResourceFactory;
import nz.org.riskscape.engine.resource.ResourceProblems;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ResultOrProblems;

public class Ini4jConfigTest {

  private ResourceFactory factory = new DefaultResourceFactory();
  File basedir = new File("src/test/resources/" + getClass().getPackage().getName().replace(".", "/"));
  CustomProtocolTestingResourceLoader resourceLoader;

  @Before
  public void setup() {
    resourceLoader = new CustomProtocolTestingResourceLoader("test", basedir);
    factory.add(new FileResourceLoader());
    factory.add(resourceLoader);
  }

  @Test
  public void willLoadConfigFromAUri() throws Exception {
    URI uri = URI.create("test:simple/project.ini");
    Ini4jConfig config = Ini4jConfig.load(uri, factory).get();

    // this is the global project section
    ConfigSection section = config.getSection("project").get();
    assertThat(
      section.toMap(),
      equalTo(ImmutableMap.of(
          "foo", "bar",
          // check that duplicate values are handled 'correctly'
          "duplicated", "2" // last one wins, but maybe this needs a warning?
      ))
    );

    assertThat(
      section.getOne("duplicated"),
      equalTo(Optional.of(ResultOrProblems.of(
        "2",
        ConfigProblems.get().duplicateKey(uri, "project", "duplicated")
      )))
    );


    assertThat(
      section.getOneRequired("duplicated"),
      equalTo(ResultOrProblems.of(
        "2",
        ConfigProblems.get().duplicateKey(uri, "project", "duplicated")
      ))
    );

    assertThat(
      section.toMultiMap(),
      equalTo(ImmutableMap.of(
          "foo", Arrays.asList("bar"),
          "duplicated", Arrays.asList("1", "2")
      ))
    );

    // this asserts correct multi-line behaviour
    ConfigSection pipeline = config.getSection("model pipeline").get();
    assertThat(
      pipeline.toMap(),
      equalTo(ImmutableMap.of(
          "framework", "pipeline",
          "pipeline", "this spans across lines"
      ))
    );

    // check how empty values are handled
    //  - location is given twice, one is empty
    //  - other-thing given once and is empty
    ConfigSection bookmarkCool = config.getSection("bookmark cool").get();
    assertThat(
      bookmarkCool.getOne("location"),
      equalTo(Optional.of(ResultOrProblems.of("https://google.com/my/data.zip")))
    );
    assertThat(
      bookmarkCool.getAll("location"),
      equalTo(Arrays.asList("https://google.com/my/data.zip"))
    );
    assertThat(
      bookmarkCool.getOne("other-thing"),
      equalTo(Optional.empty())
    );
    assertThat(
      bookmarkCool.getAll("other-thing"),
      equalTo(Arrays.asList())
    );
    assertThat(
      bookmarkCool.toMultiMap(),
      equalTo(ImmutableMap.of(
        "location", Arrays.asList("https://google.com/my/data.zip"),
        "other-thing", Arrays.asList() // this is a bit weird, not sure it matters too much - maybe it's good cos it
        // shows the keys presence?
      ))
    );

    // check all sections are present and correct
    assertThat(
      config.getAll().stream().map(cs -> cs.getName()).collect(Collectors.toList()),
      // would be nice if order was respected. but the ini library is too mappy
      containsInAnyOrder("project", "bookmark cool", "bookmark story", "model pipeline", "model test", "random")
    );
  }

  @Test
  public void willLoadConfigAndLoadRelativeImportsFromAUri() throws Exception {
    Ini4jConfig config = Ini4jConfig.load(URI.create("test:/imports/project.ini"), factory).get();

    assertThat(
      config.getAll().stream().map(cs -> cs.getName()).collect(Collectors.toList()),
      // would be nice if order was respected. but the ini library is too mappy
      containsInAnyOrder(
        "project",
        "model foo_model",
        // types.ini
        "type this type",
        "type that type",
        // types_foo.ini
        "type foo",
        "type foo no prefix",
        // types_bar.ini
        "type bar",
        "type typebar", // check that the implicit name is handled correct with id starts with it
        "type bookmark bar bookmark", // note that this is weird - we might want a warning here
        // randomly_named
        "bookmark randomly_named_without_a_prefix",
        "bookmark randomly_named_with_a_prefix",
        "bookmark model randomly named model", // same here - trying to add a resource of different type
        "bookmark prefix is not a recognized one so will be part of the name",
        // other_project.ini
        "model bar_model",
        "unrecognized prefix"
      )
    );

    // assert not included for clarity
    assertTrue(!config.getSection("model will not be loaded").isPresent());

    // check that sections retain a link to where they came from
    assertThat(config.getSection("model foo_model").get().getLocation(),
        equalTo(URI.create("test:/imports/project.ini")));

    assertThat(config.getSection("bookmark randomly_named_without_a_prefix").get().getLocation(),
        equalTo(URI.create("test:/imports/bookmarks/randomly_named.ini")));
  }

  @Test
  public void willLoadConfigAndLoadAbsoluteImportsFromAUri() throws Exception {
    Ini4jConfig config = Ini4jConfig.load(URI.create("test:/imports/project_absolutes.ini"), factory).get();

    assertThat(
      config.getAll().stream().map(cs -> cs.getName()).collect(Collectors.toList()),
      // would be nice if order was respected. but the ini library is too mappy
      containsInAnyOrder(
        "project",
        "model foo_model",
        // types.ini
        "type this type",
        "type that type",
        // types_foo.ini
        "type foo",
        "type foo no prefix",
        // types_bar.ini
        "type bar",
        "type typebar", // check that the implicit name is handled correct with id starts with it
        "type bookmark bar bookmark", // note that this is weird - we might want a warning here
        // randomly_named
        "bookmark randomly_named_without_a_prefix",
        "bookmark randomly_named_with_a_prefix",
        "bookmark model randomly named model", // same here - trying to add a resource of different type
        "bookmark prefix is not a recognized one so will be part of the name",
        // other_project.ini
        "model bar_model",
        "unrecognized prefix"
      )
    );
    // check that sections retain a link to where they came from
    assertThat(config.getSection("model foo_model").get().getLocation(),
        equalTo(URI.create("test:/imports/project_absolutes.ini")));

    assertThat(config.getSection("bookmark randomly_named_without_a_prefix").get().getLocation(),
        equalTo(URI.create("test:/imports/bookmarks/randomly_named.ini")));
  }

  @Test
  public void willLoadFirstProjectSectionAndWarnOnDuplicates() throws Exception {
    List<Problem> collected = new LinkedList<>();
    URI uri = URI.create("test:/dupe_project/project.ini");
    Ini4jConfig config = Ini4jConfig.load(uri, factory)
        .drainWarnings(p -> collected.add(p))
        .get();

    assertThat(
      config.getAll().stream().map(cs -> cs.getName()).collect(Collectors.toList()),
      containsInAnyOrder(
        "project",
        "type foo"
      )
    );

    assertThat(
      collected,
      // TODO eventually we can add line numbers to locations, but that needs a new ini parser that preserves the text
      // file behind the scenes
      hasItem(ConfigProblems.get().duplicateSection("project", uri, uri))
    );
  }

  @Test
  public void willSucceedWithAWarningIfAnImportFailsToLoad() throws Exception {

  }

  @Test
  public void willFailIfConfigUriDoesNotExist() throws Exception {
    URI uri = URI.create("test:/missing/project.ini");
    assertThat(
      Ini4jConfig.load(uri, factory).getProblems(),
      contains(
        ResourceProblems.get().notFound(uri)
      )
    );
  }

  @Test
  public void ifAFileThenWillAutoImportSurroundingIniFilesMatchingWellKnownPrefixes() throws Exception {
    URI uri = basedir.toURI().resolve("imports/no_imports.ini");
    Ini4jConfig config = Ini4jConfig.load(uri, factory).get();

    assertThat(
      config.getAll().stream().map(cs -> cs.getName()).collect(Collectors.toList()),
      // would be nice if order was respected. but the ini library is too mappy
      containsInAnyOrder(
        "project",
        "bookmark in_project",
        // types.ini
        "type this type",
        "type that type",
        // types_foo.ini
        "type foo",
        "type foo no prefix",
        // types_bar.ini
        "type bar",
        "type typebar", // check that the implicit name is handled correct with id starts with it
        "type bookmark bar bookmark", // note that this is weird - we might want a warning here
        // models.ini - actually gets loaded - auto import picks it up
        "model will not be loaded", //
        "model does not have a prefix"
      )
    );

    // sample a few sections and check where they came from
    assertThat(
      config.getSection("type this type").get().getLocation(),
      equalTo(uri.resolve("types.ini"))
    );

    // sample a few sections and check where they came from
    assertThat(
      config.getSection("model will not be loaded").get().getLocation(),
      equalTo(uri.resolve("models.ini"))
    );
  }

  @Test
  public void autoimportCanBeDisabled() throws Exception {
    URI uri = basedir.toURI().resolve("imports/auto_import_off.ini");
    Ini4jConfig config = Ini4jConfig.load(uri, factory).get();

    assertThat(
      config.getAll().stream().map(cs -> cs.getName()).collect(Collectors.toList()),
      // would be nice if order was respected. but the ini library is too mappy
      containsInAnyOrder(
        "project",
        "type not-from-auto-import",
        // types.ini
        "type this type",
        "type that type"
      )
    );

    assertThat(
      config.getSection("type this type").get().getLocation(),
      equalTo(uri.resolve("types.ini"))
    );
  }

  @Test
  public void duplicateSectionsGiveWarnings() throws Exception {
    URI uri = URI.create("test:/dupe_sections/project.ini");
    ResultOrProblems<Ini4jConfig> configOr =
        Ini4jConfig.load(uri, factory);

    // dupes within the same file
    List<Problem> collected = new LinkedList<>();
    Ini4jConfig config = configOr.drainWarnings(p -> collected.add(p)).get();

    // first one wins
    assertThat(
      config.getSection("type foo").get().toMap(),
      equalTo(ImmutableMap.of("from", "project.ini"))
    );

    assertThat(
      collected,
      // TODO eventually we can add line numbers to locations, but that needs a new ini parser that preserves the text
      // file behind the scenes
      hasItem(ConfigProblems.get().duplicateSection("type foo", uri, uri))
    );

    // dupe between project and imported thing

    // first one wins
    assertThat(
      config.getSection("model foo").get().toMap(),
      equalTo(ImmutableMap.of("from", "project.ini"))
    );
    assertThat(
      config.getSection("model bar").get().toMap(),
      equalTo(ImmutableMap.of("from", "project.ini"))
    );

    assertThat(
      collected,
      hasItems(
          // foo is missing prefix in the second file, bar isn't
        ConfigProblems.get().duplicateSection("model foo", uri, uri.resolve("models.ini")),
        ConfigProblems.get().duplicateSection("model bar", uri, uri.resolve("models.ini"))
      )
    );

    // dupe between imports
    assertThat(
      config.getSection("bookmark foo").get().toMap(),
      equalTo(ImmutableMap.of("from", "bookmarks1"))
    );
    assertThat(
      collected,
      hasItem(
          // foo is missing prefix in the second file, bar isn't
        ConfigProblems.get().duplicateSection(
          "bookmark foo",
          uri.resolve("bookmarks1.ini"),
          uri.resolve("bookmarks2.ini")
        )
      )
    );

    // project section is special, don't warn because of it
    assertThat(
      configOr.getProblems(),
      not(hasItem(
        ConfigProblems.get().duplicateSection(
          "project",
          uri,
          uri.resolve("other_import.ini")
        )
      ))
    );
  }

  @Test
  public void testKeysAndValuesComeOutInTheOrderTheyWereDefined() throws Exception {
    Ini4jConfig config = Ini4jConfig.load(URI.create("test:/simple/ordering.ini"), factory).get();

    ConfigSection section = config.getSection("foo").get();
    Map<String,List<String>> multiMap = section.toMultiMap();

    //  add it in to an array in iteration order, check it was as defined
    List<String> keys = new ArrayList<>(multiMap.keySet());
    assertThat(keys, contains("doh", "ray", "me", "fah", "soh"));
  }
}
