import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { ConfigManager } from '../../config/config-manager.js';
import { SecurityScanner } from './scanner.js';
import { SecurityManager } from '../../utils/security-manager.js';
import { promises as fs } from 'fs';
import path from 'path';
let configManager;
let securityScanner;
let securityManager;
export async function setupSecurityTools(server, config) {
    configManager = config || new ConfigManager();
    securityScanner = new SecurityScanner(configManager);
    securityManager = SecurityManager.getInstance();
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
        const { name, arguments: args } = request.params;
        if (!args) {
            throw new Error('No arguments provided');
        }
        switch (name) {
            case 'get_security_status': {
                try {
                    const status = await securityManager.getSecurityStatus();
                    return {
                        content: [{
                                type: 'text',
                                text: formatSecurityStatus(status)
                            }],
                        structured: {
                            type: 'security_status',
                            status,
                            generatedAt: new Date().toISOString()
                        }
                    };
                }
                catch (error) {
                    throw new Error(`Failed to get security status: ${error.message}`);
                }
            }
            case 'get_security_events': {
                const { timeRange = '24h', eventTypes, severity = 'low' } = args;
                try {
                    const events = await securityManager.getSecurityEvents({
                        timeRange,
                        eventTypes,
                        severity
                    });
                    return {
                        content: [{
                                type: 'text',
                                text: formatSecurityEvents(events, timeRange)
                            }],
                        structured: {
                            type: 'security_events',
                            timeRange,
                            eventCount: events.length,
                            events,
                            generatedAt: new Date().toISOString()
                        }
                    };
                }
                catch (error) {
                    throw new Error(`Failed to get security events: ${error.message}`);
                }
            }
            case 'configure_security_policy': {
                const { requireApprovalFor = [], roles = {}, riskThresholds = {}, logLevel = 'info' } = args;
                try {
                    await securityManager.configureSecurityPolicy({
                        requireApprovalFor,
                        roles,
                        riskThresholds,
                        logLevel
                    });
                    return {
                        content: [{
                                type: 'text',
                                text: formatSecurityPolicyUpdate({
                                    requireApprovalFor,
                                    roles,
                                    riskThresholds,
                                    logLevel
                                })
                            }],
                        structured: {
                            type: 'security_policy_updated',
                            configuration: {
                                requireApprovalFor,
                                roles,
                                riskThresholds,
                                logLevel
                            },
                            updatedAt: new Date().toISOString()
                        }
                    };
                }
                catch (error) {
                    throw new Error(`Failed to configure security policy: ${error.message}`);
                }
            }
            case 'process_security_approval': {
                const { approvalId, decision, reason } = args;
                if (!approvalId || !decision) {
                    throw new Error('Approval ID and decision are required');
                }
                try {
                    const result = await securityManager.processApproval({
                        approvalId,
                        decision,
                        reason
                    });
                    return {
                        content: [{
                                type: 'text',
                                text: formatApprovalResult(result)
                            }],
                        structured: {
                            type: 'approval_processed',
                            approvalId,
                            decision,
                            reason,
                            result,
                            processedAt: new Date().toISOString()
                        }
                    };
                }
                catch (error) {
                    throw new Error(`Failed to process approval: ${error.message}`);
                }
            }
            case 'security_scan': {
                const { scanType = 'comprehensive', includeFiles = true, includeDependencies = true, includeSecrets = true, includePermissions = true, outputFormat = 'detailed', } = args;
                try {
                    const config = {
                        scanType,
                        includeFiles,
                        includeDependencies,
                        includeSecrets,
                        includePermissions,
                        outputFormat,
                    };
                    const scanResult = await securityScanner.performScan(config);
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatScanResult(scanResult, outputFormat),
                            },
                        ],
                        structured: {
                            scanResult,
                            timestamp: new Date().toISOString(),
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Security scan failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'check_secrets': {
                const { scanPath = '.', excludePaths = ['.git', 'node_modules', '.atlas'], customPatterns = [], } = args;
                try {
                    const secretsFound = await securityScanner.scanForSecrets({
                        scanPath,
                        excludePaths,
                        customPatterns,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatSecretsReport(secretsFound),
                            },
                        ],
                        structured: {
                            secretsFound,
                            scanCompleted: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Secrets scan failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'vulnerability_check': {
                const { checkNpm = true, checkYarn = true, severity = 'moderate', autoFix = false, } = args;
                try {
                    const vulnerabilities = await securityScanner.checkVulnerabilities({
                        checkNpm,
                        checkYarn,
                        severity,
                        autoFix,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatVulnerabilityReport(vulnerabilities),
                            },
                        ],
                        structured: {
                            vulnerabilities,
                            scanCompleted: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Vulnerability check failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'setup_security_config': {
                const { enablePreCommitScans = true, enableSecretDetection = true, enableVulnerabilityChecks = true, createSecurityPolicy = true, setupGitHooks = true, } = args;
                try {
                    const setupResult = await securityScanner.setupSecurityConfiguration({
                        enablePreCommitScans,
                        enableSecretDetection,
                        enableVulnerabilityChecks,
                        createSecurityPolicy,
                        setupGitHooks,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ Security configuration completed!

📋 Security features enabled:
• Pre-commit scans: ${enablePreCommitScans ? '✅' : '❌'}
• Secret detection: ${enableSecretDetection ? '✅' : '❌'}
• Vulnerability checks: ${enableVulnerabilityChecks ? '✅' : '❌'}
• Security policy: ${createSecurityPolicy ? '✅' : '❌'}
• Git hooks: ${setupGitHooks ? '✅' : '❌'}

📄 Files created:
${setupResult.filesCreated.map(file => `• ${file}`).join('\n')}

🔧 Tools configured:
${setupResult.toolsConfigured.map(tool => `• ${tool}`).join('\n')}

🚀 Next steps:
${setupResult.nextSteps.map((step, i) => `${i + 1}. ${step}`).join('\n')}`,
                            },
                        ],
                        structured: {
                            setupResult,
                            configuration: {
                                enablePreCommitScans,
                                enableSecretDetection,
                                enableVulnerabilityChecks,
                                createSecurityPolicy,
                                setupGitHooks,
                            },
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Security setup failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'generate_security_report': {
                const { includeOverview = true, includeDetails = true, includeRecommendations = true, outputPath = 'SECURITY.md', } = args;
                try {
                    const report = await securityScanner.generateSecurityReport({
                        includeOverview,
                        includeDetails,
                        includeRecommendations,
                    });
                    // Save report to file
                    await fs.writeFile(path.join(process.cwd(), outputPath), report.markdown);
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ Security report generated!

📄 Report saved to: ${outputPath}
📊 Summary:
• Issues found: ${report.summary.totalIssues}
• Critical: ${report.summary.critical}
• High: ${report.summary.high}
• Medium: ${report.summary.medium}
• Low: ${report.summary.low}

📋 Sections included:
• Overview: ${includeOverview ? '✅' : '❌'}
• Details: ${includeDetails ? '✅' : '❌'}
• Recommendations: ${includeRecommendations ? '✅' : '❌'}`,
                            },
                        ],
                        structured: {
                            reportGenerated: true,
                            outputPath,
                            summary: report.summary,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Report generation failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'check_data_access': {
                const { scanPath = '.', excludePaths = ['.git', 'node_modules', 'dist', 'build'], includeWarnings = true, includeSuggestions = true, } = args;
                try {
                    const accessViolations = await securityScanner.checkDataAccess({
                        scanPath,
                        excludePaths,
                        includeWarnings,
                        includeSuggestions,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatDataAccessReport(accessViolations),
                            },
                        ],
                        structured: {
                            violations: accessViolations,
                            scanCompleted: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Data access check failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            default:
                return null;
        }
    });
    return {
        tools: [
            {
                name: 'get_security_status',
                description: 'Get comprehensive security status overview including recent events, policy status, and system health. Use this to monitor overall security posture.',
                inputSchema: {
                    type: 'object',
                    properties: {},
                    required: [],
                    additionalProperties: false
                }
            },
            {
                name: 'get_security_events',
                description: 'Retrieve security events and incidents with filtering options. Use this to investigate security issues and monitor activity.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        timeRange: {
                            type: 'string',
                            enum: ['1h', '24h', '7d', '30d'],
                            default: '24h',
                            description: 'Time range for event retrieval'
                        },
                        eventTypes: {
                            type: 'array',
                            items: {
                                type: 'string',
                                enum: ['access_denied', 'approval_required', 'policy_violation', 'suspicious_activity', 'error']
                            },
                            description: 'Filter events by type'
                        },
                        severity: {
                            type: 'string',
                            enum: ['low', 'medium', 'high', 'critical'],
                            default: 'low',
                            description: 'Minimum severity level to include'
                        }
                    },
                    required: [],
                    additionalProperties: false
                }
            },
            {
                name: 'configure_security_policy',
                description: 'Configure security policies including approval requirements, role definitions, and risk thresholds. Use this to customize security behavior.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        requireApprovalFor: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'List of operations requiring human approval'
                        },
                        roles: {
                            type: 'object',
                            additionalProperties: {
                                type: 'array',
                                items: { type: 'string' }
                            },
                            description: 'Role definitions with permissions'
                        },
                        riskThresholds: {
                            type: 'object',
                            additionalProperties: { type: 'number' },
                            description: 'Risk threshold values for different operations'
                        },
                        logLevel: {
                            type: 'string',
                            enum: ['debug', 'info', 'warn', 'error'],
                            default: 'info',
                            description: 'Security logging level'
                        }
                    },
                    required: [],
                    additionalProperties: false
                }
            },
            {
                name: 'process_security_approval',
                description: 'Process pending security approval requests. Use this to approve or deny operations requiring human authorization.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        approvalId: {
                            type: 'string',
                            description: 'Unique identifier for the approval request',
                            minLength: 1
                        },
                        decision: {
                            type: 'string',
                            enum: ['approve', 'deny'],
                            description: 'Decision for the approval request'
                        },
                        reason: {
                            type: 'string',
                            description: 'Optional reason for the decision'
                        }
                    },
                    required: ['approvalId', 'decision'],
                    additionalProperties: false
                }
            },
            {
                name: 'security_scan',
                description: 'Perform comprehensive security scan of the project',
                inputSchema: {
                    type: 'object',
                    properties: {
                        scanType: {
                            type: 'string',
                            enum: ['quick', 'comprehensive', 'deep'],
                            default: 'comprehensive',
                            description: 'Type of security scan to perform'
                        },
                        includeFiles: {
                            type: 'boolean',
                            default: true,
                            description: 'Scan source files for security issues'
                        },
                        includeDependencies: {
                            type: 'boolean',
                            default: true,
                            description: 'Check dependencies for vulnerabilities'
                        },
                        includeSecrets: {
                            type: 'boolean',
                            default: true,
                            description: 'Scan for exposed secrets and credentials'
                        },
                        includePermissions: {
                            type: 'boolean',
                            default: true,
                            description: 'Check file permissions and access controls'
                        },
                        outputFormat: {
                            type: 'string',
                            enum: ['summary', 'detailed', 'json'],
                            default: 'detailed',
                            description: 'Format for scan results'
                        },
                    },
                    required: []
                },
            },
            {
                name: 'check_secrets',
                description: 'Scan for exposed secrets, API keys, and credentials',
                inputSchema: {
                    type: 'object',
                    properties: {
                        scanPath: {
                            type: 'string',
                            default: '.',
                            description: 'Path to scan for secrets'
                        },
                        excludePaths: {
                            type: 'array',
                            items: { type: 'string' },
                            default: ['.git', 'node_modules', '.atlas'],
                            description: 'Paths to exclude from scanning'
                        },
                        customPatterns: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Custom regex patterns to detect secrets'
                        },
                    },
                    required: []
                },
            },
            {
                name: 'vulnerability_check',
                description: 'Check dependencies for known vulnerabilities',
                inputSchema: {
                    type: 'object',
                    properties: {
                        checkNpm: {
                            type: 'boolean',
                            default: true,
                            description: 'Check npm dependencies'
                        },
                        checkYarn: {
                            type: 'boolean',
                            default: true,
                            description: 'Check yarn dependencies'
                        },
                        severity: {
                            type: 'string',
                            enum: ['low', 'moderate', 'high', 'critical'],
                            default: 'moderate',
                            description: 'Minimum severity level to report'
                        },
                        autoFix: {
                            type: 'boolean',
                            default: false,
                            description: 'Automatically fix vulnerabilities when possible'
                        },
                    },
                    required: []
                },
            },
            {
                name: 'setup_security_config',
                description: 'Configure comprehensive security tools and policies',
                inputSchema: {
                    type: 'object',
                    properties: {
                        enablePreCommitScans: {
                            type: 'boolean',
                            default: true,
                            description: 'Enable security scans in pre-commit hooks'
                        },
                        enableSecretDetection: {
                            type: 'boolean',
                            default: true,
                            description: 'Enable secret detection in CI/CD'
                        },
                        enableVulnerabilityChecks: {
                            type: 'boolean',
                            default: true,
                            description: 'Enable dependency vulnerability checks'
                        },
                        createSecurityPolicy: {
                            type: 'boolean',
                            default: true,
                            description: 'Create SECURITY.md policy file'
                        },
                        setupGitHooks: {
                            type: 'boolean',
                            default: true,
                            description: 'Setup Git hooks for security checks'
                        },
                    },
                    required: []
                },
            },
            {
                name: 'generate_security_report',
                description: 'Generate comprehensive security report for the project',
                inputSchema: {
                    type: 'object',
                    properties: {
                        includeOverview: {
                            type: 'boolean',
                            default: true,
                            description: 'Include security overview section'
                        },
                        includeDetails: {
                            type: 'boolean',
                            default: true,
                            description: 'Include detailed findings'
                        },
                        includeRecommendations: {
                            type: 'boolean',
                            default: true,
                            description: 'Include security recommendations'
                        },
                        outputPath: {
                            type: 'string',
                            default: 'SECURITY.md',
                            description: 'Path to save the security report'
                        },
                    },
                    required: []
                },
            },
            {
                name: 'check_data_access',
                description: 'Monitor and detect improper access to .atlas/ directory',
                inputSchema: {
                    type: 'object',
                    properties: {
                        scanPath: {
                            type: 'string',
                            default: '.',
                            description: 'Path to scan for data access violations'
                        },
                        excludePaths: {
                            type: 'array',
                            items: { type: 'string' },
                            default: ['.git', 'node_modules', 'dist', 'build'],
                            description: 'Paths to exclude from scanning'
                        },
                        includeWarnings: {
                            type: 'boolean',
                            default: true,
                            description: 'Include warnings for potential violations'
                        },
                        includeSuggestions: {
                            type: 'boolean',
                            default: true,
                            description: 'Include suggestions for proper MCP tool usage'
                        },
                    },
                    required: []
                },
            },
        ],
        resources: [],
    };
}
function formatScanResult(result, format) {
    if (format === 'summary') {
        return `🔍 Security Scan Summary

📊 Overall Status: ${result.summary.status}
🎯 Issues Found: ${result.summary.totalIssues}
• Critical: ${result.summary.critical}
• High: ${result.summary.high}
• Medium: ${result.summary.medium}
• Low: ${result.summary.low}

⏱️ Scan completed in ${result.summary.scanTime}ms`;
    }
    const sections = [];
    sections.push(`🔍 Security Scan Results

📊 **Overall Status**: ${result.summary.status}
🎯 **Issues Found**: ${result.summary.totalIssues}
⏱️ **Scan Time**: ${result.summary.scanTime}ms

## Summary by Severity
• 🔴 Critical: ${result.summary.critical}
• 🟠 High: ${result.summary.high}
• 🟡 Medium: ${result.summary.medium}
• 🔵 Low: ${result.summary.low}`);
    if (result.findings.length > 0) {
        sections.push('\n## Findings\n');
        result.findings.forEach((finding, i) => {
            const emoji = getSeverityEmoji(finding.severity);
            sections.push(`${i + 1}. ${emoji} **${finding.title}** (${finding.severity})
   📄 File: ${finding.file || 'N/A'}
   📝 ${finding.description}
   ${finding.recommendation ? `💡 Recommendation: ${finding.recommendation}` : ''}`);
        });
    }
    if (result.recommendations?.length > 0) {
        sections.push('\n## Recommendations\n');
        result.recommendations.forEach((rec, i) => {
            sections.push(`${i + 1}. ${rec}`);
        });
    }
    return sections.join('\n');
}
function formatSecretsReport(secrets) {
    if (secrets.length === 0) {
        return `✅ No secrets detected!

🔍 Scanned for common secret patterns:
• API keys
• Database credentials
• Authentication tokens
• Private keys
• Passwords

Your codebase appears to be free of exposed secrets.`;
    }
    return `⚠️ Secrets detected in your codebase!

🚨 **${secrets.length} potential secret(s) found:**

${secrets.map((secret, i) => `${i + 1}. **${secret.type}** in ${secret.file}:${secret.line}
   Pattern: ${secret.pattern}
   ${secret.severity === 'high' ? '🔴 HIGH RISK' : secret.severity === 'medium' ? '🟡 MEDIUM RISK' : '🔵 LOW RISK'}`).join('\n\n')}

💡 **Immediate Actions Required:**
1. Remove or encrypt these secrets
2. Rotate any exposed credentials
3. Add these files to .gitignore if needed
4. Use environment variables for sensitive data`;
}
function formatVulnerabilityReport(vulnerabilities) {
    if (vulnerabilities.total === 0) {
        return `✅ No vulnerabilities found!

🛡️ All dependencies are up to date and secure.
Last checked: ${new Date().toISOString()}`;
    }
    return `⚠️ Vulnerabilities found in dependencies!

📊 **Summary:**
• Total vulnerabilities: ${vulnerabilities.total}
• Critical: ${vulnerabilities.critical}
• High: ${vulnerabilities.high}
• Moderate: ${vulnerabilities.moderate}
• Low: ${vulnerabilities.low}

${vulnerabilities.details?.length > 0 ? `
🔍 **Top Vulnerabilities:**
${vulnerabilities.details.slice(0, 5).map((vuln, i) => `${i + 1}. ${vuln.name} (${vuln.severity})
   📦 Package: ${vuln.package}
   🔧 Fix: ${vuln.recommendation}`).join('\n\n')}` : ''}

💡 **Recommended Actions:**
1. Run 'npm audit fix' to auto-fix issues
2. Update vulnerable packages manually
3. Consider alternative packages for unfixable issues
4. Monitor dependencies regularly`;
}
function getSeverityEmoji(severity) {
    switch (severity.toLowerCase()) {
        case 'critical': return '🔴';
        case 'high': return '🟠';
        case 'medium': return '🟡';
        case 'low': return '🔵';
        default: return '⚪';
    }
}
function formatDataAccessReport(violations) {
    if (!violations || violations.length === 0) {
        return `✅ No data access violations detected!

🔍 Scanned for:
• Direct .atlas/ directory access
• Hardcoded paths to Atlas data
• Bypassing MCP tool layer
• Improper data file imports

Your code properly uses MCP tools for all data access. Great job! 🎉`;
    }
    const violationsByType = violations.reduce((acc, v) => {
        acc[v.type] = (acc[v.type] || 0) + 1;
        return acc;
    }, {});
    return `⚠️ Data access violations detected!

🚨 **${violations.length} violation(s) found**

📊 **Violations by Type:**
${Object.entries(violationsByType).map(([type, count]) => `• ${type}: ${count}`).join('\n')}

## Detailed Violations:

${violations.slice(0, 10).map((v, i) => `### ${i + 1}. ${v.severity} - ${v.type}
📄 **File**: ${v.file}:${v.line}
📝 **Issue**: ${v.description}
💡 **Fix**: ${v.suggestion}
\`\`\`typescript
${v.codeSnippet}
\`\`\`
`).join('\n')}

${violations.length > 10 ? `\n... and ${violations.length - 10} more violations\n` : ''}

## 🛠️ How to Fix:

1. **Replace direct file access** with MCP tool calls
2. **Remove hardcoded paths** to .atlas/ directory
3. **Use provided MCP tools** for all data operations

### Common Replacements:

| Instead of... | Use... |
|--------------|--------|
| \`fs.readFile('.atlas/...')\` | \`mcp.call('appropriate_tool')\` |
| \`require('.atlas/...')\` | MCP tool for that data type |
| Direct JSON parsing | MCP data access tools |

### Available MCP Tools:
- \`check_project_status\` - Project configuration
- \`list_boards\`, \`get_tasks\` - Task management  
- \`search_memories\` - Memory queries
- \`perform_business_review\` - Business data
- \`run_tests\` - Test results

Run this check regularly to ensure compliance with data access patterns!`;
}
function formatSecurityStatus(status) {
    const { overall, recentEvents, policies, alerts } = status;
    return `# Security Status Report

## 🛡️ Overall Security Health: ${overall.status}

### System Status
- **Security Level**: ${overall.level}
- **Last Scan**: ${overall.lastScan}
- **Active Policies**: ${policies?.active || 0}
- **Pending Approvals**: ${overall.pendingApprovals || 0}

### Recent Activity (24h)
- **Security Events**: ${recentEvents?.total || 0}
- **Access Denials**: ${recentEvents?.denials || 0}
- **Policy Violations**: ${recentEvents?.violations || 0}
- **Approvals Processed**: ${recentEvents?.approvals || 0}

${alerts?.length > 0 ? `
### 🚨 Active Alerts
${alerts.slice(0, 3).map((alert, i) => `${i + 1}. **${alert.severity.toUpperCase()}**: ${alert.message}`).join('\n')}
${alerts.length > 3 ? `\n... and ${alerts.length - 3} more alerts` : ''}
` : '### ✅ No Active Security Alerts'}

### Security Policies
- **Access Control**: ${policies?.accessControl ? 'Enabled' : 'Disabled'}
- **Human Approval**: ${policies?.humanApproval ? 'Enabled' : 'Disabled'}
- **Audit Logging**: ${policies?.auditLogging ? 'Enabled' : 'Disabled'}
- **Risk Assessment**: ${policies?.riskAssessment ? 'Enabled' : 'Disabled'}

💡 **Recommendations**:
${overall.recommendations?.slice(0, 3).map((rec, i) => `${i + 1}. ${rec}`).join('\n') || 'All security measures are properly configured.'}`;
}
function formatSecurityEvents(events, timeRange) {
    if (events.length === 0) {
        return `# Security Events Report (${timeRange})

✅ **No security events found** in the specified time range.

This indicates:
- No unauthorized access attempts
- No policy violations  
- No suspicious activity detected
- System operating normally

Continue monitoring for security events regularly.`;
    }
    const eventsByType = events.reduce((acc, event) => {
        acc[event.type] = (acc[event.type] || 0) + 1;
        return acc;
    }, {});
    const eventsBySeverity = events.reduce((acc, event) => {
        acc[event.severity] = (acc[event.severity] || 0) + 1;
        return acc;
    }, {});
    return `# Security Events Report (${timeRange})

## 📊 Summary
- **Total Events**: ${events.length}
- **Time Range**: ${timeRange}

### Events by Type
${Object.entries(eventsByType).map(([type, count]) => `- **${type}**: ${count}`).join('\n')}

### Events by Severity  
${Object.entries(eventsBySeverity).map(([severity, count]) => `- **${severity}**: ${count}`).join('\n')}

## 🔍 Recent Events

${events.slice(0, 10).map((event, i) => `### ${i + 1}. ${getSeverityEmoji(event.severity)} ${event.type.replace('_', ' ').toUpperCase()}
- **Time**: ${event.timestamp}
- **Severity**: ${event.severity}
- **Description**: ${event.description}
- **Source**: ${event.source || 'System'}
${event.details ? `- **Details**: ${event.details}` : ''}
${event.action ? `- **Action Taken**: ${event.action}` : ''}`).join('\n\n')}

${events.length > 10 ? `\n... and ${events.length - 10} more events\n` : ''}

## 🛠️ Recommendations

${events.some((e) => e.severity === 'critical' || e.severity === 'high') ? `
⚠️ **High-priority events detected**:
1. Review critical and high-severity events immediately
2. Investigate unauthorized access attempts
3. Consider strengthening security policies
4. Enable additional monitoring if needed
` : `
✅ **Security status is healthy**:
1. Continue regular monitoring
2. Review events periodically
3. Keep security policies updated
4. Consider automated alerting for critical events
`}`;
}
function formatSecurityPolicyUpdate(config) {
    const { requireApprovalFor, roles, riskThresholds, logLevel } = config;
    return `# Security Policy Updated Successfully

## 🔧 Configuration Changes

### Approval Requirements
${requireApprovalFor?.length > 0 ? `
**Operations requiring human approval**:
${requireApprovalFor.map((op, i) => `${i + 1}. ${op}`).join('\n')}
` : '**No specific approval requirements set** (using system defaults)'}

### Role Definitions
${Object.keys(roles).length > 0 ? `
**Role-based permissions**:
${Object.entries(roles).map(([role, perms]) => `- **${role}**: ${Array.isArray(perms) ? perms.join(', ') : perms}`).join('\n')}
` : '**Using default role permissions**'}

### Risk Thresholds
${Object.keys(riskThresholds).length > 0 ? `
**Risk assessment thresholds**:
${Object.entries(riskThresholds).map(([operation, threshold]) => `- **${operation}**: ${threshold}`).join('\n')}
` : '**Using default risk thresholds**'}

### Logging Configuration
- **Log Level**: ${logLevel}
- **Audit Trail**: Enabled
- **Event Monitoring**: Active

## ✅ Policy Status
- Configuration applied successfully
- Security validation enabled
- Monitoring active
- Ready for operation

💡 **Next Steps**:
1. Test the new policy with non-critical operations
2. Monitor security events for any issues
3. Adjust thresholds if needed
4. Notify team members of any changes`;
}
function formatApprovalResult(result) {
    const { approvalId, operation, decision, reason, executionResult } = result;
    const statusEmoji = decision === 'approve' ? '✅' : '❌';
    const statusText = decision === 'approve' ? 'APPROVED' : 'DENIED';
    return `# Security Approval Processed

## ${statusEmoji} Request ${statusText}

### Approval Details
- **Approval ID**: ${approvalId}
- **Operation**: ${operation}
- **Decision**: ${decision.toUpperCase()}
- **Processed At**: ${new Date().toISOString()}
${reason ? `- **Reason**: ${reason}` : ''}

${decision === 'approve' && executionResult ? `
### Execution Result
- **Status**: ${executionResult.success ? 'Success' : 'Failed'}
${executionResult.message ? `- **Message**: ${executionResult.message}` : ''}
${executionResult.data ? `- **Data**: ${JSON.stringify(executionResult.data, null, 2)}` : ''}
` : ''}

${decision === 'deny' ? `
### ⚠️ Operation Blocked
The requested operation has been blocked and will not be executed.
${reason ? `Security team reason: ${reason}` : ''}
` : ''}

### Security Log
This approval decision has been logged for audit purposes:
- Approval request and decision recorded
- Security event generated
- Audit trail updated
- Compliance requirements met

💡 **What happens next**:
${decision === 'approve' ?
        `1. Operation has been executed
2. Results are available above  
3. Security monitoring continues
4. No further action required` :
        `1. Operation was blocked for security
2. Requester has been notified
3. Alternative approaches may be needed
4. Security team can provide guidance`}`;
}
//# sourceMappingURL=index.js.map