import { createLogger } from "../../utils/logger/index.js";
import { init_logger } from "../../utils/logger.js";
//#region src/agent/session/session-lifecycle.ts
init_logger();
const log = createLogger("SessionLifecycleManager");
var SessionLifecycleManager = class {
	sessionStore;
	sessionTracker;
	lifecycleManager;
	events;
	sessionStartTimes = /* @__PURE__ */ new Map();
	constructor(sessionStore, sessionTracker, lifecycleManager, events = {}) {
		this.sessionStore = sessionStore;
		this.sessionTracker = sessionTracker;
		this.lifecycleManager = lifecycleManager;
		this.events = events;
	}
	/**
	* Start a session and emit lifecycle events
	*/
	async startSession(context) {
		const { sessionKey } = context;
		log.debug({ sessionKey }, "Starting session");
		this.sessionTracker.touchSession(sessionKey);
		this.sessionStartTimes.set(sessionKey, Date.now());
		await this.lifecycleManager.emit("session_start", sessionKey, {
			channel: context.channel,
			chatId: context.chatId,
			senderId: context.senderId,
			isGroup: context.isGroup
		}, context);
		if (this.events.onSessionStart) await this.events.onSessionStart(context);
	}
	/**
	* End a session and emit lifecycle events
	*/
	async endSession(context) {
		const { sessionKey } = context;
		log.debug({ sessionKey }, "Ending session");
		const messageCount = await this.getMessageCount(sessionKey);
		const startTime = this.sessionStartTimes.get(sessionKey);
		const durationMs = startTime ? Date.now() - startTime : void 0;
		const stats = {
			messageCount,
			durationMs
		};
		await this.lifecycleManager.emit("session_end", sessionKey, {
			messageCount,
			durationMs
		}, context);
		this.sessionStartTimes.delete(sessionKey);
		if (this.events.onSessionEnd) await this.events.onSessionEnd(context, stats);
	}
	/**
	* Get the number of messages in a session
	*/
	async getMessageCount(sessionKey) {
		try {
			return (await this.sessionStore.load(sessionKey)).length;
		} catch {
			return 0;
		}
	}
	/**
	* Get the start time for a session
	*/
	getSessionStartTime(sessionKey) {
		return this.sessionStartTimes.get(sessionKey);
	}
	/**
	* Check if a session is currently active
	*/
	isSessionActive(sessionKey) {
		return this.sessionStartTimes.has(sessionKey);
	}
};
//#endregion
export { SessionLifecycleManager };

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