import { OLLAMA_API_BASE_URL } from '$lib/constants';

export const getOllamaVersion = async (
	base_url: string = OLLAMA_API_BASE_URL,
	token: string = ''
) => {
	let error = null;

	const res = await fetch(`${base_url}/version`, {
		method: 'GET',
		headers: {
			Accept: 'application/json',
			'Content-Type': 'application/json',
			...(token && { authorization: `Bearer ${token}` })
		}
	})
		.then(async (res) => {
			if (!res.ok) throw await res.json();
			return res.json();
		})
		.catch((error) => {
			console.log(error);
			if ('detail' in error) {
				error = error.detail;
			} else {
				error = 'Server connection failed';
			}
			return null;
		});

	if (error) {
		throw error;
	}

	return res?.version ?? '0';
};

export const getOllamaModels = async (
	base_url: string = OLLAMA_API_BASE_URL,
	token: string = ''
) => {
	let error = null;

	const res = await fetch(`${base_url}/tags`, {
		method: 'GET',
		headers: {
			Accept: 'application/json',
			'Content-Type': 'application/json',
			...(token && { authorization: `Bearer ${token}` })
		}
	})
		.then(async (res) => {
			if (!res.ok) throw await res.json();
			return res.json();
		})
		.catch((error) => {
			console.log(error);
			if ('detail' in error) {
				error = error.detail;
			} else {
				error = 'Server connection failed';
			}
			return null;
		});

	if (error) {
		throw error;
	}

	return res?.models ?? [];
};
