"""Read only synthetic evidence; emit counts, never raw rows/settings/auth/logs."""
import collections,json,pathlib,re,sqlite3,os
S=pathlib.Path(os.environ['RUNTIME_DIR'])
BASE=pathlib.Path(os.environ['EVIDENCE_PARENT'])
VALUES={'plaintext':'t3repro-synthetic-6f1c2a9e','marker':'[redacted T3_REPRO_SECRET]','control':'PUBLIC_CONTROL_24790','ordinary':'ORDINARY_OUTPUT_24790','completion':'COMMAND_COMPLETE_24790'}
def counts(text): return {k:text.count(v) for k,v in VALUES.items()}
def decoded(text):
 try: return json.dumps(json.loads(text),ensure_ascii=False)
 except (ValueError,TypeError): return str(text)
def db_summary(home):
 c=sqlite3.connect(f'file:{home}/userdata/statev2.sqlite?mode=ro',uri=True)
 out={}; total=0; raw=0
 for (table,) in c.execute("select name from sqlite_master where type='table' order by name").fetchall():
  rows=c.execute('SELECT * FROM "'+table.replace('"','""')+'"').fetchall()
  text='\n'.join(decoded(cell) for row in rows for cell in row if isinstance(cell,str))
  total+=len(rows); raw+=counts(text)['plaintext']
  if table in ['orchestration_events','orchestration_v2_projection_turn_items']: out[table]={'rows':len(rows),**counts(text)}
 out['all_tables']={'tables':len(c.execute("select name from sqlite_master where type='table'").fetchall()),'rows':total,'plaintext':raw}
 c.close(); return out
def log_summary(home):
 out={}; streams=collections.defaultdict(list)
 for p in sorted((home/'userdata/logs/provider').glob('*.log')):
  lines=p.read_text().splitlines()
  out[p.name]={'records':len(lines),**counts('\n'.join(lines))}
  for line in lines:
   m=re.match(r'^\[[^\]]+\] (NTIVE|CANON|ORCH): (.*)$',line)
   if not m: raise RuntimeError('Unexpected log record; inspect privately')
   streams[m[1]].append(decoded(m[2]))
 return {'files':out,'streams':{k:{'records':len(streams[k]),**counts('\n'.join(streams[k]))} for k in ['NTIVE','CANON','ORCH']}}
wire=json.loads((S/'evidence/after-wire.json').read_text())
frames=wire['frames']; wire_summary=[]
for item,fs in frames.items():
 reconstructed=''; appends=''
 for f in fs:
  if 'error' in f: raise RuntimeError('RPC subscriber failed')
  if f['kind']=='replace': reconstructed=f['text']
  else: reconstructed+=f['text']; appends+=f['text']
 wire_summary.append({'itemId':item,'frames':len(fs),'frameShapes':[{'kind':f['kind'],'running':f['running'],'length':len(f['text'])} for f in fs],'final':counts(reconstructed),'appends':counts(appends),'allFrames':counts(json.dumps(fs)),'terminal':bool(fs) and fs[-1]['running']==False})
fetched=[a['item'] for a in wire['fetched']]
projection=json.loads((S/'evidence/after-projection.json').read_text())
summary={'baseline':{'db':db_summary(BASE/'home'),'logs':log_summary(BASE/'home')},'head':{'db':db_summary(S/'after-home-1'),'logs':log_summary(S/'after-home-1'),'runStatuses':[r['status'] for r in projection['runs']],'fetchedCommands':[{'id':i['id'],'status':i['status'],'exitCode':i.get('exitCode'),'counts':counts(i.get('output',''))} for i in fetched],'wire':wire_summary}}
(S/'evidence/runtime-counts.json').write_text(json.dumps(summary,indent=2)+'\n')
print(json.dumps(summary,indent=2))

head=summary['head']
assert head['runStatuses']==['completed']
assert summary['baseline']['db']['all_tables']['plaintext']==2
assert summary['baseline']['logs']['streams']['NTIVE']['plaintext']==1
assert head['db']['all_tables']['plaintext']==0
for table in ['orchestration_events','orchestration_v2_projection_turn_items']:
    assert head['db'][table]['plaintext']==0
    assert head['db'][table]['marker']>=2
    assert all(head['db'][table][key]>=1 for key in ['control','ordinary','completion'])
native=head['logs']['streams']['NTIVE']
assert native['records']>0 and native['plaintext']==0 and native['marker']>=2
assert all(native[key]>=1 for key in ['control','ordinary','completion'])
command=next(c for c in head['fetchedCommands'] if c['counts']['completion'])
assert command['status']=='completed' and command['exitCode']==0
assert command['counts']['plaintext']==0 and command['counts']['marker']==2
stream=next(w for w in head['wire'] if w['final']['completion'])
assert stream['terminal'] and stream['allFrames']['plaintext']==0
assert stream['appends']['marker']==2
assert all(stream['appends'][key]>=1 for key in ['control','ordinary','completion'])
print('PASS: baseline leak, head successful completion, non-vacuous DB/native-log/API/live-wire checks')
