import { HIGH_RISK_OPERATIONS } from '../approval-system/types.js';
export class ApprovalToolWrapper {
    server;
    approvalManager;
    originalHandlers = new Map();
    pendingApprovals = new Map();
    constructor(server, approvalManager) {
        this.server = server;
        this.approvalManager = approvalManager;
    }
    wrapTool(toolName, handler) {
        return async (request) => {
            const { name, arguments: args } = request.params;
            // Check if this operation requires approval
            const requiresApproval = this.checkRequiresApproval(toolName, name, args);
            if (requiresApproval) {
                // Check if we have a pending approval for this exact request
                const approvalKey = this.generateApprovalKey(toolName, name, args);
                const pendingApproval = this.pendingApprovals.get(approvalKey);
                if (pendingApproval && pendingApproval.status === 'approved') {
                    // Execute the approved action
                    this.pendingApprovals.delete(approvalKey);
                    return handler(request);
                }
                // Create approval request
                const approvalRequest = await this.approvalManager.createApprovalRequest({
                    toolName,
                    action: name,
                    parameters: args,
                    userId: args.userId || 'system',
                    ttl: this.getApprovalTTL(toolName, name)
                });
                if (!approvalRequest) {
                    // Auto-approved
                    return handler(request);
                }
                // Store pending approval
                this.pendingApprovals.set(approvalKey, {
                    request: approvalRequest,
                    originalRequest: request,
                    status: 'pending'
                });
                // Set up approval listener
                this.approvalManager.once('approval-granted', (approved) => {
                    if (approved.id === approvalRequest.id) {
                        const pending = this.pendingApprovals.get(approvalKey);
                        if (pending) {
                            pending.status = 'approved';
                        }
                    }
                });
                this.approvalManager.once('approval-rejected', (rejected) => {
                    if (rejected.id === approvalRequest.id) {
                        this.pendingApprovals.delete(approvalKey);
                    }
                });
                // Return approval required message
                return {
                    content: [{
                            type: 'text',
                            text: `⚠️ Approval Required for High-Risk Operation

**Tool**: ${toolName}
**Action**: ${name}
**Risk Level**: ${approvalRequest.riskLevel}
**Impact**: ${approvalRequest.impact.join(', ')}

This operation requires approval before execution. 

Request ID: ${approvalRequest.id}

To approve this operation:
1. Review the parameters and impact
2. Use \`approve_request\` with the request ID
3. The operation will execute automatically once approved

To check pending approvals: \`list_pending_approvals\``
                        }],
                    structured: {
                        approvalRequired: true,
                        requestId: approvalRequest.id,
                        toolName,
                        action: name
                    }
                };
            }
            // No approval required, execute normally
            return handler(request);
        };
    }
    checkRequiresApproval(toolName, action, args) {
        // Check HIGH_RISK_OPERATIONS
        if (HIGH_RISK_OPERATIONS[toolName]?.[action]) {
            return true;
        }
        // Check custom policies from approval manager
        const policy = this.approvalManager.getActionPolicy(toolName, action);
        return policy.requiresApproval;
    }
    generateApprovalKey(toolName, action, args) {
        // Create a unique key for this specific request
        return `${toolName}:${action}:${JSON.stringify(args)}`;
    }
    getApprovalTTL(toolName, action) {
        const risk = HIGH_RISK_OPERATIONS[toolName]?.[action];
        if (!risk)
            return 1800; // 30 minutes default
        switch (risk.riskLevel) {
            case 'critical': return 300; // 5 minutes
            case 'high': return 900; // 15 minutes
            case 'medium': return 1800; // 30 minutes
            default: return 3600; // 1 hour
        }
    }
    wrapAllTools(toolHandlers) {
        const wrappedHandlers = new Map();
        for (const [toolName, handler] of toolHandlers) {
            wrappedHandlers.set(toolName, this.wrapTool(toolName, handler));
        }
        return wrappedHandlers;
    }
}
//# sourceMappingURL=tool-wrapper.js.map