// @crash-shield-ignore-file — config/cache reader for Planu-controlled JSON; writer is this codebase, shape guaranteed by build/seed.
// engine/autopilot/action-executor.ts — SPEC-413: Executes trigger actions
import { readFile, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { DEFAULT_TRIGGER_RULES } from './trigger-rules.js';
import { executeAction, hasActionHandler } from './action-registry.js';
const CONFIG_PATH_IN_PLANU = 'planu/autopilot-config.json';
export async function loadAutopilotConfig(projectPath) {
    const localPath = join(projectPath, CONFIG_PATH_IN_PLANU);
    try {
        const raw = await readFile(localPath, 'utf-8');
        return JSON.parse(raw);
    }
    catch {
        // Fall back to bundled defaults
        const { createRequire } = await import('node:module');
        const req = createRequire(import.meta.url);
        return req('../../config/autopilot-config.json');
    }
}
export async function saveAutopilotConfig(projectPath, config) {
    const localPath = join(projectPath, CONFIG_PATH_IN_PLANU);
    await writeFile(localPath, JSON.stringify(config, null, 2), 'utf-8');
}
function conditionMet(condition, event) {
    if (!condition) {
        return true;
    }
    const payload = event.payload ?? {};
    if (condition.minEstimatedHours !== undefined) {
        const hours = typeof payload.estimatedHours === 'number' ? payload.estimatedHours : 0;
        if (hours < condition.minEstimatedHours) {
            return false;
        }
    }
    if (condition.riskLevel !== undefined) {
        const risk = typeof payload.risk === 'string' ? payload.risk : '';
        if (!condition.riskLevel.includes(risk)) {
            return false;
        }
    }
    if (condition.minDriftScore !== undefined) {
        const score = typeof payload.driftScore === 'number' ? payload.driftScore : 0;
        if (score < condition.minDriftScore) {
            return false;
        }
    }
    return true;
}
/**
 * SPEC-454: Executes all enabled trigger rules that match the given event.
 * Actions with registered handlers are EXECUTED (fire-and-forget).
 * Actions without handlers are logged for future implementation.
 */
export async function executeTriggersForEvent(event) {
    const config = await loadAutopilotConfig(event.projectPath);
    const triggered = [];
    for (const rule of DEFAULT_TRIGGER_RULES) {
        if (rule.event !== event.name) {
            continue;
        }
        // Check config override
        const ruleConfig = config.rules[rule.id];
        const isEnabled = ruleConfig !== undefined ? ruleConfig.enabled : rule.enabled;
        if (!isEnabled) {
            continue;
        }
        // Check conditions
        if (!conditionMet(rule.condition, event)) {
            continue;
        }
        triggered.push(rule.action);
        // SPEC-454: Actually execute the action if a handler exists
        if (hasActionHandler(rule.action)) {
            // Fire-and-forget — never block the event pipeline
            void executeAction(rule.action, event)
                .then((result) => {
                if (result !== null) {
                    console.error(`[autopilot] executed: ${rule.action} for ${event.name}` +
                        (event.specId ? ` (${event.specId})` : '') +
                        ` — ${result.success ? 'OK' : 'FAIL'}: ${result.summary} (${result.durationMs}ms)`);
                }
            })
                .catch((err) => {
                /* v8 ignore start */
                const msg = err instanceof Error ? err.message : String(err);
                console.error(`[autopilot] action error ${rule.action}: ${msg}`);
                /* v8 ignore stop */
            });
        }
        else {
            console.error(`[autopilot] triggered (no handler): ${rule.id} for ${event.name}` +
                (event.specId ? ` (${event.specId})` : ''));
        }
    }
    return triggered;
}
/**
 * Returns the current autopilot status for a project.
 */
export async function getAutopilotStatus(projectPath) {
    const config = await loadAutopilotConfig(projectPath);
    const rules = DEFAULT_TRIGGER_RULES.map((rule) => {
        const override = config.rules[rule.id];
        return { ...rule, enabled: override !== undefined ? override.enabled : rule.enabled };
    });
    const disabledRules = rules.filter((r) => !r.enabled).map((r) => r.id);
    return {
        totalRules: rules.length,
        enabledRules: rules.filter((r) => r.enabled).length,
        disabledRules,
        rules,
    };
}
//# sourceMappingURL=action-executor.js.map