import { readFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, resolve } from "node:path";
import { z } from "zod";
import { resolveIntegrationDocumentation, } from "@superblocksteam/sdk-api/dist/integrations/documentation.js";
import { createToolFactory, ToolCategory } from "../../tools2/types.js";
const require = createRequire(import.meta.url);
const SDK_API_PACKAGE_DIRECTORY = dirname(require.resolve("@superblocksteam/sdk-api/package.json"));
const SDK_API_INTEGRATIONS_DIRECTORY = resolve(SDK_API_PACKAGE_DIRECTORY, "src/integrations");
const SDK_API_ROOT_README_PATH = resolve(SDK_API_PACKAGE_DIRECTORY, "README.md");
async function getSdkRootReadmeDocumentation() {
    try {
        return await readFile(SDK_API_ROOT_README_PATH, "utf8");
    }
    catch {
        return "";
    }
}
async function getResolvedIntegrationReadme(pluginId, pluginVersion) {
    const normalizedVersion = pluginVersion && /^\d+\.\d+\.\d+$/.test(pluginVersion)
        ? pluginVersion
        : undefined;
    try {
        return await resolveIntegrationDocumentation(pluginId, {
            pluginVersion: normalizedVersion,
            integrationsDirectory: SDK_API_INTEGRATIONS_DIRECTORY,
        });
    }
    catch (error) {
        if (error instanceof Error &&
            "code" in error &&
            error.code === "ENOENT") {
            return "";
        }
        throw error;
    }
}
async function buildSdkPluginReadmeDocumentation(pluginIds, services) {
    const rootReadme = await getSdkRootReadmeDocumentation();
    const docs = [rootReadme || ""];
    const seen = new Set();
    const resolvedPluginIds = [];
    for (const pluginId of pluginIds) {
        if (seen.has(pluginId)) {
            continue;
        }
        seen.add(pluginId);
        const pluginVersion = services.integrationStore.getPluginExecutionVersion(pluginId);
        const resolvedReadme = await getResolvedIntegrationReadme(pluginId, pluginVersion);
        if (resolvedReadme) {
            docs.push(resolvedReadme);
            resolvedPluginIds.push(pluginId);
        }
    }
    return {
        documentation: docs.join("\n\n"),
        pluginIds: resolvedPluginIds,
    };
}
function resolveRequestedPluginIds(integrationIds, pluginIds, services) {
    const requestedPluginIds = [];
    const seen = new Set();
    for (const pluginId of pluginIds) {
        if (seen.has(pluginId)) {
            continue;
        }
        seen.add(pluginId);
        requestedPluginIds.push(pluginId);
    }
    for (const integrationId of integrationIds) {
        const header = services.integrationStore.getHeader(integrationId);
        if (!header) {
            continue;
        }
        const pluginId = header.plugin.id;
        if (seen.has(pluginId)) {
            continue;
        }
        seen.add(pluginId);
        requestedPluginIds.push(pluginId);
    }
    return requestedPluginIds;
}
export const getSdkApiDocsToolFactory = createToolFactory("getSdkApiDocs", (services) => ({
    category: ToolCategory.API,
    readOnly: true,
    description: `
Retrieve SDK API implementation guidance for both generic and integration-specific API development.

This tool provides:
- Generic SDK API-building guidance when no integration IDs or plugin IDs are provided
- Integration-specific method and usage guidance when integration IDs or plugin IDs are provided
- Version-aware plugin documentation matched to the app's integration versions
- A returned list of resolved plugin IDs so you can verify coverage

ALWAYS call this tool:
- Before building or modifying SDK APIs
- When validating how to implement an API with a specific integration/plugin
- When integration IDs/plugin IDs are unavailable and you still need SDK API guidance
`,
    inputSchema: z.object({
        integrationIds: z
            .array(z.string())
            .describe("Integration IDs to include plugin-specific SDK documentation for. Pass integration IDs from the current app context.")
            .optional(),
        pluginIds: z
            .array(z.string())
            .describe("Plugin IDs to include plugin-specific SDK documentation for. Use this when you know plugin types directly.")
            .optional(),
    }),
    skipOutputLimit: (_output) => {
        return true;
    },
    execute: async ({ integrationIds = [], pluginIds = [] }) => {
        const requestedPluginIds = resolveRequestedPluginIds(integrationIds, pluginIds, services);
        if (requestedPluginIds.length === 0) {
            return {
                documentation: await getSdkRootReadmeDocumentation(),
                pluginIds: [],
            };
        }
        const { documentation, pluginIds: resolvedPluginIds } = await buildSdkPluginReadmeDocumentation(requestedPluginIds, services);
        return {
            documentation,
            pluginIds: resolvedPluginIds,
        };
    },
    getSummary: (_input, output) => {
        const pluginCount = Array.isArray(output.pluginIds)
            ? output.pluginIds.length
            : 0;
        return {
            input: "sdk docs lookup",
            output: `${pluginCount} plugin${pluginCount === 1 ? "" : "s"}`,
        };
    },
}));
//# sourceMappingURL=get-sdk-api-docs.js.map