import asyncio,json,sys
from pathlib import Path
sys.path.insert(0,str(Path.cwd()/'server'))
from device_gateway.control.projects import ProjectRegistry
from device_gateway.control.models import Settings
from device_gateway.control.codex import CodexAdapter
from device_gateway.control.approvals import ApprovalRegistry
from device_gateway.control.user_input import UserInputs
from device_gateway.control.pi import PiAdapter
from device_gateway.integrations.pi import PiSessionRegistry
async def main():
 p=ProjectRegistry('.cache/native-probe/projects.json');project=p.get('probe');approvals=ApprovalRegistry();inputs=UserInputs();c=CodexAdapter(p,approvals=approvals,user_inputs=inputs)
 try:
  result=await c.create_session(project,'Reply exactly NATIVE_READY without tools.',Settings(model='gpt-5.6-luna',effort='low',permissions='user'),lambda sid:None);sid=result['session_id']
  async def settle():
   for _ in range(120):
    session=await c.get_session(sid)
    if session.state in ('DONE','FAILED'):return session.state
    await asyncio.sleep(.5)
   return 'TIMEOUT'
  assert await settle()=='DONE'
  await c.call('turn/start',{'threadId':sid,'collaborationMode':{'mode':'plan','settings':{'model':'gpt-5.6-luna','reasoning_effort':'low','developer_instructions':None}},'input':[{'type':'text','text':'Use the native request_user_input tool now. Ask two questions: choose Red or Blue; then choose One, Two, Three with Other allowed. Wait for the actual answers, then respond NATIVE_INPUT_DONE. Do not run commands or modify files.'}]})
  for _ in range(120):
   if inputs.pending():break
   await asyncio.sleep(.5)
  if not inputs.pending():raise RuntimeError('No native user-input request received')
  entry=inputs.pending()[0];print('REAL Codex native input',json.dumps(inputs.wire(entry),ensure_ascii=False),flush=True)
  while entry['state']=='PENDING':
   q=entry['questions'][entry['index']];rid=entry['request_id'];inputs.presentations['probe']=(rid,q['id'])
   answer='native free text answer' if q.get('isOther') or not q.get('options') else q['options'][0]['label']
   assert inputs.resolve('probe',rid,q['id'],answer)
  print('Native input completed',await settle(),flush=True)
  await c.call('thread/settings/update',{'threadId':sid,'approvalPolicy':'on-request','approvalsReviewer':'user'})
  await c.call('turn/start',{'threadId':sid,'collaborationMode':{'mode':'default','settings':{'model':'gpt-5.6-luna','reasoning_effort':'low','developer_instructions':None}},'input':[{'type':'text','text':'For a native approval bridge test, call exec_command to run exactly printf NAVIGATOR_APPROVAL_OK with sandbox_permissions require_escalated and justification Native approval bridge test. Await the native request approval before executing. Do not do any other commands or writes.'}]})
  for _ in range(120):
   if approvals.list_pending():break
   await asyncio.sleep(.5)
  if not approvals.list_pending():raise RuntimeError('No native approval request received')
  approval=approvals.list_pending()[0];print('REAL Codex native approval',approval.choices,approval.detail,flush=True)
  if 'accept' not in approval.choices:raise RuntimeError('No one-shot approval offered')
  assert approvals.resolve(approval.approval_id,'accept')
  print('Native approval completed',await settle(),flush=True)
 finally:await c.close()
 pi=PiAdapter(p,PiSessionRegistry(),user_inputs=inputs)
 try:
  models=await pi.creation_models(project);model=models[0]['id'];print('Pi model',model,flush=True)
  created=[]
  result=await pi.create_session(project,'Reply exactly PI_NATIVE_READY. Do not use tools.',Settings(model=model),created.append,operation_id='native-probe-pi')
  print('REAL Pi create+first input',result,flush=True)
  for _ in range(120):
   settings=await pi.get_settings(result['session_id'])
   session=await pi.get_session(result['session_id'])
   if session.state not in ('RUNNING','WAITING_INPUT'):break
   await asyncio.sleep(.5)
  print('Pi readback',settings['model'],settings['effort'],flush=True)
 finally:await pi.close()
asyncio.run(main())
