// tools/suggest-tooling/otel-catalog.ts — SPEC-044
// Loads and formats OTel tooling recommendations from the config catalog.
import { readFile } from 'node:fs/promises';
let configCache = null;
/** Reset the in-memory cache (for testing only). */
export function resetOtelCatalogCache() {
    configCache = null;
}
async function loadOtelConfig() {
    if (configCache) {
        return configCache;
    }
    try {
        const configPath = new URL('../../config/otel-tooling.json', import.meta.url);
        const content = await readFile(configPath, 'utf-8');
        const raw = JSON.parse(content);
        delete raw._description;
        configCache = raw;
        return configCache;
    }
    catch {
        return { languages: {}, backends: {}, ebpf: {} };
    }
}
/** Detect if a project has Kubernetes in its stack */
function hasKubernetes(knowledge) {
    const all = [...knowledge.stack, ...Object.keys(knowledge.tooling)].map((s) => s.toLowerCase());
    return all.some((s) => s.includes('kubernetes') || s.includes('k8s') || s.includes('helm'));
}
/**
 * Build OTel tooling recommendation lines for projects with OTel detected or needed.
 * Only emits if `knowledge.otelDetection?.isInstalled` or `needsOtel` is true.
 */
export async function buildOtelToolingLines(knowledge) {
    const otel = knowledge.otelDetection;
    // Only emit if OTel is installed or needed
    if (!otel || (!otel.isInstalled && !otel.needsOtel)) {
        return [];
    }
    const config = await loadOtelConfig();
    const lang = knowledge.language.toLowerCase();
    const langEntry = config.languages[lang];
    const lines = ['## OpenTelemetry Stack', ''];
    if (otel.isInstalled) {
        lines.push(`**OTel detectado** en el proyecto (SDK: ${otel.sdkLanguage ?? lang})`);
        lines.push(`**Señales activas:** ${otel.signals.length > 0 ? otel.signals.join(', ') : 'traces'}`);
        if (otel.backend) {
            lines.push(`**Backend configurado:** ${otel.backend}`);
        }
        lines.push('');
    }
    else {
        lines.push('> **OTel no detectado** — el proyecto tiene patrones que requieren observabilidad distribuida.');
        lines.push('');
    }
    if (langEntry) {
        lines.push('### SDK y Paquetes Recomendados');
        lines.push('');
        lines.push(`**SDK principal:** \`${langEntry.sdkPackage}\``);
        if (langEntry.autoInstrumentation) {
            lines.push(`**Auto-instrumentación:** \`${langEntry.autoInstrumentation}\``);
        }
        lines.push(`**Exporter OTLP:** \`${langEntry.exporterPackage}\``);
        lines.push(`**Docs:** ${langEntry.docsUrl}`);
        lines.push('');
    }
    // Backend recommendations by scale
    lines.push('### Backend de Telemetría por Escala');
    lines.push('');
    const localBackend = config.backends.local;
    if (localBackend) {
        lines.push(`**Desarrollo local:** ${localBackend.name}`);
        if (localBackend.dockerCompose) {
            lines.push(`\`\`\`bash\n${localBackend.dockerCompose}\n\`\`\``);
        }
        lines.push(`- Docs: ${localBackend.docsUrl}`);
        lines.push('');
    }
    const stagingBackend = config.backends.staging;
    if (stagingBackend) {
        lines.push(`**Staging:** ${stagingBackend.name}`);
        lines.push(`- Docs: ${stagingBackend.docsUrl}`);
        lines.push('');
    }
    const prodSmall = config.backends['production-small'];
    if (prodSmall) {
        lines.push(`**Producción pequeña:** ${prodSmall.name}`);
        lines.push(`- Docs: ${prodSmall.docsUrl}`);
        lines.push('');
    }
    const prodEnterprise = config.backends['production-enterprise'];
    if (prodEnterprise?.options) {
        lines.push(`**Producción enterprise:** ${prodEnterprise.name}`);
        lines.push(`- Opciones cloud: ${prodEnterprise.options.join(', ')}`);
        lines.push(`- Docs: ${prodEnterprise.docsUrl}`);
        lines.push('');
    }
    // eBPF alternatives for Kubernetes projects
    if (hasKubernetes(knowledge)) {
        lines.push('### Alternativas eBPF (nivel: avanzado)');
        lines.push('');
        lines.push('> Para proyectos con Kubernetes y alta carga — auto-instrumentación sin cambios de código.');
        lines.push('');
        for (const [, ebpfEntry] of Object.entries(config.ebpf)) {
            lines.push(`**${ebpfEntry.name}** *(${ebpfEntry.level})*`);
            lines.push(ebpfEntry.description);
            lines.push(`- Docs: ${ebpfEntry.docsUrl}`);
            lines.push('');
        }
    }
    return lines;
}
//# sourceMappingURL=otel-catalog.js.map