#!/usr/bin/env python3
"""Assemble the documentation source tree for MkDocs.

The learning content is spread across the repository root (README, ROADMAP,
journal/, cheatsheets/, …). MkDocs requires its `site_dir` to live outside its
`docs_dir`, which rules out using the repo root directly. So this script copies
the publishable content (preserving paths, so relative links keep working) into
./docs_build, which mkdocs.yml uses as `docs_dir`.

Run before building/serving:
    python3 scripts/build-docs.py && mkdocs build
"""
import pathlib
import shutil

ROOT = pathlib.Path(__file__).resolve().parent.parent
BUILD = ROOT / "docs_build"

# Top-level Markdown pages (plus the awesome-pages nav order file).
ROOT_FILES = [
    "README.md", "ROADMAP.md", "PROGRESS.md", "LEARNING_LOG.md", "CHANGELOG.md",
    "RESOURCES.md", "NOTES.md", "FAQ.md", "CONTRIBUTING.md", ".pages",
]

# Content directories to publish (code dirs come along so in-note source links
# resolve; they're served as static files).
DIRS = [
    "journal", "cheatsheets", "interview", "examples", "exercises",
    "projects", "algorithms", "patterns", "docs", "templates", "scripts", "assets",
]

IGNORE = shutil.ignore_patterns(
    "node_modules", "site", "docs_build", ".git", "*.test", "coverage.*", "*.out",
)


def main():
    if BUILD.exists():
        shutil.rmtree(BUILD)
    BUILD.mkdir(parents=True)

    copied = 0
    for name in ROOT_FILES:
        src = ROOT / name
        if src.exists():
            shutil.copy2(src, BUILD / name)
            copied += 1
    for name in DIRS:
        src = ROOT / name
        if src.is_dir():
            shutil.copytree(src, BUILD / name, ignore=IGNORE, dirs_exist_ok=True)
            copied += 1

    md = sum(1 for _ in BUILD.rglob("*.md"))
    print(f"assembled {BUILD.relative_to(ROOT)}/ from {copied} sources — {md} markdown pages")


if __name__ == "__main__":
    main()
