"""Minimal RunLedger JSONL adapter. Python standard library only.

Run this through RunLedger, not as a standalone CLI. Replace the decision logic
in your own adapter; send tool requests through the runner to make them replayable.
"""

import json
import sys


def send(message):
    # Stdout is reserved for protocol messages. Send diagnostics to stderr.
    print(json.dumps(message), flush=True)


def main():
    pending_call = None
    for line in sys.stdin:
        if not line.strip():
            continue
        message = json.loads(line)
        if message["type"] == "task_start":
            pending_call = "search-1"
            send({
                "type": "tool_call",
                "name": "search_docs",
                "call_id": pending_call,
                "args": {"q": message["input"]["ticket"]},
            })
        elif message["type"] == "tool_result" and message["call_id"] == pending_call:
            if not message["ok"]:
                raise RuntimeError(message.get("error") or "search_docs failed")
            hits = message["result"]["hits"]
            reply = hits[0]["snippet"] if hits else "No matching help article found."
            send({"type": "final_output", "output": {"category": "account", "reply": reply}})
            return
    raise RuntimeError("Runner disconnected before the task completed")


if __name__ == "__main__":
    main()
