// engine/ide-config/detector.ts — Auto-detect installed IDEs (SPEC-080 AC-09)
import { existsSync } from 'node:fs';
import { execSync } from 'node:child_process';
import { join } from 'node:path';
import { homedir } from 'node:os';
/**
 * Check if a binary is available in PATH.
 */
export function isBinaryInPath(binary) {
    try {
        /* v8 ignore next 1 */
        const cmd = process.platform === 'win32' ? `where ${binary}` : `which ${binary}`;
        execSync(cmd, { stdio: 'ignore' });
        return true;
    }
    catch {
        return false;
    }
}
/**
 * Check if any config directories exist in the user's home.
 */
function hasConfigDirs(ide, platform) {
    const home = homedir();
    const dirs = ide.configDirs[platform];
    return dirs.some((dir) => existsSync(join(home, dir)));
}
/**
 * Check if IDE config files/dirs exist in the project.
 */
function hasProjectConfig(ide, projectPath, platform) {
    const configPath = ide.configPath[platform];
    if (configPath.startsWith('~/')) {
        return false; // global-only IDE
    }
    /* v8 ignore next 1 */
    return existsSync(join(projectPath, configPath.split('/')[0] ?? ''));
}
/**
 * Detect a single IDE.
 */
export function detectIde(ide, platform, projectPath) {
    // Check project-level config first (highest confidence)
    if (hasProjectConfig(ide, projectPath, platform)) {
        return {
            ide: ide.id,
            detected: true,
            confidence: 'project_detected',
            details: `${ide.name} project configuration found`,
        };
    }
    // Check if config directories exist in home
    if (hasConfigDirs(ide, platform)) {
        return {
            ide: ide.id,
            detected: true,
            confidence: 'config_found',
            details: `${ide.name} configuration directory found`,
        };
    }
    // Check if binary is in PATH
    const binaryFound = ide.binaryNames.some((bin) => isBinaryInPath(bin));
    if (binaryFound) {
        return {
            ide: ide.id,
            detected: true,
            confidence: 'installed',
            details: `${ide.name} binary found in PATH`,
        };
    }
    return {
        ide: ide.id,
        detected: false,
        confidence: 'installed',
        details: `${ide.name} not detected`,
    };
}
/**
 * Detect all IDEs from the registry.
 */
export function detectAllIdes(ides, platform, projectPath) {
    return ides.map((ide) => detectIde(ide, platform, projectPath));
}
/**
 * Filter to only detected IDEs, sorted by confidence (project > config > installed).
 */
export function getDetectedIdes(results) {
    const confidenceOrder = {
        project_detected: 0,
        config_found: 1,
        installed: 2,
    };
    return results
        .filter((r) => r.detected)
        .sort((a, b) => confidenceOrder[a.confidence] - confidenceOrder[b.confidence]);
}
//# sourceMappingURL=detector.js.map