/**
 * 🔐 Code Integrity Checker
 * Provides basic protection against source code modification attacks
 */

import { createHash } from 'crypto';
import { readFileSync, existsSync } from 'fs';
import { join } from 'path';

export class CodeIntegrityChecker {
  constructor() {
    this.criticalFiles = [
      'src/licensing/licenseManager.js',
      'src/licensing/licenseEnforcementEngine.js',
      'src/licensing/mcpLicenseValidator.js',
      'src/index.js'
    ];
    
    this.expectedChecksums = new Map();
    this.integrityViolations = [];
  }

  /**
   * Initialize integrity checking
   */
  async initialize() {
    try {
      console.log('🔐 Initializing code integrity checker...');
      
      // Calculate checksums for critical files
      for (const filePath of this.criticalFiles) {
        const checksum = this.calculateFileChecksum(filePath);
        if (checksum) {
          this.expectedChecksums.set(filePath, checksum);
        }
      }
      
      console.log(`🔐 Code integrity baseline established for ${this.expectedChecksums.size} files`);
      return true;
    } catch (error) {
      console.error('❌ Code integrity checker initialization failed:', error.message);
      return false;
    }
  }

  /**
   * Calculate SHA-256 checksum of a file
   */
  calculateFileChecksum(filePath) {
    try {
      const fullPath = join(process.cwd(), filePath);
      
      if (!existsSync(fullPath)) {
        console.warn(`⚠️ Critical file not found: ${filePath}`);
        return null;
      }
      
      const content = readFileSync(fullPath, 'utf8');
      
      // Normalize content (remove comments and whitespace variations)
      const normalizedContent = this.normalizeCode(content);
      
      const hash = createHash('sha256');
      hash.update(normalizedContent);
      return hash.digest('hex');
      
    } catch (error) {
      console.error(`❌ Failed to calculate checksum for ${filePath}:`, error.message);
      return null;
    }
  }

  /**
   * Normalize code content for consistent checksums
   */
  normalizeCode(content) {
    return content
      // Remove single-line comments
      .replace(/\/\/.*$/gm, '')
      // Remove multi-line comments
      .replace(/\/\*[\s\S]*?\*\//g, '')
      // Normalize whitespace
      .replace(/\s+/g, ' ')
      // Remove leading/trailing whitespace
      .trim();
  }

  /**
   * Verify integrity of critical files
   */
  async verifyIntegrity() {
    try {
      console.log('🔐 Verifying code integrity...');
      
      let violations = 0;
      this.integrityViolations = [];
      
      for (const [filePath, expectedChecksum] of this.expectedChecksums) {
        const currentChecksum = this.calculateFileChecksum(filePath);
        
        if (!currentChecksum) {
          this.integrityViolations.push({
            file: filePath,
            type: 'FILE_MISSING',
            message: 'Critical file is missing'
          });
          violations++;
          continue;
        }
        
        if (currentChecksum !== expectedChecksum) {
          this.integrityViolations.push({
            file: filePath,
            type: 'CHECKSUM_MISMATCH',
            message: 'File has been modified',
            expected: expectedChecksum.substring(0, 16) + '...',
            actual: currentChecksum.substring(0, 16) + '...'
          });
          violations++;
        }
      }
      
      if (violations > 0) {
        console.error(`🚨 CODE INTEGRITY VIOLATIONS DETECTED: ${violations} file(s) modified`);
        for (const violation of this.integrityViolations) {
          console.error(`  ❌ ${violation.file}: ${violation.message}`);
        }
        return false;
      }
      
      console.log('✅ Code integrity verification passed');
      return true;
      
    } catch (error) {
      console.error('❌ Code integrity verification failed:', error.message);
      return false;
    }
  }

  /**
   * Get integrity status
   */
  getIntegrityStatus() {
    return {
      filesMonitored: this.criticalFiles.length,
      violations: this.integrityViolations.length,
      violationDetails: this.integrityViolations,
      lastCheck: new Date().toISOString()
    };
  }

  /**
   * Enable runtime integrity monitoring
   */
  enableRuntimeMonitoring(intervalMs = 300000) { // 5 minutes
    console.log(`🔐 Enabling runtime integrity monitoring (${intervalMs}ms interval)`);
    
    setInterval(async () => {
      const isValid = await this.verifyIntegrity();
      if (!isValid) {
        console.error('🚨 SECURITY ALERT: Code integrity violations detected during runtime!');
        // In production, this could trigger additional security measures
      }
    }, intervalMs);
  }

  /**
   * Check if integrity violations should block operations
   */
  shouldBlockOperations() {
    // For now, we'll log violations but not block operations
    // In a production environment, this could be more strict
    return this.integrityViolations.length > 2; // Block if more than 2 files modified
  }

  /**
   * Generate integrity report
   */
  generateIntegrityReport() {
    const report = {
      timestamp: new Date().toISOString(),
      status: this.integrityViolations.length === 0 ? 'SECURE' : 'COMPROMISED',
      filesMonitored: this.criticalFiles.length,
      violations: this.integrityViolations.length,
      details: this.integrityViolations.map(v => ({
        file: v.file,
        type: v.type,
        message: v.message
      }))
    };
    
    return report;
  }
}

/**
 * 🔐 SECURITY WARNING SYSTEM
 * Display security warnings for integrity violations
 */
export function displaySecurityWarnings(integrityChecker) {
  const status = integrityChecker.getIntegrityStatus();
  
  if (status.violations > 0) {
    console.log('\n🚨 SECURITY WARNING: CODE INTEGRITY VIOLATIONS DETECTED');
    console.log('='.repeat(60));
    console.log('The following critical files have been modified:');
    
    for (const violation of status.violationDetails) {
      console.log(`  ❌ ${violation.file}: ${violation.message}`);
    }
    
    console.log('\n⚠️  This could indicate:');
    console.log('   • Unauthorized code modification');
    console.log('   • Potential security compromise');
    console.log('   • License bypass attempts');
    console.log('\n🔐 Recommendation: Verify file integrity and restore from trusted source');
    console.log('='.repeat(60));
  }
}

/**
 * 🔐 ANTI-TAMPERING MEASURES
 * Basic protection against common tampering techniques
 */
export class AntiTamperingProtection {
  constructor() {
    this.tamperingAttempts = [];
  }

  /**
   * Detect common tampering patterns
   */
  detectTampering() {
    const suspiciousPatterns = [
      // Check for debugger statements
      /debugger\s*;/gi,
      // Check for eval usage
      /eval\s*\(/gi,
      // Check for license bypass patterns
      /return\s+true\s*;.*license/gi,
      // Check for test license patterns in production
      /ZAI-TEST-.*BYPASS/gi
    ];

    // This is a basic implementation - in production, this would be more sophisticated
    console.log('🔐 Anti-tampering protection active');
    return false; // No tampering detected in this basic implementation
  }

  /**
   * Log tampering attempts
   */
  logTamperingAttempt(type, details) {
    const attempt = {
      timestamp: new Date().toISOString(),
      type,
      details,
      stackTrace: new Error().stack
    };
    
    this.tamperingAttempts.push(attempt);
    console.error(`🚨 TAMPERING ATTEMPT DETECTED: ${type}`, details);
  }
}
