#!/usr/bin/env python3
"""Assemble progress_report.html from template.html + pages/*.html fragments.

Each fragment's FIRST LINE must be a metadata comment:

    <!-- page: Tab label | Full page title -->

Pages are included in lexicographic filename order (use NN- prefixes).
To add a page: drop pages/NN-something.html with that first line, re-run:

    python3 build.py
"""
import datetime
import html
import pathlib
import re
import sys

ROOT = pathlib.Path(__file__).parent
META_RE = re.compile(r"<!--\s*page:\s*(.+?)\s*\|\s*(.+?)\s*-->")
INCLUDE_RE = re.compile(r"^[ \t]*<!--\s*include:\s*(\S+)\s*-->[ \t]*$", re.M)


def _expand_includes(text):
    """Replace `<!-- include: path -->` lines with the file's contents
    (path relative to report/). Missing files become a visible placeholder
    so a not-yet-generated trace include never silently vanishes."""
    def sub(m):
        p = ROOT / m.group(1)
        if p.exists():
            return p.read_text()
        return (f'<p class="callout warn">[include missing: '
                f'{m.group(1)} — run report_examples.py]</p>')
    return INCLUDE_RE.sub(sub, text)


def main():
    pages = sorted((ROOT / "pages").glob("*.html"))
    if not pages:
        sys.exit("no pages found in pages/")
    tabs, sections = [], []
    for path in pages:
        text = _expand_includes(path.read_text())
        first, _, body = text.partition("\n")
        m = META_RE.search(first)
        if not m:
            sys.exit(f"{path.name}: first line must be "
                     f"'<!-- page: Tab label | Page title -->'")
        label, title = m.groups()
        slug = re.sub(r"[^a-z0-9]+", "-", label.lower()).strip("-")
        tabs.append(f'<button class="tab" data-tab="{slug}">{label}</button>')
        sections.append(
            f'<section class="page" id="{slug}">\n'
            f'<h1>{html.escape(title)}</h1>\n{body}\n</section>')
    out = ((ROOT / "template.html").read_text()
           .replace("{{NAV}}", "\n".join(tabs))
           .replace("{{SECTIONS}}", "\n".join(sections))
           .replace("{{BUILD_DATE}}", datetime.date.today().isoformat()))
    out_path = ROOT / "progress_report.html"
    out_path.write_text(out)
    print(f"wrote {out_path} ({len(out) // 1024} kB, {len(pages)} pages)")


if __name__ == "__main__":
    main()
