#!/usr/bin/env bun
import { createInterface } from "node:readline";
import { createFrameworkMcpServer } from "./index.ts";

export async function runMcpStdio(root = process.cwd()): Promise<void> {
  const server = createFrameworkMcpServer(root);
  const lines = createInterface({ input: process.stdin, terminal: false });
  for await (const line of lines) {
    if (!line.trim()) continue;
    let message: unknown;
    try {
      message = JSON.parse(line);
    } catch {
      process.stdout.write(
        `${JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } })}\n`,
      );
      continue;
    }
    const response = await server.handle(message);
    if (response) process.stdout.write(`${JSON.stringify(response)}\n`);
  }
}

if (import.meta.main) {
  const root = process.argv.find((value) => value.startsWith("--root="))?.slice(7) ?? process.cwd();
  await runMcpStdio(root);
}
