import { getLogger } from "./utils/logger.js";
import { SessionContext, runWithContext } from "./context.js";
import { randomUUID } from "node:crypto";

//#region src/middleware.ts
/**
* HTTP middleware for automatic session tracking in Express/Koa/Hono apps.
*
* Port of the Python ASGI middleware (AmplitudeAIMiddleware).
* For Express-like frameworks, use createAmplitudeAIMiddleware().
*/
function resolveOption(value, req) {
	if (typeof value === "function") return value(req) ?? null;
	return value ?? null;
}
/**
* Creates Express-compatible middleware.
*
* Usage:
*   app.use(createAmplitudeAIMiddleware({
*     amplitudeAI: ai,
*     userIdResolver: (req) => req.headers['x-user-id'],
*   }));
*/
function createAmplitudeAIMiddleware(options) {
	const { amplitudeAI, userIdResolver, sessionIdResolver = () => randomUUID(), agentId = null, env = null, agentVersion = null, customerOrgId = null, context = null, groups = null, trackSessionEvents = true, flushOnResponse = true } = options;
	const logger = getLogger(amplitudeAI.amplitude);
	return (req, res, next) => {
		const userId = userIdResolver(req);
		const sessionId = sessionIdResolver(req);
		let traceId = req.headers["x-trace-id"];
		if (!traceId && req.headers.traceparent) {
			const parts = String(req.headers.traceparent).split("-");
			traceId = parts.length >= 2 ? parts[1] : void 0;
		}
		if (!traceId) traceId = randomUUID();
		const resolvedCustomerOrgId = resolveOption(customerOrgId, req);
		const resolvedContext = resolveOption(context, req);
		const resolvedGroups = resolveOption(groups, req);
		runWithContext(new SessionContext({
			sessionId,
			traceId,
			userId,
			agentId,
			env,
			agentVersion,
			customerOrgId: resolvedCustomerOrgId,
			context: resolvedContext,
			groups: resolvedGroups,
			nextTurnIdFn: () => amplitudeAI._nextTurnId(sessionId),
			amplitude: amplitudeAI.amplitude
		}), () => {
			res.on("finish", () => {
				if (trackSessionEvents && userId != null) try {
					amplitudeAI.trackSessionEnd({
						userId,
						sessionId,
						traceId: traceId ?? void 0,
						env,
						agentId,
						agentVersion,
						customerOrgId: resolvedCustomerOrgId,
						context: resolvedContext,
						groups: resolvedGroups
					});
				} catch (error) {
					logger.warn(`Failed to track session end in middleware: ${error instanceof Error ? error.message : String(error)}`);
				}
				if (flushOnResponse) try {
					amplitudeAI.flush();
				} catch (error) {
					logger.warn(`Failed to flush events in middleware: ${error instanceof Error ? error.message : String(error)}`);
				}
			});
			next();
		});
	};
}

//#endregion
export { createAmplitudeAIMiddleware };
//# sourceMappingURL=middleware.js.map