"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.anonymizeResponseOutput = void 0;
// Check if output is a binary file response (base64 encoded)
// These don't contain PII and are too large for NLP processing
const isBinaryFileOutput = (output) => {
    return (typeof output === 'object' &&
        output !== null &&
        output.type === 'file' &&
        output.encoding === 'base64' &&
        typeof output.data === 'string');
};
// Function to call bulk analyze API for encryption
const callBulkAnalyzeAPI = async (texts, language = 'en') => {
    try {
        const response = await fetch('https://presidio-analyzer.spydra.app/bulk_analyze', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'x-api-key': 'abde3594-4450-41e7-a41c-1450cb0808a9',
            },
            body: JSON.stringify({
                texts,
                language,
            }),
        });
        const result = await response.json();
        return result;
    }
    catch (error) {
        console.error('Error calling bulk analyze API:', error);
        throw error;
    }
};
// Function to anonymize response output
const anonymizeResponseOutput = async (response, language = 'en') => {
    try {
        // If no response or no output, return as is
        if (!response || !response.output) {
            return response;
        }
        // Skip anonymization for binary file responses
        if (isBinaryFileOutput(response.output)) {
            return {
                ...response,
                anonymized_output: response.output,
            };
        }
        const outputText = typeof response.output === 'string' ? response.output : JSON.stringify(response.output);
        // Skip anonymization if text is too long (> 900,000 chars to be safe under 1M limit)
        // This prevents memory allocation errors in NLP models
        const MAX_TEXT_LENGTH = 900000;
        if (outputText.length > MAX_TEXT_LENGTH) {
            console.warn(`[Anonymize] Text length (${outputText.length} chars) exceeds maximum (${MAX_TEXT_LENGTH}). Skipping anonymization.`);
            return {
                ...response,
                anonymized_output: response.output,
            };
        }
        // Call bulk analyze API to detect sensitive information
        const bulkAnalyzeResult = await callBulkAnalyzeAPI([outputText], language);
        // Filter results to only include those with analyzer_results scores > 0.75
        const filteredBulkAnalyzeResult = bulkAnalyzeResult
            .map((item) => {
            if (item.analyzer_results && Array.isArray(item.analyzer_results)) {
                const filteredAnalyzerResults = item.analyzer_results.filter((result) => result.score >= 0.75);
                return {
                    ...item,
                    analyzer_results: filteredAnalyzerResults,
                };
            }
            return item;
        })
            .filter((item) => {
            return item.analyzer_results && item.analyzer_results.length > 0;
        });
        // If no sensitive information detected, return response with original output
        if (filteredBulkAnalyzeResult.length === 0) {
            return {
                ...response,
                anonymized_output: response.output,
            };
        }
        // Create payload for bulk_anonymize endpoint
        const anonymizePayload = filteredBulkAnalyzeResult.map((item) => ({
            text: item.text,
            anonymizers: {
                PERSON: {
                    type: 'fpe',
                    key: 'NjrK7ZmS0zNwN3PsnReNWg==',
                    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz@_. ',
                },
                PHONE_NUMBER: {
                    type: 'fpe',
                    key: 'NjrK7ZmS0zNwN3PsnReNWg==',
                    alphabet: '0123456789+ ()-',
                },
                EMAIL_ADDRESS: {
                    type: 'fpe',
                    key: 'NjrK7ZmS0zNwN3PsnReNWg==',
                    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz@_.',
                },
                PAN: {
                    type: 'fpe',
                    key: 'NjrK7ZmS0zNwN3PsnReNWg==',
                    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz',
                },
                CREDIT_CARD: {
                    type: 'fpe',
                    key: 'NjrK7ZmS0zNwN3PsnReNWg==',
                    alphabet: '0123456789- ',
                },
                LOCATION: {
                    type: 'fpe',
                    key: 'NjrK7ZmS0zNwN3PsnReNWg==',
                    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz@_. ',
                },
            },
            analyzer_results: item.analyzer_results,
        }));
        // Call bulk_anonymize endpoint
        try {
            const anonymizeResponse = await fetch('https://presidio-anonymizer.spydra.app/bulk_anonymize', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'x-api-key': 'abde3594-4450-41e7-a41c-1450cb0808a9',
                },
                body: JSON.stringify(anonymizePayload),
            });
            if (!anonymizeResponse.ok) {
                const errorText = await anonymizeResponse.text();
                console.error('Bulk anonymize API error:', anonymizeResponse.status, errorText);
                // If anonymization fails, return response with original output
                return {
                    ...response,
                    anonymized_output: response.output,
                };
            }
            const anonymizeResult = await anonymizeResponse.json();
            // Update response with anonymized output
            if (anonymizeResult && Array.isArray(anonymizeResult) && anonymizeResult.length > 0) {
                const anonymizedOutput = anonymizeResult[0]?.anonymized_text || response.output;
                return {
                    ...response,
                    anonymized_output: anonymizedOutput,
                };
            }
            // If no anonymization result, return response with original output
            return {
                ...response,
                anonymized_output: response.output,
            };
        }
        catch (anonymizeError) {
            console.error('Error calling bulk anonymize API:', anonymizeError);
            // If anonymization fails, return response with original output
            return {
                ...response,
                anonymized_output: response.output,
            };
        }
    }
    catch (error) {
        console.error('Error anonymizing response output:', error);
        // If anonymization fails, return response with original output
        return {
            ...response,
            anonymized_output: response.output,
        };
    }
};
exports.anonymizeResponseOutput = anonymizeResponseOutput;
//# sourceMappingURL=anonymizeResponse.js.map