import { parseTimeout } from './config-loader.js';
import { executeAction, hasActionHandler } from './action-registry.js';
export async function runCascadeActions(actions, registry, ctx) {
    const enabled = actions.filter((a) => !a.disabled);
    const parallel = enabled.filter((a) => a.parallel);
    const sequential = enabled.filter((a) => !a.parallel);
    // Run parallel first (fire-and-forget promises)
    const parallelPromises = parallel.map((a) => runAction(a, registry, ctx));
    await Promise.all(parallelPromises);
    // Then sequential
    for (const action of sequential) {
        await runAction(action, registry, ctx);
    }
}
async function runAction(action, registry, ctx) {
    const fn = registry.get(action.action);
    const timeoutMs = parseTimeout(action.timeout);
    if (fn) {
        // Local registry handler (closure-based, no context needed)
        const timeoutPromise = new Promise((resolve) => {
            setTimeout(resolve, timeoutMs);
        });
        try {
            await Promise.race([fn(), timeoutPromise]);
        }
        catch (err) {
            console.error(`[planu] Cascade action ${action.action} failed:`, err);
        }
        return;
    }
    // Fallback: delegate to action-registry if ctx is provided
    if (ctx && hasActionHandler(action.action)) {
        const syntheticEvent = {
            name: 'spec:created',
            projectPath: ctx.projectPath,
            projectId: ctx.projectId,
            specId: ctx.specId,
            payload: ctx.payload,
        };
        const timeoutPromise = new Promise((resolve) => {
            setTimeout(resolve, timeoutMs);
        });
        try {
            await Promise.race([
                executeAction(action.action, syntheticEvent).then(() => undefined),
                timeoutPromise,
            ]);
        }
        catch (err) {
            console.error(`[planu] Cascade action ${action.action} failed:`, err);
        }
        return;
    }
    console.error(`[planu] Unknown cascade action: ${action.action}`);
}
//# sourceMappingURL=cascade-executor.js.map