/*
 * 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 java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.net.URI;
import java.util.List;
import java.util.Map;

import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Geometry;

import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.coverage.TypedCoverage;
import nz.org.riskscape.engine.data.BaseBookmarkResolver;
import nz.org.riskscape.engine.data.Bookmark;
import nz.org.riskscape.engine.data.BookmarkFactory;
import nz.org.riskscape.engine.data.BookmarkParameters;
import nz.org.riskscape.engine.function.geometry.Bounds;
import nz.org.riskscape.engine.geo.IntersectionIndex;
import nz.org.riskscape.engine.problem.ProblemFactory;
import nz.org.riskscape.engine.types.CoverageType;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
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.ProblemException;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * Resolves {@link MosaicCoverage}s from a url that is expected to be a plain text file that is a list of urls that
 * comprise the mosaic
 */
public class MosaicCoverageResolver extends BaseBookmarkResolver<MosaicCoverageResolver.Params> {

  public interface LocalProblems extends ProblemFactory {
    Problem emptyMosaic(URI location);

    Problem boundsRequired(URI childLocation);

    Problem crsMismatch(URI childLocation, CoordinateReferenceSystem expected, CoordinateReferenceSystem actual);
  }

  public static final LocalProblems PROBLEMS = Problems.get(LocalProblems.class);

  public MosaicCoverageResolver(Engine engine) {
    super(engine);
  }

  public static class Params extends BookmarkParameters {

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

  @Override
  protected Map<String, String> getExtensionsToFormats() {
    return Map.of("mosaic", "mosaic");
  }

  @Override
  protected ResultOrProblems<TypedCoverage> build(Params parameters) {
    return ProblemException.catching((problems) -> {
      try {
        return buildInternal(problems, parameters);
      } catch (IOException e) {
        throw new ProblemException(Problems.caught(e));
      }
    });
  }

  private TypedCoverage buildInternal(List<Problem> problems, BookmarkParameters parameters)
      throws IOException, ProblemException {
    // create reader from location
    Reader reader = engine.getResourceFactory().load(parameters.location).getContentReader();
    BufferedReader lineReader = new BufferedReader(reader);
    SRIDSet sridSet = parameters.getProject().getSridSet();

    // only floating point coverages supported for now, but could be extended
    final CoverageType coverageType = new CoverageType(Types.FLOATING);

    // these get set up when we see the first coverage
    IntersectionIndex index = null;
    Struct indexedType = null;
    CoordinateReferenceSystem crs = null;

    /*
     * Populate the index using each line from the bookmark's location
     */

    StructMember coverageMember = null;
    String location;
    while ((location = lineReader.readLine()) != null) {
      // remove any leading or trailing whitespace from user input
      location = location.trim();

      if (location.isEmpty()) {
        // skip whitespace lines
        continue;
      }

      // XXX do we want to support some metadata at the beginning, e.g. things like a mode?

      URI bookmarkLocation = BookmarkFactory.uriFromLocation(location, parameters.location).getOrThrow();
      Bookmark bookmark = Bookmark.fromURI(bookmarkLocation);
      // XXX: We could support expressions here as well?  Would make it quite flexible...

      TypedCoverage child =
          engine.getBookmarkResolvers()
            .resolve(bookmark, parameters.getExecutionContext())
            .flatMap(resolved -> resolved.getData(TypedCoverage.class))
            .composeProblems(Problems.foundWith(bookmarkLocation))
            .drainWarnings(problems::add)
            .getOrThrow();


      // make sure they are all the right type
      if (!child.getScalarDataType().equals(coverageType)) {
        throw new ProblemException(TypeProblems.get().mismatch(
            bookmarkLocation,
            coverageType, child.getScalarDataType())
        );
      }

      if (index == null) {
        // use the first coverage to set up the index
        indexedType = Struct.of("coverage", coverageType, "geom", Types.GEOMETRY);
        StructMember geomMember = indexedType.getEntry("geom");
        coverageMember = indexedType.getEntry("coverage");
        index = new IntersectionIndex(geomMember, sridSet, IntersectionIndex.defaultOptions());
        crs = child.getCoordinateReferenceSystem();
      } else {
        if (!CRS.equalsIgnoreMetadata(crs, child.getCoordinateReferenceSystem())) {
          throw new ProblemException(PROBLEMS.crsMismatch(bookmarkLocation, crs, child.getCoordinateReferenceSystem()));
        }
      }

      // NB bounds is required
      ReferencedEnvelope referencedEnvelope = child.getEnvelope()
          .orElseThrow(() -> new ProblemException(PROBLEMS.boundsRequired(bookmarkLocation)));

      Geometry boundsGeom = Bounds.toBoundsGeom(
          referencedEnvelope,
          referencedEnvelope.getCoordinateReferenceSystem(),
          sridSet
      );

      Tuple toInsert = Tuple.ofValues(indexedType, child, boundsGeom);
      index.insert(toInsert);
    }

    if (index == null) {
      // fail if there are no coverages
      // this could possibly be a warning but if that were the case we would need to ensure that warnings
      // are drained from ResolvedBookmark.getData() which is is not currently the case (not by LookupBookmark
      // anyway).
      problems.add(PROBLEMS.emptyMosaic(parameters.getLocation()));
      return new TypedCoverage.Empty(Types.NOTHING);
    }

    return new MosaicCoverage(index, coverageMember, coverageType.getMemberType());
  }

}
