"""Build a Markdown index of the example notes. Uses only Python's standard library."""
from pathlib import Path
from urllib.parse import quote


def render_index(notes):
    entries = []
    for path in notes.glob("*.md"):
        if not path.is_file():
            continue
        lines = path.read_text(encoding="utf-8").splitlines()
        title = next((line[2:].strip() for line in lines if line.startswith("# ")), path.stem)
        title = title.replace("[", r"\[").replace("]", r"\]")
        destination = quote("notes/" + path.relative_to(notes).as_posix(), safe="/")
        entries.append((title, destination))
    entries.sort(key=lambda entry: entry[0].casefold())
    links = [f"- [{title}]({destination})" for title, destination in entries]
    return "# Notes index\n\n" + "\n".join(links) + ("\n" if links else "")


if __name__ == "__main__":
    project = Path(__file__).resolve().parent
    result = render_index(project / "notes")
    (project / "INDEX.md").write_text(result, encoding="utf-8")
    print("Wrote INDEX.md")
