// src/layer/KbToolInjectLayer.ts
import type { Layer, SavingEvent } from "./types.ts";

const KB_TOOL_SCHEMA = {
  name: "ftRetrieve",
  description: "Retrieve indexed tool output by query.",
  input_schema: {
    type: "object",
    properties: {
      q: { type: "string" },
      id: { type: "string" },
    },
    required: ["q"],
  },
} as const;

export class KbToolInjectLayer implements Layer {
  readonly id = "kb-tool-inject";

  init(): void {}

  outbound(body: unknown): unknown {
    if (typeof body !== "object" || body === null) return body;
    const b = body as Record<string, unknown>;
    if (!Array.isArray(b.tools)) return body;
    const tools = b.tools as unknown[];
    const alreadyPresent = tools.some(
      t => {
        if (typeof t !== "object" || t === null) return false;
        const name = (t as Record<string, unknown>).name;
        return name === "ftRetrieve" || name === "kb";
      },
    );
    if (alreadyPresent) return body;
    return { ...b, tools: [...tools, KB_TOOL_SCHEMA] };
  }

  inbound(body: unknown): unknown {
    return body;
  }

  observe(): SavingEvent[] {
    return [];
  }

  dispose(): void {}
}
