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

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import lombok.Getter;
import nz.org.riskscape.engine.OutputProblems;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.defaults.data.jdbc.GeoPackageFormat;
import nz.org.riskscape.engine.defaults.data.jdbc.GeoPackageOutputStore;
import nz.org.riskscape.engine.pipeline.RealizedPipeline;
import nz.org.riskscape.engine.pipeline.sink.SaveSink;
import nz.org.riskscape.engine.resource.CreateException;
import nz.org.riskscape.engine.resource.CreateRequest;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * Allows pipeline outputs to be stored to a GeoPackage format file.
 */
public class GeoPackagePipelineOutputStore implements PipelineOutputStore {

  class GeoPackagePipelineOutputContainer extends BaseJdbcPipelineOutputContainer<GeoPackageOutputStore> {

    GeoPackagePipelineOutputContainer(
      PipelineOutputStore outputStore,
      GeoPackageOutputStore backingStore,
      RealizedPipeline pipeline,
      PipelineOutputOptions options
    ) {
      super(outputStore, backingStore, pipeline, options);
    }

    @Override
    public URI getStoredAt() {
      // NB this is a file uri, but maybe we want a jdbc uri?  Note that for most databases, these will be useless
      // outside the context of a particular deployment, as most databases aren't (or shouldn't be) exposed to the
      // internet
      return backingStore.getGeoPackageFile().toURI();
    }

    @Override
    protected ResultOrProblems<SaveSink> createSink(SinkParameters parameters) {
      List<Problem> warnings = new ArrayList<>();

      // if the user has given a format and it's not geopackage (which we support with file-like output store) we
      // inform the user we're ignoring the parameter
      boolean formatMatchesOutput = parameters.getFormat()
          .map(format -> format.getId().equals(GeoPackageFormat.ID))
          .orElse(true);

      if (!formatMatchesOutput) {
        warnings.add(OutputProblems.get().userSpecifiedFormatIgnored(parameters.getFormat().get(), getStore()));
      }

      return super.createSink(parameters).withMoreProblems(warnings);
    }

    @Override
    public void close() {
      // call super to write the manifest
      super.close();

      // now we need to close the GeoPackage backing store to ensure the shared connection is closed.
      try {
        this.backingStore.close();
      } catch (Exception e) {
        throw new RiskscapeException(Problems.caught(e));
      }
    }
  }

  @Getter
  private final String id = "geopackage";

  @Override
  public int isApplicable(URI outputLocation) {
    // a GeoPackage must be a file URI ending with a '.gpkg' suffix
    if ("file".equals(outputLocation.getScheme())
        && outputLocation.getPath() != null
        && outputLocation.getPath().endsWith(".gpkg")) {
      return PRIORITY_HIGH;
    }
    return PRIORITY_NA;
  }

  @Override
  public ResultOrProblems<PipelineOutputContainer> create(URI outputLocation, RealizedPipeline pipeline,
      PipelineOutputOptions options) {
    List<Problem> warnings = new ArrayList<>();

    Format userSpecifiedDefault = options.getFormat().orElse(null);
    if (userSpecifiedDefault != null) {
      if (! GeoPackageFormat.ID.equals(userSpecifiedDefault.getId())) {
        warnings.add(OutputProblems.get().userSpecifiedFormatIgnored(userSpecifiedDefault, this));
      }
      // set the default to null, we're ignoring it so don't want warnings every time
      // it is ignored
      options.setFormat(null);
    }
    if (options.isChecksum()) {
      warnings.add(OutputProblems.get().checksumNotSupported(this));
    }

    File geoPackageFile = new File(outputLocation);
    if (! geoPackageFile.exists()) {
      try {
      CreateRequest createRequest = new CreateRequest(geoPackageFile.getParentFile().toURI(),
          geoPackageFile.getName(), "application/geopackage+sqlite3");
      pipeline.getContext().getEngine().getResourceFactory().create(createRequest);
      } catch (CreateException e) {
        return ResultOrProblems.failed(Problems.caught(e));
      }
    }

    GeoPackageOutputStore backingStore = new GeoPackageOutputStore(geoPackageFile, options.isReplace());

    return ResultOrProblems.of(new GeoPackagePipelineOutputContainer(this, backingStore, pipeline, options), warnings);
  }

}
