#!/usr/bin/env python3

import fileinput
import re
import sys

# Read Prometheus metrics from the files provided on the command line,
# or on stdin, and save their types and descriptions into `metrics`.
metrics = {}
for line in fileinput.input(encoding="utf-8"):
    if line.startswith("#"):
        comment, keyword, name, args = line.strip().split(maxsplit=3)
        if comment == "#" and keyword in ["TYPE", "HELP"]:
            metrics.setdefault(name, {})[keyword] = args.replace(
                "\\n", "<br/>"
            ).replace("\\\\", "\\")

# Read Markdown template from metrics.md.in, making some substitutions:
#
# - Delete lines up to the first `#`, and copy that line to the output.
#
# - Add a warning about the file being automatically generated, so
#   that people don't edit it.  (This has to go *after* the first `#`
#   because docusaurus won't skip the comment when it goes looking
#   for the page title.)
#
# - Copy the rest of the file to the output, substituting lines that
#   are bracketed by {{}} by autogenerated metrics documentation.
template = open("metrics.md.in", "r")
output = open("metrics.md", "w")
for line in template:
    line = line.rstrip()
    if line.startswith("#"):
        break
output.write(f"""{line}

<!-- This file is automatically generated.  Do not edit!

To update the documentation, please edit metrics.md.in instead and
then regenerate this file using the instructions in that file. -->
""")
for line in template:
    line = line.rstrip()
    m = re.match(r"{{(.*)}}", line)
    if m:
        regex = re.compile(m.group(1))
        matching_metrics = sorted([key for key in metrics.keys() if regex.match(key)])
        assert matching_metrics != []
        output.write("| Name | Type | Description |\n")
        output.write("| :--- | :--- | :---------- |\n")
        for metric in matching_metrics:
            type_ = metrics[metric]["TYPE"]
            help = metrics[metric]["HELP"]
            output.write(f"| <a name='{metric}'>`{metric}`</a> |{type_} | {help} |\n")
            del metrics[metric]
    else:
        output.write(f"{line}\n")

if len(metrics) > 0:
    sys.stderr.write(
        f"error: the following metrics need to be included in documentation: {metrics.keys()}\n"
    )
    sys.exit(1)
