# Explicit cross-process hash-seed replay and paired metadata verification.
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
from hearth.persistence import load_scene, semantic_digest
from hearth.space import Box


def verify(seed, output):
    root = Path(__file__).resolve().parents[1]
    rows = []
    with tempfile.TemporaryDirectory(dir=root / 'test', prefix='tmp-replay-') as temporary:
        for hash_seed in ('3', '8675309'):
            path = Path(temporary) / f'seed {seed} hash {hash_seed}.litematic'
            env = dict(os.environ, PYTHONHASHSEED=hash_seed)
            subprocess.run([sys.executable, str(root / 'generate.py'), '--seed', str(seed), '--output', str(path)], check=True, cwd=root, env=env)
            scene = load_scene(path)
            rows.append({'seed': seed, 'PYTHONHASHSEED': hash_seed, 'digest': semantic_digest(scene), 'bounds': [Box.enclosing(scene.blocks).lo, Box.enclosing(scene.blocks).hi], 'blocks': len(scene.blocks), 'buildings': sum(n.type == 'building.rooms' for n in scene.nodes.values())})
    if rows[0]['digest'] != rows[1]['digest'] or rows[0]['bounds'] != rows[1]['bounds']:
        raise AssertionError('Cross-process replay mismatch')
    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(json.dumps({'verified': True, 'runs': rows}, indent=2))
    return rows


if __name__ == '__main__':
    p = argparse.ArgumentParser()
    p.add_argument('--seed', type=int, default=0)
    p.add_argument('--output', type=Path, default=Path('reports/replay.json'))
    a = p.parse_args()
    verify(a.seed, a.output)
