#!/usr/bin/env node

const protocolVersion = "2024-11-05";

const write = (message) => {
  process.stdout.write(`${JSON.stringify(message)}\n`);
};

const result = (id, value) => write({ jsonrpc: "2.0", id, result: value });

const error = (id, code, message) => write({ jsonrpc: "2.0", id, error: { code, message } });

const handleMessage = (message) => {
  if (!message || typeof message !== "object" || !("id" in message)) {
    return;
  }

  switch (message.method) {
    case "initialize":
      result(message.id, {
        protocolVersion,
        capabilities: { tools: {} },
        serverInfo: { name: "lazyclaude", version: "0.1.0" },
      });
      break;
    case "ping":
      result(message.id, {});
      break;
    case "tools/list":
      result(message.id, { tools: [] });
      break;
    case "tools/call":
      error(message.id, -32601, "LazyClaude MCP exposes no callable tools in this MVP.");
      break;
    default:
      error(message.id, -32601, `Unknown method: ${message.method}`);
      break;
  }
};

let buffer = "";

process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
  buffer += chunk;
  let newlineIndex = buffer.indexOf("\n");
  while (newlineIndex !== -1) {
    const line = buffer.slice(0, newlineIndex).trim();
    buffer = buffer.slice(newlineIndex + 1);
    if (line) {
      try {
        handleMessage(JSON.parse(line));
      } catch {
        error(null, -32700, "Parse error");
      }
    }
    newlineIndex = buffer.indexOf("\n");
  }
});

process.stdin.on("end", () => {
  const line = buffer.trim();
  if (line) {
    try {
      handleMessage(JSON.parse(line));
    } catch {
      error(null, -32700, "Parse error");
    }
  }
});
