
import difflib
import hashlib
import json
from pathlib import Path

ROOT = Path('data/1c-write-learning')
before = (ROOT / 'baseline.bin').read_bytes()
after_path = ROOT / 'after.bin'
if not after_path.exists():
    raise SystemExit('after.bin is missing; capture after state first')
after = after_path.read_bytes()

def ranges(a: bytes, b: bytes):
    sm = difflib.SequenceMatcher(None, a, b, autojunk=False)
    out = []
    for tag, i1, i2, j1, j2 in sm.get_opcodes():
        if tag != 'equal':
            out.append({'tag': tag, 'before': [i1, i2], 'after': [j1, j2], 'before_hex': a[i1:i2].hex(), 'after_hex': b[j1:j2].hex()})
    return out

report = {
    'before': {'bytes': len(before), 'sha1': hashlib.sha1(before).hexdigest()},
    'after': {'bytes': len(after), 'sha1': hashlib.sha1(after).hexdigest()},
    'delta_bytes': len(after) - len(before),
    'ranges': ranges(before, after),
}
(ROOT / 'byte_diff.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps({**report, 'ranges': report['ranges'][:20], 'range_count': len(report['ranges'])}, ensure_ascii=False, indent=2))
