// engine/ide-config/core.ts — Orchestrator for IDE config generation (SPEC-080 AC-10)
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { generateIdeConfig } from './generators.js';
import { detectAllIdes, getDetectedIdes } from './detector.js';
import { validateConfig } from './validator.js';
import { detectPlatform, expandHome } from './path-resolver.js';
/**
 * Load the IDE registry from the bundled JSON file.
 */
export function loadIdeRegistry() {
    const registryPath = new URL('../../config/ide-registry.json', import.meta.url);
    const raw = readFileSync(registryPath, 'utf-8');
    return JSON.parse(raw);
}
/**
 * Merge planu config into an existing JSON config file without overwriting other entries.
 */
export function mergeJsonConfig(existingContent, newContent, wrapperKey) {
    const existing = JSON.parse(existingContent);
    const incoming = JSON.parse(newContent);
    /* v8 ignore next 2 */
    const existingServers = existing[wrapperKey] ?? {};
    const incomingServers = incoming[wrapperKey] ?? {};
    existing[wrapperKey] = { ...existingServers, ...incomingServers };
    return JSON.stringify(existing, null, 2);
}
/**
 * Write config to disk, merging if the file already exists.
 */
function writeConfig(filePath, content, ide) {
    const resolvedPath = expandHome(filePath);
    const dir = dirname(resolvedPath);
    if (!existsSync(dir)) {
        mkdirSync(dir, { recursive: true });
    }
    if (existsSync(resolvedPath) && ide.configFormat === 'json') {
        try {
            const existing = readFileSync(resolvedPath, 'utf-8');
            const merged = mergeJsonConfig(existing, content, ide.wrapperKey);
            writeFileSync(resolvedPath, merged, 'utf-8');
            return { finalContent: merged, merged: true };
        }
        catch {
            // If existing file is malformed, overwrite
            writeFileSync(resolvedPath, content, 'utf-8');
            return { finalContent: content, merged: false };
        }
    }
    writeFileSync(resolvedPath, content, 'utf-8');
    return { finalContent: content, merged: false };
}
/**
 * Process a single IDE: generate config, optionally write, validate.
 */
function processIde(ide, input, platform) {
    const projectPath = resolve(input.projectPath);
    const generated = generateIdeConfig(ide, input.scope, platform, projectPath);
    const validationErrors = input.dryRun ? [] : validateConfig(generated, ide);
    let finalContent = generated.content;
    let merged = false;
    if (!input.dryRun) {
        const result = writeConfig(generated.filePath, generated.content, ide);
        finalContent = result.finalContent;
        merged = result.merged;
    }
    return {
        ide: ide.id,
        filePath: generated.filePath,
        content: finalContent,
        merged,
        instructions: generated.instructions,
        validationErrors,
    };
}
/**
 * Main entry point: generate IDE config for one or all detected IDEs.
 */
export function handleGenerateIdeConfig(input) {
    const registry = loadIdeRegistry();
    const platform = detectPlatform();
    const projectPath = resolve(input.projectPath);
    // Detect all IDEs
    const allDetections = detectAllIdes(registry.ides, platform, projectPath);
    const detectedIdes = getDetectedIdes(allDetections);
    // Determine which IDEs to generate for
    let targetIdes;
    if (input.ide === 'auto') {
        const detectedIds = new Set(detectedIdes.map((d) => d.ide));
        targetIdes = registry.ides.filter((ide) => detectedIds.has(ide.id));
    }
    else {
        const found = registry.ides.find((ide) => ide.id === input.ide);
        targetIdes = found ? [found] : [];
    }
    const results = targetIdes.map((ide) => processIde(ide, input, platform));
    return {
        results,
        detectedIdes,
        dryRun: input.dryRun,
    };
}
//# sourceMappingURL=core.js.map