<script lang="ts">
	import { onMount } from 'svelte';

	type HealthStatus = 'checking' | 'ok' | 'warming' | 'error';

	interface HealthState {
		status: HealthStatus;
		message: string;
		configuredModel: string;
		lastChecked: Date | null;
	}

	let { pollInterval = 30000 } = $props<{
		pollInterval?: number;
	}>();

	let health = $state<HealthState>({
		status: 'checking',
		message: '',
		configuredModel: '',
		lastChecked: null
	});

	async function checkHealth() {
		try {
			const res = await fetch('/api/llm-health');
			const data = await res.json();
			const status: HealthStatus =
				data.status === 'ok' ? 'ok' : data.status === 'warming' ? 'warming' : 'error';
			health = {
				status,
				message: data.message ?? '',
				configuredModel: data.configuredModel ?? '',
				lastChecked: new Date()
			};
		} catch (e) {
			health = {
				status: 'error',
				message: e instanceof Error ? e.message : 'Network error',
				configuredModel: '',
				lastChecked: new Date()
			};
		}
	}

	onMount(() => {
		checkHealth();
		const interval = setInterval(checkHealth, pollInterval);
		return () => clearInterval(interval);
	});
</script>

<div class="flex items-center gap-2 text-sm">
	<div class="flex items-center gap-1">
		{#if health.status === 'checking'}
			🟡 <span>Checking LLM...</span>
		{:else if health.status === 'ok'}
			🟢 <span class="text-green-600">LLM Ready</span>
		{:else if health.status === 'warming'}
			🟡 <span class="text-yellow-600">LLM Cold ({health.configuredModel})</span>
		{:else}
			🔴 <span class="text-red-600">LLM Unavailable</span>
		{/if}
	</div>
	<div class="text-xs text-gray-500" title={health.message}>
		{health.lastChecked ? `Last: ${health.lastChecked.toLocaleTimeString()}` : ''}
	</div>
</div>
