// Download Interceptor Script
// Intercepts JavaScript-based downloads (fetch, XMLHttpRequest, Blob URLs)

(function() {
    'use strict';
    
    console.log('🔍 Download interceptor script loaded');
    
    // Intercept fetch() calls
    const originalFetch = window.fetch;
    window.fetch = function(...args) {
        const url = args[0];
        console.log('🌐 Fetch called:', url);
        
        // Check if this looks like a download
        if (typeof url === 'string') {
            const urlLower = url.toLowerCase();
            const downloadPatterns = [
                '/download', '/export', '/file', 
                '.pdf', '.zip', '.xlsx', '.docx', 
                'attachment', 'content-disposition'
            ];
            
            if (downloadPatterns.some(pattern => urlLower.includes(pattern))) {
                console.log('📥 Potential download detected via fetch:', url);
            }
        }
        
        return originalFetch.apply(this, args);
    };
    
    // Intercept XMLHttpRequest
    const originalXHROpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function(method, url, ...rest) {
        console.log('🌐 XHR opened:', method, url);
        this._url = url;
        return originalXHROpen.apply(this, [method, url, ...rest]);
    };
    
    const originalXHRSend = XMLHttpRequest.prototype.send;
    XMLHttpRequest.prototype.send = function(...args) {
        console.log('📤 XHR send:', this._url);
        return originalXHRSend.apply(this, args);
    };
    
    // Intercept Blob URL creation
    const originalCreateObjectURL = URL.createObjectURL;
    URL.createObjectURL = function(blob) {
        console.log('🔗 Blob URL created, size:', blob.size, 'type:', blob.type);
        return originalCreateObjectURL.apply(this, arguments);
    };
    
    // Intercept anchor clicks that might be downloads
    document.addEventListener('click', function(e) {
        const target = e.target.closest('a');
        if (target && target.href) {
            const href = target.href;
            const download = target.getAttribute('download');
            
            if (download !== null) {
                console.log('📥 Download link clicked:', href, 'filename:', download);
            }
            
            // Check for blob URLs
            if (href.startsWith('blob:')) {
                console.log('📦 Blob download link clicked:', href);
            }
        }
    }, true);
    
    console.log('✅ Download interceptor active');
})();
