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

import static nz.org.riskscape.engine.Assert.*;
import static nz.org.riskscape.engine.data.BaseBookmarkResolver.*;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.hamcrest.MatcherAssert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import com.google.common.collect.ImmutableMap;

import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.RiskscapeIOException;
import nz.org.riskscape.engine.TemporaryDirectoryTestHelper;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.bind.ParamProblems;
import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.engine.bind.ParameterField;
import nz.org.riskscape.engine.pipeline.ExecutionContext;
import nz.org.riskscape.engine.resource.Resource;
import nz.org.riskscape.engine.resource.ResourceProblems;
import nz.org.riskscape.engine.resource.StreamResource;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ResultOrProblems;

public class BaseBookmarkResolverTest implements TemporaryDirectoryTestHelper {

  public static class Params extends BookmarkParameters {

    @ParameterField
    public Optional<String> important = Optional.empty();

    @Override
    public Class<?> getDataType() {
      return Object.class;
    }
  }

  Object data = "foo";

  class Subject extends BaseBookmarkResolver<Params> {

    public Map<String, String> extensions = ImmutableMap.of("ext", "format");

    Subject(Engine engine) {
      super(engine);
    }

    @Override
    protected Map<String, String> getExtensionsToFormats() {
      return extensions;
    }

    @Override
    protected ResultOrProblems<Object> build(Params memo) {
      buildParams = memo;
      return ResultOrProblems.of(data);
    }
  }


  ExecutionContext executionContext = Mockito.mock(ExecutionContext.class);
  BindingContext bindingContext = Mockito.mock(BindingContext.class);
  Engine engine = Mockito.mock(Engine.class);
  Subject subject;
  Bookmark bookmark;
  Params buildParams;
  Path tempDir;

  @Before
  public void init() throws Exception {
//    project.setRelativeTo(new File(".").toURI());
    Mockito.when(executionContext.getBindingContext()).thenReturn(bindingContext);
    subject = new Subject(engine);
    when(bindingContext.bind(any(), any(Parameter.class))).thenAnswer(a -> ResultOrProblems.of(a.getArgument(0)));
    tempDir = createTempDirectory(BaseBookmarkResolverTest.class.getName());
    when(executionContext.getTempDirectory()).thenReturn(tempDir);
  }

  @After
  public void cleanup() throws Exception {
    remove(tempDir);
  }

  @Test
  public void bookmarkNotClaimedIfExtensionMatchesFilenameEndingWithoutDot() throws Exception {
    bookmark("foo://bar/bazext", null);
    assertFalse(subject.resolve(bookmark, executionContext).isPresent());
  }

  @Test
  public void bookmarkNotClaimedIfNotAKnownFormatOrExtension() throws Exception {
    bookmark("foo://bar/baz", "unknown");
    assertFalse(subject.resolve(bookmark, executionContext).isPresent());
  }

  @Test
  public void bookmarkNotClaimedIfExtensionMatchesButFormatDoesNot() throws Exception {
    bookmark("foo://bar/baz.ext", "formoat");
    assertFalse(subject.resolve(bookmark, executionContext).isPresent());
  }

  @Test
  public void bookmarkClaimedIfExtensionMatchesWhenNoFormat() throws Exception {
    bookmark("foo://bar/baz.ext", null);
    assertTrue(subject.resolve(bookmark, executionContext).isPresent());
  }

  @Test
  public void bookmarkClaimedIfFormatMatches() throws Exception {
    bookmark("foo://bar/baz", "format");
    assertTrue(subject.resolve(bookmark, executionContext).isPresent());
  }

  @Test
  public void scalarTypeCanComeFromSelfDescribingData() throws Exception {
    data = new SelfDescribingScalarData() {

      @Override
      public Type getScalarDataType() {
        return Struct.of("foo", Types.TEXT);
      }
    };

    bookmark("foo://bar/baz", "format");
    assertEquals(Struct.of("foo", Types.TEXT), subject.resolve(bookmark, executionContext).get().getScalarType());
  }

  @Test
  public void scalarTypeFallsBackToComingFromJavaType() throws Exception {
    data = 1L;
    bookmark("foo://bar/baz", "format");
    assertEquals(Types.INTEGER, subject.resolve(bookmark, executionContext).get().getScalarType());
  }

  @Test
  public void simpleResourcesAreSavedLocally() throws Exception {
    URI target = new URI("test://resource/file.txt");
    Resource test = createResourceSupportingEnsureLocal(target, testResource("test.txt"));
    Path local = resourceToPath(test, executionContext);

    assertThat(local.getFileName().toString(), equalTo("file.txt"));
  }

  @Test
  public void savingLocallyRequiresResourceSupport() throws Exception {
    URI target = new URI("test://resource/file.txt");
    Resource test = new StreamResource(target, testResource("test.txt")) {
      @Override
      public ResultOrProblems<Path> ensureLocal(Resource.Options options) {
        return ResultOrProblems.failed(ResourceProblems.get().ensureLocalNotSupported(getLocation()));
      }
    };

    // resourceToPath only supports resources that support ensureLocal.
    RiskscapeIOException ex = assertThrows(RiskscapeIOException.class, () -> resourceToPath(test, executionContext));
    assertThat(ex.getProblem(), is(ResourceProblems.get().ensureLocalNotSupported(target)));
  }

  @Test
  public void zipResourcesAreSavedAndExtracted() throws Exception {
    URI target = new URI("test://resource/test.txt.zip");
    Resource test = createResourceSupportingEnsureLocal(target, testResource("test.txt.zip"));

    Path local = resourceToPath(test, executionContext);
    assertThat(local.getFileName().toString(), equalTo("test.txt"));
    //Ensure the sidecar file is present
    Path sidecar = local.resolveSibling("test.sidecar");
    assertThat(sidecar.toFile().exists(), is(true));
  }

  @Test
  public void resourcesWillBeGivenLocalNameBasedOnURI() throws Exception {
    MatcherAssert.assertThat(localFilename(new URI("test://auth/path/to/file.txt")), is("file.txt"));
    MatcherAssert.assertThat(localFilename(new URI("test://auth/path/to/")), is("resource"));
    MatcherAssert.assertThat(localFilename(new URI("test://auth/file")), is("file"));
    MatcherAssert.assertThat(localFilename(new URI("test://auth/path/to/file.txt.zip")), is("file.txt.zip"));
  }

  @Test
  public void resolvedBookmarkToStringIsUseful() throws Exception {
    bookmark = Bookmark.builder().id("foo").format("cool-format").location(URI.create("http://google.com")).build();
    Params params = new Params();
    params.bookmark = bookmark;
    ResolvedBookmarkImpl<?> resolved = new ResolvedBookmarkImpl<>(subject, params);
    assertThat(resolved.toString(), containsString("foo(format=cool-format, location=http://google.com)"));
  }

  @Test
  public void canConvertAMapWithPrefixedKeysInToAMapOfMaps() throws Exception {
    Map<String, List<?>> sourceMap = new HashMap<>();

    // goes unmolested without dots
    sourceMap.put("simple-foo", Arrays.asList("easy-bar"));
    assertThat(
      subject.findMapishOptions(sourceMap, null),
      equalTo(ImmutableMap.of("simple-foo", Arrays.asList("easy-bar")))
    );

    // single entry
    sourceMap.put("foo.bar", Arrays.asList("baz"));
    assertThat(
      subject.findMapishOptions(sourceMap, null),
      hasEntry(equalTo("foo"), contains(Matchers.instanceOfAnd(Map.class, hasEntry(equalTo("bar"), equalTo("baz")))))
    );

    // add a second entry, check it comes out
    sourceMap.put("foo.baz", Arrays.asList("bar"));
    assertThat(
      subject.findMapishOptions(sourceMap, null),
      equalTo(ImmutableMap.of(
        "simple-foo", Arrays.asList("easy-bar"),
        "foo",
        Arrays.asList(ImmutableMap.of("bar", "baz", "baz", "bar"))
      ))
    );

    // duplicates takes the last value
    sourceMap.put("foo.baz", Arrays.asList("bar", "baz"));
    List<Problem> problems = new ArrayList<>();
    assertThat(
      subject.findMapishOptions(sourceMap, problems),
      equalTo(ImmutableMap.of(
        "simple-foo", Arrays.asList("easy-bar"),
        "foo",
        Arrays.asList(ImmutableMap.of("bar", "baz", "baz", "baz"))
      ))
    );
    assertThat(problems, contains(ParamProblems.get().wrongNumberGiven("foo.baz", "1", 2)));
  }

  private Resource createResourceSupportingEnsureLocal(URI target, InputStream is) {
    return new StreamResource(target, is);
  }

  private InputStream testResource(String string) {
    return BaseBookmarkResolverTest.class.getResourceAsStream("/nz/org/riskscape/engine/data/" + string);
  }

  private void bookmark(String uriString, String format) {
    try {
      this.bookmark = new Bookmark("id", "desc", format, new URI(uriString), Collections.emptyMap());
    } catch (URISyntaxException e) {
      fail(e.getMessage());
    }
  }

}
