// engine/autopilot/bootstrap.ts — SPEC-450: Wires event-bus to action-executor
// Call bootstrapAutopilotHandlers() once at server startup (src/index.ts).
import { onAutopilotEvent } from './event-bus.js';
import { executeTriggersForEvent } from './action-executor.js';
/**
 * SPEC-585: Fire-and-forget session-context freshness check on spec:status:done.
 * Regenerates session-context.md when it is stale (> 1 day behind newest spec.md).
 */
function registerSessionContextFreshnessListener() {
    onAutopilotEvent('spec:status:done', (event) => {
        void (async () => {
            try {
                const { checkSessionContextFreshness } = await import('../session-safeguard/session-context-freshness.js');
                const freshness = await checkSessionContextFreshness(event.projectPath);
                if (!freshness.stale) {
                    return;
                }
                const { generateSessionContext } = await import('../session-context-generator.js');
                await generateSessionContext(event.projectPath, event.projectId);
            }
            catch {
                /* best-effort — never surface to user */
            }
        })();
    });
}
/**
 * SPEC-600: Fire-and-forget cascade on approved→implementing.
 * Auto-recommends model + generates orchestration plan for complex specs.
 */
function registerImplementingCascadeListener() {
    onAutopilotEvent('spec:status:implementing', (event) => {
        void (async () => {
            try {
                const { handleRecommendModel } = await import('../../tools/recommend-model-handler.js');
                handleRecommendModel({ specId: event.specId });
            }
            catch {
                /* best-effort */
            }
            try {
                const { handleContextWindowStatus } = await import('../../tools/context-manager-handler.js');
                await handleContextWindowStatus({ projectPath: event.projectPath });
            }
            catch {
                /* best-effort */
            }
        })();
    });
}
// SPEC-649: registerDoneCascadeListener (optimize_context on done) removed — cascade reduced to
// exactly 2 actions: session.json update + releases/pending.json append.
/**
 * SPEC-628: Fire-and-forget auto_fix_health on cron:daily.
 * Moved from update_status(done) cascade to reduce latency on done transitions.
 */
function registerDailyCronListener() {
    onAutopilotEvent('cron:daily', (event) => {
        void (async () => {
            /* v8 ignore start */
            try {
                const { autoFixHealth } = await import('../health/auto-fixer.js');
                await autoFixHealth(event.projectPath, event.projectId);
            }
            catch {
                /* best-effort */
            }
            /* v8 ignore stop */
        })();
    });
}
/**
 * SPEC-605: Fire-and-forget auto-activate handler on plugin:installed.
 * Marks newly installed plugins as active so they are available immediately.
 */
function registerPluginInstalledListener() {
    onAutopilotEvent('plugin:installed', (event) => {
        void (async () => {
            try {
                const pluginIds = event.payload?.pluginIds;
                if (!Array.isArray(pluginIds) || pluginIds.length === 0) {
                    return;
                }
                const { handleManagePlugins } = await import('../../tools/manage-plugins-handler.js');
                for (const pluginId of pluginIds) {
                    if (typeof pluginId !== 'string') {
                        continue;
                    }
                    await handleManagePlugins({
                        action: 'activate',
                        pluginId,
                        projectPath: event.projectPath,
                    });
                }
            }
            catch {
                /* best-effort */
            }
        })();
    });
}
const AUTOPILOT_EVENTS = [
    'spec:created',
    'spec:status:approved',
    'spec:status:implementing',
    'spec:status:done',
    'drift:detected',
    'cron:daily',
];
/**
 * Registers executeTriggersForEvent as a handler for every known AutopilotEventName.
 * Must be called once at server startup before any events are emitted.
 * Safe to call multiple times in tests if clearAutopilotHandlers() is used between calls.
 */
export function bootstrapAutopilotHandlers() {
    for (const eventName of AUTOPILOT_EVENTS) {
        onAutopilotEvent(eventName, (event) => {
            // fire-and-forget — never block the event emitter
            void executeTriggersForEvent(event).catch((err) => {
                /* v8 ignore start */
                const msg = err instanceof Error ? err.message : String(err);
                console.error(`[autopilot] trigger error for ${event.name}: ${msg}`);
                /* v8 ignore stop */
            });
        });
    }
    // SPEC-585: Register session-context freshness listener
    registerSessionContextFreshnessListener();
    // SPEC-600: Register cascade listener for implementing transition
    // SPEC-649: registerDoneCascadeListener removed — optimize_context no longer auto-runs on done
    registerImplementingCascadeListener();
    // SPEC-605: Register plugin:installed handler for auto-activation
    registerPluginInstalledListener();
    // SPEC-628: Register daily cron for auto_fix_health (moved from update_status cascade)
    registerDailyCronListener();
}
//# sourceMappingURL=bootstrap.js.map