"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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCurrentCursorStepId = getCurrentCursorStepId;
exports.getCurrentCursorFlatIndex = getCurrentCursorFlatIndex;
const fs = __importStar(require("fs"));
const expandSteps_1 = require("./expandSteps");
const buildDebugSessionState_1 = require("./buildDebugSessionState");
const debugConstants_1 = require("./debugConstants");
const CliTestGenerationState_1 = require("../trainer/cli/CliTestGenerationState");
const stepIndexUtils_1 = require("../trainer/sharedUtils/stepIndexUtils");
async function getCurrentCursorStepId(sessionId, snapshot, sessionCurrentStepIndex) {
    const flatIndex = await getCurrentCursorFlatIndex(sessionId, snapshot, sessionCurrentStepIndex);
    const expanded = (0, expandSteps_1.expandSessionSteps)(snapshot);
    if (flatIndex >= expanded.length) {
        return undefined;
    }
    return (0, expandSteps_1.addressableStepId)(expanded[flatIndex], flatIndex);
}
async function getCurrentCursorFlatIndex(sessionId, snapshot, sessionCurrentStepIndex) {
    const stateFile = (0, buildDebugSessionState_1.debugStateFilePath)(sessionId);
    if (!fs.existsSync(stateFile)) {
        return sessionCurrentStepIndex;
    }
    const state = await CliTestGenerationState_1.CliTestGenerationState.load(stateFile);
    const expanded = (0, expandSteps_1.expandSessionSteps)(snapshot);
    const getNestedSteps = (0, stepIndexUtils_1.createNestedStepResolver)((0, buildDebugSessionState_1.buildFlowStepsResolverFromSnapshot)(snapshot, state));
    const stepAtCursor = (0, stepIndexUtils_1.getStepAtPath)(state.getSteps(), state.getNextStepIndex(), getNestedSteps);
    if (!stepAtCursor?.id) {
        warnCursorFallback(sessionId, `state.json cursor at ${JSON.stringify(state.getNextStepIndex())} resolved to no step (state.steps length ${state.getSteps().length}); using session.currentStepIndex=${sessionCurrentStepIndex}`);
        return sessionCurrentStepIndex;
    }
    const matched = expanded.findIndex((entry) => entry.step.stepId() === stepAtCursor.id);
    if (matched < 0) {
        warnCursorFallback(sessionId, `state.json step id ${stepAtCursor.id} not found in expanded snapshot (${expanded.length} steps); using session.currentStepIndex=${sessionCurrentStepIndex}`);
        return sessionCurrentStepIndex;
    }
    return matched;
}
function warnCursorFallback(sessionId, detail) {
    if (process.env[debugConstants_1.MABL_DEBUG_VERBOSE_ENV_VAR]) {
        process.stderr.write(`debug cursor: falling back to session.json for ${sessionId} — ${detail}\n`);
    }
}
