/*
 * 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.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

import nz.org.riskscape.engine.OutputProblems;
import nz.org.riskscape.engine.RiskscapeIOException;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.defaults.data.jdbc.BaseJdbcOutputStore;
import nz.org.riskscape.engine.defaults.data.jdbc.BaseJdbcOutputStore.JdbcRiskscapeWriter;
import nz.org.riskscape.engine.pipeline.Manifest;
import nz.org.riskscape.engine.pipeline.RealizedPipeline;
import nz.org.riskscape.engine.pipeline.sink.SaveSink;
import nz.org.riskscape.engine.types.RSList;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.ProblemSink;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

public abstract class BaseJdbcPipelineOutputContainer<S extends BaseJdbcOutputStore>
    extends BasePipelineOutputContainer {

  public static final String MANIFEST_TABLE = "riskscape_manifest";
  public static final Struct MANIFEST_TYPE = Struct.of(
      "version", Types.TEXT,
      "reference", Types.TEXT,
      "started", Types.DATE,
      "finished", Types.DATE)
      .and("manifest", Types.TEXT)
      .and("pipeline", Types.TEXT)
      .and("stats", Types.TEXT)
      .and("output_tables", RSList.create(Types.TEXT));

  protected final S backingStore;
  protected final List<String> outputTables = new ArrayList<>();

  public BaseJdbcPipelineOutputContainer(
      PipelineOutputStore outputStore,
      S backingStore,
      RealizedPipeline pipeline,
      PipelineOutputOptions options
  ) {
    super(outputStore, pipeline, options);
    this.backingStore = backingStore;
  }

  @Override
  protected ResultOrProblems<SaveSink> createSink(SinkParameters parameters) {
    return backingStore.writerFor(parameters.getType(), parameters.getName())
        .flatMap(writer -> {
          outputTables.add(writer.getTableName());
          SaveSink sink = new SaveSink(writer);
          return ResultOrProblems.of(sink);
        });
  }

  @Override
  public void close() {
    LocalDateTime finishedAt = currentTime.get();
    manifest.finishTime = finishedAt;
    addOutputInfoToManifest(manifest);

    ByteArrayOutputStream manifestBos = new ByteArrayOutputStream();
    manifest.write(manifestBos);

    ByteArrayOutputStream statsBos = new ByteArrayOutputStream();
    buildStatsWriter().writeStats(statsBos);

    ResultOrProblems<JdbcRiskscapeWriter> manifestWriterOr =
        backingStore.appendingWriterFor(MANIFEST_TYPE, MANIFEST_TABLE);
    if (manifestWriterOr.hasErrors()) {
      // manifests are nice but not having one doesn't affect the results. so we throw the error at the
      // problem sink and carry on.
      pipeline.getContext().getProblemSink().log(
          OutputProblems.get().cannotWriteManifest(getStore(), backingStore.getTableURI(MANIFEST_TABLE))
              .withChildren(manifestWriterOr.getProblems())
      );
    } else {
      try (RiskscapeWriter manifestWriter = manifestWriterOr
          .drainWarnings(p -> ProblemSink.DEVNULL.log(p)) // send any warnings to dev null, the user can't do anything
                                                          // about it any way. GeoPackage will have warning for no
                                                          // mapping for the output table list.
          .get()) {
        manifestWriter.write(Tuple.ofValues(MANIFEST_TYPE,
            getEngine().getBuildInfo().getVersion(), options.getReference(),
            Timestamp.valueOf(startedAt), Timestamp.valueOf(finishedAt),
            manifestBos.toString("UTF-8"), getPipelineSource().orElse(null), statsBos.toString("UTF-8"),
            outputTables
        ));
      } catch (IOException e) {
        throw new RiskscapeIOException(Problems.caught(e));
      }
    }
  }

  private void addOutputInfoToManifest(Manifest manifest) {
    for (Entry<String, SaveSink> entry : sinks.entrySet()) {
      SaveSink instance = entry.getValue();
      manifest.add(new Manifest.OutputInfo(instance.getStoredAt().toString(), "unknown", "unknown"));
    }
  }

}
