"""Validate exported source-mask feedback without promoting it to training labels."""
from __future__ import annotations
import argparse,collections,hashlib,json
from pathlib import Path
ROOT=Path(__file__).resolve().parent.parent
BATCH=ROOT/'results/r112/source-mask-review/batch.json'
CHOICES={'unanswered','center','minus','plus','equivalent','none','unsure'}
TARGETS={'unanswered','yes','no','unsure'}
ROLES={'unknown','nonexpert','expert'}
def sha(path):
 h=hashlib.sha256()
 with Path(path).open('rb') as f:
  for chunk in iter(lambda:f.read(1024*1024),b''):h.update(chunk)
 return h.hexdigest()
def validate(payload,batch_path=BATCH):
 batch_path=Path(batch_path);batch=json.loads(batch_path.read_text());cases={x['id']:x for x in batch['cases']}
 if len(cases)!=len(batch['cases']):raise ValueError('Duplicate case in batch')
 if not isinstance(payload,dict) or payload.get('format')!='r112-source-mask-review-feedback-v1' or payload.get('batch_sha256')!=sha(batch_path) or not isinstance(payload.get('records'),list):raise ValueError('Feedback does not match this exact review batch')
 seen=set();out=[]
 for row in payload['records']:
  if not isinstance(row,dict):raise ValueError('Invalid feedback record')
  ident=row.get('id')
  if not isinstance(ident,str) or ident not in cases or ident in seen:raise ValueError('Unknown or duplicate case')
  seen.add(ident);c=cases[ident]
  if row.get('source_sha256')!=c['source_sha256'] or row.get('proposal_sha256')!=c['proposal_sha256']:raise ValueError('Source or proposal checksums do not match')
  if row.get('choice') not in CHOICES or row.get('target') not in TARGETS or row.get('role') not in ROLES or not isinstance(row.get('notes'),str) or len(row['notes'])>2000:raise ValueError('Invalid decision, role or note')
  out.append(row)
 return {'format':'r112-source-mask-feedback-validation-v1','batch_sha256':sha(batch_path),'valid_records':len(out),'choices':dict(collections.Counter(x['choice'] for x in out)),'target_observations':dict(collections.Counter(x['target'] for x in out)),'self_reported_roles':dict(collections.Counter(x['role'] for x in out)),'warning':'This validates file structure and provenance only. Feedback is not an expert adjudication, verified ground truth, or a training-label import.'}
def main():
 ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('feedback',type=Path);ap.add_argument('--batch',type=Path,default=BATCH,help='Exact review batch JSON used for the export');args=ap.parse_args();size=args.feedback.stat().st_size
 if size>5*1024*1024:raise ValueError('Feedback file exceeds 5 MB')
 print(json.dumps(validate(json.loads(args.feedback.read_text()),args.batch),indent=2))
if __name__=='__main__':main()
