#!/usr/bin/env python3
"""Check real-worker due candidate selection with an intentionally unconfigured provider.
Usage: verify-due.py CHECKOUT MEASUREMENT_DIRECTORY PORT. Run after verify-malformed.py.
No real provider may be invoked: these records refer only to missing synthetic-provider.
"""
import sys,os,json,time,sqlite3,subprocess,re,datetime
from pathlib import Path
checkout=Path(sys.argv[1]);out=Path(sys.argv[2]);port=int(sys.argv[3]);home=out/'home';db=home/'userdata/statev2.sqlite'
c=sqlite3.connect(db);reset=(datetime.datetime.now(datetime.timezone.utc)-datetime.timedelta(seconds=60)).isoformat(timespec='milliseconds').replace('+00:00','Z')
for i in range(3):
 tid=f'fixture-thread-{i:04}';rid=f'{tid}-run-15'
 raw=c.execute('SELECT payload_json FROM orchestration_v2_projection_threads WHERE thread_id=?',(tid,)).fetchone()[0];t=json.loads(raw)
 t['providerInstanceId']='synthetic-provider';t['modelSelection']['instanceId']='synthetic-provider';t['limitRecovery']=dict(runId=rid,resetAt=reset,autoResume=True,snooze=False,requestId='synthetic-due')
 c.execute('UPDATE orchestration_v2_projection_threads SET provider_instance_id=?,payload_json=? WHERE thread_id=?',('synthetic-provider',json.dumps(t),tid))
 raw=c.execute('SELECT payload_json FROM orchestration_v2_projection_runs WHERE run_id=?',(rid,)).fetchone()[0];r=json.loads(raw);r['providerInstanceId']='synthetic-provider';r['modelSelection']['instanceId']='synthetic-provider'
 c.execute('UPDATE orchestration_v2_projection_runs SET provider_instance_id=?,payload_json=? WHERE run_id=?',('synthetic-provider',json.dumps(r),rid))
 iid=f'{rid}-item-0';item=json.loads(c.execute('SELECT payload_json FROM orchestration_v2_projection_turn_items WHERE turn_item_id=?',(iid,)).fetchone()[0]);item['failure']['resetAt']=reset
 c.execute('UPDATE orchestration_v2_projection_turn_items SET payload_json=? WHERE turn_item_id=?',(json.dumps(item),iid))
c.commit();c.close()
logpath=out/'private-due-server.log';log=open(logpath,'w');p=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--host','127.0.0.1','--port',str(port),'--base-dir',str(home),'--no-browser'],cwd=checkout,env={**os.environ,'T3CODE_DEV_SEED':'0','T3CODE_TRACE_MAX_BYTES':'100000000'},stdout=log,stderr=log)
try:
 deadline=time.monotonic()+90;selected=[]
 while time.monotonic()<deadline:
  s=logpath.read_text();selected=sorted(set(re.findall(r"orchestration-v2.limit-recovery.dispatch-failed\s*\{\s*threadId: '(fixture-thread-\d+)',\s*cause: 'ThreadManagementProviderInstanceDisabledError",s)))
  if len(selected)==3:break
  if p.poll() is not None:raise RuntimeError('Server exited')
  time.sleep(.2)
 report=dict(commit=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip(),resetAt=reset,dueThreadIdsSelectedForContinuation=selected,expectedThreadIds=[f'fixture-thread-{i:04}' for i in range(3)],selectionPreserved=selected==[f'fixture-thread-{i:04}' for i in range(3)],provider='synthetic-provider (intentionally not configured)',limitation='Continuation dispatch is intentionally rejected before a provider can start; this verifies due selection, not an actual model continuation.')
 # Keep only the useful failure line, with no stack traces, filesystem paths or credentials.
 report['dispatchTranscript']=[f'{tid}: continuation rejected: synthetic-provider is disabled for fixture-project' for tid in selected]
 (out/'due-selection.json').write_text(json.dumps(report,indent=2));print(json.dumps(report,indent=2))
finally:
 p.terminate()
 try:p.wait(timeout=15)
 except subprocess.TimeoutExpired:p.kill();p.wait()
 log.close()
