import csv, hashlib, json, pathlib, sys
mode, directory, argument, output = sys.argv[1:]
root = pathlib.Path(directory)
raw_comments = (root/'comments.json').read_bytes()
integrity_bytes = (root/'integrity.json').read_bytes()
integrity = json.loads(integrity_bytes)
if hashlib.sha256(raw_comments).hexdigest() != integrity['comments_sha256']: raise ValueError('Comment evidence changed')
for filename,key in [('pagination.json','pagination_sha256'),('input-manifest.json','manifest_sha256')]:
if hashlib.sha256((root/filename).read_bytes()).hexdigest()!=integrity[key]: raise ValueError('Export provenance changed')
for source in integrity['sources']:
if pathlib.Path(source['file']).name!=source['file']: raise ValueError('Invalid source path')
if hashlib.sha256((root/source['file']).read_bytes()).hexdigest()!=source['sha256']: raise ValueError('Raw source changed')
records=json.loads(raw_comments);by_id={r['evidence_id']:r for r in records}
if len(by_id)!=len(records): raise ValueError('Duplicate evidence ID')
def write_new(path,value):
with pathlib.Path(path).open('x',encoding='utf-8') as f:json.dump(value,f,ensure_ascii=False,indent=2)
if mode=='prepare':
if not argument.strip(): raise ValueError('Name the brand/product in scope')
items=[{k:r[k] for k in ['evidence_id','note_id','comment_id','source_sha256']} for r in records]
for item in items:item.update(decision='unreviewed',category='',priority='',quote='',brand_context='',next_step='',reason='')
write_new(output,{'brand_scope':argument,'comments_sha256':integrity['comments_sha256'],'items':items})
print(json.dumps({'review_items':len(items),'executed_calls':0}))
elif mode=='finalize':
review_bytes=pathlib.Path(argument).read_bytes();review=json.loads(review_bytes)
brand=review.get('brand_scope');items=review.get('items')
if not isinstance(brand,str) or not brand.strip() or review.get('comments_sha256')!=integrity['comments_sha256']: raise ValueError('Wrong brand scope or evidence export')
if not isinstance(items,list) or len(items)!=len(records) or {x['evidence_id'] for x in items}!=set(by_id): raise ValueError('Review every evidence row exactly once')
queue,unrelated,context=[],[],[]
for item in items:
r=by_id[item['evidence_id']]
if any(item.get(k)!=r[k] for k in ['note_id','comment_id','source_sha256']): raise ValueError('Review belongs to another source')
decision=item.get('decision');reason=item.get('reason')
if decision not in ('relevant','unrelated','needs_context') or not isinstance(reason,str) or not reason.strip(): raise ValueError('Every decision needs a review reason')
if decision=='unrelated':
unrelated.append({'evidence_id':r['evidence_id'],'reason':reason});continue
quote=item.get('quote');next_step=item.get('next_step')
if not isinstance(quote,str) or not quote.strip() or len(quote)>500 or quote not in r['text']: raise ValueError('Use an exact short source excerpt')
if not isinstance(next_step,str) or not next_step.strip(): raise ValueError('Record the next internal verification step')
if decision=='needs_context':
context.append({'evidence_id':r['evidence_id'],'note_id':r['note_id'],'comment_id':r['comment_id'],'quote':quote,'reason':reason,'next_step':next_step});continue
if item.get('category') not in ('product','logistics','service','other') or item.get('priority') not in ('routine','priority'): raise ValueError('Choose category and human-assigned review priority')
if not isinstance(item.get('brand_context'),str) or not item['brand_context'].strip(): raise ValueError('Explain how you verified brand/product relevance from the source context')
queue.append({'evidence_id':r['evidence_id'],'note_id':r['note_id'],'comment_id':r['comment_id'],
'brand_scope':brand,'category':item['category'],'review_priority':item['priority'],
'quote':quote,'brand_context':item['brand_context'],'review_reason':reason,'next_step':next_step,
'source_file':r['source_file'],'source_sha256':r['source_sha256'],'request_id':r['request_id'],
'claim_verified':False,'contacted_anyone':False})
target=pathlib.Path(output);target.mkdir()
(target/'review-input.json').write_bytes(review_bytes)
(target/'integrity.json').write_bytes(integrity_bytes)
write_new(target/'issue-queue.json',{'brand_scope':brand,'items':queue,'needs_context':context,'unrelated':unrelated,
'coverage':{'reviewed_comments':len(records),'relevant_signals':len(queue),'unrelated':len(unrelated),'needs_context':len(context),'distinct_notes_with_signals':len({r['note_id'] for r in queue})},
'review_sha256':hashlib.sha256(review_bytes).hexdigest(),'scope':'Human-reviewed signals in the saved sample, not verified incidents, unique customers or population prevalence','executed_calls':0})
fields=['evidence_id','note_id','comment_id','brand_scope','category','review_priority','quote','brand_context','review_reason','next_step','source_file','source_sha256','request_id']
with (target/'issue-queue.csv').open('w',encoding='utf-8-sig',newline='') as f:
w=csv.DictWriter(f,fieldnames=fields);w.writeheader()
for row in queue:
cells={k:str(row[k]) for k in fields};w.writerow({k:"'"+v if v.lstrip().startswith(('=','+','-','@')) else v for k,v in cells.items()})
print(json.dumps({'signals':len(queue),'needs_context':len(context),'unrelated':len(unrelated),'executed_calls':0}))
else: raise ValueError('Use prepare EXPORT_DIR BRAND OUTPUT_JSON or finalize EXPORT_DIR REVIEW_JSON OUTPUT_DIR')