"""Generate the code reference pages."""

from pathlib import Path

import mkdocs_gen_files

root = Path(__file__).parent.parent
src = root / "src" / "polytropos"

module_titles = {
    "build": "`build`",
    "build/manifest": "`build.manifest`",
    "build/pep517": "`build.pep517`",
    "build/primitives": "`build.primitives`",
    "ph": "`ph`",
    "__main__": "`__main__`",
}


def generate_doc(module_path: Path, title: str):
    """Generate a documentation page for a module."""
    module_name = module_path.as_posix().replace("/", ".")
    full_module_name = f"polytropos.{module_name}"
    full_doc_path = Path("api") / f"{module_path.as_posix()}.md"

    with mkdocs_gen_files.open(full_doc_path, "w") as f:
        print(f"# {title}", file=f)
        print("", file=f)
        print('!!! warning "Private Methods"', file=f)
        print(
            "    Private methods (starting with `_`) are documented for completeness",
            file=f,
        )
        print(
            "    but do **not** offer any stability guarantees. They may change or be",
            file=f,
        )
        print("    removed at any time without notice.", file=f)
        print("", file=f)
        print(f"::: {full_module_name}", file=f)


# Generate docs for the build package __init__.py
generate_doc(Path("build"), "`build`")

# Generate docs for all other .py files
for path in sorted(src.rglob("*.py")):
    if path.name == "__init__.py":
        continue
    module_path = path.relative_to(src).with_suffix("")
    title = module_titles.get(module_path.as_posix(), module_path.name.title())
    generate_doc(module_path, title)
