#!/usr/bin/env python3
"""@librarian — bullpen worker: rule-dispatched (no LLM). Body IS the recall query.
Searches fleet memory (apropos) + the room's own /bullpen artifacts.
  bullpen-librarian            # room loop (systemd)
  bullpen-librarian --once "NPU aperture"
"""
import json, os, re, subprocess, sys
sys.path[:0] = [p for p in (os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "lib"), "/usr/local/lib/bullpen") if os.path.isdir(p)]
import bullpen_worker as bw
import bullpen_mem as mem

MAXBODY = 800

def _bullpen_recall(query):
    hits = mem.recall(query, ns="/bullpen", k=3)
    return "\n".join("- " + " ".join(str(h.get("text", "")).split())[:160] for h in hits)

SCORE_MIN = 0.5   # below this, a "hit" is just the nearest fleet node, not a real match

def _keep_relevant(text):
    out = []
    for line in text.splitlines():
        m = re.search(r"\(score (\d+\.\d+)\)", line)
        if m:
            if float(m.group(1)) >= SCORE_MIN:
                out.append(line)
        elif line.strip() and not line.strip().startswith("bullpen artifacts"):
            out.append(line)   # keep non-scored context lines
    return "\n".join(out).strip()

def search(query):
    parts = []
    a = _keep_relevant(bw.lmcp("apropos", query=query).stdout)   # broad fleet knowledge
    if a: parts.append(a)
    b = _keep_relevant(_bullpen_recall(query))                  # the room's own fetched artifacts
    if b: parts.append("bullpen artifacts:\n" + b)
    return "\n".join(parts).strip()

def dispatch(msg):
    res = search(msg.get("body", ""))
    if not res:
        return ("no relevant fleet memory for that. (I recall the fleet's ops/kernel/infra "
                "knowledge base + pages @callboy fetched — I'm not a general/web search. "
                "For the web ask @callboy; for news use news-de.)")
    return res[:MAXBODY].rstrip() + " …" if len(res) > MAXBODY else res

if __name__ == "__main__":
    if len(sys.argv) > 2 and sys.argv[1] == "--once":
        print(search(sys.argv[2]))
    else:
        bw.run("librarian", dispatch,
               online="librarian online — recalls FLEET ops/kernel/infra memory (not general/web). @librarian <topic>", ack="…searching")
