"""Generate the code reference pages automatically.

This script is run by mkdocs-gen-files during the build process.
It scans the osipy package and creates a reference page for each module.

Nav ordering: CLI config → CLI module → common → dce → dsc → asl → ivim →
pipeline → standalone reference pages (vendor DICOM tags, etc.)
"""

from collections import defaultdict
from pathlib import Path

import mkdocs_gen_files

src = Path("osipy")
mod = Path("reference")

# Desired top-level package order (CLI-first, then common, then modalities).
PACKAGE_ORDER = ["cli", "common", "dce", "dsc", "asl", "ivim", "pipeline"]

# --- Phase 1: Generate individual module .md files and collect nav entries ---

# entries_by_package[pkg] = [(parts_tuple, doc_path_str), ...]
entries_by_package: dict[str, list[tuple[tuple[str, ...], str]]] = defaultdict(list)

for path in sorted(src.rglob("*.py")):
    # Skip private modules and __pycache__
    if any(part.startswith("_") for part in path.parts):
        continue

    module_path = path.relative_to(src.parent).with_suffix("")
    doc_path = path.relative_to(src).with_suffix(".md")
    full_doc_path = mod / doc_path

    parts = tuple(module_path.parts)

    # Group by the first sub-package (e.g. "cli", "common", "dce")
    pkg = parts[1] if len(parts) > 1 else parts[0]
    entries_by_package[pkg].append((parts, doc_path.as_posix()))

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

    mkdocs_gen_files.set_edit_path(full_doc_path, path)

# --- Phase 2: Build SUMMARY.md with explicit ordering ---

with mkdocs_gen_files.open(mod / "SUMMARY.md", "w") as nav_file:
    # index.md must be first so Material's navigation.indexes uses it
    # as the Reference section landing page instead of the first module.
    nav_file.write("* [Reference](index.md)\n")

    # YAML Configuration reference (auto-generated by gen_config_docs.py)
    nav_file.write("* [YAML Configuration (CLI)](cli-config.md)\n")

    # Module API pages in desired order
    nav = mkdocs_gen_files.Nav()
    for pkg in PACKAGE_ORDER:
        for parts, doc_path_str in entries_by_package.get(pkg, []):
            nav[parts] = doc_path_str

    # Include any remaining packages not in PACKAGE_ORDER
    for pkg in sorted(entries_by_package):
        if pkg not in PACKAGE_ORDER:
            for parts, doc_path_str in entries_by_package[pkg]:
                nav[parts] = doc_path_str

    nav_file.writelines(nav.build_literate_nav())

    # Standalone reference pages from docs/reference/ (vendor DICOM tags, etc.)
    docs_ref = Path("docs") / "reference"
    if docs_ref.is_dir():
        for path in sorted(docs_ref.glob("*.md")):
            if path.name in ("SUMMARY.md", "index.md"):
                continue
            title = path.stem.replace("-", " ").title()
            nav_file.write(f"* [{title}]({path.name})\n")
