import { _getAdapter } from "./sf-db-core.js";

export function loadSessionModeState() {
	const currentDb = _getAdapter();
	if (!currentDb) return null;
	try {
		const row = currentDb
			.prepare("SELECT * FROM session_mode_state WHERE id = 1")
			.get();
		if (!row) return null;
		return {
			workMode: row["work_mode"] ?? "chat",
			runControl: row["run_control"] ?? "manual",
			permissionProfile: row["permission_profile"] ?? "restricted",
			modelMode: row["model_mode"] ?? "smart",
			surface: row["surface"] ?? "tui",
			updatedAt: row["updated_at"] ?? null,
		};
	} catch {
		return null;
	}
}

export function saveSessionModeState(mode) {
	const currentDb = _getAdapter();
	if (!currentDb) return false;
	currentDb
		.prepare(`
		INSERT INTO session_mode_state (id, work_mode, run_control, permission_profile, model_mode, surface, updated_at)
		VALUES (1, :workMode, :runControl, :permissionProfile, :modelMode, :surface, :updatedAt)
		ON CONFLICT(id) DO UPDATE SET
			work_mode = excluded.work_mode,
			run_control = excluded.run_control,
			permission_profile = excluded.permission_profile,
			model_mode = excluded.model_mode,
			surface = excluded.surface,
			updated_at = excluded.updated_at
	`)
		.run({
			":workMode": mode.workMode,
			":runControl": mode.runControl,
			":permissionProfile": mode.permissionProfile,
			":modelMode": mode.modelMode,
			":surface": mode.surface ?? "tui",
			":updatedAt": mode.updatedAt ?? new Date().toISOString(),
		});
	return true;
}
