// @crash-shield-ignore-file — config/cache reader for Planu-controlled JSON; writer is this codebase, shape guaranteed by build/seed.
// engine/auto-updater/config-patcher.ts — Patches the MCP config file to enable auto-update.
// SPEC-443
// Creates a backup before any modification. Restores backup on write failure.
import { readFile, writeFile } from 'node:fs/promises';
export const PLANU_MCP_STARTUP_TIMEOUT_SEC = 120;
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function dateStr() {
    return new Date().toISOString().slice(0, 10);
}
function backupPathFor(configPath) {
    return configPath.replace(/\.json$/, `.backup-${dateStr()}.json`);
}
// ---------------------------------------------------------------------------
// Patch operations
// ---------------------------------------------------------------------------
/**
 * Patches the mcpServers.planu entry in the given config file.
 * Steps:
 *   1. Read existing content (throws if not valid JSON)
 *   2. Create a backup
 *   3. Write patched content
 *   4. If write fails, restore from backup
 *
 * Returns the backup path so callers can report it.
 */
export async function patchPlanuEntry(configPath, newEntry) {
    const raw = await readFile(configPath, 'utf-8');
    // Validate JSON before touching anything
    let config;
    try {
        config = JSON.parse(raw);
    }
    catch (err) {
        throw new Error(`Config file at ${configPath} is not valid JSON. Aborting — no changes made. Error: ${String(err)}`, { cause: err });
    }
    const previousEntry = config.mcpServers?.planu ?? null;
    // Create backup BEFORE modifying anything
    const backupPath = backupPathFor(configPath);
    await writeFile(backupPath, raw, 'utf-8');
    // Patch
    const updated = {
        ...config,
        mcpServers: {
            ...(config.mcpServers ?? {}),
            planu: newEntry,
        },
    };
    try {
        await writeFile(configPath, JSON.stringify(updated, null, 2) + '\n', 'utf-8');
    }
    catch (writeErr) {
        // Restore from backup
        await writeFile(configPath, raw, 'utf-8');
        throw new Error(`Failed to write updated config to ${configPath}. Restored original from backup. Error: ${String(writeErr)}`, { cause: writeErr });
    }
    return { backupPath, previousEntry };
}
/**
 * Returns the standard npx @latest entry for Planu.
 */
export function buildNpxLatestEntry() {
    return {
        command: 'npx',
        args: ['-y', '@planu/cli@latest'],
        startup_timeout_sec: PLANU_MCP_STARTUP_TIMEOUT_SEC,
    };
}
/**
 * Returns an npx entry pinned to a specific version.
 */
export function buildPinnedEntry(version) {
    return {
        command: 'npx',
        args: ['-y', `@planu/cli@${version}`],
        startup_timeout_sec: PLANU_MCP_STARTUP_TIMEOUT_SEC,
    };
}
//# sourceMappingURL=config-patcher.js.map