#!/usr/bin/env python3
"""Read Codex native active and archived lists, emitting public fields only.
Usage: native-list.py SCRATCH_CODEX_HOME OUTPUT_JSON
"""
import subprocess,json,os,sys
from pathlib import Path
home,out=sys.argv[1:]
p=subprocess.Popen(['codex','app-server'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,text=True,env={**os.environ,'CODEX_HOME':home})
def call(i,method,params):
 p.stdin.write(json.dumps({'id':i,'method':method,'params':params})+'\n');p.stdin.flush()
 while True:
  line=p.stdout.readline()
  if not line:raise RuntimeError('Codex app-server closed')
  d=json.loads(line)
  if d.get('id')==i:
   if 'error' in d:raise RuntimeError('Native list failed')
   return d['result']
try:
 call(1,'initialize',{'clientInfo':{'name':'evidence','version':'1.0'}})
 result={}
 for i,archived in enumerate([False,True],2):
  d=call(i,'thread/list',{'archived':archived,'limit':100})
  result['archived' if archived else 'active']=[{'id':r['id'],'source':r.get('source')} for r in d['data']]
 Path(out).write_text(json.dumps(result,indent=2)+'\n')
 print(json.dumps(result,indent=2))
finally:p.terminate();p.wait()
