import fs from 'node:fs';
import path from 'node:path';
import { zodToJsonSchema } from 'zod-to-json-schema';
import { mcpToolDefinitions } from '../ee/AiAgent/schemas/tools/toolDefinitions';
const SNAPSHOT_VERSION = '1';
export const getRepoRoot = () => path.resolve(__dirname, '../../../../');
export const getOutputPath = () => path.join(getRepoRoot(), 'packages/common/src/schemas/json/mcp-tools-1.0.json');
const schemaToJson = (schema) => {
    if (!schema)
        return null;
    return zodToJsonSchema(schema, { target: 'jsonSchema7' });
};
/**
 * PURE. Build the snapshot object from the MCP tool definitions. Exported for
 * testing/reuse; the IO `run` wraps it.
 */
export const buildMcpToolsSnapshot = () => {
    const tools = mcpToolDefinitions
        .map((definition) => {
        const view = definition.for('mcp');
        const entry = {
            name: view.name,
            title: view.title,
            description: view.description,
            annotations: (view.annotations ?? {}),
            inputSchema: schemaToJson(view.inputSchema),
            outputSchema: 'outputSchema' in view && view.outputSchema
                ? schemaToJson(view.outputSchema)
                : null,
        };
        return entry;
    })
        .sort((left, right) => String(left.name).localeCompare(String(right.name)));
    return {
        schemaVersion: SNAPSHOT_VERSION,
        tools,
    };
};
const sortKeysDeep = (value) => {
    if (Array.isArray(value)) {
        return value.map((item) => sortKeysDeep(item));
    }
    if (!value || typeof value !== 'object') {
        return value;
    }
    const objectValue = value;
    const sortedEntries = Object.entries(objectValue)
        .sort(([left], [right]) => left.localeCompare(right))
        .map(([key, child]) => [key, sortKeysDeep(child)]);
    return Object.fromEntries(sortedEntries);
};
const toStableJson = (value) => `${JSON.stringify(sortKeysDeep(value), null, 4)}\n`;
const run = () => {
    const checkMode = process.argv.includes('--check');
    const outputPath = getOutputPath();
    const nextContent = toStableJson(buildMcpToolsSnapshot());
    if (checkMode) {
        const currentContent = fs.readFileSync(outputPath, 'utf8');
        const normalizedCurrentContent = toStableJson(JSON.parse(currentContent));
        if (normalizedCurrentContent !== nextContent) {
            console.error('mcp-tools snapshot is out of date. Run `pnpm generate:mcp-tools-snapshot`.');
            process.exit(1);
        }
        return;
    }
    fs.writeFileSync(outputPath, nextContent, 'utf8');
};
if (require.main === module) {
    run();
}
//# sourceMappingURL=generateMcpToolsSnapshot.js.map