import { writable } from 'svelte/store';
import { getSettings } from '$lib/api';

/**
 * Reactive view of the configured stats collection interval (seconds).
 * Set to 0 when collection is disabled. Refreshed on mount and after the
 * settings page saves. Components can subscribe with `$statsInterval` to
 * render contextual messages ("samples every Ns", "collection disabled").
 */
export const statsInterval = writable<number>(15);

let loaded = false;

export async function refreshStatsInterval(): Promise<void> {
	try {
		const s = await getSettings();
		const v = s?.stats_interval_seconds;
		statsInterval.set(typeof v === 'number' ? v : 15);
		loaded = true;
	} catch {
		// Leave the previous value if the request fails.
	}
}

export function ensureStatsIntervalLoaded(): void {
	if (!loaded) void refreshStatsInterval();
}
