import { createLogger } from "../utils/logger/index.js";
import { init_logger } from "../utils/logger.js";
import { init_agent_scope, resolveDefaultAgentId } from "../agent/agent-scope.js";
import { init_paths, resolveSessionsMapPath } from "../config/paths.js";
import { SessionConfigSchema, init_schema } from "../config/schema.js";
import { init_agent_session_key, normalizeAgentId, resolveAgentIdFromSessionKey } from "../routing/agent-session-key.js";
import { init_session_key, parseSessionKey } from "../routing/session-key.js";
import { readSessionsJsonFile } from "./parity/sessions-json-file.js";
import { normalizeThinkLevel, normalizeVerboseLevel } from "../agent/transcript/thinking-types.js";
import { evaluateSessionFreshness, resolveSessionResetPolicy } from "./reset-policy.js";
import { resolveChannelResetConfig, resolveSessionResetType } from "./reset-type.js";
import { resolveSessionLifecycleTimestamps } from "./lifecycle-timestamps.js";
import { randomUUID } from "node:crypto";
//#region src/session/resolve-session.ts
init_schema();
init_paths();
init_agent_scope();
init_agent_session_key();
init_session_key();
init_logger();
const log = createLogger("ResolveSession");
async function resolveSessionKeyForRequest(opts) {
	const defaultAgentId = resolveDefaultAgentId(opts.cfg);
	const explicitKey = opts.sessionKey?.trim();
	const requestedSessionId = opts.sessionId?.trim();
	const storeAgentId = explicitKey ? resolveAgentIdFromSessionKey(explicitKey) : opts.agentId?.trim() ? normalizeAgentId(opts.agentId) : defaultAgentId;
	const storePath = resolveSessionsMapPath(opts.cfg, storeAgentId);
	const sessionStore = await readSessionsJsonFile(storePath);
	let sessionKey = explicitKey;
	if (requestedSessionId && !sessionKey) {
		for (const [key, entry] of Object.entries(sessionStore)) if (entry?.sessionId === requestedSessionId) {
			sessionKey = key;
			break;
		}
	}
	if (requestedSessionId && !sessionKey) sessionKey = `agent:${normalizeAgentId(opts.agentId ?? storeAgentId)}:explicit:${requestedSessionId}`;
	return {
		sessionKey,
		sessionStore,
		storePath
	};
}
async function resolveSession(opts) {
	const sessionCfg = opts.cfg.session ?? SessionConfigSchema.parse({});
	const { sessionKey, sessionStore, storePath } = await resolveSessionKeyForRequest(opts);
	const now = Date.now();
	const sessionEntry = sessionKey ? sessionStore[sessionKey] : void 0;
	const parsed = sessionKey ? parseSessionKey(sessionKey) : null;
	const peerKind = parsed?.peerKind;
	const resetType = resolveSessionResetType({
		sessionKey,
		isGroup: peerKind === "group" || peerKind === "channel",
		isThread: Boolean(parsed?.threadId)
	});
	const meta = sessionEntry?.pluginExtensions?.xopc?.metadata;
	const resetPolicy = resolveSessionResetPolicy({
		sessionCfg,
		resetType,
		resetOverride: resolveChannelResetConfig({
			sessionCfg,
			channel: parsed?.source ?? meta?.sourceChannel
		})
	});
	const lifecycle = resolveSessionLifecycleTimestamps({ entry: sessionEntry });
	const fresh = (sessionEntry ? evaluateSessionFreshness({
		updatedAt: sessionEntry.updatedAt,
		...lifecycle,
		now,
		policy: resetPolicy
	}) : { fresh: false }).fresh;
	const sessionId = opts.sessionId?.trim() || (fresh ? sessionEntry?.sessionId : void 0) || randomUUID();
	const isNewSession = !fresh && !opts.sessionId?.trim();
	if (isNewSession && sessionKey) log.debug({
		sessionKey,
		previousSessionId: sessionEntry?.sessionId,
		sessionId,
		resetType
	}, "Session reset boundary — new transcript id for turn");
	return {
		sessionId,
		sessionKey,
		sessionEntry,
		sessionStore,
		storePath,
		isNewSession,
		persistedThinking: fresh && sessionEntry?.thinkingLevel ? normalizeThinkLevel(sessionEntry.thinkingLevel) : void 0,
		persistedVerbose: fresh && sessionEntry?.verboseLevel ? normalizeVerboseLevel(sessionEntry.verboseLevel) : void 0
	};
}
//#endregion
export { resolveSession, resolveSessionKeyForRequest };

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