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

export interface ImageModelInfo {
	id: string;
	label: string;
	provider: string;
	supports_ref: boolean;
	recommended_for: string[]; // "cover" | "chapter"
	description: string;
}

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

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

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

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