"use strict";
/**
 * Compliance Service
 * Provides unified compliance and security management functionality
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ComplianceService = void 0;
class ComplianceService {
    constructor(config = {}) {
        this.securityEvents = [];
        this.config = {
            enableDataAccessValidation: true,
            enableSecurityLogging: true,
            frameworks: ['GDPR', 'HIPAA', 'SOC2', 'ISO27001'],
            dataLocalization: {
                enabled: true,
                defaultRegion: 'US',
            },
            codeOwnership: {
                enabled: true,
                requireCodeowners: true,
            },
            ...config,
        };
    }
    /**
     * Log a security event
     */
    async logSecurityEvent(event) {
        if (!this.config.enableSecurityLogging) {
            return;
        }
        const securityEvent = {
            ...event,
            timestamp: new Date().toISOString(),
        };
        this.securityEvents.push(securityEvent);
        // In a real implementation, this would send to logging service
        console.log('Security event logged:', securityEvent);
    }
    /**
     * Validate data access permissions
     */
    async validateDataAccess(request) {
        if (!this.config.enableDataAccessValidation) {
            return {
                allowed: true,
                reason: 'Data access validation is disabled',
            };
        }
        // Check tenant isolation
        if (request.userTenant !== request.entityTenant) {
            // Check if user has cross-tenant access
            if (!request.roles.includes('admin') && !request.roles.includes('cross_tenant_access')) {
                return {
                    allowed: false,
                    reason: 'Cross-tenant access denied',
                    additionalInfo: {
                        userTenant: request.userTenant,
                        entityTenant: request.entityTenant,
                    },
                };
            }
        }
        // Check operation permissions
        const requiredRole = this.getRequiredRole(request.operation, request.entityType);
        if (requiredRole && !request.roles.includes(requiredRole)) {
            return {
                allowed: false,
                reason: `Insufficient permissions for ${request.operation} on ${request.entityType}`,
                additionalInfo: {
                    requiredRole,
                    userRoles: request.roles,
                },
            };
        }
        return {
            allowed: true,
            reason: 'Access granted',
        };
    }
    /**
     * Analyze code ownership
     */
    async analyzeCodeOwnership(repositoryPath) {
        // Mock implementation - would integrate with actual code analysis tools
        return {
            files: [
                {
                    path: 'src/components/Button.tsx',
                    owners: ['@ui-team', '@accessibility-team'],
                    lastModified: '2025-01-07T10:00:00Z',
                    reviewerPredictions: ['alice@company.com', 'bob@company.com'],
                },
                {
                    path: 'src/services/api.ts',
                    owners: ['@backend-team'],
                    lastModified: '2025-01-06T15:30:00Z',
                    reviewerPredictions: ['charlie@company.com'],
                },
            ],
            silos: [
                {
                    area: 'legacy-auth',
                    owners: ['old-dev@company.com'],
                    riskLevel: 'high',
                },
            ],
            complianceScore: 85,
        };
    }
    /**
     * Detect knowledge silos
     */
    async detectKnowledgeSilos(repositoryPath) {
        const analysis = await this.analyzeCodeOwnership(repositoryPath);
        return analysis.silos;
    }
    /**
     * Predict reviewers for changes
     */
    async predictReviewers(mergeRequestData) {
        // Mock implementation - would use ML/AI for actual predictions
        const ownershipAnalysis = await this.analyzeCodeOwnership('');
        const predictedReviewers = new Set();
        for (const file of mergeRequestData.changedFiles) {
            const fileInfo = ownershipAnalysis.files.find(f => f.path === file);
            if (fileInfo) {
                fileInfo.reviewerPredictions.forEach(reviewer => predictedReviewers.add(reviewer));
            }
        }
        return Array.from(predictedReviewers).filter(reviewer => reviewer !== mergeRequestData.author);
    }
    /**
     * Generate compliance report
     */
    async generateComplianceReport(repositoryPath, frameworks = this.config.frameworks) {
        const timestamp = new Date().toISOString();
        const codeOwnership = await this.analyzeCodeOwnership(repositoryPath);
        const frameworkReports = frameworks.map(framework => {
            const score = this.calculateFrameworkScore(framework, codeOwnership);
            return {
                name: framework,
                status: score >= 80 ? 'compliant' : score >= 60 ? 'warning' : 'non-compliant',
                score,
                issues: this.getFrameworkIssues(framework, codeOwnership),
            };
        });
        const overallScore = frameworkReports.reduce((sum, f) => sum + f.score, 0) / frameworkReports.length;
        return {
            timestamp,
            frameworks: frameworkReports,
            overallScore,
            summary: this.generateComplianceSummary(frameworkReports, overallScore),
        };
    }
    /**
     * Get compliance dashboard data
     */
    async getComplianceDashboardData() {
        const today = new Date().toDateString();
        const eventsToday = this.securityEvents.filter(event => new Date(event.timestamp).toDateString() === today).length;
        const report = await this.generateComplianceReport('');
        const criticalIssues = report.frameworks.reduce((sum, f) => sum + f.issues.filter(i => i.severity === 'critical').length, 0);
        return {
            securityStats: {
                eventsToday,
                criticalIssues,
                complianceScore: Math.round(report.overallScore),
            },
            recentEvents: this.securityEvents.slice(-10),
            complianceStatus: report.frameworks.map(f => ({
                framework: f.name,
                status: f.status,
                score: f.score,
            })),
        };
    }
    /**
     * Generate dashboard CSS styles
     */
    getDashboardStyles() {
        return `
.unified-compliance-dashboard {
  margin: 20px 0;
  padding: 0;
}

.dashboard-header {
  margin-bottom: 20px;
}

.dashboard-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  grid-gap: 20px;
}

.dashboard-item {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.security-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 10px;
  background: #f9f9f9;
  border-radius: 4px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

.status-indicator {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  border-radius: 4px;
  margin-bottom: 10px;
}

.status-indicator.passing {
  background: #dff0d8;
  color: #3c763d;
}

.status-indicator.warning {
  background: #fcf8e3;
  color: #8a6d3b;
}

.status-indicator.failing {
  background: #f2dede;
  color: #a94442;
}

.event-item {
  padding: 8px;
  margin-bottom: 8px;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
}

.event-item.info {
  background: #e8f4fd;
}

.event-item.warning {
  background: #fff8e6;
}

.event-item.error {
  background: #feeeee;
}

.event-item.critical {
  background: #ffdede;
}
`;
    }
    getRequiredRole(operation, entityType) {
        const roleMap = {
            'create': 'editor',
            'update': 'editor',
            'delete': 'admin',
            'publish': 'publisher',
        };
        return roleMap[operation] || null;
    }
    calculateFrameworkScore(framework, codeOwnership) {
        // Mock scoring logic - would be more sophisticated in real implementation
        let score = codeOwnership.complianceScore;
        if (framework === 'GDPR') {
            // Penalize if data localization is not properly configured
            if (!this.config.dataLocalization.enabled) {
                score -= 20;
            }
        }
        if (framework === 'SOC2') {
            // Penalize for high-risk knowledge silos
            const highRiskSilos = codeOwnership.silos.filter(s => s.riskLevel === 'high');
            score -= highRiskSilos.length * 10;
        }
        return Math.max(0, Math.min(100, score));
    }
    getFrameworkIssues(framework, codeOwnership) {
        const issues = [];
        if (framework === 'GDPR' && !this.config.dataLocalization.enabled) {
            issues.push({
                severity: 'high',
                description: 'Data localization not properly configured',
                recommendation: 'Enable and configure data localization settings',
            });
        }
        codeOwnership.silos.forEach(silo => {
            if (silo.riskLevel === 'high') {
                issues.push({
                    severity: 'medium',
                    description: `Knowledge silo detected in ${silo.area}`,
                    recommendation: 'Distribute knowledge and add additional code owners',
                });
            }
        });
        return issues;
    }
    generateComplianceSummary(frameworks, overallScore) {
        const compliantFrameworks = frameworks.filter(f => f.status === 'compliant').length;
        const totalFrameworks = frameworks.length;
        if (overallScore >= 80) {
            return `Excellent compliance score! ${compliantFrameworks}/${totalFrameworks} frameworks are fully compliant.`;
        }
        else if (overallScore >= 60) {
            return `Good compliance score with room for improvement. ${compliantFrameworks}/${totalFrameworks} frameworks are fully compliant.`;
        }
        else {
            return `Compliance needs attention. Only ${compliantFrameworks}/${totalFrameworks} frameworks are fully compliant.`;
        }
    }
}
exports.ComplianceService = ComplianceService;
exports.default = ComplianceService;
//# sourceMappingURL=compliance-service.js.map