"""Regenerate declared docs only, retaining the initial check outcome unchanged."""
import importlib.util
import json
from pathlib import Path
import sys
sys.dont_write_bytecode = True
SOURCE = Path(__file__).with_name('run.py')
spec = importlib.util.spec_from_file_location('initial302docs', SOURCE)
p = importlib.util.module_from_spec(spec)
spec.loader.exec_module(p)
ALLOWED = {'docs-site/src/cli/reference.md', 'docs-site/src/changelog.md'}

def main():
    phase = p.Phase('docs-gen')
    code = 1
    try:
        phase.prepare()
        phase.receipt['docs_driver_sha256'] = p.g.digest(Path(__file__))
        phase.run('gen',[str(p.g.TARGET/'debug/xtask.exe'),'gen'],timeout=600)
        phase.run('docs-check',[str(p.g.TARGET/'debug/xtask.exe'),'check'],timeout=600)
        phase.run('trace',['traceable-reqs','check','--json'],timeout=600)
        phase.receipt['status'] = 'passed'
        code = 0
    except BaseException as error:
        phase.receipt.update(status='refused-or-failed',error=repr(error))
    finally:
        try:
            phase.receipt['source_after'] = phase.source('after')
            before = json.loads(Path(phase.receipt['source_before']['source_map']).read_bytes())
            after = json.loads(Path(phase.receipt['source_after']['source_map']).read_bytes())
            changed = [k for k in before.keys() | after.keys() if before.get(k) != after.get(k)]
            phase.receipt['source_changes'] = changed
            if set(changed) - ALLOWED:
                raise RuntimeError('generator changed undeclared source: '+repr(changed))
            phase.receipt['processes_after'] = p.g.census()
            phase.receipt['free_bytes_end'] = p.g.shutil.disk_usage(p.g.TREE).free
            phase.receipt['target_bytes_end'] = p.g.target_bytes()
        except BaseException as error:
            phase.receipt.update(status='refused-or-failed',finalization_error=repr(error))
            code = 1
        phase.receipt.update(end=p.g.now(),driver_exit=code)
        phase.flush()
        print(phase.dir/'receipt.json')
    return code

if __name__ == '__main__':
    sys.exit(main())
