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

import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;

import hdf.hdf5lib.exceptions.HDF5SymbolTableException;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.data.coverage.Dataset2D;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.hdf5.H5Attribute;
import nz.org.riskscape.hdf5.H5Dataset;
import nz.org.riskscape.hdf5.H5DatasetPath;
import nz.org.riskscape.hdf5.H5File;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * Helper to read a datasets from an USGS shakemap file (e.g. shake_result.hdf) and turn it into
 * a spatial coverage. Shakemaps are slightly different to other HDF5 files in that the lat/long
 * coordinates aren't present in a dataset, but instead the bounds/extent of the data is encoded
 * as HDF5 attributes as part of the dataset, i.e. xmin, xmax, ymin, ymax.
 */
@RequiredArgsConstructor
public class UsgsShakeMapReader {

  private final H5File file;

  private final String datasetName;

  protected H5Dataset openDataset(String dataset) {
    return file.openDataset(H5DatasetPath.parse(dataset));
  }

  /**
   * Returns the underlying HDF5 data in a form that can be queried by an x,y index.
   */
  public ResultOrProblems<Dataset2D> getData() {
    return getDataset2D(datasetName);
  }

  protected ResultOrProblems<Dataset2D> getDataset2D(String datasetPath) {
    try (
        H5Dataset dataset = openDataset(datasetPath);
    ) {
      // Read the raw shakemap data. This data is a 2-D grid, but we can treat it like
      // a 1-D array. We traverse the grid horizontally, i.e. it's in the order y, x
      double[] values = dataset.getElementsAsDouble();
      long[] dimensions = dataset.getDataSpace().getExtent();
      int height = (int) dimensions[0];
      int width = (int) dimensions[1];

      return ResultOrProblems.of(Dataset2D.fromDoubles(width, height, values));
    } catch (HDF5SymbolTableException ex) {
      return ResultOrProblems.failed(
          GeneralProblems.get().noSuchObjectExists(datasetPath, H5Dataset.class));
    }
  }

  /**
   * Reads the latitude/longitude co-ordinates used for the given dataset in the shakemap.
   * @return an envelope that holds the extent of the PGA grid
   */
  public ResultOrProblems<ReferencedEnvelope> getExtent() {
    try (H5Dataset dataset = openDataset(datasetName)) {

      // the shakemap coordinates are in WGS84 format
      CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84;
      return ProblemException.catching(() -> {
        // read the x/y min/max HDF5 attributes. These hold the lat/long
        // co-ordinates for the PGA grid
        double xMax = H5Attribute.readValue(dataset, "xmax", Double.class).getOrThrow();
        double xMin = H5Attribute.readValue(dataset, "xmin", Double.class).getOrThrow();
        double yMax = H5Attribute.readValue(dataset, "ymax", Double.class).getOrThrow();
        double yMin = H5Attribute.readValue(dataset, "ymin", Double.class).getOrThrow();

        return new ReferencedEnvelope(xMin, xMax, yMin, yMax, crs);

      }).composeProblems(Problems.foundWith(H5Dataset.class, datasetName));

    } catch (HDF5SymbolTableException ex) {
      return ResultOrProblems.failed(
          GeneralProblems.get().noSuchObjectExists(datasetName, H5Dataset.class));
    }
  }
}
