"""Real streaming Ollama request, without third-party dependencies."""
import json
import sys
import time
import urllib.request

model = sys.argv[1] if len(sys.argv) > 1 else 'gpt-oss:120b-cloud'
payload = {'model': model, 'messages': [{'role': 'user', 'content': 'In no more than 60 words, describe prefill (prompt processing and KV cache) and decode (one new token using cached K/V). Use exactly three short sentences.'}],
           'stream': True, 'options': {'num_predict': 384}}
if model.startswith('gpt-oss'):
    payload['think'] = 'low'
request = urllib.request.Request('http://localhost:11434/api/chat', json.dumps(payload).encode(), {'Content-Type': 'application/json'})
started = time.perf_counter()
with urllib.request.urlopen(request, timeout=180) as response:
    for line in response:
        frame = json.loads(line)
        if frame.get('error'):
            raise RuntimeError(frame['error'])
        print(frame.get('message', {}).get('content', ''), end='', flush=True)
        if frame.get('done'):
            print(f'\n\nClient elapsed: {time.perf_counter()-started:.2f}s')
            for key in ['prompt_eval_count', 'eval_count', 'prompt_eval_duration', 'eval_duration', 'total_duration']:
                print(f'{key}: {frame.get(key, "not reported")}')
