#!/usr/bin/env python3

# Copyright (C) 2026 Internet Systems Consortium, Inc. ("ISC")
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import os
import pathlib
import sys


def main():
    parent_dir = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0])))
    root_dir = f'{parent_dir}/..'
    all_jsons = sorted(pathlib.Path(root_dir).glob('doc/examples/**/*.json'))
    content = """
..
    File generated by "tools/add-config-examples-to-arm.py". Do not edit by hand.

.. _config-examples:

######################
Configuration Examples
######################

This is the set of configuration examples included in ``doc/examples`` in the
sources of Kea version |release|.


"""
    # Up to 7 nested levels are supported.
    adornment_characters = ['=', '-', '~', '*', '#', '^', '"']
    subdirs = 7 * [None]
    for json in all_jsons:
        relative = json.relative_to(pathlib.Path(root_dir) / 'doc' / 'examples')
        for i, part in enumerate(relative.parts):
            if subdirs[i] != part:
                up_to_current = relative.parts[0:i+1]
                anchor = '.. _config-example-' + '-'.join(up_to_current).replace('.', '-') + ':\n\n'
                subtitle = '/'.join(up_to_current)

                content += anchor
                content += len(subtitle) * adornment_characters[i] + '\n'
                content += subtitle + '\n'
                content += len(subtitle) * adornment_characters[i] + '\n'
                content += '\n'

                subdirs[i] = part
                # We've just changed subdirectory, so reset all the subdirectories and files that follow.
                for j in range(i + 1, len(relative.parts)):
                    subdirs[j] = None
        content += '.. code-block::\n'
        content += '    :linenos:\n'
        content += '\n'
        with open(json, 'r', encoding='utf-8') as f:
            indented = '\n'.join('    ' + line for line in f.read().splitlines())
            content += indented
            content += '\n\n'

    # Remove trailing spaces.
    content = '\n'.join(line.rstrip() for line in content.splitlines())

    with open('doc/sphinx/config-examples.rst', 'w', encoding='utf-8') as config_examples_rst:
        config_examples_rst.write(content)


if __name__ == '__main__':
    main()
