"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.register = register;
const zod_1 = require("zod");
const defaults_1 = require("../../../lib/defaults");
function register(server, mgr) {
    const graph = mgr.graph;
    server.registerTool('docs_explain_symbol', {
        description: 'Find documentation that explains a specific symbol. ' +
            'Searches code blocks in docs for the symbol, then returns both the code example ' +
            'and the surrounding text section that provides context/explanation. ' +
            'Use this to understand what a function, class, or type does based on documentation.',
        inputSchema: {
            symbol: zod_1.z.string().min(1).max(defaults_1.MAX_SEARCH_QUERY_LEN).describe('Symbol name to look up, e.g. "createUser", "AuthService"'),
            limit: zod_1.z.number().optional().describe('Max results to return (default 10)'),
        },
    }, async ({ symbol, limit = defaults_1.LIST_LIMIT_SMALL }) => {
        const symbolLower = symbol.toLowerCase();
        const results = [];
        graph.forEachNode((id, attrs) => {
            if (results.length >= limit)
                return;
            if (attrs.symbols.length === 0)
                return;
            if (!attrs.symbols.some(s => s === symbol || s.toLowerCase() === symbolLower))
                return;
            // Find the parent text section
            const parent = findParentTextSection(graph, id, attrs);
            results.push({
                codeBlock: {
                    id,
                    language: attrs.language,
                    symbols: attrs.symbols,
                    content: attrs.content,
                },
                explanation: parent
                    ? { id: parent.id, title: parent.title, content: parent.content }
                    : null,
                fileId: attrs.fileId,
            });
        });
        if (results.length === 0) {
            return { content: [{ type: 'text', text: `No documentation found for symbol: ${symbol}` }] };
        }
        const clean = (_k, v) => (v === null || (Array.isArray(v) && v.length === 0) ? undefined : v);
        return { content: [{ type: 'text', text: JSON.stringify(results, clean, 2) }] };
    });
}
function findParentTextSection(graph, nodeId, attrs) {
    // The code block's in-neighbor with same fileId, lower level, and no language = parent text section
    for (const neighbor of graph.inNeighbors(nodeId)) {
        const nAttrs = graph.getNodeAttributes(neighbor);
        if (nAttrs.fileId === attrs.fileId && nAttrs.language === undefined && nAttrs.level < attrs.level) {
            return { id: neighbor, title: nAttrs.title, content: nAttrs.content };
        }
    }
    return null;
}
