/**
 * versionStore - Build version information
 *
 * - `build`: llama.cpp build number from `build.json`, embedded at llama.cpp
 *   build time (LLAMA_BUILD_NUMBER). Shown in the UI when `showBuildVersion`
 *   is enabled.
 * - `frontend`: frontend build version from SvelteKit's `_app/version.json`,
 *   generated by the @vite-pwa/sveltekit plugin. Changes on every build, so
 *   comparing it against localStorage reliably detects server upgrades.
 *
 * In dev mode both fall back to `'dev'`.
 */

import { browser } from '$app/environment';
import { base } from '$app/paths';

class VersionStore {
	build = $state<string>('');
	frontend = $state<string>('');

	/**
	 * Fetch the version files. Called by initStores(); order-independent,
	 * so it runs in the background.
	 */
	initialize(): void {
		if (!browser) return;

		if (import.meta.env.DEV) {
			this.build = 'dev';
			this.frontend = 'dev';

			return;
		}

		void this.load();
	}

	private async load(): Promise<void> {
		try {
			const res = await fetch(`${base}/build.json`, { cache: 'no-store' });

			if (res.ok) {
				const data = await res.json();

				this.build = data.version ?? '';
			}
		} catch {
			// build.json missing or unreachable - leave as empty string
		}

		try {
			const res = await fetch(`${base}/_app/version.json`, { cache: 'no-store' });

			if (res.ok) {
				const data = await res.json();

				this.frontend = data.version ?? '';
			}
		} catch {
			// version.json missing or unreachable - leave as empty string
		}
	}
}

export const versionStore = new VersionStore();
