import { getLogger } from "../util/logger.js";
import { datasourceSdkClassByType, builtInIntegrationTypes } from "./const.js";
import llmobs from "./llmobs/index.js";
export const getIntegrationErrorsInFiles = llmobs.wrap({ kind: "task", name: "getIntegrationErrorsInFiles" }, (files, availableIntegrations) => {
    const logger = getLogger();
    const availableIntegrationIds = new Set(availableIntegrations
        .map((integration) => integration.id)
        .filter(Boolean));
    logger.debug("[ai-service] Debug - availableIntegrations:", availableIntegrations);
    const integrationErrors = {};
    for (const file of files) {
        const integrationReferences = extractIntegrationReferences(file.content);
        for (const ref of integrationReferences) {
            if (!availableIntegrationIds.has(ref.id)) {
                if (!integrationErrors[file.filePath]) {
                    integrationErrors[file.filePath] = [];
                }
                integrationErrors[file.filePath].push(`Integration ID "${ref.id}" not found. Use searchIntegrations to find valid integration IDs.`);
            }
        }
    }
    return Object.keys(integrationErrors).length > 0 ? integrationErrors : null;
});
function extractIntegrationReferences(code) {
    const references = [];
    const lines = code.split("\n");
    for (let i = 0; i < lines.length; i++) {
        const line = lines[i];
        if (!line)
            continue;
        // Look for patterns like: new IntegrationClassName("step_name", "integration-id")
        const integrationPattern = /new\s+(\w+)\s*\(\s*["']([^"']+)["']\s*,\s*["']([^"']+)["']/g;
        const matches = Array.from(line.matchAll(integrationPattern));
        for (const match of matches) {
            const className = match[1];
            const stepName = match[2];
            const id = match[3];
            // We can use some integrations all of the time
            if (builtInIntegrationTypes.includes(id)) {
                continue;
            }
            // Check if this className is a known integration SDK class
            if (className &&
                stepName &&
                id &&
                Object.values(datasourceSdkClassByType).includes(className)) {
                references.push({
                    id,
                    className,
                    filePath: "generated-file", // This will be updated by the caller
                    line: i + 1,
                });
            }
        }
    }
    return references;
}
//# sourceMappingURL=integration-validator.js.map