"""Execute the published local comparison checks; synthetic mutations stay temporary.
Usage: python3 verify_release_compare.py release_compare.py manifest.json snapshots published-output review.json
"""
import copy, hashlib, importlib.util, json, platform, subprocess, sys, tempfile
from pathlib import Path

script, manifest, snapshots, published, report=map(Path,sys.argv[1:])
spec=importlib.util.spec_from_file_location('release_compare',script)
mod=importlib.util.module_from_spec(spec);spec.loader.exec_module(mod)
m=json.loads(manifest.read_text());a,b=[json.loads((snapshots/m[k]['file']).read_text()) for k in ['before','after']]
checks=[]
def check(name,condition,detail):
    if not condition:raise AssertionError(name)
    checks.append(dict(check=name,result='pass',detail=detail))
def run(out,root=snapshots):
    return subprocess.run([sys.executable,str(script.resolve()),str(manifest.resolve()),str(root.resolve()),str(out)],capture_output=True,text=True)
with tempfile.TemporaryDirectory() as td:
    tmp=Path(td)
    for name in ['run1','run2']:
        r=run(tmp/name);assert r.returncode==0,r.stderr
    files=['changes.json','counts.csv','changed-records.csv','chart.svg','receipt.json','metadata-changes.json']
    check('two fresh runs and published artifacts agree',all((tmp/'run1'/f).read_bytes()==(tmp/'run2'/f).read_bytes()==(published/f).read_bytes() for f in files),'Two fresh Python subprocesses; byte equality for all six outputs.')
    result=json.loads((published/'changes.json').read_text()); aa={r['id']:r for r in a['records']};bb={r['id']:r for r in b['records']}
    check('membership and full record preservation',result['counts']['before']==len(aa) and result['counts']['after']==len(bb) and {r['id']:r for r in result['added']}=={k:bb[k] for k in bb.keys()-aa.keys()} and all(aa[k]==bb[k] for k in result['unchanged_ids']),'Reconcile counts and unchanged IDs to input records; added records retain all fields.')
    metadata=copy.deepcopy(a);metadata['scope']='Synthetic changed scope';delta=mod.compare(a,metadata)
    check('metadata-only edit distinguished from record edits',delta['counts']['unchanged']==len(a['records']) and all(delta['counts'][k]==0 for k in ['added','removed','changed']) and delta['metadata_changes']==[dict(field='scope',before_present=True,before=a['scope'],after_present=True,after='Synthetic changed scope')],'Synthetic scope edit changes metadata only; no invented record addition.')
    changed=copy.deepcopy(a);field='evidence_status' if 'evidence_status' in a['records'][0] else 'ai_involvement';old=changed['records'][0][field];changed['records'][0][field]='synthetic altered label'
    change=mod.compare(a,changed)
    check('deliberate evidence-label change detected',change['counts']['changed']==1 and change['changed'][0]['fields']==[dict(field=field,before_present=True,before=old,after_present=True,after='synthetic altered label')],'Synthetic in-memory mutation; full before/after field values retained. Not published incident data.')
    removed=copy.deepcopy(a);gone=removed['records'].pop(0);change=mod.compare(a,removed)
    check('deliberate removal detected',change['counts']['removed']==1 and change['removed']==[gone],'Synthetic removal; original ID and full record retained in comparison.')
    reordered=copy.deepcopy(a);reordered['records'].reverse();change=mod.compare(a,reordered)
    check('record reordering creates no field change',change['counts']['unchanged']==len(a['records']) and all(change['counts'][k]==0 for k in ['added','removed','changed']),'Declared semantic rule ignores only record-list order; exact input hashes still differ if bytes change.')
    duplicate=copy.deepcopy(a);duplicate['records'].append(copy.deepcopy(duplicate['records'][0]));rejected=False
    try:mod.compare(a,duplicate)
    except ValueError as e:rejected='duplicate ID' in str(e)
    check('duplicate ID rejected',rejected,'Duplicate IDs cannot be silently overwritten during record matching.')
    bad=tmp/'bad-input';bad.mkdir()
    for key in ['before','after']:
        filename=m[key]['file'];(bad/filename).write_bytes((snapshots/filename).read_bytes())
    p=bad/m['after']['file'];p.write_bytes(p.read_bytes()+b'\n');out=tmp/'bad-output';r=run(out,bad)
    check('changed input bytes rejected before output',r.returncode!=0 and 'hash mismatch' in r.stderr and not out.exists(),'Appended one newline to after snapshot; original trusted manifest unchanged.')
    original={f:(tmp/'run1'/f).read_bytes() for f in files};r=run(tmp/'run1')
    check('existing output preserved',r.returncode!=0 and all((tmp/'run1'/f).read_bytes()==original[f] for f in files),'Attempt to reuse existing output directory rejected; prior bytes unchanged.')
out=dict(date='2026-11-01',scope='Local incident-release comparison; no AI inference or live business action.',runtime=dict(python=platform.python_version(),platform=platform.platform()),script_sha256=mod.digest(script.read_bytes()),verifier_sha256=mod.digest(Path(__file__).read_bytes()),manifest=m,checks=checks,limitations=['Does not verify source truth or legal status.','Does not test production permissions, replay, human exception handling or independent evaluator protection.','No cross-platform repeatability claim.'])
report.write_text(json.dumps(out,ensure_ascii=False,indent=2)+'\n');print(f'{len(checks)} checks passed')
