import json,random,statistics,subprocess,time,uuid
from pathlib import Path
QUERIES=[
 'take and save a single utility customer payment',
 'open payment window batch',
 'apply a postmark date to utility payment',
 'void posted miscellaneous AR payment by Pay ID',
 'reverse one NJ tax payment and assess NSF fee',
 'create miscellaneous AR quick entry invoice',
 'apply customer overpayment to open invoices',
 'run high low meter exception report',
 'run utility billing register before printing',
 'open utility account work order and add notes',
 'create standard payroll time entries',
 'calculate payroll budget distribution',
 'set up employee direct deposit',
 'update employee base salary rate',
 'create purchase order quick entry',
 'approve received PO lines for payment',
 'create recurring GL batch',
 'auto balance multi fund journal entry',
 'review requisition setup and listing parameters',
 'map miscellaneous payment code to budget account',
]
OUT=Path('C:/MCSJAgent/foster-workflow-catalog/benchmarks');OUT.mkdir(parents=True,exist_ok=True)
random.Random(260711).shuffle(QUERIES)
rows=[]
for i,q in enumerate(QUERIES):
    live=(i%5==0)
    cmd=['python','C:/MCSJAgent/mcsj-speed-prime.py',q,'--limit','3']
    if not live: cmd.append('--no-state')
    t=time.perf_counter(); p=subprocess.run(cmd,capture_output=True,text=True,timeout=12); wall=round((time.perf_counter()-t)*1000,1)
    try:d=json.loads(p.stdout)
    except Exception:d={}
    matches=d.get('matches',[])
    top=matches[0] if matches else {}
    rows.append({'n':i+1,'query':q,'live_state':live,'exit':p.returncode,'wall_ms':wall,'reported_ms':d.get('total_ms'),'top_task':top.get('task'),'top_source':top.get('source'),'top_score':top.get('score'),'registry_id':top.get('registry_id'),'curated':top.get('curated',False),'matched':bool(matches)})
vals=[r['wall_ms'] for r in rows]; lookup=[r['wall_ms'] for r in rows if not r['live_state']]; livevals=[r['wall_ms'] for r in rows if r['live_state']]
def pct(a,p):
    if not a:return None
    s=sorted(a);return s[min(len(s)-1,max(0,int((len(s)-1)*p)))]
summary={'run_id':str(uuid.uuid4()),'queries':len(rows),'all_exit_0':all(r['exit']==0 for r in rows),'all_matched':all(r['matched'] for r in rows),'all_priority_correct':all(r['curated'] and r['registry_id'] for r in rows),'wall_ms':{'p50':statistics.median(vals),'p95':pct(vals,.95),'max':max(vals)},'lookup_only_ms':{'p50':statistics.median(lookup),'p95':pct(lookup,.95),'max':max(lookup)},'lookup_plus_live_ms':{'p50':statistics.median(livevals),'p95':pct(livevals,.95),'max':max(livevals)},'rows':rows}
path=OUT/f"prime-{summary['run_id']}.json";path.write_text(json.dumps(summary,indent=2),encoding='utf-8')
(OUT/'latest.json').write_text(json.dumps(summary,indent=2),encoding='utf-8')
print(json.dumps({'artifact':str(path).replace('\\','/'),'queries':summary['queries'],'all_exit_0':summary['all_exit_0'],'all_matched':summary['all_matched'],'all_priority_correct':summary['all_priority_correct'],'wall_ms':summary['wall_ms'],'lookup_only_ms':summary['lookup_only_ms'],'lookup_plus_live_ms':summary['lookup_plus_live_ms']},indent=2))
