#!/usr/bin/env python3
"""Antevo for Ollama: ask your own local model a question, and let it use Antevo's free tools.

Ollama runs the model on your computer. This file is the missing half: it connects to
Antevo's free engines over MCP, shows your model what tools exist, makes the tool calls
your model asks for, and hands the answers back.

    ollama pull qwen3:8b
    python3 antevo-ollama.py                       # chat
    python3 antevo-ollama.py "Is the name Nordwerk free for software?"
    python3 antevo-ollama.py --model qwen3:8b --engines executive,trademark

Python 3.9+, standard library only. Your model runs on your computer; each tool request
goes to Antevo's servers. Small models make more mistakes with tools than large ones.
Not investment advice.
"""
import argparse, json, sys, urllib.request

ENGINES = {
    "executive": "https://api.antevo.ch/mcp/executive/mcp",
    "tremor": "https://api.antevo.ch/mcp/tremor/mcp",
    "strategy": "https://api.antevo.ch/mcp/strategy/mcp",
    "trademark": "https://trademark.antevo.ch/mcp",
}
HEADERS = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream",
           "User-Agent": "antevo-ollama/1.0"}
SYSTEM = ("You answer questions using Antevo's tools. When a question needs facts, call a tool "
          "first and answer only from what the tool returned, saying the date it gives. "
          "If no tool fits, say so. Keep answers short and plain. Never give investment advice.")
CAVEAT = ("AI models can give wrong or incomplete answers, and smaller models make more mistakes. "
          "Check what the model says against Antevo's own answer before you rely on it. "
          "Not investment, legal or tax advice.")
MAX_RESULT = 6000  # characters of each tool answer passed to the model (small context windows)


class Engine:
    """A minimal MCP client: initialize once, list tools, call tools."""

    def __init__(self, url):
        self.url, self.sid, self.n = url, None, 0
        self._rpc("initialize", {"protocolVersion": "2025-06-18", "capabilities": {},
                                 "clientInfo": {"name": "antevo-ollama", "version": "1.0"}})
        self._post({"jsonrpc": "2.0", "method": "notifications/initialized"})

    def _post(self, payload):
        h = dict(HEADERS)
        if self.sid:
            h["Mcp-Session-Id"] = self.sid
        req = urllib.request.Request(self.url, json.dumps(payload).encode(), h)
        with urllib.request.urlopen(req, timeout=90) as r:
            self.sid = r.headers.get("Mcp-Session-Id") or self.sid
            return r.read().decode()

    def _rpc(self, method, params):
        self.n += 1
        raw = self._post({"jsonrpc": "2.0", "id": self.n, "method": method, "params": params})
        if "data:" in raw[:300]:  # streamable HTTP answers as server-sent events
            raw = [l[5:].strip() for l in raw.splitlines() if l.startswith("data:")][-1]
        msg = json.loads(raw)
        if "error" in msg:
            raise RuntimeError(f"{method}: {msg['error']}")
        return msg["result"]

    def tools(self):
        return self._rpc("tools/list", {})["tools"]

    def call(self, tool, args):
        res = self._rpc("tools/call", {"name": tool, "arguments": args})
        return "\n".join(c.get("text", "") for c in res.get("content", []))


def ollama(host, payload):
    req = urllib.request.Request(f"{host}/api/chat", json.dumps(payload).encode(),
                                 {"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=600) as r:
        return json.loads(r.read())["message"]


def connect(names, only_tools=None):
    """Return (ollama tool list, {tool name: engine})."""
    specs, route = [], {}
    for name in names:
        try:
            eng = Engine(ENGINES[name])
            for t in eng.tools():
                if only_tools and t["name"] not in only_tools:
                    continue
                route[t["name"]] = eng
                specs.append({"type": "function", "function": {
                    "name": t["name"], "description": (t.get("description") or "")[:600],
                    "parameters": t.get("inputSchema") or {"type": "object", "properties": {}}}})
        except Exception as e:  # one engine down should not stop the others
            print(f"  (could not reach {name}: {e})", file=sys.stderr)
    return specs, route


def compact(text):
    """Indented JSON wastes a small model's attention: send it on one line."""
    try:
        return json.dumps(json.loads(text), ensure_ascii=False, separators=(",", ":"))
    except ValueError:
        return text


def ask(question, history, specs, route, a):
    history.append({"role": "user", "content": question})
    for _ in range(a.max_steps):
        msg = ollama(a.host, {"model": a.model, "messages": history, "tools": specs,
                              "stream": False, "options": {"num_ctx": a.ctx, "temperature": 0}})
        history.append(msg)
        calls = msg.get("tool_calls") or []
        if not calls:
            return msg.get("content", "").strip()
        for c in calls:
            fn = c["function"]
            args = fn.get("arguments") or {}
            if isinstance(args, str):
                args = json.loads(args or "{}")
            print(f"  → {fn['name']} {json.dumps(args, ensure_ascii=False)}", file=sys.stderr)
            if fn["name"] not in route:
                out = f"There is no tool called {fn['name']}."
            else:
                try:
                    out = route[fn["name"]].call(fn["name"], args)
                except Exception as e:
                    out = f"The tool answered with an error: {e}"
            if a.show_answers:
                print(f"  ← Antevo answered: {compact(out)[:1500]}", file=sys.stderr)
            history.append({"role": "tool", "content": compact(out)[:MAX_RESULT],
                            "tool_name": fn["name"], "tool_call_id": c.get("id", "")})
    return "(stopped: too many tool calls in a row)"


if __name__ == "__main__":
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("question", nargs="*", help="ask once and exit; leave out to chat")
    ap.add_argument("--model", default="qwen3:8b")
    ap.add_argument("--engines", default="executive,tremor,strategy,trademark",
                    help="which free Antevo engines to connect, comma-separated")
    ap.add_argument("--tools", help="only these tools, comma-separated (fewer tools help small models)")
    ap.add_argument("--host", default="http://localhost:11434")
    ap.add_argument("--ctx", type=int, default=16384, help="context window passed to Ollama")
    ap.add_argument("--show-answers", action="store_true",
                    help="print Antevo's own answer beside the model's, to compare")
    ap.add_argument("--max-steps", type=int, default=6)
    a = ap.parse_args()

    only = set(a.tools.split(",")) if a.tools else None
    specs, route = connect([e.strip() for e in a.engines.split(",") if e.strip()], only)
    print(f"Connected {len(specs)} Antevo tools to {a.model}.", file=sys.stderr)
    print(CAVEAT, file=sys.stderr)
    history = [{"role": "system", "content": SYSTEM}]
    if a.question:
        print(ask(" ".join(a.question), history, specs, route, a))
        sys.exit(0)
    print("Ask a question (empty line to stop).", file=sys.stderr)
    while True:
        try:
            q = input("\n> ").strip()
        except EOFError:
            break
        if not q:
            break
        print("\n" + ask(q, history, specs, route, a))
