"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VectorBatchOperations = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
/**
 * Vector Batch Operations Component
 *
 * A component for performing batch operations on vector databases,
 * including import, export, and bulk modifications.
 */
const react_1 = require("react");
const ui_1 = require("../ui");
const icons_1 = require("../icons");
// Batch operation statuses
var OperationStatus;
(function (OperationStatus) {
    OperationStatus["IDLE"] = "idle";
    OperationStatus["PREPARING"] = "preparing";
    OperationStatus["IN_PROGRESS"] = "in_progress";
    OperationStatus["COMPLETE"] = "complete";
    OperationStatus["ERROR"] = "error";
})(OperationStatus || (OperationStatus = {}));
// Batch operation types
var OperationType;
(function (OperationType) {
    OperationType["IMPORT"] = "import";
    OperationType["EXPORT"] = "export";
    OperationType["DELETE"] = "delete";
    OperationType["UPDATE"] = "update";
})(OperationType || (OperationType = {}));
/**
 * Vector Batch Operations Component
 */
const VectorBatchOperations = ({ apiEndpoint = '/api/experience-builder/vector/batch', databaseConfig = {}, enableFileImport = true, enableUrlImport = true, enableTextImport = true, enableExport = true, enableBatchDelete = true, enableBatchUpdate = true, maxFileSize = 10, maxTextLength = 100000, acceptedFileTypes = ['.json', '.csv', '.txt', '.jsonl'], onOperationComplete, variant = 'default', }) => {
    // Refs
    const fileInputRef = (0, react_1.useRef)(null);
    // State
    const [activeTab, setActiveTab] = (0, react_1.useState)(0);
    const [operation, setOperation] = (0, react_1.useState)(OperationType.IMPORT);
    const [operationStatus, setOperationStatus] = (0, react_1.useState)(OperationStatus.IDLE);
    const [progress, setProgress] = (0, react_1.useState)(0);
    const [error, setError] = (0, react_1.useState)(null);
    const [result, setResult] = (0, react_1.useState)(null);
    const [database, setDatabase] = (0, react_1.useState)(databaseConfig?.collection || '');
    const [importFile, setImportFile] = (0, react_1.useState)(null);
    const [importUrl, setImportUrl] = (0, react_1.useState)('');
    const [importText, setImportText] = (0, react_1.useState)('');
    const [importType, setImportType] = (0, react_1.useState)('json');
    const [deletionFilter, setDeletionFilter] = (0, react_1.useState)('');
    const [deleteMetadata, setDeleteMetadata] = (0, react_1.useState)(false);
    const [updateFilter, setUpdateFilter] = (0, react_1.useState)('');
    const [updateField, setUpdateField] = (0, react_1.useState)('metadata');
    const [updateValue, setUpdateValue] = (0, react_1.useState)('');
    const [exportFormat, setExportFormat] = (0, react_1.useState)('json');
    const [exportFilter, setExportFilter] = (0, react_1.useState)('');
    const [upsert, setUpsert] = (0, react_1.useState)(true);
    // Handle tab change
    const handleTabChange = (event, newValue) => {
        setActiveTab(newValue);
        // Map tab index to operation type
        const operations = [
            OperationType.IMPORT,
            OperationType.EXPORT,
            OperationType.DELETE,
            OperationType.UPDATE,
        ];
        setOperation(operations[newValue]);
        // Reset state when changing tabs
        setOperationStatus(OperationStatus.IDLE);
        setProgress(0);
        setError(null);
        setResult(null);
    };
    // Handle file selection
    const handleFileChange = (event) => {
        if (event.target.files && event.target.files.length > 0) {
            const file = event.target.files[0];
            // Check file size
            if (file.size > maxFileSize * 1024 * 1024) {
                setError(`File size exceeds the maximum allowed size of ${maxFileSize}MB`);
                return;
            }
            // Check file type
            const fileExtension = file.name.split('.').pop()?.toLowerCase();
            if (fileExtension && !acceptedFileTypes.some(type => type.includes(fileExtension))) {
                setError(`File type not supported. Accepted types: ${acceptedFileTypes.join(', ')}`);
                return;
            }
            setImportFile(file);
            setError(null);
        }
    };
    // Trigger file input click
    const handleFileInputClick = () => {
        if (fileInputRef.current) {
            fileInputRef.current.click();
        }
    };
    // Perform import operation
    const handleImport = async () => {
        if (!database) {
            setError('Please select a database collection');
            return;
        }
        setOperationStatus(OperationStatus.PREPARING);
        setProgress(0);
        setError(null);
        setResult(null);
        try {
            const formData = new FormData();
            formData.append('database', database);
            formData.append('upsert', upsert.toString());
            formData.append('type', importType);
            if (importFile) {
                // File import
                formData.append('file', importFile);
                formData.append('importMethod', 'file');
            }
            else if (importUrl) {
                // URL import
                formData.append('url', importUrl);
                formData.append('importMethod', 'url');
            }
            else if (importText) {
                // Text import
                formData.append('text', importText);
                formData.append('importMethod', 'text');
            }
            else {
                setError('Please provide import data via file, URL, or text');
                setOperationStatus(OperationStatus.IDLE);
                return;
            }
            // Start progress simulation
            setOperationStatus(OperationStatus.IN_PROGRESS);
            const progressInterval = simulateProgress();
            // Perform import
            const response = await fetch(`${apiEndpoint}/import`, {
                method: 'POST',
                body: formData,
            });
            // Clear progress simulation
            clearInterval(progressInterval);
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || 'Import operation failed');
            }
            const resultData = await response.json();
            setProgress(100);
            setOperationStatus(OperationStatus.COMPLETE);
            setResult(resultData);
            if (onOperationComplete) {
                onOperationComplete(resultData);
            }
        }
        catch (err) {
            setError(err.message);
            setOperationStatus(OperationStatus.ERROR);
        }
    };
    // Perform export operation
    const handleExport = async () => {
        if (!database) {
            setError('Please select a database collection');
            return;
        }
        setOperationStatus(OperationStatus.PREPARING);
        setProgress(0);
        setError(null);
        setResult(null);
        try {
            // Start progress simulation
            setOperationStatus(OperationStatus.IN_PROGRESS);
            const progressInterval = simulateProgress();
            // Build query params
            const params = new URLSearchParams({
                database,
                format: exportFormat,
                filter: exportFilter,
            });
            // Perform export
            const response = await fetch(`${apiEndpoint}/export?${params.toString()}`, {
                method: 'GET',
            });
            // Clear progress simulation
            clearInterval(progressInterval);
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || 'Export operation failed');
            }
            // For file download, trigger browser download
            const contentDisposition = response.headers.get('content-disposition');
            let filename = 'vector-data.json';
            if (contentDisposition) {
                const filenameMatch = contentDisposition.match(/filename="(.+)"/);
                if (filenameMatch) {
                    filename = filenameMatch[1];
                }
            }
            const blob = await response.blob();
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
            setProgress(100);
            setOperationStatus(OperationStatus.COMPLETE);
            setResult({
                success: true,
                message: `Exported data from ${database} successfully`,
                details: {
                    filename,
                    format: exportFormat,
                    filter: exportFilter || 'none',
                },
            });
            if (onOperationComplete) {
                onOperationComplete({
                    operation: OperationType.EXPORT,
                    status: 'success',
                    details: {
                        filename,
                        format: exportFormat,
                    },
                });
            }
        }
        catch (err) {
            setError(err.message);
            setOperationStatus(OperationStatus.ERROR);
        }
    };
    // Perform delete operation
    const handleDelete = async () => {
        if (!database) {
            setError('Please select a database collection');
            return;
        }
        if (!deletionFilter && !window.confirm('Are you sure you want to delete all vectors from this collection? This cannot be undone.')) {
            return;
        }
        setOperationStatus(OperationStatus.PREPARING);
        setProgress(0);
        setError(null);
        setResult(null);
        try {
            // Start progress simulation
            setOperationStatus(OperationStatus.IN_PROGRESS);
            const progressInterval = simulateProgress();
            // Perform delete
            const response = await fetch(`${apiEndpoint}/delete`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    database,
                    filter: deletionFilter,
                    deleteMetadata,
                }),
            });
            // Clear progress simulation
            clearInterval(progressInterval);
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || 'Delete operation failed');
            }
            const resultData = await response.json();
            setProgress(100);
            setOperationStatus(OperationStatus.COMPLETE);
            setResult(resultData);
            if (onOperationComplete) {
                onOperationComplete(resultData);
            }
        }
        catch (err) {
            setError(err.message);
            setOperationStatus(OperationStatus.ERROR);
        }
    };
    // Perform update operation
    const handleUpdate = async () => {
        if (!database) {
            setError('Please select a database collection');
            return;
        }
        if (!updateField || !updateValue) {
            setError('Please provide field and value to update');
            return;
        }
        setOperationStatus(OperationStatus.PREPARING);
        setProgress(0);
        setError(null);
        setResult(null);
        try {
            // Start progress simulation
            setOperationStatus(OperationStatus.IN_PROGRESS);
            const progressInterval = simulateProgress();
            // Prepare update data
            let updateData;
            try {
                // Try parsing as JSON if it looks like JSON
                if (updateValue.trim().startsWith('{') || updateValue.trim().startsWith('[')) {
                    updateData = JSON.parse(updateValue);
                }
                else {
                    updateData = updateValue;
                }
            }
            catch (parseError) {
                // Use as string if JSON parsing fails
                updateData = updateValue;
            }
            // Perform update
            const response = await fetch(`${apiEndpoint}/update`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    database,
                    filter: updateFilter,
                    field: updateField,
                    value: updateData,
                    upsert,
                }),
            });
            // Clear progress simulation
            clearInterval(progressInterval);
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || 'Update operation failed');
            }
            const resultData = await response.json();
            setProgress(100);
            setOperationStatus(OperationStatus.COMPLETE);
            setResult(resultData);
            if (onOperationComplete) {
                onOperationComplete(resultData);
            }
        }
        catch (err) {
            setError(err.message);
            setOperationStatus(OperationStatus.ERROR);
        }
    };
    // Simulate progress for better UX
    const simulateProgress = () => {
        // Reset progress
        setProgress(0);
        // Simulate progress increases
        return setInterval(() => {
            setProgress((prevProgress) => {
                const nextProgress = prevProgress + Math.random() * 10;
                return nextProgress >= 90 ? 90 : nextProgress;
            });
        }, 500);
    };
    // Get operation button text
    const getOperationButtonText = () => {
        switch (operationStatus) {
            case OperationStatus.PREPARING:
                return 'Preparing...';
            case OperationStatus.IN_PROGRESS:
                return `Processing (${Math.round(progress)}%)`;
            case OperationStatus.COMPLETE:
                return 'Operation Completed';
            case OperationStatus.ERROR:
                return 'Retry Operation';
            default:
                switch (operation) {
                    case OperationType.IMPORT:
                        return 'Start Import';
                    case OperationType.EXPORT:
                        return 'Export Data';
                    case OperationType.DELETE:
                        return 'Delete Vectors';
                    case OperationType.UPDATE:
                        return 'Update Vectors';
                }
        }
    };
    // Render import tab
    const renderImportTab = () => ((0, jsx_runtime_1.jsxs)(ui_1.Box, { mt: 2, children: [(0, jsx_runtime_1.jsxs)(ui_1.Grid, { container: true, spacing: 3, children: [(0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsxs)(ui_1.FormControl, { fullWidth: true, children: [(0, jsx_runtime_1.jsx)(ui_1.FormLabel, { children: "Database Collection" }), (0, jsx_runtime_1.jsx)(ui_1.TextField, { value: database, onChange: (e) => setDatabase(e.target.value), placeholder: "Enter collection name", required: true }), (0, jsx_runtime_1.jsx)(ui_1.FormHelperText, { children: "Collection/index to import vectors into" })] }) }), (0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, sm: 6, children: (0, jsx_runtime_1.jsxs)(ui_1.FormControl, { fullWidth: true, children: [(0, jsx_runtime_1.jsx)(ui_1.FormLabel, { children: "Import Format" }), (0, jsx_runtime_1.jsxs)(ui_1.Select, { value: importType, onChange: (e) => setImportType(e.target.value), children: [(0, jsx_runtime_1.jsx)(ui_1.MenuItem, { value: "json", children: "JSON" }), (0, jsx_runtime_1.jsx)(ui_1.MenuItem, { value: "csv", children: "CSV" }), (0, jsx_runtime_1.jsx)(ui_1.MenuItem, { value: "jsonl", children: "JSON Lines" }), (0, jsx_runtime_1.jsx)(ui_1.MenuItem, { value: "txt", children: "Plain Text (for chunking)" })] }), (0, jsx_runtime_1.jsx)(ui_1.FormHelperText, { children: "Format of the imported data" })] }) }), (0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, sm: 6, children: (0, jsx_runtime_1.jsxs)(ui_1.FormControl, { fullWidth: true, children: [(0, jsx_runtime_1.jsx)(ui_1.FormLabel, { children: "Import Mode" }), (0, jsx_runtime_1.jsxs)(ui_1.Box, { display: "flex", alignItems: "center", children: [(0, jsx_runtime_1.jsx)(ui_1.Switch, { checked: upsert, onChange: (e) => setUpsert(e.target.checked) }), (0, jsx_runtime_1.jsx)(ui_1.Typography, { variant: "body2", sx: { ml: 1 }, children: "Upsert (update existing vectors)" })] }), (0, jsx_runtime_1.jsx)(ui_1.FormHelperText, { children: "Enable to update existing vectors, disable to only add new ones" })] }) }), enableFileImport && ((0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsxs)(ui_1.Paper, { variant: "outlined", sx: {
                                p: 2,
                                border: '1px dashed #ccc',
                                textAlign: 'center',
                                cursor: 'pointer',
                                '&:hover': {
                                    borderColor: 'primary.main',
                                },
                            }, onClick: handleFileInputClick, children: [(0, jsx_runtime_1.jsx)("input", { type: "file", ref: fileInputRef, style: { display: 'none' }, onChange: handleFileChange, accept: acceptedFileTypes.join(',') }), (0, jsx_runtime_1.jsxs)(ui_1.Box, { display: "flex", flexDirection: "column", alignItems: "center", children: [(0, jsx_runtime_1.jsx)(icons_1.FileUpload, { sx: { fontSize: 48, color: 'primary.main', mb: 2 } }), (0, jsx_runtime_1.jsx)(ui_1.Typography, { variant: "subtitle1", gutterBottom: true, children: importFile
                                                ? `Selected: ${importFile.name} (${(importFile.size / 1024 / 1024).toFixed(2)} MB)`
                                                : 'Drag & drop a file here, or click to select' }), (0, jsx_runtime_1.jsxs)(ui_1.Typography, { variant: "caption", color: "textSecondary", children: ["Accepted formats: ", acceptedFileTypes.join(', '), " (Max: ", maxFileSize, "MB)"] })] })] }) })), enableUrlImport && ((0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsxs)(ui_1.FormControl, { fullWidth: true, children: [(0, jsx_runtime_1.jsx)(ui_1.FormLabel, { children: "Import from URL" }), (0, jsx_runtime_1.jsx)(ui_1.TextField, { value: importUrl, onChange: (e) => setImportUrl(e.target.value), placeholder: "Enter URL to import from", InputProps: {
                                        startAdornment: ((0, jsx_runtime_1.jsx)(icons_1.CloudUpload, { sx: { mr: 1, color: 'action.active' } })),
                                    } }), (0, jsx_runtime_1.jsx)(ui_1.FormHelperText, { children: "URL to a file containing vector data" })] }) })), enableTextImport && ((0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsxs)(ui_1.FormControl, { fullWidth: true, children: [(0, jsx_runtime_1.jsx)(ui_1.FormLabel, { children: "Import from Text" }), (0, jsx_runtime_1.jsx)(ui_1.TextField, { value: importText, onChange: (e) => {
                                        const text = e.target.value;
                                        if (text.length <= maxTextLength) {
                                            setImportText(text);
                                        }
                                    }, placeholder: "Paste JSON, CSV, or text data here", multiline: true, rows: 6, inputProps: {
                                        maxLength: maxTextLength,
                                    }, helperText: `${importText.length}/${maxTextLength} characters` }), (0, jsx_runtime_1.jsx)(ui_1.FormHelperText, { children: "Paste data directly for small imports" })] }) }))] }), (0, jsx_runtime_1.jsx)(ui_1.Box, { mt: 3, display: "flex", justifyContent: "flex-end", children: (0, jsx_runtime_1.jsx)(ui_1.Button, { variant: "contained", color: "primary", onClick: handleImport, disabled: operationStatus === OperationStatus.IN_PROGRESS || operationStatus === OperationStatus.PREPARING, startIcon: operationStatus === OperationStatus.IN_PROGRESS || operationStatus === OperationStatus.PREPARING ?
                        (0, jsx_runtime_1.jsx)(ui_1.CircularProgress, { size: 20 }) : (0, jsx_runtime_1.jsx)(icons_1.Upload, {}), children: getOperationButtonText() }) })] }));
    // Render export tab
    const renderExportTab = () => ((0, jsx_runtime_1.jsxs)(ui_1.Box, { mt: 2, children: [(0, jsx_runtime_1.jsxs)(ui_1.Grid, { container: true, spacing: 3, children: [(0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsxs)(ui_1.FormControl, { fullWidth: true, children: [(0, jsx_runtime_1.jsx)(ui_1.FormLabel, { children: "Database Collection" }), (0, jsx_runtime_1.jsx)(ui_1.TextField, { value: database, onChange: (e) => setDatabase(e.target.value), placeholder: "Enter collection name", required: true }), (0, jsx_runtime_1.jsx)(ui_1.FormHelperText, { children: "Collection/index to export vectors from" })] }) }), (0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, sm: 6, children: (0, jsx_runtime_1.jsxs)(ui_1.FormControl, { fullWidth: true, children: [(0, jsx_runtime_1.jsx)(ui_1.FormLabel, { children: "Export Format" }), (0, jsx_runtime_1.jsxs)(ui_1.Select, { value: exportFormat, onChange: (e) => setExportFormat(e.target.value), children: [(0, jsx_runtime_1.jsx)(ui_1.MenuItem, { value: "json", children: "JSON" }), (0, jsx_runtime_1.jsx)(ui_1.MenuItem, { value: "csv", children: "CSV" }), (0, jsx_runtime_1.jsx)(ui_1.MenuItem, { value: "jsonl", children: "JSON Lines" }), (0, jsx_runtime_1.jsx)(ui_1.MenuItem, { value: "tsv", children: "TSV" })] }), (0, jsx_runtime_1.jsx)(ui_1.FormHelperText, { children: "Format for the exported data" })] }) }), (0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsxs)(ui_1.FormControl, { fullWidth: true, children: [(0, jsx_runtime_1.jsx)(ui_1.FormLabel, { children: "Filter (Optional)" }), (0, jsx_runtime_1.jsx)(ui_1.TextField, { value: exportFilter, onChange: (e) => setExportFilter(e.target.value), placeholder: `JSON filter query (e.g., {"metadata.type": "document"})`, multiline: true, rows: 4 }), (0, jsx_runtime_1.jsx)(ui_1.FormHelperText, { children: "JSON filter to select specific vectors (leave empty for all)" })] }) })] }), (0, jsx_runtime_1.jsx)(ui_1.Box, { mt: 3, display: "flex", justifyContent: "flex-end", children: (0, jsx_runtime_1.jsx)(ui_1.Button, { variant: "contained", color: "primary", onClick: handleExport, disabled: operationStatus === OperationStatus.IN_PROGRESS || operationStatus === OperationStatus.PREPARING, startIcon: operationStatus === OperationStatus.IN_PROGRESS || operationStatus === OperationStatus.PREPARING ?
                        (0, jsx_runtime_1.jsx)(ui_1.CircularProgress, { size: 20 }) : (0, jsx_runtime_1.jsx)(icons_1.Download, {}), children: getOperationButtonText() }) })] }));
    // Render delete tab
    const renderDeleteTab = () => ((0, jsx_runtime_1.jsxs)(ui_1.Box, { mt: 2, children: [(0, jsx_runtime_1.jsxs)(ui_1.Alert, { severity: "warning", sx: { mb: 3 }, children: [(0, jsx_runtime_1.jsx)(ui_1.Typography, { variant: "subtitle1", fontWeight: "bold", children: "Caution: Delete operations cannot be undone" }), (0, jsx_runtime_1.jsx)(ui_1.Typography, { variant: "body2", children: "Vectors deleted from the database cannot be recovered. Use filters to limit the scope of deletion." })] }), (0, jsx_runtime_1.jsxs)(ui_1.Grid, { container: true, spacing: 3, children: [(0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsxs)(ui_1.FormControl, { fullWidth: true, children: [(0, jsx_runtime_1.jsx)(ui_1.FormLabel, { children: "Database Collection" }), (0, jsx_runtime_1.jsx)(ui_1.TextField, { value: database, onChange: (e) => setDatabase(e.target.value), placeholder: "Enter collection name", required: true }), (0, jsx_runtime_1.jsx)(ui_1.FormHelperText, { children: "Collection/index to delete vectors from" })] }) }), (0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsxs)(ui_1.FormControl, { fullWidth: true, children: [(0, jsx_runtime_1.jsx)(ui_1.FormLabel, { children: "Filter (Optional)" }), (0, jsx_runtime_1.jsx)(ui_1.TextField, { value: deletionFilter, onChange: (e) => setDeletionFilter(e.target.value), placeholder: `JSON filter query (e.g., {"metadata.type": "document"})`, multiline: true, rows: 4 }), (0, jsx_runtime_1.jsx)(ui_1.FormHelperText, { children: "JSON filter to select vectors for deletion (leave empty to delete all)" })] }) }), (0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsxs)(ui_1.FormControl, { fullWidth: true, children: [(0, jsx_runtime_1.jsx)(ui_1.FormLabel, { children: "Delete Options" }), (0, jsx_runtime_1.jsxs)(ui_1.Box, { display: "flex", alignItems: "center", children: [(0, jsx_runtime_1.jsx)(ui_1.Switch, { checked: deleteMetadata, onChange: (e) => setDeleteMetadata(e.target.checked) }), (0, jsx_runtime_1.jsx)(ui_1.Typography, { variant: "body2", sx: { ml: 1 }, children: "Delete metadata only (preserve vectors)" })] }), (0, jsx_runtime_1.jsx)(ui_1.FormHelperText, { children: "Enable to delete only metadata while preserving vector embeddings" })] }) })] }), (0, jsx_runtime_1.jsx)(ui_1.Box, { mt: 3, display: "flex", justifyContent: "flex-end", children: (0, jsx_runtime_1.jsx)(ui_1.Button, { variant: "contained", color: "error", onClick: handleDelete, disabled: operationStatus === OperationStatus.IN_PROGRESS || operationStatus === OperationStatus.PREPARING, startIcon: operationStatus === OperationStatus.IN_PROGRESS || operationStatus === OperationStatus.PREPARING ?
                        (0, jsx_runtime_1.jsx)(ui_1.CircularProgress, { size: 20 }) : (0, jsx_runtime_1.jsx)(icons_1.Delete, {}), children: getOperationButtonText() }) })] }));
    // Render update tab
    const renderUpdateTab = () => ((0, jsx_runtime_1.jsxs)(ui_1.Box, { mt: 2, children: [(0, jsx_runtime_1.jsxs)(ui_1.Grid, { container: true, spacing: 3, children: [(0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsxs)(ui_1.FormControl, { fullWidth: true, children: [(0, jsx_runtime_1.jsx)(ui_1.FormLabel, { children: "Database Collection" }), (0, jsx_runtime_1.jsx)(ui_1.TextField, { value: database, onChange: (e) => setDatabase(e.target.value), placeholder: "Enter collection name", required: true }), (0, jsx_runtime_1.jsx)(ui_1.FormHelperText, { children: "Collection/index to update vectors in" })] }) }), (0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsxs)(ui_1.FormControl, { fullWidth: true, children: [(0, jsx_runtime_1.jsx)(ui_1.FormLabel, { children: "Filter (Optional)" }), (0, jsx_runtime_1.jsx)(ui_1.TextField, { value: updateFilter, onChange: (e) => setUpdateFilter(e.target.value), placeholder: `JSON filter query (e.g., {"metadata.type": "document"})`, multiline: true, rows: 3 }), (0, jsx_runtime_1.jsx)(ui_1.FormHelperText, { children: "JSON filter to select vectors for updating (leave empty to update all)" })] }) }), (0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, sm: 6, children: (0, jsx_runtime_1.jsxs)(ui_1.FormControl, { fullWidth: true, children: [(0, jsx_runtime_1.jsx)(ui_1.FormLabel, { children: "Field to Update" }), (0, jsx_runtime_1.jsxs)(ui_1.Select, { value: updateField, onChange: (e) => setUpdateField(e.target.value), children: [(0, jsx_runtime_1.jsx)(ui_1.MenuItem, { value: "metadata", children: "Metadata" }), (0, jsx_runtime_1.jsx)(ui_1.MenuItem, { value: "text", children: "Text Content" }), (0, jsx_runtime_1.jsx)(ui_1.MenuItem, { value: "label", children: "Label" }), (0, jsx_runtime_1.jsx)(ui_1.MenuItem, { value: "custom", children: "Custom Field" })] }), (0, jsx_runtime_1.jsx)(ui_1.FormHelperText, { children: "Field to update in the selected vectors" })] }) }), (0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, sm: 6, children: (0, jsx_runtime_1.jsxs)(ui_1.FormControl, { fullWidth: true, children: [(0, jsx_runtime_1.jsx)(ui_1.FormLabel, { children: "Update Mode" }), (0, jsx_runtime_1.jsxs)(ui_1.Box, { display: "flex", alignItems: "center", children: [(0, jsx_runtime_1.jsx)(ui_1.Switch, { checked: upsert, onChange: (e) => setUpsert(e.target.checked) }), (0, jsx_runtime_1.jsx)(ui_1.Typography, { variant: "body2", sx: { ml: 1 }, children: "Upsert (create if not exists)" })] }), (0, jsx_runtime_1.jsx)(ui_1.FormHelperText, { children: "Enable to create new vectors if filter doesn't match any" })] }) }), (0, jsx_runtime_1.jsx)(ui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsxs)(ui_1.FormControl, { fullWidth: true, children: [(0, jsx_runtime_1.jsx)(ui_1.FormLabel, { children: "New Value" }), (0, jsx_runtime_1.jsx)(ui_1.TextField, { value: updateValue, onChange: (e) => setUpdateValue(e.target.value), placeholder: "Enter new value (text or JSON)", multiline: true, rows: 6 }), (0, jsx_runtime_1.jsx)(ui_1.FormHelperText, { children: "New value for the field (can be JSON object for metadata)" })] }) })] }), (0, jsx_runtime_1.jsx)(ui_1.Box, { mt: 3, display: "flex", justifyContent: "flex-end", children: (0, jsx_runtime_1.jsx)(ui_1.Button, { variant: "contained", color: "primary", onClick: handleUpdate, disabled: operationStatus === OperationStatus.IN_PROGRESS || operationStatus === OperationStatus.PREPARING, startIcon: operationStatus === OperationStatus.IN_PROGRESS || operationStatus === OperationStatus.PREPARING ?
                        (0, jsx_runtime_1.jsx)(ui_1.CircularProgress, { size: 20 }) : (0, jsx_runtime_1.jsx)(icons_1.Save, {}), children: getOperationButtonText() }) })] }));
    // Render operation result
    const renderResult = () => {
        if (!result)
            return null;
        return ((0, jsx_runtime_1.jsxs)(ui_1.Box, { mt: 3, children: [(0, jsx_runtime_1.jsxs)(ui_1.Alert, { severity: result.success ? "success" : "error", action: (0, jsx_runtime_1.jsx)(ui_1.IconButton, { color: "inherit", size: "small", onClick: () => setResult(null), children: "\u00D7" }), children: [(0, jsx_runtime_1.jsx)(ui_1.Typography, { variant: "subtitle1", children: result.message }), result.details && ((0, jsx_runtime_1.jsxs)(ui_1.Box, { mt: 1, children: [(0, jsx_runtime_1.jsxs)(ui_1.Typography, { variant: "body2", children: [(0, jsx_runtime_1.jsx)("strong", { children: "Operation:" }), " ", operation] }), (0, jsx_runtime_1.jsxs)(ui_1.Typography, { variant: "body2", children: [(0, jsx_runtime_1.jsx)("strong", { children: "Collection:" }), " ", database] }), result.details.count !== undefined && ((0, jsx_runtime_1.jsxs)(ui_1.Typography, { variant: "body2", children: [(0, jsx_runtime_1.jsx)("strong", { children: "Affected items:" }), " ", result.details.count] })), result.details.errors && result.details.errors.length > 0 && ((0, jsx_runtime_1.jsxs)(ui_1.Box, { mt: 1, children: [(0, jsx_runtime_1.jsxs)(ui_1.Typography, { variant: "body2", fontWeight: "bold", children: ["Errors (", result.details.errors.length, "):"] }), (0, jsx_runtime_1.jsxs)("ul", { style: { margin: 0, paddingLeft: 16 }, children: [result.details.errors.slice(0, 5).map((err, index) => ((0, jsx_runtime_1.jsx)("li", { children: err }, index))), result.details.errors.length > 5 && ((0, jsx_runtime_1.jsxs)("li", { children: ["...and ", result.details.errors.length - 5, " more errors"] }))] })] }))] }))] }), result.success && result.details && result.details.stats && ((0, jsx_runtime_1.jsxs)(ui_1.Box, { mt: 2, children: [(0, jsx_runtime_1.jsx)(ui_1.Typography, { variant: "subtitle2", gutterBottom: true, children: "Operation Statistics" }), (0, jsx_runtime_1.jsx)(ui_1.TableContainer, { component: ui_1.Paper, variant: "outlined", children: (0, jsx_runtime_1.jsx)(ui_1.Table, { size: "small", children: (0, jsx_runtime_1.jsx)(ui_1.TableBody, { children: Object.entries(result.details.stats).map(([key, value]) => ((0, jsx_runtime_1.jsxs)(ui_1.TableRow, { children: [(0, jsx_runtime_1.jsx)(ui_1.TableCell, { component: "th", scope: "row", children: key.charAt(0).toUpperCase() + key.slice(1).replace(/([A-Z])/g, ' $1') }), (0, jsx_runtime_1.jsx)(ui_1.TableCell, { align: "right", children: value })] }, key))) }) }) })] }))] }));
    };
    return ((0, jsx_runtime_1.jsx)(ui_1.Card, { variant: variant === 'compact' ? 'outlined' : 'elevation', children: (0, jsx_runtime_1.jsxs)(ui_1.CardContent, { children: [(0, jsx_runtime_1.jsx)(ui_1.Typography, { variant: "h5", gutterBottom: true, children: "Vector Database Batch Operations" }), (0, jsx_runtime_1.jsxs)(ui_1.Tabs, { value: activeTab, onChange: handleTabChange, variant: "scrollable", scrollButtons: "auto", sx: { borderBottom: 1, borderColor: 'divider', mb: 2 }, children: [(0, jsx_runtime_1.jsx)(ui_1.Tab, { label: "Import", icon: (0, jsx_runtime_1.jsx)(icons_1.Upload, {}), iconPosition: "start", disabled: !enableFileImport && !enableUrlImport && !enableTextImport }), (0, jsx_runtime_1.jsx)(ui_1.Tab, { label: "Export", icon: (0, jsx_runtime_1.jsx)(icons_1.Download, {}), iconPosition: "start", disabled: !enableExport }), (0, jsx_runtime_1.jsx)(ui_1.Tab, { label: "Delete", icon: (0, jsx_runtime_1.jsx)(icons_1.Delete, {}), iconPosition: "start", disabled: !enableBatchDelete }), (0, jsx_runtime_1.jsx)(ui_1.Tab, { label: "Update", icon: (0, jsx_runtime_1.jsx)(icons_1.Edit, {}), iconPosition: "start", disabled: !enableBatchUpdate })] }), operationStatus === OperationStatus.IN_PROGRESS && ((0, jsx_runtime_1.jsxs)(ui_1.Box, { sx: { width: '100%', mb: 2 }, children: [(0, jsx_runtime_1.jsx)(ui_1.LinearProgress, { variant: "determinate", value: progress }), (0, jsx_runtime_1.jsxs)(ui_1.Typography, { variant: "caption", color: "textSecondary", sx: { display: 'block', mt: 1, textAlign: 'center' }, children: [Math.round(progress), "% - Processing operation"] })] })), error && ((0, jsx_runtime_1.jsx)(ui_1.Alert, { severity: "error", sx: { mb: 3 }, action: (0, jsx_runtime_1.jsx)(ui_1.IconButton, { color: "inherit", size: "small", onClick: () => setError(null), children: "\u00D7" }), children: error })), renderResult(), (0, jsx_runtime_1.jsx)("div", { role: "tabpanel", hidden: activeTab !== 0, children: activeTab === 0 && renderImportTab() }), (0, jsx_runtime_1.jsx)("div", { role: "tabpanel", hidden: activeTab !== 1, children: activeTab === 1 && renderExportTab() }), (0, jsx_runtime_1.jsx)("div", { role: "tabpanel", hidden: activeTab !== 2, children: activeTab === 2 && renderDeleteTab() }), (0, jsx_runtime_1.jsx)("div", { role: "tabpanel", hidden: activeTab !== 3, children: activeTab === 3 && renderUpdateTab() })] }) }));
};
exports.VectorBatchOperations = VectorBatchOperations;
exports.default = exports.VectorBatchOperations;
//# sourceMappingURL=index.js.map