"""One parent writer publishes JSON and a local-file-compatible report.html sidecar.""" from __future__ import annotations import json import os from datetime import datetime from pathlib import Path from ml_porosity.paths import outputs_dir def write_json(path: Path, data: dict) -> None: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + f'.{os.getpid()}.tmp') tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False, default=str), encoding='utf-8') tmp.replace(path) def update(**values) -> dict: root = outputs_dir() / 'p3' path = root / 'progress.json' old = json.loads(path.read_text(encoding='utf-8')) if path.exists() else {} if 'tasks' in values: values['tasks'] = old.get('tasks', {}) | values['tasks'] state = old | values | {'updated': datetime.now().astimezone().isoformat(timespec='seconds')} write_json(path, state) js = root / 'progress.js' tmp = js.with_suffix('.js.tmp') tmp.write_text('window.ML_POROSITY_P3 = ' + json.dumps(state, ensure_ascii=False, default=str) + ';\n', encoding='utf-8') tmp.replace(js) return state