import os,json,pathlib,subprocess,threading,http.server,shutil,datetime
root=pathlib.Path(__file__).parent
run=root/datetime.datetime.now().strftime('run-%Y%m%d-%H%M%S'); run.mkdir()
config=run/'private-config';config.mkdir()
for name in ['models.json','auth.json']:
 shutil.copyfile(pathlib.Path.home()/'.pi/agent'/name,config/name)
(config/'settings.json').write_text(json.dumps({'packages':[],'enabledBuiltinExtensions':['tool-search']}))
names=['t3_thread_read','t3_thread_send','t3_thread_list','t3_project_list','t3_project_read','t3_thread_create','t3_thread_archive','t3_thread_rename','t3_project_create','t3_environment_list','t3_thread_interrupt','t3_thread_resume']
tools=[{'name':n,'description':'Synthetic evidence tool '+n,'inputSchema':{'type':'object','properties':{},'additionalProperties':False},'annotations':{'readOnlyHint':True}} for n in names]
class Handler(http.server.BaseHTTPRequestHandler):
 def log_message(self,*a):pass
 def do_POST(self):
  q=json.loads(self.rfile.read(int(self.headers['Content-Length'])))
  method=q.get('method');result={}
  if method=='initialize':result={'protocolVersion':'2025-06-18','capabilities':{'tools':{}},'serverInfo':{'name':'synthetic-evidence','version':'1'}}
  if method=='tools/list':result={'tools':tools}
  if method=='tools/call':result={'content':[{'type':'text','text':'Synthetic result'}]}
  self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(json.dumps({'jsonrpc':'2.0','id':q.get('id'),'result':result}).encode())
server=http.server.HTTPServer(('127.0.0.1',0),Handler);threading.Thread(target=server.serve_forever,daemon=True).start()
for side in ['base','head']:
 sessions=run/(side+'-sessions');sessions.mkdir(); cwd=run/(side+'-cwd');cwd.mkdir()
 env=dict(os.environ,PI_CODING_AGENT_DIR=str(config),T3_MCP_URL=f'http://127.0.0.1:{server.server_port}',T3_MCP_BEARER_TOKEN='synthetic-evidence-token',T3_PI_MCP_EXTENSION_PATH=str(root/(side+'-bridge.ts')))
 common=['pi','-p','--model','openai/gpt-6-luna','-e',str(root/(side+'-bridge.ts')),'--session-dir',str(sessions),'--no-context-files','--no-skills','--no-prompt-templates']
 for turn,prompt in enumerate(['Use tool_search to load t3_thread_read, t3_thread_send, t3_thread_list and t3_project_list, then reply loaded','Say hi.'],1):
  print(f'{side} turn {turn} started',flush=True)
  p=subprocess.run(common+(['-c'] if turn==2 else [])+[prompt],cwd=cwd,env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=240)
  (run/f'{side}-turn{turn}.txt').write_text(p.stdout)
  print(f'{side} turn {turn}: exit {p.returncode}\n{p.stdout[-1800:]}',flush=True)
 summary=[]
 for file in sessions.glob('*.jsonl'):
  for line in file.read_text().splitlines():
   e=json.loads(line);m=e.get('message',{})
   if m.get('role')=='assistant':summary.append({'role':'assistant','usage':m.get('usage'),'stopReason':m.get('stopReason'),'content':m.get('content')})
   if 'toolsRemoved' in line:summary.append(e)
 (run/f'{side}-summary.json').write_text(json.dumps(summary,indent=2))
 
 for event in summary:
  if 'usage' in event:
   u=event['usage'];print(f"assistant: uncached input={u['input']} cacheRead={u['cacheRead']} output={u['output']}",flush=True)
  else: print('toolsRemoved: '+', '.join(t['name'] for t in event['message']['toolsRemoved']),flush=True)
 print('toolsRemoved events: '+str(sum('message' in e for e in summary)),flush=True)
server.shutdown()
print('Completed',run.name,flush=True)
