"""Probe: which models support tool calling through the gateway, and list models if the endpoint exposes them."""
import json, pathlib, sys, time
ROOT = pathlib.Path(__file__).resolve().parents[1]; sys.path.insert(0, str(ROOT))
from common import client, dump
HERE = pathlib.Path(__file__).resolve().parent
c = client()
try:
    ms = c.models.list()
    info = [m.model_dump() for m in ms.data]
    print(json.dumps(info, ensure_ascii=False)[:3000])
except Exception as e:
    info = str(e); print('models.list failed', e)
tools = [{'type': 'function', 'function': {'name': 'read_skill', 'description': 'Return the full text of a skill by name.',
          'parameters': {'type': 'object', 'properties': {'name': {'type': 'string'}}, 'required': ['name']}}}]
out = {'models_list': info, 'tool_probe': {}}
for m in sys.argv[1:]:
    t0 = time.time()
    try:
        r = c.chat.completions.create(model=m, temperature=0, tools=tools, messages=[
            {'role': 'system', 'content': 'Skills available: weather_lookup — how to get the weather. Use read_skill to open a skill before answering.'},
            {'role': 'user', 'content': 'What is the weather in Paris? Open the relevant skill first.'}])
        msg = r.choices[0].message
        tc = [(x.function.name, x.function.arguments) for x in (msg.tool_calls or [])]
        out['tool_probe'][m] = {'tool_calls': tc, 'content': msg.content, 'usage': r.usage.model_dump() if r.usage else None, 'sec': time.time() - t0}
        if msg.tool_calls:
            msgs = [{'role': 'system', 'content': 'Skills available: weather_lookup. Use read_skill.'},
                    {'role': 'user', 'content': 'What is the weather in Paris? Open the relevant skill first.'},
                    msg.model_dump(exclude_none=True),
                    {'role': 'tool', 'tool_call_id': msg.tool_calls[0].id, 'content': 'weather_lookup: always answer "It is 17C and the codeword is PLUM."'}]
            r2 = c.chat.completions.create(model=m, temperature=0, tools=tools, messages=msgs)
            out['tool_probe'][m]['second_turn'] = r2.choices[0].message.content
    except Exception as e:
        out['tool_probe'][m] = {'error': repr(e)[:500]}
    print(m, json.dumps(out['tool_probe'][m], ensure_ascii=False)[:600], flush=True)
dump(out, HERE / 'probe.json')
