// engine/config-health/otel-checker.ts — SPEC-044 TD-P14-01
// Checks OpenTelemetry package version compatibility.
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
async function readPackageJson(projectPath) {
    try {
        const raw = await readFile(join(projectPath, 'package.json'), 'utf-8');
        return JSON.parse(raw);
    }
    catch {
        return {};
    }
}
/**
 * Extract the minor version portion from a semver string.
 * Returns null if the string is not a recognisable semver.
 * Strips leading "^", "~", ">=", etc.
 */
function extractMinorVersion(raw) {
    const cleaned = raw.replace(/^[^0-9]*/, '');
    const parts = cleaned.split('.');
    if (parts.length < 2) {
        return null;
    }
    // minor version = parts[1] — parts.length >= 2 guaranteed by guard above
    /* v8 ignore next 2 */
    return `${parts[0] ?? '0'}.${parts[1] ?? '0'}`;
}
/**
 * Check that @opentelemetry/api and @opentelemetry/sdk-node are on the same
 * minor version.  A version skew between these two packages is the #1 cause of
 * silent instrumentation failures.
 */
export async function checkOtelVersionCompatibility(projectPath) {
    const findings = [];
    const pkg = await readPackageJson(projectPath);
    const allDeps = {
        ...(pkg.dependencies ?? {}),
        ...(pkg.devDependencies ?? {}),
    };
    const apiVersion = allDeps['@opentelemetry/api'];
    const sdkVersion = allDeps['@opentelemetry/sdk-node'];
    // If only one package is installed → informational finding
    if (apiVersion && !sdkVersion) {
        findings.push({
            severity: 'info',
            checker: 'otel-version',
            file: 'package.json',
            message: `@opentelemetry/api (${apiVersion}) is installed without @opentelemetry/sdk-node. ` +
                'Add @opentelemetry/sdk-node to enable automatic instrumentation.',
            fix: 'Install @opentelemetry/sdk-node at the same minor version as @opentelemetry/api.',
        });
        return findings;
    }
    if (!sdkVersion || !apiVersion) {
        return findings;
    }
    const apiMinor = extractMinorVersion(apiVersion);
    const sdkMinor = extractMinorVersion(sdkVersion);
    if (apiMinor === null || sdkMinor === null) {
        return findings;
    }
    if (apiMinor !== sdkMinor) {
        findings.push({
            severity: 'warning',
            checker: 'otel-version',
            file: 'package.json',
            message: `@opentelemetry/api (${apiVersion}) and @opentelemetry/sdk-node (${sdkVersion}) ` +
                'are on different minor versions — this is the #1 cause of silent instrumentation failures',
            fix: 'Update both packages to the same minor version in a single PR. ' +
                'Also update all @opentelemetry/* instrumentation packages at the same time.',
        });
    }
    return findings;
}
//# sourceMappingURL=otel-checker.js.map