"""Reanalyze the bundled manual transcription; this does not run TrojanGYM.
Usage: python reanalyze_table.py data/trojangym_v3_table_iii_transcription.csv
"""
import csv,sys,json
from collections import Counter
with open(sys.argv[1],newline='',encoding='utf-8') as f: rows=list(csv.DictReader(f))
assert len(rows)==64
assert len({(r['model'],r['design'],r['trojan_type']) for r in rows})==64
for r in rows:
    attempts=[r['attempt_'+str(i)] for i in range(1,5)]
    terminal=next(x for x in reversed(attempts) if x!='N')
    assert terminal==r['terminal_status']
    assert all(x in {'E','X','S','N'} for x in attempts)
    if 'N' in attempts:
        first_n=attempts.index('N'); assert 'E' in attempts[:first_n]
    if 'E' in attempts:
        e=attempts.index('E'); assert all(x=='N' for x in attempts[e+1:])
counts=Counter(r['terminal_status'] for r in rows)
assert counts=={'E':23,'X':14,'S':27}
summary={'source':'TrojanGYM v3 Table III; manual transcription',
         'terminal_status_counts':dict(counts),
         'end_to_end_evasion_fraction':counts['E']/len(rows),
         'terminal_E_or_X_conditional_evasion_fraction':counts['E']/(counts['E']+counts['X']),
         'cumulative_evasion':{str(k):sum(any(r['attempt_'+str(j)]=='E' for j in range(1,k+1)) for r in rows) for k in range(1,5)},
         'limits':'Descriptive table arithmetic, not reproduction, detector sensitivity, or a representative sample.'}
print(json.dumps(summary,indent=2))
