/**
 * Registers MCP tools contributed by installed marketplace packs.
 *
 * Scans for packs with mcpEntrypoint in their manifest. For each,
 * imports the entrypoint and calls its registerMcpTools(mcp) function.
 */
import * as path from 'path';
import { listInstalledPackages } from '../marketplace/registry.js';
import { VERSION } from '../generated-version.js';
function compareVersions(a, b) {
    const pa = a.split('.').map(Number);
    const pb = b.split('.').map(Number);
    for (let i = 0; i < 3; i++) {
        const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
        if (diff !== 0)
            return diff;
    }
    return 0;
}
function checkPackEngineVersion(pkg) {
    const required = pkg.manifest.engineVersion;
    if (!required)
        return;
    const minVersion = required.replace(/^>=?\s*/, '');
    const current = VERSION;
    if (compareVersions(current, minVersion) < 0) {
        process.stderr.write(`\x1b[33mWarning: ${pkg.name} requires flow-weaver >=${minVersion} but ${current} is installed.\x1b[0m\n`);
        process.stderr.write(`\x1b[33mRun: npm install @synergenius/flow-weaver@latest\x1b[0m\n`);
    }
}
export async function registerPackMcpTools(mcp) {
    const projectDir = process.cwd();
    let packages;
    try {
        packages = await listInstalledPackages(projectDir);
    }
    catch {
        return;
    }
    for (const pkg of packages) {
        const manifest = pkg.manifest;
        if (!manifest.mcpEntrypoint || !manifest.mcpTools?.length)
            continue;
        checkPackEngineVersion(pkg);
        const entrypointPath = path.join(pkg.path, manifest.mcpEntrypoint);
        try {
            const mod = await import(entrypointPath);
            if (typeof mod.registerMcpTools === 'function') {
                await mod.registerMcpTools(mcp);
            }
        }
        catch (err) {
            const msg = err instanceof Error ? err.message : String(err);
            // Log to stderr so it doesn't interfere with MCP JSON-RPC on stdout
            process.stderr.write(`[mcp] Failed to load pack tools from ${pkg.name}: ${msg}\n`);
        }
    }
}
//# sourceMappingURL=pack-tools.js.map