import { defineCommand, UserError } from "toolcraft";
import { S, toJsonSchema } from "toolcraft-schema";
import { resolveCommandEntries } from "./tree.js";
const getSchemasParams = S.Object({
    names: S.Array(S.String({ description: "Dotted command path." }), {
        description: "Dotted command paths to fetch schemas for."
    })
});
function indexEntriesByPath(entries) {
    const entriesByPath = new Map();
    for (const entry of entries) {
        entriesByPath.set(entry.path, entry);
    }
    return entriesByPath;
}
export function makeGetSchemasCommand({ entries, scope = ["mcp", "sdk"] }) {
    let entriesByPathPromise;
    return defineCommand({
        name: "get_schemas",
        description: "Get params schemas for commands by path.",
        scope,
        params: getSchemasParams,
        handler: async ({ params }) => {
            entriesByPathPromise ??= resolveCommandEntries(entries).then(indexEntriesByPath);
            const entriesByPath = await entriesByPathPromise;
            const missingNames = new Set();
            const result = {};
            for (const name of params.names) {
                const entry = entriesByPath.get(name);
                if (entry === undefined) {
                    missingNames.add(name);
                    continue;
                }
                result[name] = {
                    description: entry.command.description ?? "",
                    params: toJsonSchema(entry.command.params)
                };
            }
            if (missingNames.size > 0) {
                throw new UserError(`Unknown command path(s): ${[...missingNames].join(", ")}`);
            }
            return result;
        }
    });
}
