"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDocsServer = createDocsServer;
exports.stopDocsServer = stopDocsServer;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
const zod_1 = require("zod");
const logger_1 = require("../../lib/logger");
// Resolve docs directory (works from ts-node root and compiled build/)
function docsDir() {
    const candidates = [
        path.join(__dirname, '..', '..', 'docs'),
        path.join(__dirname, '..', '..', '..', 'docs'),
    ];
    for (const dir of candidates) {
        if (fs.existsSync(dir))
            return dir;
    }
    return candidates[0];
}
function listMarkdownFiles(dir, prefix = '') {
    if (!fs.existsSync(dir))
        return [];
    const results = [];
    for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
        const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
        if (entry.isDirectory()) {
            results.push(...listMarkdownFiles(path.join(dir, entry.name), rel));
        }
        else if (entry.name.endsWith('.md')) {
            const content = fs.readFileSync(path.join(dir, entry.name), 'utf-8');
            const firstLine = content.split('\n').find(l => l.startsWith('# '));
            const title = firstLine ? firstLine.replace(/^#\s+/, '') : entry.name;
            results.push({ path: rel, title });
        }
    }
    return results;
}
const listDocsSchema = zod_1.z.object({});
const searchDocsSchema = zod_1.z.object({
    query: zod_1.z.string().describe('Search term or phrase to find in documentation'),
});
const readDocSchema = zod_1.z.object({
    path: zod_1.z.string().describe('Document path relative to docs/ (e.g. "mcp.md" or "api/tasks.md")'),
});
function registerTools(srv) {
    srv.registerTool('list_docs', {
        title: 'List Documentation',
        description: 'List all available documentation files with their titles.',
        inputSchema: listDocsSchema,
    }, async () => {
        const docs = listMarkdownFiles(docsDir());
        return {
            content: [{ type: 'text', text: JSON.stringify({ docs }) }],
        };
    });
    srv.registerTool('search_docs', {
        title: 'Search Documentation',
        description: 'Search across all documentation for a keyword or phrase. Returns matching files with line context.',
        inputSchema: searchDocsSchema,
    }, async (args) => {
        const dir = docsDir();
        const files = listMarkdownFiles(dir);
        const query = args.query.toLowerCase();
        const matches = [];
        for (const file of files) {
            const content = fs.readFileSync(path.join(dir, file.path), 'utf-8');
            const fileLines = content.split('\n');
            const hits = [];
            for (let i = 0; i < fileLines.length; i++) {
                if (fileLines[i].toLowerCase().includes(query)) {
                    // Include surrounding context
                    const start = Math.max(0, i - 1);
                    const end = Math.min(fileLines.length, i + 2);
                    hits.push(fileLines.slice(start, end).join('\n'));
                }
            }
            if (hits.length > 0) {
                matches.push({ path: file.path, title: file.title, lines: hits.slice(0, 5) });
            }
        }
        return {
            content: [{ type: 'text', text: JSON.stringify({ query: args.query, matches }) }],
        };
    });
    srv.registerTool('read_doc', {
        title: 'Read Documentation',
        description: 'Read the full content of a documentation file.',
        inputSchema: readDocSchema,
    }, async (args) => {
        const filePath = path.join(docsDir(), args.path);
        if (!fs.existsSync(filePath)) {
            return {
                content: [{ type: 'text', text: JSON.stringify({ error: `Document not found: ${args.path}` }) }],
            };
        }
        const content = fs.readFileSync(filePath, 'utf-8');
        return {
            content: [{ type: 'text', text: JSON.stringify({ path: args.path, content }) }],
        };
    });
}
async function createDocsServer(options) {
    const name = options?.name || 'long-tail-docs';
    const instance = new mcp_js_1.McpServer({ name, version: '1.0.0' });
    registerTools(instance);
    const docs = listMarkdownFiles(docsDir());
    logger_1.loggerRegistry.info(`[lt-mcp:docs] ${name} ready (3 tools, ${docs.length} docs indexed)`);
    return instance;
}
async function stopDocsServer() {
    logger_1.loggerRegistry.info('[lt-mcp:docs] stopped');
}
