import { parseAgentSessionKey } from "../routing/session-key-utils.js";
import { init_agent_session_key } from "../routing/agent-session-key.js";
import { appendHistoryToChatLog } from "./chat-history.js";
import { clearPendingToolCallIds } from "./tui-agent-events.js";
//#region src/tui/tui-session-actions.ts
init_agent_session_key();
function createSessionActions(context) {
	const { client, chatLog, tui, state, assembler, resolveSessionKey, updateHeader, updateFooter, setActivityStatus, historyLimit = 200, onAgentIdChange } = context;
	let refreshSessionInfoPromise = Promise.resolve();
	const updateAgentFromSessionKey = (key) => {
		const parsed = parseAgentSessionKey(key);
		if (!parsed?.agentId) return;
		onAgentIdChange?.(parsed.agentId);
	};
	const runRefreshSessionInfo = async () => {
		try {
			state.sessionInfo = await client.getSessionInfo(state.currentSessionKey);
			updateFooter();
			tui.requestRender();
		} catch {}
	};
	const refreshSessionInfo = async () => {
		refreshSessionInfoPromise = refreshSessionInfoPromise.then(runRefreshSessionInfo, runRefreshSessionInfo);
		await refreshSessionInfoPromise;
	};
	const clearChatForSessionSwitch = () => {
		assembler.clear();
		chatLog.clearAll();
		clearPendingToolCallIds();
		state.historyLoaded = false;
		state.messageFollowUpQueue.length = 0;
	};
	const loadHistory = async () => {
		try {
			const { messages } = await client.loadHistory({
				sessionKey: state.currentSessionKey,
				limit: historyLimit
			});
			chatLog.clearAll();
			appendHistoryToChatLog(chatLog, messages, state.toolsExpanded);
		} catch {} finally {
			state.historyLoaded = true;
			await refreshSessionInfo();
			tui.requestRender();
		}
	};
	const setSession = async (rawKey) => {
		const nextKey = resolveSessionKey(rawKey);
		updateAgentFromSessionKey(nextKey);
		state.currentSessionKey = nextKey;
		state.activeRunId = null;
		setActivityStatus("idle");
		clearChatForSessionSwitch();
		updateHeader();
		updateFooter();
		await loadHistory();
	};
	const abortActive = async (opts) => {
		if (!state.activeRunId) return;
		const runId = state.activeRunId;
		state.activeRunId = null;
		assembler.drop(runId);
		if (opts?.clearUi !== false) chatLog.dropAssistant(runId);
		setActivityStatus("idle");
		tui.requestRender();
		await client.abortChat({
			sessionKey: state.currentSessionKey,
			runId
		}).catch(() => {});
	};
	const resetCurrentSession = async () => {
		await client.resetSession(state.currentSessionKey);
		clearChatForSessionSwitch();
		await loadHistory();
	};
	return {
		refreshSessionInfo,
		loadHistory,
		setSession,
		abortActive,
		resetCurrentSession,
		clearChatForSessionSwitch
	};
}
//#endregion
export { createSessionActions };

//# sourceMappingURL=tui-session-actions.js.map