#!/usr/bin/env python3

"""Updates the list of proposals in proposals/README.md."""

__copyright__ = """
Part of the Carbon Language project, under the Apache License v2.0 with LLVM
Exceptions. See /LICENSE for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""

import io
import os
import importlib.util
import re
import sys

# Do some extra work to support direct runs.
try:
    from carbon.proposals.scripts import proposals
except ImportError:
    proposals_spec = importlib.util.spec_from_file_location(
        "proposals", os.path.join(os.path.dirname(__file__), "proposals.py")
    )
    proposals = importlib.util.module_from_spec(proposals_spec)
    proposals_spec.loader.exec_module(proposals)

if __name__ == "__main__":
    proposals_path = proposals.get_path()

    with io.StringIO() as out:
        out.write("<!-- Generated by ./scripts/update_proposal_list.py -->\n\n")
        results = out.getvalue()
        for title, filename in proposals.get_list(proposals_path):
            indent = ""
            if filename.endswith("decision.md"):
                indent = "    "
            out.write("%s-   [%s](%s)\n" % (indent, title, filename))
        toc = out.getvalue()

    # Replace the README content if needed.
    readme_path = os.path.join(proposals_path, "README.md")
    with open(readme_path) as f:
        old_content = f.read()
    proposals_re = re.compile(
        r"(.*<!-- proposals -->)(?:.*)(<!-- endproposals -->)",
        re.DOTALL | re.MULTILINE,
    )
    if not proposals_re.match(old_content):
        print(
            "ERROR: proposals/README.md is missing the <!-- proposals --> ... "
            "<!-- endproposals --> marker."
        )
        sys.exit(1)
    new_content = proposals_re.sub(r"\1\n%s\n\2" % toc, old_content)
    if old_content != new_content:
        print("Updating proposals/README.md")
        with open(readme_path, "w") as f:
            f.write(new_content)
