"""One local OpenAI-compatible raw-completion stream; no prompt logging."""
import argparse,json,time,urllib.request,urllib.error
from pathlib import Path

def events(lines):
    data=[]
    for raw in lines:
        line=raw.decode('utf-8').rstrip('\r\n')
        if not line:
            if data: yield '\n'.join(data);data=[]
        elif line.startswith('data:'): data.append(line[5:].lstrip())
    if data: yield '\n'.join(data)

def probe(base,model,prompt,max_tokens=64,timeout=60):
    result={'id':str(time.time_ns()),'group':'smoke','start_s':time.time(),
            'first_s':None,'end_s':None,'input_tokens':None,'output_tokens':None,
            'finish_reason':None,'error':None,'quality_pass':None}
    start_wall=result['start_s'];start=time.perf_counter();done=False
    body={'model':model,'prompt':prompt,'max_tokens':max_tokens,'temperature':0,
          'stream':True,'stream_options':{'include_usage':True}}
    request=urllib.request.Request(base.rstrip('/')+'/v1/completions',
        data=json.dumps(body).encode(),headers={'Content-Type':'application/json'})
    try:
        with urllib.request.urlopen(request,timeout=timeout) as response:
            for event in events(response):
                if event=='[DONE]': done=True;break
                item=json.loads(event)
                if item.get('error'): raise RuntimeError('server_stream_error')
                choices=item.get('choices') or []
                if choices:
                    choice=choices[0]
                    if choice.get('text') and result['first_s'] is None:
                        result['first_s']=start_wall+time.perf_counter()-start
                    if choice.get('finish_reason'): result['finish_reason']=choice['finish_reason']
                usage=item.get('usage')
                if usage:
                    result['input_tokens']=usage.get('prompt_tokens')
                    result['output_tokens']=usage.get('completion_tokens')
        if not done and result['finish_reason'] is None: result['error']='incomplete_stream'
        elif result['first_s'] is None: result['error']='no_text_output'
    except urllib.error.HTTPError as e: result['error']='http_'+str(e.code)
    except Exception as e: result['error']=type(e).__name__
    result['end_s']=start_wall+time.perf_counter()-start
    return result

if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--base-url',default='http://127.0.0.1:8000')
    p.add_argument('--model',required=True);p.add_argument('--prompt',required=True)
    p.add_argument('--max-tokens',type=int,default=64);p.add_argument('--timeout',type=float,default=60)
    p.add_argument('--output',type=Path,required=True)
    a=p.parse_args()
    if a.max_tokens<1 or a.timeout<=0:p.error('positive max-tokens and timeout required')
    row=probe(a.base_url,a.model,a.prompt,a.max_tokens,a.timeout)
    with a.output.open('a') as f:f.write(json.dumps(row,ensure_ascii=False)+'\n')
    print(json.dumps(row,ensure_ascii=False,indent=2))
    if row['error']:raise SystemExit(1)
