"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isFindOneEventMessage = isFindOneEventMessage;
exports.recordStepAndTrackResult = recordStepAndTrackResult;
exports.pathAtOffsetFromCursor = pathAtOffsetFromCursor;
exports.isReplayResponsePassed = isReplayResponsePassed;
const mablscript_step_types_1 = require("../sharedUtils/mablscript-step-types");
const utilities_1 = require("../utilities");
const humanize_1 = require("../sharedUtils/mablscript/humanize");
const stepIndexUtils_1 = require("../sharedUtils/stepIndexUtils");
const generation_types_1 = require("../sharedUtils/generation-types");
const BaseStep_1 = __importDefault(require("../sharedUtils/mablscript/canonical/BaseStep"));
const mablscriptFind_1 = require("@mablhq/test-model/mablscriptFind");
const VISUAL_FIND_TIMEOUT_MS = 120_000;
function isFindOneEventMessage(step) {
    return step?.type === 'find_one';
}
async function recordStepAndTrackResult(buildStepFn, sleepTimeMs, stateProvider, eventHandler, logger, visualFindContext) {
    try {
        const result = await buildStepFn();
        const steps = result.steps;
        const cursorBeforeDispatch = stateProvider.getNextStepIndex();
        await eventHandler.dispatchSteps(steps);
        const visualFindPromise = visualFindContext
            ? Promise.race([
                generateVisualFindForSteps(steps, visualFindContext, logger),
                (0, utilities_1.sleep)(VISUAL_FIND_TIMEOUT_MS).then(() => {
                    logger.error('Visual find generation timed out');
                }),
            ]).catch((error) => {
                logger.error('Failed to generate visual find:', error);
            })
            : undefined;
        if (sleepTimeMs > 0) {
            await (0, utilities_1.sleep)(sleepTimeMs);
        }
        if (visualFindPromise) {
            await visualFindPromise;
        }
        const variables = stateProvider.getVariables();
        const createdStepsInfo = steps
            .filter((step) => step instanceof BaseStep_1.default)
            .map((step, stepOffset) => {
            const [humanizedStep] = (0, humanize_1.generateHumanizedSteps)([], [step], variables);
            const insertedPath = pathAtOffsetFromCursor(cursorBeforeDispatch, stepOffset);
            return {
                index: insertedPath,
                displayStepNumber: (0, stepIndexUtils_1.pathToStepIndex)(insertedPath),
                humanizedStep,
            };
        });
        const { success, errorMessage } = isReplayResponsePassed(stateProvider);
        const finalSuccess = success && createdStepsInfo.length > 0;
        const finalErrorMessage = finalSuccess
            ? undefined
            : errorMessage || 'No steps were created';
        return {
            success: finalSuccess,
            errorMessage: finalErrorMessage,
            createdStepsInfo,
        };
    }
    catch (error) {
        logger.error('Error recording step:', error);
        return {
            success: false,
        };
    }
}
function pathAtOffsetFromCursor(cursor, offset) {
    if (cursor.length === 0) {
        return [offset];
    }
    const parent = cursor.slice(0, -1);
    const lastIndex = cursor[cursor.length - 1];
    return [...parent, lastIndex + offset];
}
function isReplayResponsePassed(stateProvider) {
    const replayResponse = stateProvider.getReplayResponse();
    const success = (0, mablscript_step_types_1.isStepStatusSuccessful)(replayResponse.status);
    return {
        success,
        errorMessage: success
            ? undefined
            : (0, generation_types_1.removeInternalContent)(replayResponse.message),
    };
}
const VISUAL_FIND_STEP_TYPES = new Set([mablscript_step_types_1.StepType.CLICK]);
async function generateVisualFindForSteps(steps, context, logger) {
    for (const step of steps) {
        if (!VISUAL_FIND_STEP_TYPES.has(step.stepType)) {
            continue;
        }
        if (!(0, mablscript_step_types_1.isStepWithFind)(step)) {
            continue;
        }
        if (!(0, mablscriptFind_1.isFindOneDescriptor)(step.findDescriptor)) {
            continue;
        }
        const selector = step.findDescriptor.selector;
        if (!selector || selector.find_prompt) {
            continue;
        }
        try {
            const apiClient = context.getMablApiClient();
            const response = await apiClient.generateElementDescription(context.workspaceId, {
                bounding_box: context.boundingBox,
                screenshot: context.screenshotBase64,
            });
            const generatedPrompt = response.description?.trim();
            if (generatedPrompt) {
                selector.find_prompt = generatedPrompt;
                if (response.prompt_id) {
                    selector.find_prompt_prompt_id = response.prompt_id;
                }
            }
        }
        catch (error) {
            logger.error(`Failed to generate visual find for step ${step.id}:`, error);
        }
    }
}
