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


import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.stream.Stream;

import com.codahale.metrics.MetricRegistry;

import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.output.CsvWriter;
import nz.org.riskscape.engine.types.Nullable;
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;

/**
 * Writes stats from a {@link MetricRegistry} to file.
 */
@RequiredArgsConstructor
public class StatsWriter {

  private static final Struct TYPE = Struct.of(
      "name", Types.TEXT,
      "runtime-ms", Nullable.INTEGER,
      "runtime-average-ms", Nullable.TEXT,
      "tuples-in", Nullable.INTEGER,
      "tuples-in-per-sec", Nullable.TEXT)
      .and("tuples-out", Nullable.INTEGER)
      .and("tuples-out-per-sec", Nullable.TEXT)
      .and("context-switches", Nullable.INTEGER);

  private static final Comparator<Tuple> RUNTIME_COMPARATOR = (t1, t2) -> {
    Long rt1 = t1.fetch("runtime-ms");
    Long rt2 = t2.fetch("runtime-ms");

    // we swap the order here because we want to sort largest to smallest
    return Long.compare(rt2, rt1);
  };

  private final MetricRegistry registry;

  /**
   * The default output location to write the pipeline stats to.
   */
  public static final String FILENAME = "model-run-stats.csv";

  public static final String CONTENT_TYPE = "text/csv";

  /**
   * Writes the stats in the MetricRegistry to the given output filepath.
   */
  public void writeStats(Path outputFilepath) {
    FileUtils.rewrite(outputFilepath, out -> writeStats(out));
  }

  /**
   * Writes the stats in the MetricRegistry to the given output stream.
   */
  public void writeStats(OutputStream os) {
    try (CsvWriter writer = new CsvWriter(TYPE, ProblemSink.DEVNULL, new PrintWriter(os))) {
      stepNames()
          .map(name -> stepMetrics(name))
          .sorted(RUNTIME_COMPARATOR)
          .forEachOrdered(t -> writer.write(t));
    } catch (IOException e) {
      throw new RiskscapeException(Problems.caught(e));
    }
  }

  /**
   * Returns step names by trawling the {@link MetricRegistry} looking for metrics that have
   * `runtime` and `tuples-in` and/or `tuples-out`.
   */
  private Stream<String> stepNames() {
    return registry.getNames().stream()
        .filter(name -> name.endsWith(".tuples-in") || name.endsWith(".tuples-out"))
        .map(name -> name.substring(0, name.indexOf(".")))
        .distinct()
        .filter(step -> registry.getMetrics().containsKey(step + ".runtime"));
  }

  private Tuple stepMetrics(String step) {
    Tuple toWrite = Tuple.ofValues(TYPE, step);
    if (registry.getCounters().containsKey(step + ".runtime")) {
      toWrite.set("runtime-ms", registry.getCounters().get(step + ".runtime").getCount());
    }
    if (registry.getHistograms().containsKey(step + ".runtime-average")) {
      toWrite.set(
          "runtime-average-ms",
          String.format("%.2f", registry.getHistograms().get(step + ".runtime-average").getSnapshot().getMean())
      );
    }
    if (registry.getMeters().containsKey(step + ".tuples-in")) {
      toWrite.set("tuples-in", registry.getMeters().get(step + ".tuples-in").getCount());
    }
    if (registry.getGauges().containsKey(step + ".tuples-in.per-sec")) {
      toWrite.set(
          "tuples-in-per-sec",
          String.format("%.2f", registry.getGauges().get(step + ".tuples-in.per-sec").getValue())
      );
    }
    if (registry.getMeters().containsKey(step + ".tuples-out")) {
      toWrite.set("tuples-out", registry.getMeters().get(step + ".tuples-out").getCount());
    }
    if (registry.getGauges().containsKey(step + ".tuples-out.per-sec")) {
      toWrite.set(
          "tuples-out-per-sec",
          String.format("%.2f", registry.getGauges().get(step + ".tuples-out.per-sec").getValue())
      );
    }
    if (registry.getCounters().containsKey(step + ".context-switches")) {
      toWrite.set("context-switches", registry.getCounters().get(step + ".context-switches").getCount());
    }
    return toWrite;
  }
}
