/*
 * 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 java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import org.geotools.geometry.jts.ReferencedEnvelope;

import com.google.common.collect.Range;

import hdf.hdf5lib.exceptions.HDF5Exception;
import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.bind.ParamProblems;
import nz.org.riskscape.engine.bind.ParameterField;
import nz.org.riskscape.engine.coverage.TypedCoverage;
import nz.org.riskscape.engine.data.BaseBookmarkResolver;
import nz.org.riskscape.engine.data.BookmarkParameters;
import nz.org.riskscape.engine.data.coverage.Dataset2D;
import nz.org.riskscape.engine.data.coverage.DatasetCoverage;
import nz.org.riskscape.engine.data.coverage.DatasetCoverage.GridStartPoint;
import nz.org.riskscape.engine.data.coverage.MappedCoverage;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.hdf5.H5File;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ExpressionParser;

/**
 * Resolves bookmarks for shakemap HDF5 files downloaded from the usgs.gov
 * website. USGS produces shakemaps after major earthquakes and these can be
 * used to calculate losses post-event.
 */
public class UsgsShakeMapResolver extends BaseBookmarkResolver<UsgsShakeMapResolver.Params> {

  // Peak Ground Acceleration (PGA) data stored in the shakemap
  private static final List<String> DEFAULT_DATASETS = Arrays.asList(
      "/arrays/imts/GREATER_OF_TWO_HORIZONTAL/PGA/mean",
      "/arrays/imts/GREATER_OF_TWO_HORIZONTAL/PGA/std"
  );

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

  // default to just returning the median/mean
  private static final float DEFAULT_PERCENTILE = 50.0f;

  public static class Params extends BookmarkParameters {
    @ParameterField
    public Optional<Float> percentile = Optional.empty();

    @ParameterField
    public List<String> dataset = Collections.emptyList();

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

    /* Note that USGS shakemap coordinates are always in the WGS84/EPSG:4326
     * format, so we don't offer a CRS parameter here */
  }

  @Override
  public Set<String> getFormats() {
    return Collections.singleton("usgs-shakemap");
  }

  @Override
  protected Map<String, String> getExtensionsToFormats() {
    return Collections.emptyMap();
  }

  @Override
  protected void validateParameters(Params params, BindingContext context) {
    super.validateParameters(params, context);

    if (params.percentile.isPresent()) {
      if (!params.dataset.isEmpty()) {
        params.problems.add(ParamProblems.get().mutuallyExclusive("percentile", "dataset"));
      }

      // sanity-check the percentile value is in range (it's unlikely the user
      // would ever want a percentile less than 1, and this will catch them trying
      // to use 0.9 instead of 90.0)
      Range<Float> range = Range.closed(1.0F, 100F);
      if (!range.contains(params.percentile.get())) {
        params.problems.add(GeneralProblems.get().valueOutOfRange("percentile", params.percentile.get(), range));
      }
    }
  }

  @Override
  protected ResultOrProblems<? extends Object> build(Params parameters) {
    Path hdf5 = getBookmarkedPath(parameters);

    return ProblemException.catching(() -> {
      try (H5File file = new H5File(hdf5)) {
        UsgsShakeMapReader reader;
        // NB we are trading off setting a default in the parameters object (which is visible to the user) with keeping
        // the code simpler vis. detecting whether the user has messed with the datasets parameter.  Below we apply the
        // lognorm_ppf function to the data only if the dataset parameter is untouched.
        boolean isDefaultCoverage = parameters.dataset.isEmpty();
        List<String> datasets = isDefaultCoverage ? DEFAULT_DATASETS : parameters.dataset;

        if (datasets.size() == 1) {
          reader = new UsgsShakeMapReader(file, datasets.get(0));
        } else {
          reader = new UsgsShakeMapMultiDatasetReader(file, datasets);
        }

        // get the extent (latitude/longitude grid) that the PGA values cover
        ReferencedEnvelope sourceExtent = reader.getExtent().getOrThrow();
        Dataset2D pgaData = reader.getData().getOrThrow();

        /* build a TypedCoverage that maps the 2D grid to the lat/long extent.
         * Index 0,0 in the PGA data starts at the upper left (north-west corner) */
        GridStartPoint dataStartsAt = GridStartPoint.NORTH_WEST_CORNER;

        TypedCoverage coverage = new DatasetCoverage(sourceExtent, pgaData,
            dataStartsAt, parameters.getProject().getSridSet());

        // by default, we return a coverage that's easy to work with, so we
        // convert the raw log(g) mean/stddev values into an average PGA, in g units.
        if (isDefaultCoverage) {
          // the bookmark percentile lets the user configure the degree of uncertainty
          // they want WRT the shaking. We use the PPF function to work out a PGA value
          // that matches the given percentile, based on a log-normal distribution
          float percentile = parameters.percentile.orElse(DEFAULT_PERCENTILE);
          return MappedCoverage.build(parameters.getRealizationContext(),
              coverage,
              "sampled",
              ExpressionParser.INSTANCE.parse(
                  String.format("lognorm_ppf(%f / 100, sampled.mean, sampled.std)", percentile)
              )).getOrThrow();
        } else {
          // otherwise the coverage will return the raw values from the dataset(s) as is
          return coverage;
        }
      } catch (HDF5Exception ex) {
        throw new ProblemException(Problems.caught(ex));
      }
      // put a bad shakemap error around any failure
    }).composeProblems(UsgsProblems.get().badShakemap(hdf5));
  }
}
