"""Recheck published subset exports and failure controls. Python 3.9+; no network.
Usage: python3 verify_subset.py tracker SNAPSHOT subset.py membership.csv PUBLISHED_FOLDER review.json
CC BY 4.0. Credit Hallucination-Free and Deterministic AI; identify changes.
"""
import csv
import hashlib
import json
import platform
import subprocess
import sys
import tempfile
from pathlib import Path

def check(ok, message):
 if not ok: raise ValueError(message)

def main():
 dataset,snapshot,script,membership,published,out=sys.argv[1:]
 snapshot,script,membership,published,out=map(Path,[snapshot,script,membership,published,out])
 filters=['record_type=documented incident','ai_involvement=confirmed'] if dataset=='tracker' else ['evidence_status=finding']
 empty=['ai_involvement=admitted','failure_type=false claim'] if dataset=='tracker' else ['category=deception','evidence_status=allegation']
 checks=[]
 def passed(name,evidence): checks.append({'check':name,'outcome':'pass','evidence':evidence})
 def run(source,dest,conditions):
  args=[sys.executable,str(script.resolve()),dataset,str(source.resolve()),str(dest)]
  for condition in conditions: args += ['--where',condition]
  return subprocess.run(args,capture_output=True,text=True)
 with tempfile.TemporaryDirectory() as temp:
  base=Path(temp)
  for name,conditions in [('first',filters),('second',list(reversed(filters)))]:
   r=run(snapshot,base/name,conditions);check(r.returncode==0,r.stderr)
  names=['records.csv','records.json','selection.json']
  check(all((base/'first'/n).read_bytes()==(base/'second'/n).read_bytes()==(published/n).read_bytes() for n in names),'Fresh outputs differ')
  passed('Fresh exports and filter-order invariance','Two fresh subprocesses matched all three published files byte for byte.')
  receipt=json.loads((base/'first/selection.json').read_text())
  # Independently select through the prior published membership CSV, then compare full raw records.
  members=list(csv.DictReader(membership.open()))
  if dataset=='tracker': expected=sorted(r['id'] for r in members if r['record_type']=='documented incident' and r['ai_involvement']=='confirmed')
  else: expected=sorted(r['id'] for r in members if r['evidence_status']=='finding')
  check(receipt['selected_ids']==expected and len(expected)==(23 if dataset=='tracker' else 24),'Membership selection mismatch')
  check(receipt['source_count']==len(members),'Denominator mismatch')
  original={r['id']:r for r in json.loads(snapshot.read_text())['records']}
  selected=json.loads((base/'first/records.json').read_text())['records']
  selected_csv=list(csv.DictReader((base/'first/records.csv').open()))
  check(selected==[original[i] for i in expected] and selected_csv==selected,'Full record fields lost')
  check(all(hashlib.sha256((base/'first'/n).read_bytes()).hexdigest()==h for n,h in receipt['output_sha256'].items()),'Output hash mismatch')
  passed('Membership, denominator, full record and output-hash checks',str(len(expected))+' selected IDs agree with the earlier membership index; JSON and CSV retain every original field.')
  r=run(snapshot,base/'empty',empty);check(r.returncode==0,r.stderr)
  e=json.loads((base/'empty/selection.json').read_text());check(e['selected_count']==0 and not e['selected_ids'],'Expected valid empty selection')
  check(list(csv.DictReader((base/'empty/records.csv').open()))==[],'Empty CSV has rows')
  passed('Valid empty selection','Known labels with no intersecting records returned zero, with receipt and CSV header.')
  for name,conditions in [('unknown-field',['typo=value']),('unknown-value',[filters[0].split('=')[0]+'=TYPO'])]:
   r=run(snapshot,base/name,conditions);check(r.returncode!=0 and not (base/name).exists(),'Invalid filter accepted')
  passed('Invalid filters rejected','Unknown field and unknown value each failed before output creation.')
  altered=base/'changed.json';altered.write_bytes(snapshot.read_bytes()+b'\n')
  r=run(altered,base/'changed-output',filters);check(r.returncode!=0 and not (base/'changed-output').exists(),'Changed snapshot accepted')
  passed('Changed input bytes rejected','One added newline leaves parsed JSON unchanged but failed the pinned-byte check before output creation.')
  before={n:(base/'first'/n).read_bytes() for n in names}
  r=run(snapshot,base/'first',filters);check(r.returncode!=0 and all((base/'first'/n).read_bytes()==b for n,b in before.items()),'Prior output overwritten')
  passed('Existing output preserved','Rerun into an existing directory failed and preserved all three prior files.')
 result={'review_date':'2026-10-17','dataset':dataset,'scope':'Local frozen-data selection only; no AI inference, source truth, production approval or external action tested.','python':platform.python_version(),'platform':platform.system()+' '+platform.machine(),'script_sha256':hashlib.sha256(script.read_bytes()).hexdigest(),'verifier_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),'snapshot_sha256':hashlib.sha256(snapshot.read_bytes()).hexdigest(),'membership_sha256':hashlib.sha256(membership.read_bytes()).hexdigest(),'checks':checks}
 out.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n');print(dataset+': '+str(len(checks))+' checks passed')
if __name__=='__main__': main()
