"""Use the frozen board prompts and graders. Stream observation changes no grading logic."""
from pathlib import Path
from types import SimpleNamespace
import json
import sys
import time
import urllib.request
import urllib.error
import http.client

ROOT=Path(__file__).resolve().parent
BOARD=Path.home()/'kingy-board-v03'
sys.path.insert(0,str(BOARD/'harness'))
from board import run
model=sys.argv[1]
url='http://127.0.0.1:18265'
out=ROOT/'results'/model
out.mkdir(parents=True,exist_ok=True)
jobs='chart,bugfix,longdoc,landing,tracker,game,motion,videocut,tools'.split(',')
params={'temperature':0.6,'top_p':0.95,'top_k':20,'min_p':0,'repeat_penalty':1.0,'presence_penalty':0,'cache_prompt':False,'chat_template_kwargs':{'enable_thinking':False,'reasoning_effort':'off'}}
def write_row(path,item):
    with path.open('a') as f:
        f.write(json.dumps(item,ensure_ascii=False)+'\n');f.flush()
def stream(base_url,model,messages,settings,max_tokens,timeout,key=None,tools=None):
    body=dict(settings,model=model,messages=messages,max_tokens=max_tokens,stream=True,stream_options={'include_usage':True})
    if tools:body['tools']=tools
    req=urllib.request.Request(base_url.rstrip('/')+'/chat/completions',json.dumps(body).encode(),{'Content-Type':'application/json'})
    start=time.monotonic();first=visible=None;usage=timings=finish=served=None;reply=[];reason=[];calls={};done=False
    with urllib.request.urlopen(req,timeout=timeout) as response:
        for raw in response:
            if not raw.startswith(b'data:'):continue
            payload=raw[5:].strip()
            if payload==b'[DONE]':done=True;break
            e=json.loads(payload)
            if 'error' in e:raise RuntimeError(str(e['error'])[:350])
            usage=e.get('usage') or usage;timings=e.get('timings') or timings;served=e.get('model') or served
            ch=(e.get('choices') or [{}])[0];delta=ch.get('delta',{});finish=ch.get('finish_reason') or finish
            txt=delta.get('content') or '';thought=delta.get('reasoning_content') or delta.get('reasoning') or ''
            tc=delta.get('tool_calls') or []
            if first is None and (txt or thought or tc):first=time.monotonic()-start
            if visible is None and (txt or tc):visible=time.monotonic()-start
            reply.append(txt);reason.append(thought)
            for op in tc:
                call=calls.setdefault(op.get('index',0),{'type':'function','id':'','function':{'name':'','arguments':''}})
                if op.get('id'):call['id']=op['id']
                for k in ('name','arguments'):call['function'][k]+=op.get('function',{}).get(k) or ''
    if not done or not usage or not timings or not finish or served!=model:
        raise RuntimeError(f'Incomplete or mismatched response: {done=} {finish=} {served=} {bool(timings)=}')
    response=dict(reply=''.join(reply),reasoning=''.join(reason),tool_calls=[calls[k] for k in sorted(calls)],finish=finish,usage=usage,timings=timings,seconds=round(time.monotonic()-start,3),served_model=served,ttft=first,visible_ttft=visible,transport_retries=0)
    write_row(out/'timings.jsonl',{**current,**{k:v for k,v in response.items() if k not in ('reply','reasoning','tool_calls')},'reasoning_chars':len(response['reasoning'])})
    return response
current={}
def context_cases():
    # Identical texts; actual tokenizer lengths retained for each model.
    for fillers in (60,240,500,870):
        for rep,(name,other,old,new,decoy) in enumerate([('Lark','Tern',4817,3642,3652),('Moor','Vale',7241,6813,6831),('Aster','Reed',3146,2764,2746)]):
            lines=[f'[S{i:04d}] Routine archive entry {i}. The duty clerk inspected the north store, signed the register, checked both seals and returned the key at closing.' for i in range(1,fillers+1)]
            ix=[int(fillers*x) for x in (.12,.61,.89)]
            if rep==1:ix=[int(fillers*x) for x in (.04,.83,.55)]
            if rep==2:ix=[int(fillers*x) for x in (.28,.74,.94)]
            originals=[f'The original allocation for {name} was {old} units.',f'The signed correction supersedes the original allocation for {name}. Its current allocation is {new} units.',f'The current allocation for {other} is {decoy} units.']
            ids=[f'S{i+1:04d}' for i in ix]
            for i,cite,passage in zip(ix,ids,originals):lines[i]=f'[{cite}] {passage}'
            prompt='\n'.join(lines)+f'\n\nWhat is the current allocation for {name}? Return only a JSON object with keys value (integer), original and correction. Each of the last two must be an object with id (for example S0004) and quote (the complete passage verbatim, omitting the bracketed id).'
            yield fillers,rep,prompt,new,ids,originals
def run_context():
    path=out/'context.jsonl'; done={(r['fillers'],r['rep']) for r in map(json.loads,path.open())} if path.exists() else set()
    for count,rep,prompt,expected,ids,passages in context_cases():
        if (count,rep) in done:continue
        current.update(job='context',rep=rep,fillers=count)
        try:
            ans=stream(url+'/v1',model,[{'role':'user','content':prompt}],dict(params,seed=47000+rep),256,1800)
        except urllib.error.HTTPError as error:
            detail=error.read().decode(errors='replace')
            if error.code != 400 or 'context' not in detail.lower():
                raise RuntimeError(f'Invalid inference response: {error.code} {detail[:250]}') from error
            token_req=urllib.request.Request(url+'/tokenize',json.dumps({'content':prompt}).encode(),{'Content-Type':'application/json'})
            with urllib.request.urlopen(token_req,timeout=30) as token_response:
                count_raw=len(json.load(token_response)['tokens'])
            write_row(path,dict(fillers=count,rep=rep,expected=expected,expected_ids=ids[:2],value_pass=False,original_pass=False,correction_pass=False,prompt_tokens=count_raw,token_count_type='raw document and request before chat template',status='context capacity rejected',server_error=detail[:500]))
            print('context capacity rejected',count,rep,count_raw,flush=True)
            continue
        raw=ans['reply'].strip().removeprefix('```json').removeprefix('```').removesuffix('```').strip()
        try: parsed=json.loads(raw)
        except ValueError:parsed={}
        if not isinstance(parsed,dict):parsed={}
        citations=[]
        for i,k in enumerate(('original','correction')):
            cell=parsed.get(k);citations.append(isinstance(cell,dict) and str(cell.get('id','')).strip('[]')==ids[i] and cell.get('quote')==passages[i])
        record=dict(fillers=count,rep=rep,expected=expected,expected_ids=ids[:2],expected_quotes=passages[:2],value_pass=parsed.get('value')==expected,original_pass=citations[0],correction_pass=citations[1],prompt_tokens=ans['usage']['prompt_tokens'],reply=ans['reply'],seconds=ans['seconds'],ttft=ans['ttft'])
        write_row(path,record);print('context',count,rep,record['prompt_tokens'],record['value_pass'],citations,flush=True)
def suite(job_names):
    run.llm.call=stream
    args=SimpleNamespace(base_url=url+'/v1',model=model,max_tokens=4096,timeout=3600,api_key_env=None)
    donepath=out/'results.jsonl'
    done={(r['job'],r['rep']) for r in map(json.loads,donepath.open())} if donepath.exists() else set()
    for name in job_names:
        job=run.load_job(name)
        for rep in range(3):
            if (name,rep) in done:continue
            current.clear();current.update(job=name,rep=rep)
            start=time.monotonic()
            r=run.one(job,rep,args,dict(params,seed=34100+100*jobs.index(name)+rep),out,lambda row:write_row(out/'replies.jsonl',row))
            r['wall_seconds']=round(time.monotonic()-start,2)
            if r.get('check_error') and ('HTTP' in r['check_error'] or 'URLError' in r['check_error'] or 'mismatched response' in r['check_error'] or 'Connection' in r['check_error']): 
                write_row(out/'infra.jsonl',r);raise RuntimeError(r['check_error'])
            write_row(donepath,r);print(name,rep,r['passed'],r['total'],r['wall_seconds'],flush=True)
if __name__=='__main__':
    current.update(job='warmup',rep=0)
    warm=stream(url+'/v1',model,[{'role':'user','content':'Reply only with the word ready.'}],dict(params,seed=1234),64,600)
    print('warmup',warm['reply'],warm['timings'],flush=True)
    if sys.argv[2]=='priority':suite(['chart']);run_context()
    else:suite(jobs)
