// engine/auto-updater/index.ts — Public API for the auto-updater engine.
// SPEC-443
import { detectPlanuInstall } from './config-detector.js';
import { buildNpxLatestEntry, buildPinnedEntry, patchPlanuEntry } from './config-patcher.js';
import { fetchLatestVersion } from './npm-registry.js';
import { PLANU_VERSION } from '../../config/version.js';
// ---------------------------------------------------------------------------
// check_update_status
// ---------------------------------------------------------------------------
/**
 * Checks the current install info and npm registry for update availability.
 */
export async function checkForUpdates() {
    const [installInfo, latestVersion] = await Promise.all([
        detectPlanuInstall(),
        fetchLatestVersion(),
    ]);
    const isUpToDate = latestVersion === null ? true : latestVersion === installInfo.currentVersion;
    const autoUpdateActive = installInfo.method === 'npx-latest';
    let updateCommand;
    if (autoUpdateActive) {
        updateCommand =
            'Auto-update is active — Planu updates automatically on each Claude session start.';
    }
    else if (installInfo.method === 'global') {
        updateCommand = 'npm install -g @planu/cli@latest';
    }
    else if (installInfo.method === 'local-path') {
        updateCommand = 'Update your local installation and rebuild.';
    }
    else {
        updateCommand = 'Run enable_auto_update to switch to npx @latest for automatic updates.';
    }
    return {
        currentVersion: installInfo.currentVersion,
        latestVersion,
        isUpToDate,
        installMethod: installInfo.method,
        updateCommand,
        autoUpdateActive,
    };
}
// ---------------------------------------------------------------------------
// enable_auto_update
// ---------------------------------------------------------------------------
/**
 * Enables auto-update by patching the MCP config to use npx @planu/cli@latest.
 * If confirm is false (default), returns a preview of changes without applying.
 * If confirm is true, applies the change immediately.
 */
export async function enableAutoUpdate(confirm, overrideConfigPath) {
    let installInfo;
    if (overrideConfigPath !== undefined) {
        // Build a minimal install info using the override path
        installInfo = {
            method: 'unknown',
            currentVersion: PLANU_VERSION,
            configPath: overrideConfigPath,
            mcpEntry: null,
        };
    }
    else {
        installInfo = await detectPlanuInstall();
    }
    if (installInfo.method === 'npx-latest') {
        return {
            configPath: installInfo.configPath ?? '(unknown)',
            previousEntry: installInfo.mcpEntry,
            newEntry: buildNpxLatestEntry(),
            backupPath: '',
            alreadyOptimal: true,
            message: 'Auto-update is already active. Planu uses npx @planu/cli@latest — it updates automatically on each Claude session start.',
        };
    }
    if (installInfo.configPath === null) {
        throw new Error('Could not find MCP config file (~/.claude.json or Claude Desktop config). ' +
            'Please specify the path manually using the configPath parameter.');
    }
    const newEntry = buildNpxLatestEntry();
    if (!confirm) {
        return {
            configPath: installInfo.configPath,
            previousEntry: installInfo.mcpEntry,
            newEntry,
            backupPath: '',
            alreadyOptimal: false,
            message: `Preview: The planu entry in ${installInfo.configPath} will be updated to use ` +
                `"command": "npx", "args": ["-y", "@planu/cli@latest"]. ` +
                'Call enable_auto_update with confirm=true to apply.',
        };
    }
    const { backupPath, previousEntry } = await patchPlanuEntry(installInfo.configPath, newEntry);
    return {
        configPath: installInfo.configPath,
        previousEntry,
        newEntry,
        backupPath,
        alreadyOptimal: false,
        message: `Auto-update enabled. Config updated at ${installInfo.configPath}. ` +
            `Backup saved to ${backupPath}. ` +
            'Restart Claude to activate the change.',
    };
}
// ---------------------------------------------------------------------------
// pin_version
// ---------------------------------------------------------------------------
/**
 * Pins Planu to a specific version in the MCP config.
 * Requires confirm=true to apply the change.
 */
export async function pinVersion(version, confirm) {
    const installInfo = await detectPlanuInstall();
    if (installInfo.configPath === null) {
        throw new Error('Could not find MCP config file. Please ensure Claude Code or Claude Desktop is configured.');
    }
    const pinnedEntry = buildPinnedEntry(version);
    if (!confirm) {
        return {
            configPath: installInfo.configPath,
            pinnedVersion: version,
            backupPath: '',
            message: `Preview: The planu entry in ${installInfo.configPath} will be pinned to ` +
                `@planu/cli@${version}. Call pin_version with confirm=true to apply. ` +
                'To return to auto-update, call enable_auto_update.',
        };
    }
    const { backupPath } = await patchPlanuEntry(installInfo.configPath, pinnedEntry);
    return {
        configPath: installInfo.configPath,
        pinnedVersion: version,
        backupPath,
        message: `Version pinned to @planu/cli@${version} in ${installInfo.configPath}. ` +
            `Backup saved to ${backupPath}. ` +
            'Restart Claude to activate. To return to auto-update, call enable_auto_update.',
    };
}
//# sourceMappingURL=index.js.map