/**
 * Iron Dome — Action Gate
 *
 * Controls whether external actions (send email, delete file, API call, etc.)
 * are allowed, require approval, or are blocked.
 */
import { logIronDomeAudit } from './audit.js';
/**
 * Check if an action is allowed under the current Iron Dome configuration.
 */
export function isActionAllowed(action, config, source) {
    if (!config.enabled) {
        return {
            decision: 'approved',
            action,
            reason: 'Iron Dome is not active',
        };
    }
    const normAction = action.toLowerCase();
    let result;
    // Check sub-agent restrictions first
    if (source?.type === 'agent') {
        const blocked = config.subAgentRestrictions.blockedOperations
            .some(op => normAction.includes(op.toLowerCase()));
        if (blocked) {
            result = {
                decision: 'blocked',
                action: normAction,
                reason: `Action "${normAction}" is blocked for sub-agents`,
            };
            logIronDomeAudit({
                action: 'action_gate',
                actionType: normAction,
                allowed: false,
                reason: result.reason,
                source,
            });
            return result;
        }
    }
    // Check auto-approve list
    const autoApproved = config.autoApprove
        .some(a => normAction.includes(a.toLowerCase()));
    if (autoApproved) {
        result = {
            decision: 'approved',
            action: normAction,
            reason: `Action "${normAction}" is auto-approved`,
        };
        logIronDomeAudit({
            action: 'action_gate',
            actionType: normAction,
            allowed: true,
            reason: result.reason,
            source,
        });
        return result;
    }
    // Check require-approval list
    const needsApproval = config.requireApproval
        .some(a => normAction.includes(a.toLowerCase()));
    if (needsApproval) {
        result = {
            decision: 'requires_approval',
            action: normAction,
            reason: `Action "${normAction}" requires explicit approval`,
        };
        logIronDomeAudit({
            action: 'action_gate',
            actionType: normAction,
            allowed: false,
            reason: result.reason,
            source,
        });
        return result;
    }
    // Default: allow actions not in either list
    result = {
        decision: 'approved',
        action: normAction,
        reason: `Action "${normAction}" is not restricted`,
    };
    logIronDomeAudit({
        action: 'action_gate',
        actionType: normAction,
        allowed: true,
        reason: result.reason,
        source,
    });
    return result;
}
