import type { PageServerLoad } from './$types';
import { listTextModels } from '$lib/server/scraper';
import { log } from '$lib/server/logger';
import { listBooks } from '$lib/server/pocketbase';

export interface BookSummary {
	slug: string;
	title: string;
}

export interface TextModelInfo {
	id: string;
	label: string;
	provider: string;
	context_size: number;
	description: string;
}

export const load: PageServerLoad = async () => {
	// Await models immediately — in-memory list, no I/O, returns instantly.
	// Books are streamed so the page renders at once and the selector
	// populates a moment later without blocking navigation.
	const modelsResult = await listTextModels<TextModelInfo>().catch((e) => {
		log.warn('admin/text-gen', 'failed to load models', { err: String(e) });
		return [] as TextModelInfo[];
	});

	const booksPromise = listBooks()
		.then((all) =>
			all.map((b) => ({ slug: b.slug, title: b.title })) as BookSummary[]
		)
		.catch(() => [] as BookSummary[]);

	return {
		models: modelsResult,
		// Streamed — SvelteKit resolves this after the initial HTML is sent.
		books: booksPromise
	};
};
