import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import { registerAllTools } from "./tools/registry.js";
import { buildLibraryMapInstructions } from "./lib/library-map.js";
import { Env } from "./types.js";

export async function handleMcpRequest(
  request: Request,
  env: Env,
  orgNamespace: string,
  partnerToken: string,
): Promise<Response> {
  // library-map SDD M4（design §4/§6）：連線時把全館藏書地圖嵌進 server instructions，
  // session 一開就知道館裡有哪些庫（push 零查詢）。builder 內建 timeout＋isolate TTL 快取
  //（選型理由見 lib/library-map.ts 檔頭）；任何失敗回 null → 靜默略過，絕不擋 MCP 連線（鐵律）。
  const mapInstructions = await buildLibraryMapInstructions(env);

  const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined });
  const server = new McpServer(
    { name: "arcrun-mcp-server", version: "1.0.0" },
    mapInstructions ? { instructions: mapInstructions } : undefined,
  );

  registerAllTools(server, env, orgNamespace, partnerToken);
  await server.connect(transport);

  return transport.handleRequest(request);
}
