#!/usr/bin/env python3
"""Rebuild everything generated in the implementation plan and the design folder, in dependency order.

Run:    python3 docs/implementation_plan/tools/build.py

Stops at the first step that fails, and ends with the link check.
"""
import os, subprocess, sys, time

HERE = os.path.dirname(os.path.abspath(__file__))

STEPS = [
    ('apply_decisions.py', [], 'write outcomes into the specifications and the technology stack page'),
    ('build_adrs.py', [], 'architecture decision records and their index'),
    ('build_events.py', [], 'consumed-event tables in the specifications, event catalogue'),
    ('extract.py', [], 'backlog, dependency graph, blocking decisions'),
    ('build_gates.py', [], 'vertical slices and stage gates'),
    ('build_decisions.py', [], 'decision plan'),
    ('build_screens.py', [], 'screen inventory'),
    ('build_roles.py', [], 'user roles'),
    ('build_sessions.py', [], 'session plan'),
    ('check_links.py', [], 'link check'),
]

for script, extra, what in STEPS:
    t = time.time()
    print(f'== {script}: {what}', flush=True)
    r = subprocess.run([sys.executable, '-B', os.path.join(HERE, script)] + extra, capture_output=True, text=True)
    out = (r.stdout + r.stderr).strip().split('\n')
    print('\n'.join('   ' + x for x in out[-6:] if x))
    if r.returncode != 0 or (script == 'check_links.py' and ' broken: 0 ' not in r.stdout):
        sys.exit(f'stopped: {script} failed (exit {r.returncode})')
    print(f'   ({time.time() - t:.1f}s)')
print('build complete')
