import { createLogger } from "../../utils/logger/index.js";
import { init_logger } from "../../utils/logger.js";
//#region src/agent/lifecycle/manager.ts
init_logger();
const logger = createLogger("lifecycle-manager");
var LifecycleManager = class {
	handlers = /* @__PURE__ */ new Map();
	on(eventType, handler) {
		const existing = this.handlers.get(eventType) || [];
		existing.push(handler);
		this.handlers.set(eventType, existing);
		logger.debug({
			eventType,
			handlerName: handler.name
		}, "Registered lifecycle handler");
		return this;
	}
	async emit(eventType, sessionKey, payload, context) {
		const handlers = this.handlers.get(eventType) || [];
		if (handlers.length === 0) {
			logger.debug({
				eventType,
				sessionKey
			}, "No handlers registered for event");
			return;
		}
		const event = {
			type: eventType,
			sessionKey,
			payload,
			timestamp: Date.now()
		};
		logger.debug({
			eventType,
			sessionKey,
			handlerCount: handlers.length
		}, "Emitting lifecycle event");
		const results = await Promise.allSettled(handlers.map(async (handler) => {
			try {
				await handler.handle(event, context);
				logger.debug({
					handler: handler.name,
					eventType
				}, "Lifecycle handler completed");
			} catch (error) {
				logger.warn({
					handler: handler.name,
					eventType,
					error
				}, "Lifecycle handler failed");
				throw error;
			}
		}));
		const succeeded = results.filter((r) => r.status === "fulfilled").length;
		const failed = results.filter((r) => r.status === "rejected").length;
		if (failed > 0) logger.warn({
			eventType,
			succeeded,
			failed,
			total: handlers.length
		}, "Some lifecycle handlers failed");
		else logger.debug({
			eventType,
			succeeded,
			total: handlers.length
		}, "All lifecycle handlers completed");
	}
	getRegisteredHandlers() {
		const result = {};
		for (const [eventType, handlers] of this.handlers.entries()) result[eventType] = handlers.map((h) => h.name);
		return result;
	}
	clear() {
		this.handlers.clear();
		logger.debug("All lifecycle handlers cleared");
	}
};
//#endregion
export { LifecycleManager };

//# sourceMappingURL=manager.js.map