# from https://mkdocstrings.github.io/recipes/#generate-pages-on-the-fly
"""Generate the code reference pages."""

from pathlib import Path

import mkdocs_gen_files

# modify the mkdoc "nav" to add pages automatically
nav = mkdocs_gen_files.Nav()
nav_folder_name_for_code_pages = "reference"

root_folder_path = Path(__file__).parent.parent.parent # root folder of repository
print("ROOT_FOLDER_PATH", root_folder_path)
src_folder_paths= [root_folder_path / "stereograph", root_folder_path / "scripts"]
#src_folder_path = root_folder_path / "stereograph" 
print("SRC_FOLDER_PATH", src_folder_paths)

for src_folder_path in src_folder_paths:
  
  print("SRC_FOLDER_PATH", src_folder_path)
  for source_file_path in sorted(src_folder_path.rglob("*.py")):

        module_path = source_file_path.relative_to(src_folder_path).with_suffix("")

        doc_path = source_file_path.relative_to(src_folder_path).with_suffix(".md")

        full_doc_path = Path(nav_folder_name_for_code_pages, doc_path)

        parts = tuple(module_path.parts)
        print("PARTS", parts)

        if parts[-1] == "__init__":
            parts = parts[:-1]

        if not parts:
            print("skip empty parts")
            continue
            # make section selectable and have them documented with content of __init__
            doc_path = doc_path.with_name("index.md")
            print("DOC_PATH", doc_path)
            full_doc_path = full_doc_path.with_name("index.md")
            print
        elif parts[-1] == "__main__":
            continue

        nav[parts] = doc_path.as_posix()


        with mkdocs_gen_files.open(full_doc_path, "w") as fd:
            identifier = ".".join(parts)

            print("::: " + identifier, file=fd)

        mkdocs_gen_files.set_edit_path(
            full_doc_path, source_file_path.relative_to(root_folder_path)
        )

with mkdocs_gen_files.open(
    nav_folder_name_for_code_pages + "/SUMMARY.md", "w"
) as nav_file:
    nav_file.writelines(nav.build_literate_nav())
