import { z } from 'zod';
import { config } from '../../config.js';
import { detectProject } from '../../lib/frameworks/detect.js';
import { readComposerJson } from '../../lib/frameworks/composer.js';
import { errorResult, jsonResult, toErrorMessage } from '../shared.js';
function extractMajorMinor(versionConstraint) {
    if (!versionConstraint)
        return '4';
    const match = versionConstraint.match(/(\d+)\.(\d+)/);
    if (!match)
        return '4';
    const [, major] = match;
    return `${major}`;
}
export function registerSearchCodeIgniterDocsTool(server) {
    server.registerTool('search_codeigniter_docs', {
        title: 'Search CodeIgniter Docs',
        description: 'Return a deep link to the CodeIgniter 4 user guide for a topic, version-matched to the codeigniter4/framework constraint in composer.json.',
        inputSchema: {
            topic: z.string().min(1).describe('Documentation topic, e.g. "models" or "database".'),
            version: z.string().optional().describe('Override the major version, e.g. "4". Auto-detected by default.'),
        },
    }, async ({ topic, version }) => {
        try {
            const detected = detectProject(config.workspaceRoot);
            const ciRoot = detected.backend?.kind === 'codeigniter' ? detected.backend.root : config.workspaceRoot;
            const composerJson = readComposerJson(ciRoot);
            const constraint = composerJson?.require?.['codeigniter4/framework'];
            const docsVersion = version ?? extractMajorMinor(constraint);
            const slug = topic.toLowerCase().replace(/\s+/g, '_');
            const url = `https://codeigniter4.github.io/userguide/${docsVersion}/${slug}.html`;
            return jsonResult({
                topic,
                version: docsVersion,
                composerConstraint: constraint ?? null,
                url,
                note: 'This is a best-effort documentation link. If the topic page does not exist, the user guide index may help.',
            });
        }
        catch (error) {
            return errorResult(toErrorMessage(error));
        }
    });
}
//# sourceMappingURL=searchCodeIgniterDocs.js.map