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

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import nz.org.riskscape.picocli.CommandLine.Help.Ansi.Text;

/**
 * A convinent wrapper around a StringBuilder that allows you to build a
 * markdown file. Call the various `addHeading`, `addText` methods,
 * then at the end call `writeToFile`
 */
public class MarkdownHelper {

  private StringBuilder builder = new StringBuilder();

  /**
   * Returns the markdown as a String
   */
  public String build() {
    return builder.toString();
  }

  /**
   * Adds a markdown styled heading
   */
  public void addHeading(String text) {
    addHeading(text, 1);
  }

  /**
   * Adds a markdown styled heading
   * @param level The size of the heading (1 is biggest, higher numbers create
   * subheadings.)
   */
  public void addHeading(String text, int level) {
    addLine("#".repeat(level) + " " + text);
  }

  /**
   * Adds two newlines. Equivalent to `addLine("")`
   */
  public void addLine() {
    addLine("");
  }

  /**
   * Adds the given String to the buffer, and adds two newline characters.
   * (This corresponds to one newline once the markdown is parsed)
   */
  public void addLine(String text) {
    addText(text + "\n\n");
  }

  /**
   * Directly adds the given String to the buffer
   */
  public void addText(String text) {
    builder.append(text);
  }

  public void addTable(Table table) {
    addTable(table, Optional.empty());
  }

  public void addTable(Table table, Optional<String> emptyTableMessage) {
    List<Text> header = table.getHeader();
    List<List<Text>> rows = table.getRows();
    List<String> stringHeader = header.stream().map(Text::plainString).toList();
    if (rows.isEmpty()) {
      emptyTableMessage.ifPresent(msg -> addLine(msg));
      return;
    }
    builder.append(markdownRow(stringHeader));
    builder.append(markdownRow(Collections.nCopies(stringHeader.size(), "---")));
    for (List<Text> row : rows) {
      List<String> stringRow = buildRow(row);
      builder.append(markdownRow(stringRow));
    }
  }

  private List<String> buildRow(List<Text> row) {
    return row.stream()
        .map(Text::plainString)
        .map(col -> {
          // columns may contain line breaks or lists that need some conversion
          // see https://www.markdownguide.org/hacks/#table-formatting
          StringBuilder sb = new StringBuilder();
          String[] lines = col.split("\n");
          boolean first = true;
          boolean list = false;
          for (String line: lines) {
            line = line.trim();
            if (line.startsWith("-")) {
              if (!list) {
                sb.append("<ul>");
                list = true;
              }
              sb.append("<li>").append(line.substring(1)).append("</li>");
            } else {
              if (list) {
                sb.append("</ul>");
                list = false;
              } else if (! first) {
                sb.append("<br><br>");
              }
              sb.append(line);
            }
            first = false;
          }
          if (list) {
            sb.append("</ul>");
          }
          return sb.toString();
        })
        .toList();
  }

  private String markdownRow(List<String> row) {
    return "| " + String.join(" | ", row) + " |\n";
  }

  /**
   * Writes the stored content to the given path.
   *
   * @return The path that was written to
   */
  public Path writeToFile(Path path, String filename) throws IOException {
    Files.createDirectories(path);
    return Files.writeString(path.resolve(filename), builder);
  }
}
