"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertDownloadExecutor = void 0;
const toolExecutor_types_1 = require("../toolExecutor-types");
const stepCapture_1 = require("../../background/capture/stepCapture");
const DownloadBaseStep_1 = require("../../sharedUtils/mablscript/canonical/DownloadBaseStep");
exports.assertDownloadExecutor = {
    needsFind: () => false,
    getStepType: () => 'download',
    execute: async (payload, stateProvider, eventHandler, logger) => {
        const toolParams = payload.toolCall.toolParams;
        if (!toolParams || !isAssertDownloadParams(toolParams)) {
            logger.error('Assert download executor requires valid parameters');
            return { success: false };
        }
        const recentDownload = eventHandler.getRecentDownload?.();
        if (!recentDownload) {
            logger.error('No download detected. The execute_assert_download tool must be called after an action that triggers a file download.');
            return {
                success: false,
                errorMessage: 'No download was detected. Make sure a prior action (e.g., clicking a download link) triggered a file download before calling this tool.',
            };
        }
        logger.info(`Using captured download metadata: ${recentDownload.file_name} (${recentDownload.file_size_bytes} bytes)`);
        const fileNameExpected = toolParams.file_name ?? recentDownload.file_name ?? '';
        const fileNameMatchMode = toolParams.file_name
            ? toolParams.file_name_match_mode ?? 'equals'
            : undefined;
        if (toolParams.file_name &&
            recentDownload.file_name &&
            !fileNameMatches(recentDownload.file_name, toolParams.file_name, fileNameMatchMode ?? 'equals')) {
            return {
                success: false,
                errorMessage: `The specified file_name "${toolParams.file_name}" does not match the most recently downloaded file "${recentDownload.file_name}". ` +
                    'Retry without file_name to use the actual downloaded file name, or adjust file_name / file_name_match_mode to match.',
            };
        }
        const assertions = [
            {
                name: DownloadBaseStep_1.DownloadProperty.FileName,
                type: 'string',
                desc: 'File name',
                init: recentDownload.file_name ?? '',
                expected: fileNameExpected,
            },
        ];
        const mimeTypeExpected = toolParams.file_mime_type ?? recentDownload.file_mime_type;
        if (mimeTypeExpected) {
            assertions.push({
                name: DownloadBaseStep_1.DownloadProperty.MimeType,
                type: 'string',
                desc: 'File type',
                init: recentDownload.file_mime_type ?? '',
                expected: mimeTypeExpected,
            });
        }
        const capturedSizeInit = String(recentDownload.file_size_bytes ?? 0);
        if (toolParams.file_size_bytes !== undefined) {
            assertions.push({
                name: DownloadBaseStep_1.DownloadProperty.SizeBytes,
                type: 'number',
                desc: 'Exact file size (bytes)',
                init: capturedSizeInit,
                expected: toolParams.file_size_bytes,
            });
        }
        if (toolParams.file_size_bytes_min !== undefined) {
            assertions.push({
                name: DownloadBaseStep_1.DownloadProperty.SizeBytesMin,
                type: 'number',
                desc: 'Min file size (bytes)',
                init: capturedSizeInit,
                expected: toolParams.file_size_bytes_min,
            });
        }
        if (toolParams.file_size_bytes_max !== undefined) {
            assertions.push({
                name: DownloadBaseStep_1.DownloadProperty.SizeBytesMax,
                type: 'number',
                desc: 'Max file size (bytes)',
                init: capturedSizeInit,
                expected: toolParams.file_size_bytes_max,
            });
        }
        const detectedProps = {
            file_name: recentDownload.file_name,
            file_mime_type: recentDownload.file_mime_type || undefined,
            file_size_bytes: recentDownload.file_size_bytes,
        };
        const aiPrompt = toolParams.ai_prompt
            ? { userPrompt: toolParams.ai_prompt }
            : undefined;
        const eventMessage = {
            action: 'record',
            listener: 'download',
            downloadForm: {
                detectedProps,
                assertions,
                aiPrompt,
                fileNameMatchMode,
            },
        };
        const contextInfo = await stateProvider.getActiveContextInfo();
        return (0, toolExecutor_types_1.recordStepAndTrackResult)(() => (0, stepCapture_1.recordTrainedStep)(eventMessage, contextInfo, true, payload.toolCall.toolDescription, stateProvider, eventHandler), 0, stateProvider, eventHandler, logger);
    },
};
function isAssertDownloadParams(toolParams) {
    return typeof toolParams === 'object';
}
function fileNameMatches(actual, expected, mode) {
    const actualLower = actual.toLowerCase();
    const expectedLower = expected.toLowerCase();
    switch (mode) {
        case 'equals':
            return actualLower === expectedLower;
        case 'contains':
            return actualLower.includes(expectedLower);
        case 'starts_with':
            return actualLower.startsWith(expectedLower);
        case 'ends_with':
            return actualLower.endsWith(expectedLower);
        case 'matches_regex':
            try {
                return new RegExp(expected, 'i').test(actual);
            }
            catch {
                return false;
            }
    }
}
