"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.editStepsExecutor = void 0;
const mablApi_1 = require("../../../mablApi");
const GetTestContextDefinition_1 = require("@mablhq-internal/tool-library/testAuthoring/GetTestContextDefinition");
function describeFailure(outcome) {
    if ('opErrors' in outcome) {
        return outcome.opErrors
            .map((e) => `op ${e.op_index} (${e.op}): ${e.reason} — ${e.detail}`)
            .join('; ');
    }
    if ('flatLocatorErrors' in outcome) {
        return outcome.flatLocatorErrors
            .map((e) => `step ${e.step_index}: ${e.detail}`)
            .join('; ');
    }
    return outcome.validationErrors
        .map((e) => `${e.path.join('.')}: ${e.message}`)
        .join('; ');
}
exports.editStepsExecutor = {
    needsFind: () => false,
    getStepType: () => 'edit_steps',
    execute: (payload, stateProvider, eventHandler, logger) => {
        const toolParams = payload.toolCall.toolParams;
        const edits = toolParams.edits ?? [];
        if (edits.length === 0) {
            return Promise.resolve({
                success: false,
                errorMessage: 'No edits provided.',
            });
        }
        const editOps = edits.map((edit) => ({
            op: edit.op,
            step_id: edit.step_id,
            step: edit.step,
        }));
        const outcome = stateProvider.applyStepEdits(editOps);
        if (!outcome.success) {
            return Promise.resolve({
                success: false,
                errorMessage: describeFailure(outcome),
            });
        }
        const newLength = stateProvider.getSteps().length;
        eventHandler.setNextStepIndex([newLength]);
        logger.info(`Applied ${editOps.length} step edit(s)`);
        const rewriteNote = outcome.canonicalization.total > 0
            ? ` Canonicalized ${outcome.canonicalization.total} variable reference(s).`
            : '';
        return Promise.resolve({
            success: true,
            message: `Applied ${editOps.length} edit(s).${rewriteNote} ` +
                `Step ids are stable. Use ${mablApi_1.ExecuteToolName.PlaySteps} with step_id ranges ` +
                `to re-verify, and chain further ${mablApi_1.ExecuteToolName.EditSteps} calls ` +
                `directly — no need to call ${GetTestContextDefinition_1.GetTestContextToolDefinition.name} between edits. ` +
                `Only refresh context if you are about to use ${mablApi_1.ExecuteToolName.MoveCursor} ` +
                `(which takes a positional index).`,
        });
    },
};
