"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.encryptGeneratedDatasetRows = encryptGeneratedDatasetRows;
const logger_1 = __importDefault(require("../../logger"));
const callBulkAnalyzeAPI = async (texts, language) => {
    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,
        }),
    });
    return response.json();
};
/**
 * Encrypt / anonymize field values for rows that use `includeEncryptField` (same behavior as
 * preview generation in `generate-dataset.ts`). Mutates row objects in place.
 */
async function encryptGeneratedDatasetRows(rows, fields, presidioLanguage) {
    if (!Array.isArray(rows) || rows.length === 0 || !Array.isArray(fields) || fields.length === 0) {
        return rows;
    }
    const fieldsToEncrypt = fields.filter((field) => field?.includeEncryptField && field?.name);
    if (fieldsToEncrypt.length === 0) {
        return rows;
    }
    try {
        const batchSize = 10;
        const encryptedResults = [];
        for (let i = 0; i < rows.length; i += batchSize) {
            const batch = rows.slice(i, i + batchSize);
            const textsToAnalyze = [];
            for (const row of batch) {
                for (const field of fieldsToEncrypt) {
                    const name = String(field.name);
                    if (row[name] !== undefined && row[name] !== null) {
                        textsToAnalyze.push(`${name}: ${row[name]}`);
                    }
                }
            }
            if (textsToAnalyze.length === 0) {
                encryptedResults.push(...batch);
                continue;
            }
            const bulkAnalyzeResult = await callBulkAnalyzeAPI(textsToAnalyze, presidioLanguage);
            if (!Array.isArray(bulkAnalyzeResult)) {
                logger_1.default.warn('Presidio bulk_analyze returned non-array; skipping encryption for this batch');
                encryptedResults.push(...batch);
                continue;
            }
            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) => item.analyzer_results && item.analyzer_results.length > 0);
            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,
            }));
            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 anonymizeResult = await anonymizeResponse.json();
                    if (anonymizeResult && Array.isArray(anonymizeResult)) {
                        const textToAnonymizedMap = new Map();
                        anonymizeResult.forEach((item) => {
                            textToAnonymizedMap.set(item.text, item.anonymized_text);
                        });
                        for (const row of batch) {
                            for (const field of fieldsToEncrypt) {
                                const fieldName = String(field.name);
                                if (row[fieldName] !== undefined) {
                                    const originalText = `${fieldName}: ${row[fieldName]}`;
                                    const anonymizedText = textToAnonymizedMap.get(originalText);
                                    if (anonymizedText) {
                                        const colonIndex = anonymizedText.indexOf(':');
                                        if (colonIndex !== -1) {
                                            row[fieldName] = anonymizedText.substring(colonIndex + 1).trim();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else {
                    const errorText = await anonymizeResponse.text();
                    logger_1.default.error(`Bulk anonymize API error: ${anonymizeResponse.status} - ${errorText}`);
                }
            }
            catch (anonymizeError) {
                logger_1.default.error(`Error calling bulk anonymize API: ${anonymizeError}`);
            }
            encryptedResults.push(...batch);
        }
        return encryptedResults;
    }
    catch (error) {
        logger_1.default.error(`Error encrypting generated dataset rows: ${error}`);
        return rows;
    }
}
//# sourceMappingURL=datasetEncryptGeneratedRows.js.map