import { createLogger } from "../../utils/logger/index.js";
import { init_logger } from "../../utils/logger.js";
import { resolveEffectiveAgentProfileForSession } from "../../config/agent-profile.js";
import { resolveEffectiveReasoningLevel, resolveEffectiveThinkingLevel } from "../../session/thinking-resolve.js";
import { effectiveWorkspacePathForSession } from "../../session/session-workspace.js";
import "../../session/index.js";
import { runBtwQuery } from "../service/btw-query.js";
import { formatSessionContextReport } from "../service/session-context-report.js";
//#region src/agent/session/session-inspector.ts
init_logger();
const log = createLogger("SessionInspector");
var SessionInspector = class {
	opts;
	constructor(opts) {
		this.opts = opts;
	}
	/**
	* Manual compaction triggered by a user / API. Always forces a compaction
	* pass (`force: true` by default) and evicts the in-memory agent so the
	* next turn reloads from the compacted transcript.
	*/
	async compact(sessionKey, options) {
		const messages = await this.opts.sessionStore.load(sessionKey);
		const contextWindow = this.opts.getContextWindow();
		const result = await this.opts.sessionStore.compact(sessionKey, messages, contextWindow, options?.instructions, options?.force ?? true);
		if (result.compacted) this.opts.agentManager.removeAgent(sessionKey);
		log.info({
			sessionKey,
			result
		}, "Manual compaction complete");
		return result;
	}
	/** One-shot LLM answer for `/btw`: transcript as background, not persisted. */
	btwQuery(sessionKey, question) {
		return runBtwQuery({
			sessionKey,
			question,
			sessionStore: this.opts.sessionStore,
			modelForSession: this.opts.modelManager.getModelForSession(sessionKey),
			log
		});
	}
	/** Cheap stats used by both the report and other callers. */
	stats(sessionKey, messages) {
		return {
			windowStats: this.opts.sessionStore.getWindowStats(messages),
			compactionStats: this.opts.sessionStore.getCompactionStats(sessionKey),
			tokenEstimate: this.opts.sessionStore.estimateTokenUsage(sessionKey, messages)
		};
	}
	/** Rough context usage for TUI footer (estimated tokens vs nominal budget). */
	async contextUsage(sessionKey) {
		const messages = await this.opts.sessionStore.load(sessionKey);
		const contextWindow = this.opts.getContextWindow();
		const estimatedTokens = await this.opts.sessionStore.estimateTokenUsage(sessionKey, messages);
		return {
			estimatedTokens,
			contextWindow,
			usagePercent: contextWindow > 0 ? Math.min(100, Math.round(estimatedTokens / contextWindow * 100)) : null
		};
	}
	/** Markdown or JSON summary for `/context`. */
	async report(sessionKey, mode) {
		const cfg = this.opts.getConfig();
		if (!cfg) throw new Error("SessionInspector requires a config snapshot to render report");
		const messages = await this.opts.sessionStore.load(sessionKey);
		const cw = this.opts.getContextWindow();
		const computed = this.stats(sessionKey, messages);
		const model = this.opts.modelManager.getModelForSession(sessionKey);
		const workspace = effectiveWorkspacePathForSession(cfg, sessionKey, await this.opts.sessionConfigStore.get(sessionKey));
		const estTokens = await this.opts.sessionStore.estimateTokenUsage(sessionKey, messages);
		const profile = resolveEffectiveAgentProfileForSession(cfg, sessionKey);
		const defaults = cfg.agents?.defaults;
		const compaction = defaults?.compaction;
		const tools = defaults?.tools;
		const toolsSummary = tools && typeof tools === "object" ? Object.entries(tools).filter(([, v]) => v === true).map(([k]) => k).slice(0, 16).join(", ") || "(none explicitly true)" : "(see agents.defaults.tools in config)";
		return formatSessionContextReport({
			sessionKey,
			mode,
			model,
			workspacePath: workspace,
			agentId: profile.agentId,
			messageCount: messages.length,
			contextWindowNominal: cw,
			estimatedTranscriptTokens: estTokens,
			thinkingDefault: defaults?.thinkingDefault,
			reasoningDefault: defaults?.reasoningDefault,
			verboseDefault: defaults?.verboseDefault,
			compaction,
			toolsFlagsSummary: toolsSummary,
			windowStats: computed.windowStats,
			compactionRunStats: computed.compactionStats
		});
	}
	/** Resolved thinking / model / workspace for the Web UI. */
	async agentConfig(sessionKey) {
		await this.opts.sessionHydrator.model(sessionKey);
		const cfg = this.opts.getConfig();
		if (!cfg) throw new Error("SessionInspector requires a config snapshot to resolve agent config");
		const sc = await this.opts.sessionConfigStore.get(sessionKey);
		const profileModelRef = resolveEffectiveAgentProfileForSession(cfg, sessionKey).primaryModelRef?.trim();
		if (profileModelRef) this.opts.modelManager.setSessionProfileDefault(sessionKey, profileModelRef);
		const defThink = cfg.agents?.defaults?.thinkingDefault ?? "medium";
		const level = await resolveEffectiveThinkingLevel(this.opts.sessionConfigStore, sessionKey, null, defThink);
		const defReason = cfg.agents?.defaults?.reasoningDefault ?? "stream";
		const reasoningLevel = await resolveEffectiveReasoningLevel(this.opts.sessionConfigStore, sessionKey, defReason);
		return {
			thinkingLevel: level,
			model: this.opts.modelManager.getModelForSession(sessionKey),
			reasoningLevel,
			effectiveWorkspacePath: effectiveWorkspacePathForSession(cfg, sessionKey, sc),
			workingDirectoryLocked: Boolean(sc?.workingDirectoryOverride?.trim())
		};
	}
};
//#endregion
export { SessionInspector };

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