/*
 * 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.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;

import com.google.common.collect.Maps;

import lombok.Getter;
import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.OutputProblems;
import nz.org.riskscape.engine.Project;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.pipeline.ExecutionContext;
import nz.org.riskscape.engine.pipeline.Manifest;
import nz.org.riskscape.engine.pipeline.Manifest.LocalInfo;
import nz.org.riskscape.engine.pipeline.Manifest.VersionInfo;
import nz.org.riskscape.engine.pipeline.RealizedPipeline;
import nz.org.riskscape.engine.pipeline.Sink;
import nz.org.riskscape.engine.pipeline.sink.SaveSink;
import nz.org.riskscape.engine.plugin.Plugin;
import nz.org.riskscape.engine.plugin.PluginDescriptor;
import nz.org.riskscape.engine.resource.ResourceFactory;
import nz.org.riskscape.engine.util.StatsWriter;
import nz.org.riskscape.problem.ResultOrProblems;

public abstract class BasePipelineOutputContainer implements PipelineOutputContainer {

  @Getter
  protected final PipelineOutputStore store;

  @Getter
  protected final RealizedPipeline pipeline;
  protected final PipelineOutputOptions options;
  protected final Manifest manifest;
  protected final Supplier<LocalDateTime> currentTime;

  /**
   * Records the various sinks that were created as part of recording the pipeline's output
   */
  @Getter
  protected final Map<String, SaveSink> sinks = new HashMap<>();

  /**
   * A list of paths to files that were written as part of the pipeline's output (but weren't necessarily created by
   * sending tuples to a sink).
   */
  protected List<Path> fileOutputs = new ArrayList<>();

  protected Map<String, URI> movedFileOutputs = new HashMap<>();

  protected final LocalDateTime startedAt;

  public BasePipelineOutputContainer(
      PipelineOutputStore store,
      RealizedPipeline pipeline,
      PipelineOutputOptions options
  ) {
    this(store, pipeline, options, () -> LocalDateTime.now());
  }

  public BasePipelineOutputContainer(
      PipelineOutputStore store,
      RealizedPipeline pipeline,
      PipelineOutputOptions options,
      Supplier<LocalDateTime> currentTime
  ) {
    this.store = store;
    this.pipeline = pipeline;
    this.options = options;
    this.currentTime = currentTime;
    this.startedAt = currentTime.get();
    // the manifest must be seeded now to get the correct start time.
    this.manifest = buildManifest();
  }

  @Override
  public ResultOrProblems<Sink> createSinkForStep(SinkParameters params) {
    String sinkName = params.getName();
    if (!params.getFormat().isPresent()) {
      params = new SinkParameters(params);
      params.setFormat(options.getFormat());
    }

    return createSink(params).map(sink -> {
      sinks.put(sinkName, sink);
      return sink;
    });
  }

  /**
   * Create a {@link Sink} that will save {@link Tuple}s from a step described by the given parameters.
   * @return a sink or problems encountered
   */
  protected abstract ResultOrProblems<SaveSink> createSink(SinkParameters parameters);

  @Override
  public Map<String, URI> getPipelineOutputs() {
    Map<String, URI> sinkURIs = Maps.transformValues(sinks, sink -> sink.getStoredAt());

    HashMap<String, URI> combined = new HashMap<>(sinkURIs);
    combined.putAll(movedFileOutputs);
    return combined;
  }

  private Manifest buildManifest() {
    Project project = pipeline.getContext().getProject();
    Manifest newManifest = new Manifest(pipeline, startedAt);

    newManifest.versionInfo.add(new VersionInfo("Engine", project.getEngine().getBuildInfo().getVersion()));
    for (Plugin plugin : project.getEngine().getPlugins()) {
      PluginDescriptor desc = plugin.getDescriptor();
      newManifest.versionInfo.add(new VersionInfo(desc.getPluginId(), desc.getVersion()));
    }

    String host;
    try {
      InetAddress local = InetAddress.getLocalHost();
      host = local.getCanonicalHostName();
    } catch (UnknownHostException e) {
      host = "<unknown>";
    }
    String user = System.getProperty("user.name", "<unknown>");
    newManifest.localInfo = new LocalInfo(user, host);

    return newManifest;
  }

  protected StatsWriter buildStatsWriter() {
    return new StatsWriter(pipeline.getContext().getMetricRegistry());
  }

  protected Optional<String> getPipelineSource() {
    return options.getPipelineDeclaration().map(ep -> {
      return ep.getBoundary()
          .map(epb -> {
            if (epb.getLeft().source.equals(epb.getRight().source)) {
              // we use the source extracted from the boundary if possible because that will keep any whitespace
              // this only works if the tokens in the pipeline declaration come from the same source
              return epb.getLeft().source.substring(epb.getLeft().begin, epb.getRight().end);
            } else {
              // otherwise fall back to pipelineDecl.toSource(), but this will not contain a lot of the whitespace
              return ep.toSource();
            }
          })
          .orElse(ep.toSource());
    });
  }

  protected ResourceFactory getResourceFactory() {
    return getEngine().getResourceFactory();
  }

  public Project getProject() {
    return getExecutionContext().getProject();
  }

  protected Engine getEngine() {
    return getProject().getEngine();
  }

  public ExecutionContext getExecutionContext() {
    return pipeline.getContext();
  }

  @Override
  public void registerLocalFile(Path localFile) {
    for (Path registered: fileOutputs) {
      if (registered.endsWith(localFile.getFileName())) {
        getExecutionContext()
            .getProblemSink()
            .accept(OutputProblems.get()
                .outputAlreadyExists(localFile.getFileName().toString()));

        // Don't register the same filename twice - we'll have trouble when we try and move it into the output.
        // And it *probably* means the user is inadvertently overwriting their output.

        // Technically, we could permit registering files in different subdirectories
        // (e.g. foo/bar.txt, baz/bar.txt), but they'd show up in the output as bar.txt
        // and bar-1.txt which is a bit unintuitive. For now, we'll prohibit those as well.
        return;
      }
    }
    fileOutputs.add(localFile);
  }
}
