import OpenAI from 'openai';
import { env } from '$env/dynamic/private';
import { logError } from './utils/logger';

export const createLLM = () => {
	// Detect if we are using Ollama or OpenAI based on URL
	const baseURL = env.OPENAI_BASE_URL;
	const apiKey = env.OPENAI_API_KEY;
	const model = env.LLM_MODEL || 'gpt-4o';

	console.log('[LLM] Initializing client...');
	console.log('[LLM] Base URL:', baseURL);
	console.log('[LLM] Model:', model);

	if (!baseURL) {
		throw new Error('OPENAI_BASE_URL environment variable is not set');
	}

	if (!apiKey) {
		throw new Error('OPENAI_API_KEY environment variable is not set');
	}

	const client = new OpenAI({
		apiKey,
		baseURL
	});

	return { client, model };
};

/**
 * Health check for LLM service
 */
export async function checkLLMHealth(): Promise<boolean> {
	try {
		const { client } = createLLM();
		await client.models.list();
		console.log('[LLM] Health check passed');
		return true;
	} catch (e) {
		logError('[LLM] Health check failed', e);
		return false;
	}
}

/**
 * Check if a specific model is available in the OpenAI-compatible API
 * @param model - The model ID to check for availability
 * @returns Object with available status and optional message
 */
export async function checkModelAvailability(
	model: string
): Promise<{ available: boolean; message?: string }> {
	try {
		console.log('[LLM] Checking model availability:', model);
		const { client } = createLLM();
		const response = await client.models.list();
		const models = response.data || [];
		
		const foundModel = models.find((m) => m.id === model);
		
		if (foundModel) {
			console.log('[LLM] Model available:', model);
			return { available: true };
		} else {
			const availableModels = models.map((m) => m.id).join(', ');
			console.warn('[LLM] Model not found:', model);
			console.warn('[LLM] Available models:', availableModels);
			return {
				available: false,
				message: `Model "${model}" not found. Available models: ${availableModels}`
			};
		}
	} catch (e) {
		logError('[LLM] Model availability check failed', e);
		return {
			available: false,
			message: `Failed to check model availability: ${(e as Error).message}`
		};
	}
}