/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.accumulo.core.metrics;

import static java.nio.charset.StandardCharsets.UTF_8;

import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.TreeSet;

/**
 * This class generates documentation to inform users of the available metrics in a presentable
 * form.
 */
public class MetricsDocGen {
  private final PrintStream doc;
  private final TreeSet<Metric> sortedMetrics =
      new TreeSet<>(Comparator.comparing(Metric::getName));

  void generate() {
    pageHeader();
    generateTableOfContents();

    for (var section : Metric.MetricDocSection.values()) {
      generateCategorySection(section);
    }
  }

  void pageHeader() {
    doc.println("---");
    doc.println("title: Metrics Documentation (4.x)");
    doc.println("category: configuration");
    doc.println("order: 5");
    doc.println("---\n");
    doc.println("<!-- WARNING: Do not edit this file. It is a generated file"
        + " that is copied from Accumulo build (from core/target/generated-docs) -->\n");
    doc.println(
        "Below are the metrics used to monitor various components of Accumulo. Metrics emitted by Accumulo should"
            + " contain the folowing tags: 'instance.name', 'resource.group', 'process.name', 'host' and 'port'. Metrics"
            + " emitted by Accumulo may contain additional tags where we think it makes sense to capture per-object metrics,"
            + " for example on a table or tablet basis in the ScanServer and TabletServer, or on a per-queue basis in the"
            + " CompactionCoordinator.\n");
  }

  void generateTableOfContents() {
    doc.println("## Table of Contents\n");
    for (var category : Metric.MetricDocSection.values()) {
      String sectionId = generateSectionId(category.getSectionTitle());
      doc.println("- [" + category.getSectionTitle() + "](#" + sectionId + ")");
    }
    doc.println();
  }

  void generateCategorySection(Metric.MetricDocSection section) {
    String sectionId = generateSectionId(section.getSectionTitle());
    beginSection(section.getSectionTitle(), sectionId, section.getDescription());

    // Enable block-level HTML parsing
    doc.println("{::options parse_block_html=\"true\" /}");

    for (Metric metric : sortedMetrics) {
      if (metric.getDocSection() == section) {
        generateMetricSubsection(metric);
      }
    }

    // Disable block-level HTML parsing after the section
    doc.println("{::options parse_block_html=\"false\" /}\n");
  }

  /**
   * Starts a new section in the documentation. In this case a section is a category of metrics.
   * Adds an anchor to the section title so we can link to it.
   */
  void beginSection(String sectionTitle, String sectionId, String sectionDescription) {
    doc.println("\n## <a id=\"" + sectionId + "\"></a>" + sectionTitle + "\n");
    doc.println(sectionDescription + "\n");
  }

  /**
   * Generates a subsection for a metric. This includes the metric name, type, and description.
   */
  void generateMetricSubsection(Metric metric) {
    // Open the div block with markdown enabled
    doc.println("<div markdown=\"1\" class=\"metric-section\">");

    // Metric details
    doc.println("### " + metric.getName());
    doc.println("**Type:** " + metric.getType().name() + "  "); // Ensuring a line break in Markdown
    doc.println("**Description:** " + metric.getDescription());

    doc.println("</div>");
  }

  /**
   * Generates a section ID from a section title. This is used to create anchors for linking to
   * sections.
   */
  String generateSectionId(String sectionTitle) {
    return sectionTitle.toLowerCase().replace(" ", "-").replace(".", "");
  }

  private MetricsDocGen(PrintStream doc) {
    this.doc = doc;
    this.sortedMetrics.addAll(Arrays.asList(Metric.values()));
  }

  /**
   * Generates documentation for Accumulo metrics. Arguments are: "--generate-markdown filename"
   *
   * @param args command-line arguments
   * @throws IllegalArgumentException if args is invalid
   */
  public static void main(String[] args) throws IOException {
    if (args.length == 2 && args[0].equals("--generate-markdown")) {
      try (var printStream = new PrintStream(args[1], UTF_8)) {
        new MetricsDocGen(printStream).generate();
      }
    } else {
      throw new IllegalArgumentException(
          "Usage: " + MetricsDocGen.class.getName() + " --generate-markdown <filename>");
    }
  }
}
