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

import static nz.org.riskscape.engine.Matchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import java.net.URI;
import java.util.List;
import java.util.Optional;

import org.geotools.geometry.jts.ReferencedEnvelope;
import org.junit.Before;
import org.junit.Test;
import org.locationtech.jts.geom.Envelope;

import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.coverage.TypedCoverage;
import nz.org.riskscape.engine.data.Bookmark;
import nz.org.riskscape.engine.data.ResolvedBookmark;
import nz.org.riskscape.engine.gt.GeometryHelper;
import nz.org.riskscape.engine.resource.ByteArrayCreateHandle;
import nz.org.riskscape.engine.types.CoverageType;
import nz.org.riskscape.engine.types.TypeProblems;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problem.Severity;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

public class MosaicCoverageResolverTest extends ProjectTest {

  // see MosaicCoverageTest for details on how the mosaic itself works, this test focuses on the construction of the
  // mosaic

  TypedCoverage mockGridCoverage1 = mock(TypedCoverage.class);
  TypedCoverage mockGridCoverage2 = mock(TypedCoverage.class);

  GeometryHelper helper = GeometryHelper.nzTransverseMercator(project.getSridSet());

  @Before
  public void setup() {
    engine.getResourceFactory().add(new DataURILoader(engine));

    when(mockGridCoverage1.getScalarDataType()).thenReturn(new CoverageType(Types.FLOATING));
    when(mockGridCoverage1.getEnvelope()).thenReturn(Optional.of(new ReferencedEnvelope(
        0, 10, 0, 10, helper.getCRS()
    )));
    when(mockGridCoverage1.getCoordinateReferenceSystem()).thenReturn(helper.getCrs());
    addPickledData("fake://coverage1", mockGridCoverage1);

    when(mockGridCoverage2.getScalarDataType()).thenReturn(new CoverageType(Types.FLOATING));
    when(mockGridCoverage2.getEnvelope()).thenReturn(Optional.of(new ReferencedEnvelope(
        10, 20, 10, 20, helper.getCRS()
    )));
    when(mockGridCoverage2.getCoordinateReferenceSystem()).thenReturn(helper.getCrs());
    addPickledData("fake://coverage2", mockGridCoverage2);
  }

  @Test
  public void canBuildAMosaicFromASingleCoverage() {
    addPickledData("fake://coverage1", mockGridCoverage1);

    URI mosaicUri = ByteArrayCreateHandle.encodeData("fake://coverage1", "text/plain");

    ResolvedBookmark resolvedBookmark = new MosaicCoverageResolver(engine)
        .resolve(Bookmark.fromURI(mosaicUri).withFormat("mosaic"), executionContext)
        .get();

    TypedCoverage mosaic = resolvedBookmark.getData(TypedCoverage.class).get();

    assertThat(mosaic, instanceOf(MosaicCoverage.class));

    assertThat(mosaic.getCoordinateReferenceSystem(), is(helper.getCRS()));
    assertThat(mosaic.getEnvelope(), is(mockGridCoverage1.getEnvelope()));

    // confirm that sampling the mosaic samples the intersecting child
    mosaic.evaluate(helper.point(0, 0));
    verify(mockGridCoverage1).evaluate(helper.point(0, 0));
  }

  @Test
  public void canBuildAMosaicFromACoupleOfCoverages() {

    URI mosaicUri = ByteArrayCreateHandle.encodeData("""
        fake://coverage1
        fake://coverage2
        """, "text/plain");

    ResolvedBookmark resolvedBookmark = new MosaicCoverageResolver(engine)
        .resolve(Bookmark.fromURI(mosaicUri).withFormat("mosaic"), executionContext)
        .get();

    TypedCoverage mosaic = resolvedBookmark.getData(TypedCoverage.class).get();

    assertThat(mosaic, instanceOf(MosaicCoverage.class));

    Envelope expected = new ReferencedEnvelope(helper.getCRS());
    expected.expandToInclude(mockGridCoverage1.getEnvelope().get());
    expected.expandToInclude(mockGridCoverage2.getEnvelope().get());

    assertThat(mosaic.getCoordinateReferenceSystem(), is(helper.getCRS()));
    assertThat(mosaic.getEnvelope().get(), is(expected));

    // confirm that sampling the mosaic samples *only* the intersecting children
    mosaic.evaluate(helper.point(0, 0));
    mosaic.evaluate(helper.point(11, 11));
    verify(mockGridCoverage1).evaluate(helper.point(0, 0));
    verify(mockGridCoverage2).evaluate(helper.point(11, 11));
  }

  @Test
  public void mosaicFileCanHaveEmptyLinesAndOtherWhitespace() {

    URI mosaicUri = ByteArrayCreateHandle.encodeData("""

        fake://coverage1


            fake://coverage2

        """, "text/plain");

    ResolvedBookmark resolvedBookmark = new MosaicCoverageResolver(engine)
        .resolve(Bookmark.fromURI(mosaicUri).withFormat("mosaic"), executionContext)
        .get();

    TypedCoverage mosaic = resolvedBookmark.getData(TypedCoverage.class).get();
    Envelope expected = new ReferencedEnvelope(helper.getCRS());
    expected.expandToInclude(mockGridCoverage1.getEnvelope().get());
    expected.expandToInclude(mockGridCoverage2.getEnvelope().get());

    // this is enough to confirm the two were included
    assertThat(mosaic.getEnvelope().get(), is(expected));
  }

  @Test
  public void childrenMustDefineAnEnvelope() throws Exception {
    TypedCoverage mockCoverageNoEnvelope = mock(TypedCoverage.class);
    when(mockCoverageNoEnvelope.getScalarDataType()).thenReturn(new CoverageType(Types.FLOATING));
    when(mockCoverageNoEnvelope.getEnvelope()).thenReturn(Optional.empty());
    addPickledData("fake://coverage-no-envelope", mockCoverageNoEnvelope);

    URI mosaicUri = ByteArrayCreateHandle.encodeData("fake://coverage-no-envelope", "text/plain");

    ResolvedBookmark resolvedBookmark = new MosaicCoverageResolver(engine)
        .resolve(Bookmark.fromURI(mosaicUri).withFormat("mosaic"), executionContext)
        .get();

    ResultOrProblems<TypedCoverage> result = resolvedBookmark.getData(TypedCoverage.class);

    assertThat(result.getProblems(), contains(
        hasAncestorProblem(isProblem(Severity.ERROR, MosaicCoverageResolver.LocalProblems.class, "boundsRequired"))
    ));
  }

  @Test
  public void childrenMustAllBeOfTheSameType() throws Exception {
    TypedCoverage mockIntegerCoverage = mock(TypedCoverage.class);
    when(mockIntegerCoverage.getScalarDataType()).thenReturn(new CoverageType(Types.INTEGER));
    when(mockIntegerCoverage.getEnvelope()).thenReturn(Optional.of(new ReferencedEnvelope(
        20, 30, 20, 30, helper.getCRS()
    )));
    addPickledData("fake://coverage-integer", mockIntegerCoverage);

    URI mosaicUri = ByteArrayCreateHandle.encodeData("""
        fake://coverage1
        fake://coverage-integer
        """, "text/plain");

    ResolvedBookmark resolvedBookmark = new MosaicCoverageResolver(engine)
        .resolve(Bookmark.fromURI(mosaicUri).withFormat("mosaic"), executionContext)
        .get();

    ResultOrProblems<TypedCoverage> result = resolvedBookmark.getData(TypedCoverage.class);
    assertTrue(result.hasErrors());

    assertThat(result.getProblems(), contains(
        hasAncestorProblem(is(
            TypeProblems.get().mismatch(URI.create("fake://coverage-integer"),
                new CoverageType(Types.FLOATING), new CoverageType(Types.INTEGER))
        ))
    ));
  }

  @Test
  public void childrenMustAllHaveTheSameCRS() throws Exception {
    when(mockGridCoverage2.getCoordinateReferenceSystem()).thenReturn(SRIDSet.EPSG4326_LATLON);
    when(mockGridCoverage2.getEnvelope()).thenReturn(Optional.of(new ReferencedEnvelope(
        20, 30, 20, 30, SRIDSet.EPSG4326_LATLON
    )));
    URI mosaicUri = ByteArrayCreateHandle.encodeData("""
        fake://coverage1
        fake://coverage2
        """, "text/plain");

    ResolvedBookmark resolvedBookmark = new MosaicCoverageResolver(engine)
        .resolve(Bookmark.fromURI(mosaicUri).withFormat("mosaic"), executionContext)
        .get();

    ResultOrProblems<TypedCoverage> result = resolvedBookmark.getData(TypedCoverage.class);
    assertTrue(result.hasErrors());

    assertThat(result.getProblems(), contains(
        hasAncestorProblem(
            MosaicCoverageResolver.PROBLEMS.crsMismatch(
                URI.create("fake://coverage2"), helper.getCrs(), SRIDSet.EPSG4326_LATLON)
        )
    ));
  }

  @Test
  public void missingChildBookmarkGivesAnError() throws Exception {
    URI mosaicUri = ByteArrayCreateHandle.encodeData("""
        fake://coverage1
        fake://non-existent-coverage
        """, "text/plain");

    ResolvedBookmark resolvedBookmark = new MosaicCoverageResolver(engine)
        .resolve(Bookmark.fromURI(mosaicUri).withFormat("mosaic"), executionContext)
        .get();

    ResultOrProblems<TypedCoverage> result = resolvedBookmark.getData(TypedCoverage.class);

    assertThat(result.isPresent(), is(false));
    assertThat(result.getProblems(), contains(hasAncestorProblem(equalIgnoringChildren(
        Problems.foundWith(URI.create("fake://non-existent-coverage"), sunkProblems)))));
  }

  @Test
  public void emptyMosaicGivesAnError() throws Exception {
    URI mosaicUri = ByteArrayCreateHandle.encodeData("", "text/plain");

    ResolvedBookmark resolvedBookmark = new MosaicCoverageResolver(engine)
        .resolve(Bookmark.fromURI(mosaicUri).withFormat("mosaic"), executionContext)
        .get();

    assertThat(resolvedBookmark.getData(TypedCoverage.class), failedResult(
        hasAncestorProblem(equalIgnoringChildren(
            MosaicCoverageResolver.PROBLEMS.emptyMosaic(mosaicUri)
        ))
    ));
  }

  @Test
  public void badChildBookmarkGivesAnError() throws Exception {
    URI mosaicUri = ByteArrayCreateHandle.encodeData("""
        fake://coverage1
        fake://broken-coverage
        """, "text/plain");

    URI brokenUri = URI.create("fake://broken-coverage");

    addPickledBookmark(ResolvedBookmark.stub(Bookmark.fromURI(brokenUri), mockGridCoverage2,
        List.of(Problems.foundWith("the data")), List.of()));

    ResolvedBookmark resolvedBookmark = new MosaicCoverageResolver(engine)
        .resolve(Bookmark.fromURI(mosaicUri).withFormat("mosaic"), executionContext)
        .get();

    ResultOrProblems<TypedCoverage> result = resolvedBookmark.getData(TypedCoverage.class);

    assertThat(result.isPresent(), is(false));
    assertThat(result.getProblems(), contains(hasAncestorProblem(equalIgnoringChildren(
        Problems.foundWith(brokenUri, sunkProblems)))));
  }

  @Test
  public void warningsInChildrenAreReturnedWithTheMosaic() throws Exception {
    // Create a coverage that will come with a warning when resolved
    TypedCoverage mockCoverageWithWarning = mock(TypedCoverage.class);
    when(mockCoverageWithWarning.getScalarDataType()).thenReturn(new CoverageType(Types.FLOATING));
    when(mockCoverageWithWarning.getEnvelope()).thenReturn(Optional.of(new ReferencedEnvelope(
        30, 40, 30, 40, helper.getCRS()
    )));
    when(mockCoverageWithWarning.getCoordinateReferenceSystem()).thenReturn(helper.getCrs());
    Problem warning = Problems.foundWith("Stuff").withSeverity(Severity.WARNING);

    // Add the coverage with associated warning by creating a ResolvedBookmark with data problems
    ResolvedBookmark bookmarkWithWarning = ResolvedBookmark.withId(
        "fake://coverage-with-warning",
        mockCoverageWithWarning,
        List.of(warning),
        List.of()
    );
    addPickledBookmark(bookmarkWithWarning);

    URI mosaicUri = ByteArrayCreateHandle.encodeData("""
        fake://coverage1
        fake://coverage-with-warning
        """, "text/plain");

    ResolvedBookmark resolvedBookmark = new MosaicCoverageResolver(engine)
        .resolve(Bookmark.fromURI(mosaicUri).withFormat("mosaic"), executionContext)
        .get();

    ResultOrProblems<TypedCoverage> result = resolvedBookmark.getData(TypedCoverage.class);

    // The mosaic should be successfully created
    assertThat(result.isPresent(), is(true));

    // But should also include the warning from the child coverage
    assertThat(result.getProblems(), hasItem(
        hasAncestorProblem(is(warning))
    ));
  }
}
