"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    SessionStore: ()=>SessionStore,
    createSessionAgentOptions: ()=>createSessionAgentOptions
});
const external_node_fs_namespaceObject = require("node:fs");
const external_node_path_namespaceObject = require("node:path");
const common_namespaceObject = require("@midscene/shared/common");
const external_types_js_namespaceObject = require("./types.js");
function defaultGroupName(platform, sessionId) {
    return `Midscene ${platform} session ${sessionId}`;
}
function normalizeSessionRecord(session) {
    return {
        sessionId: session.sessionId,
        platform: session.platform,
        groupName: session.groupName ?? defaultGroupName(session.platform, session.sessionId),
        groupDescription: session.groupDescription,
        sdkVersion: session.sdkVersion ?? '',
        modelBriefs: session.modelBriefs ?? [],
        deviceType: session.deviceType ?? session.platform,
        createdAt: session.createdAt ?? Date.now(),
        updatedAt: session.updatedAt ?? Date.now(),
        executionCount: session.executionCount ?? 0,
        reportFilePath: session.reportFilePath
    };
}
function orderedRootExecutionFiles(dir) {
    if (!(0, external_node_fs_namespaceObject.existsSync)(dir)) return [];
    return (0, external_node_fs_namespaceObject.readdirSync)(dir).filter((file)=>/^\d+\.json$/.test(file)).sort((left, right)=>Number.parseInt(left, 10) - Number.parseInt(right, 10));
}
const SessionStore = {
    rootDir () {
        return (0, common_namespaceObject.getMidsceneRunSubDir)('session');
    },
    sessionDir (sessionId) {
        return (0, external_node_path_namespaceObject.join)(SessionStore.rootDir(), sessionId);
    },
    agentFilePath (sessionId) {
        return (0, external_node_path_namespaceObject.join)(SessionStore.sessionDir(sessionId), 'agent.json');
    },
    executionBasePath (sessionId, order) {
        return (0, external_node_path_namespaceObject.join)(SessionStore.sessionDir(sessionId), `${order}.json`);
    },
    reportDir (sessionId) {
        const dir = (0, external_node_path_namespaceObject.join)(SessionStore.sessionDir(sessionId), 'report');
        (0, external_node_fs_namespaceObject.mkdirSync)(dir, {
            recursive: true
        });
        return dir;
    },
    load (sessionId) {
        const filePath = SessionStore.agentFilePath(sessionId);
        if (!(0, external_node_fs_namespaceObject.existsSync)(filePath)) throw new Error(`Session not found: ${sessionId}`);
        return normalizeSessionRecord(JSON.parse((0, external_node_fs_namespaceObject.readFileSync)(filePath, 'utf-8')));
    },
    save (session) {
        (0, external_node_fs_namespaceObject.mkdirSync)(SessionStore.sessionDir(session.sessionId), {
            recursive: true
        });
        const normalized = normalizeSessionRecord(session);
        (0, external_node_fs_namespaceObject.writeFileSync)(SessionStore.agentFilePath(normalized.sessionId), JSON.stringify(normalized, null, 2), 'utf-8');
        return normalized;
    },
    ensureSession (input) {
        const now = Date.now();
        const filePath = SessionStore.agentFilePath(input.sessionId);
        if ((0, external_node_fs_namespaceObject.existsSync)(filePath)) {
            const existing = SessionStore.load(input.sessionId);
            const mergedModelBriefs = new Set(existing.modelBriefs);
            input.modelBriefs?.forEach((brief)=>mergedModelBriefs.add(brief));
            const next = {
                ...existing,
                platform: input.platform ?? existing.platform,
                groupName: input.groupName ?? existing.groupName ?? defaultGroupName(input.platform, input.sessionId),
                groupDescription: input.groupDescription ?? existing.groupDescription,
                sdkVersion: input.sdkVersion ?? existing.sdkVersion,
                modelBriefs: [
                    ...mergedModelBriefs
                ],
                deviceType: input.deviceType ?? existing.deviceType ?? existing.platform,
                updatedAt: now
            };
            return SessionStore.save(next);
        }
        return SessionStore.save({
            sessionId: input.sessionId,
            platform: input.platform,
            groupName: input.groupName ?? defaultGroupName(input.platform, input.sessionId),
            groupDescription: input.groupDescription,
            sdkVersion: input.sdkVersion ?? '',
            modelBriefs: input.modelBriefs ?? [],
            deviceType: input.deviceType ?? input.platform,
            createdAt: now,
            updatedAt: now,
            executionCount: 0
        });
    },
    markReportGenerated (sessionId, reportFilePath) {
        const session = SessionStore.load(sessionId);
        return SessionStore.save({
            ...session,
            reportFilePath,
            updatedAt: Date.now()
        });
    },
    nextOrder (sessionId) {
        const session = SessionStore.load(sessionId);
        const next = session.executionCount + 1;
        SessionStore.save({
            ...session,
            executionCount: next,
            updatedAt: Date.now()
        });
        return next;
    },
    persistExecution (sessionId, order, execution) {
        const basePath = SessionStore.executionBasePath(sessionId, order);
        external_types_js_namespaceObject.ExecutionDump.cleanupFiles(basePath);
        execution.serializeToFiles(basePath);
    },
    buildSessionDump (sessionId) {
        const session = SessionStore.load(sessionId);
        const rootExecutionFiles = orderedRootExecutionFiles(SessionStore.sessionDir(sessionId));
        if (!rootExecutionFiles.length) throw new Error(`Session ${sessionId} has no persisted executions`);
        const executions = [];
        for (const fileName of rootExecutionFiles){
            const basePath = (0, external_node_path_namespaceObject.join)(SessionStore.sessionDir(sessionId), fileName);
            const inlineJson = external_types_js_namespaceObject.ExecutionDump.fromFilesAsInlineJson(basePath);
            executions.push(JSON.parse(inlineJson));
        }
        return {
            sdkVersion: session.sdkVersion,
            groupName: session.groupName,
            groupDescription: session.groupDescription,
            modelBriefs: session.modelBriefs,
            executions,
            deviceType: session.deviceType ?? session.platform
        };
    }
};
function createSessionAgentOptions(input) {
    if (!input.sessionId) return {};
    return {
        generateReport: false,
        sessionId: input.sessionId,
        groupName: input.groupName ?? defaultGroupName(input.platform, input.sessionId),
        groupDescription: input.groupDescription
    };
}
exports.SessionStore = __webpack_exports__.SessionStore;
exports.createSessionAgentOptions = __webpack_exports__.createSessionAgentOptions;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "SessionStore",
    "createSessionAgentOptions"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});

//# sourceMappingURL=session-store.js.map