// tools/suggest-tooling/handler.ts — MCP tool handler for suggest_tooling
import { t, ti } from '../../i18n/index.js';
import { knowledgeStore } from '../../storage/index.js';
import { detectCSSFramework } from '../../engine/detectors/css-framework-detector.js';
import { fetchRecommendedSkills } from './skills-fetcher.js';
import { getPlatformTooling } from './platform-tooling-catalog.js';
import { buildAgentToolingLines, buildDesktopToolingLines } from './framework-catalog.js';
import { buildMobileToolingLines, buildKmpToolingLines, buildK3sToolingLines, } from './skills-catalog.js';
import { buildLintingToolingLines } from './linting-catalog.js';
import { buildObservabilityToolingLines, buildAlertSpecLines } from './observability-catalog.js';
import { buildResilienceToolingLines } from './resilience-catalog.js';
import { detectMonitoring } from '../../engine/detectors/monitoring-detector.js';
import { detectK3s } from '../../engine/detectors/k3s-detector.js';
import { buildDepAuditReport, buildSingleDepAuditLines } from './dep-audit-catalog.js';
import { fetchDoraMetrics, buildDoraOutputLines } from './dora-output.js';
import { buildHypermediaToolingLines } from './hypermedia-catalog.js';
import { buildIdpRecommendationLines } from './idp-catalog.js';
import { buildOtelToolingLines } from './otel-catalog.js';
import { buildSupplyChainToolingLines } from './supply-chain-catalog.js';
import { buildLlmSecurityToolingLines } from './llm-security-catalog.js';
import { buildLocalFirstToolingLines } from './local-first-catalog.js';
import { buildAdvancedTestingToolingLines } from './advanced-testing-catalog.js';
import { buildDaggerCatalogLines } from './dagger-catalog.js';
import { buildCSSFrameworkLines } from './css-framework-catalog.js';
import { loadCatalog } from './catalog-loader.js';
import { buildBuildToolSuggestionLines } from './build-tool-catalog.js';
import { buildAiNativeToolingLines } from './ai-native-catalog.js';
import { buildFrontendPerfToolingLines } from './frontend-perf-catalog.js';
import { detectFrontendPerf } from '../../engine/detectors/frontend-perf-detector.js';
import { buildMainOutputLines } from './output-formatter-catalog.js';
export async function handleSuggestTooling(args) {
    const { projectId, categories } = args;
    const knowledge = await knowledgeStore.getKnowledge(projectId);
    if (!knowledge) {
        return {
            content: [
                {
                    type: 'text',
                    text: ti('errors.projectNotFound', { projectId }),
                },
            ],
            isError: true,
        };
    }
    // SPEC-025 C1-C6: Dependency audit subcommand
    if ((categories?.length === 1 && categories[0] === 'audit-deps') ||
        args.packageName !== undefined) {
        const projectPath = knowledge.projectPath;
        const { report, lines } = await buildDepAuditReport(projectPath);
        if (args.packageName) {
            // C5: single dep pre-check — return as acceptance criteria template
            const criteriaLines = buildSingleDepAuditLines(report, args.packageName);
            return {
                content: [{ type: 'text', text: criteriaLines.join('\n') }],
            };
        }
        return {
            content: [{ type: 'text', text: lines.join('\n') }],
        };
    }
    const catalog = await loadCatalog();
    const targetCategories = categories ?? Object.keys(catalog);
    // Assess current tooling from project knowledge
    const currentTooling = [];
    const gaps = [];
    const recommendations = [];
    for (const catKey of targetCategories) {
        const category = catalog[catKey];
        if (!category) {
            continue;
        }
        // Check if any tool from this category is detected in the project stack
        const stackLower = knowledge.stack.map((s) => s.toLowerCase());
        const conventionsStr = JSON.stringify(knowledge.conventions).toLowerCase();
        const linterTools = knowledge.linting.detectedLinters.map((l) => l.tool.toLowerCase());
        let found = false;
        for (const [toolKey, toolInfo] of Object.entries(category.tools)) {
            const toolNameLower = toolInfo.name.toLowerCase();
            const toolKeyLower = toolKey.toLowerCase();
            // Check if tool is in stack, conventions, or linters
            const isDetected = stackLower.some((s) => s.includes(toolKeyLower) || s.includes(toolNameLower)) ||
                conventionsStr.includes(toolKeyLower) ||
                linterTools.some((l) => l.includes(toolKeyLower));
            if (isDetected) {
                currentTooling.push({
                    category: catKey,
                    tool: toolInfo.name,
                    status: 'configured',
                });
                found = true;
            }
        }
        if (!found) {
            // Determine importance
            const criticalCategories = [
                'version_control',
                'ci_cd',
                'testing',
                'security',
                'observability',
            ];
            const recommendedCategories = [
                'linting_formatting',
                'containerization',
                'api_documentation',
                'rate_limiting',
            ];
            const importance = criticalCategories.includes(catKey)
                ? 'critical'
                : recommendedCategories.includes(catKey)
                    ? 'recommended'
                    : 'nice-to-have';
            gaps.push({
                category: catKey,
                importance,
                reason: category.why,
            });
            // Pick the top recommended tool for this category
            const toolEntries = Object.entries(category.tools);
            const firstEntry = toolEntries[0];
            if (firstEntry) {
                const [_topKey, topTool] = firstEntry;
                const sdks = topTool.sdks ?? {};
                const langSdk = sdks[knowledge.language] ?? sdks.javascript;
                recommendations.push({
                    category: catKey,
                    tool: topTool.name,
                    reason: category.why,
                    installSteps: langSdk
                        ? [`Install: npm install ${langSdk}`, `Docs: ${topTool.docsUrl}`]
                        : [`See docs: ${topTool.docsUrl}`],
                    effort: 'moderate',
                    priority: importance === 'critical' ? 'high' : importance === 'recommended' ? 'medium' : 'low',
                });
            }
        }
    }
    // Calculate maturity score
    const totalCategories = targetCategories.length;
    const coveredCategories = currentTooling.length;
    const maturityScore = totalCategories > 0 ? Math.round((coveredCategories / totalCategories) * 100) : 0;
    // SPEC-013: Mobile tooling suggestions
    const mobileToolingLines = buildMobileToolingLines(knowledge);
    // SPEC-013 TD-P14-02: Compose Multiplatform recommendations for KMP projects
    const kmpToolingLines = buildKmpToolingLines(knowledge);
    // SPEC-033 TD-P14-03: K3s filesystem detection — augments knowledge for tooling recommendation
    const k3sDetectedOnDisk = await detectK3s(knowledge.projectPath);
    const knowledgeWithK3s = k3sDetectedOnDisk
        ? { ...knowledge, k3sDetected: true }
        : knowledge;
    // SPEC-033 TD-P14-03: K3s tooling recommendations for K3s projects
    const k3sToolingLines = buildK3sToolingLines(knowledgeWithK3s);
    // SPEC-014b: Detect desktop projects and build distribution tooling suggestions
    const desktopToolingLines = buildDesktopToolingLines(knowledge);
    // SPEC-016a: Detect AI agent projects and build agent tooling suggestions
    const agentToolingLines = buildAgentToolingLines(knowledge);
    // SPEC-015a: Smart contract and ML tooling suggestions
    const platformToolingLines = getPlatformTooling(knowledge);
    // SPEC-017a: Detect CSS framework — recommend one if missing
    const cssDetection = await detectCSSFramework(knowledge.projectPath);
    const cssToolingLines = buildCSSFrameworkLines(knowledge, cssDetection.framework);
    // SPEC-025: Linting & formatting recommendations per language
    const lintingToolingLines = buildLintingToolingLines(knowledge);
    // SPEC-026a: Detect observability stack and generate recommendations
    const monitoringDetection = await detectMonitoring(knowledge.projectPath);
    const observabilityToolingLines = buildObservabilityToolingLines(knowledge, monitoringDetection);
    const alertSpecLines = args.specId ? buildAlertSpecLines(args.specId) : [];
    // SPEC-022: Fetch recommended skills from skills.sh
    const recommendedSkills = await fetchRecommendedSkills(knowledge);
    // SPEC-034: Resilience library, health checks, and distributed rate limiting recommendations
    const resilienceToolingLines = buildResilienceToolingLines(knowledge);
    // SPEC-043: Hypermedia & backend-first tooling recommendations
    const hypermediaToolingLines = await buildHypermediaToolingLines(knowledge);
    // SPEC-048: IDP and platform engineering recommendations for multi-team projects
    const idpToolingLines = await buildIdpRecommendationLines(knowledge);
    // SPEC-044: OTel stack recommendations when OTel is installed or needed
    const otelToolingLines = await buildOtelToolingLines(knowledge);
    // SPEC-046: Supply chain security tooling when gaps detected
    const supplyChainToolingLines = await buildSupplyChainToolingLines(knowledge);
    // SPEC-045: LLM guardrails and MLOps tooling when LLM project detected
    const llmSecurityToolingLines = await buildLlmSecurityToolingLines(knowledge);
    // SPEC-047: Local-first CRDT/storage/sync tooling when local-first signals detected
    const localFirstToolingLines = await buildLocalFirstToolingLines(knowledge);
    // SPEC-049: Advanced testing patterns (PBT, mutation, chaos, a11y, synthetic data)
    const advancedTestingToolingLines = buildAdvancedTestingToolingLines(knowledge);
    // SPEC-026a TD-P15-01: Dagger CI detection and recommendations
    const daggerCatalogLines = await buildDaggerCatalogLines(knowledge);
    // SPEC-050 S2: Build tool recommendations (C4: new project→Vite 7, C5: Vite5/6→migrate, C6: Webpack4/CRA→checklist)
    const buildToolSuggestionLines = await buildBuildToolSuggestionLines(knowledge);
    // SPEC-056: AI-native tooling recommendations (observability, cache, prompt mgmt, guardrails)
    const aiNativeToolingLines = buildAiNativeToolingLines(knowledge);
    // SPEC-057: Frontend perf tooling (Lighthouse CI, MFE tools, Storybook, E2E, Chromatic)
    const frontendPerfDetection = await detectFrontendPerf(knowledge.projectPath);
    const frontendPerfMfeAware = {
        ...frontendPerfDetection,
        hasMfe: knowledge.mfeDetection?.moduleFederation !== undefined ||
            knowledge.mfeDetection?.singleSpa === true ||
            knowledge.mfeDetection?.nxMfe === true,
    };
    const frontendPerfToolingLines = buildFrontendPerfToolingLines(knowledge, frontendPerfMfeAware);
    // SPEC-033: Calculate DORA metrics if project has 90+ days of history
    const { doraMetrics } = await fetchDoraMetrics(knowledge.projectPath);
    const result = {
        mode: currentTooling.length > 0 ? 'existing' : 'new',
        currentTooling,
        gaps,
        recommendations: recommendations.sort((a, b) => {
            const pri = { high: 0, medium: 1, low: 2 };
            return pri[a.priority] - pri[b.priority];
        }),
        maturityScore,
        message: `Dev lifecycle maturity: ${maturityScore}%. ${gaps.length} gap(s) found, ${recommendations.length} recommendation(s).`,
        recommendedSkills,
    };
    // Format output — main sections delegated to output-formatter-catalog
    const lines = buildMainOutputLines(result, t('tools.suggest_tooling.description'), recommendedSkills);
    // SPEC-033: Add DORA metrics section if available
    if (doraMetrics) {
        lines.push(...buildDoraOutputLines(doraMetrics));
    }
    const content = [
        { type: 'text', text: lines.join('\n') },
    ];
    const additionalSections = [
        mobileToolingLines,
        kmpToolingLines,
        k3sToolingLines,
        desktopToolingLines,
        agentToolingLines,
        platformToolingLines,
        cssToolingLines,
        lintingToolingLines,
        observabilityToolingLines,
        alertSpecLines,
        resilienceToolingLines,
        hypermediaToolingLines,
        idpToolingLines,
        otelToolingLines,
        supplyChainToolingLines,
        llmSecurityToolingLines,
        localFirstToolingLines,
        advancedTestingToolingLines,
        daggerCatalogLines,
        buildToolSuggestionLines,
        aiNativeToolingLines,
        frontendPerfToolingLines,
    ]
        .filter((section) => section.length > 0)
        .map((section) => ({ type: 'text', text: section.join('\n') }));
    return { content: [...content, ...additionalSections] };
}
//# sourceMappingURL=handler.js.map