"""Minimal tool-calling agent: local model decides to call get_pods (real, read-only kubectl) then answers."""
import json, subprocess, urllib.request, sys
OLL = 'http://localhost:11434'
def chat(msgs, tools=None):
    body = {'model': 'qwen2.5:7b', 'messages': msgs, 'stream': False, 'options': {'temperature': 0}}
    if tools: body['tools'] = tools
    r = urllib.request.urlopen(urllib.request.Request(OLL + '/api/chat', json.dumps(body).encode(), {'Content-Type': 'application/json'}), timeout=600)
    return json.loads(r.read())['message']
TOOLS = [{'type': 'function', 'function': {'name': 'get_pods', 'description': 'List pods and their status in a Kubernetes namespace (read-only).',
          'parameters': {'type': 'object', 'properties': {'namespace': {'type': 'string'}}, 'required': ['namespace']}}}]
def get_pods(namespace):
    return subprocess.run(['kubectl', 'get', 'pods', '-n', namespace, '--as=system:serviceaccount:shop:agent-readonly'], capture_output=True, text=True).stdout
q = sys.argv[1] if len(sys.argv) > 1 else 'Is anything broken in the shop namespace?'
msgs = [{'role': 'system', 'content': 'You are an SRE assistant. Use tools to check real cluster state before answering. Be brief.'}, {'role': 'user', 'content': q}]
print('user: ' + q)
m = chat(msgs, TOOLS)
for call in m.get('tool_calls', []) or []:
    fn = call['function']; args = fn['arguments'] if isinstance(fn['arguments'], dict) else json.loads(fn['arguments'])
    print('agent -> tool call: %s(%s)' % (fn['name'], json.dumps(args)))
    out = get_pods(**args); print('tool result:'); print(out.rstrip())
    msgs += [m, {'role': 'tool', 'content': out}]
    m = chat(msgs)
print('agent: ' + m['content'].strip())
