"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.debugStateFilePath = debugStateFilePath;
exports.buildDebugSessionState = buildDebugSessionState;
exports.mutateDebugState = mutateDebugState;
exports.buildFlowStepsResolverFromSnapshot = buildFlowStepsResolverFromSnapshot;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const mablscriptFind_1 = require("@mablhq/test-model/mablscriptFind");
const CliTestGenerationState_1 = require("../trainer/cli/CliTestGenerationState");
const MablscriptImporter_1 = __importDefault(require("../trainer/sharedUtils/mablscript/MablscriptImporter"));
const DebugSession_1 = require("./DebugSession");
function debugStateFilePath(sessionId) {
    return path.join((0, DebugSession_1.sessionDir)(sessionId), 'state.json');
}
function buildDebugSessionState(snapshot, testId) {
    const url = snapshot.urlOverride ?? snapshot.test.url ?? '';
    const state = new CliTestGenerationState_1.CliTestGenerationState({
        testIntent: `mabl agent debug session for ${snapshot.test.name ?? testId}`,
        url,
        workspaceId: snapshot.test.organization_id ?? '',
        applicationId: snapshot.test.application_id,
        isEditSession: true,
        testVariantId: snapshot.test.id,
    });
    const topLevelFlowIds = new Set(snapshot.test.flows ?? []);
    const topLevelFlows = snapshot.flows.filter((flow) => flow.id !== undefined && topLevelFlowIds.has(flow.id));
    const importedSteps = [];
    for (const flow of topLevelFlows) {
        const importer = new MablscriptImporter_1.default({ steps: [], flowSelectors: new mablscriptFind_1.ElementSelectorStore() }, state.getVariables(), state.getSnippetsByInvariantId());
        importer.importFlow(flow, importedSteps);
    }
    state.addSteps(importedSteps);
    state.setNextStepIndex([0]);
    return state;
}
async function mutateDebugState(sessionId, mutator) {
    const stateFile = debugStateFilePath(sessionId);
    if (!fs.existsSync(stateFile)) {
        return false;
    }
    const state = await CliTestGenerationState_1.CliTestGenerationState.load(stateFile);
    mutator(state);
    await state.save(stateFile);
    return true;
}
function buildFlowStepsResolverFromSnapshot(snapshot, state) {
    const cache = new Map();
    return (flowId) => {
        const cached = cache.get(flowId);
        if (cached !== undefined) {
            return cached;
        }
        const flow = snapshot.flows.find((candidate) => candidate.invariant_id === flowId || candidate.id === flowId);
        if (!flow) {
            cache.set(flowId, []);
            return [];
        }
        const importedSteps = [];
        const importer = new MablscriptImporter_1.default({ steps: [], flowSelectors: new mablscriptFind_1.ElementSelectorStore() }, state.getVariables(), state.getSnippetsByInvariantId());
        importer.importFlow(flow, importedSteps);
        cache.set(flowId, importedSteps);
        return importedSteps;
    };
}
