import type { DailyVerse } from '$lib/server/db/schema';
import { getBookById } from './bible';
import { getRandomVerses, formatReference } from './xml-bible';

type ApiVerse = Omit<DailyVerse, 'id' | 'date' | 'createdAt'>;

export async function fetchRandomVerse(): Promise<ApiVerse> {
	// Get 3 random verses from the local XML Bible
	const verseData = getRandomVerses(3);

	if (!verseData) {
		throw new Error('Failed to get random verses from Bible XML');
	}

	const { bookId, bookName, chapter, startVerse, endVerse, verses } = verseData;

	// Validate bookId
	if (!getBookById(bookId)) {
		throw new Error(`Unknown book ID: ${bookId}`);
	}

	// Format the reference string (e.g., "Matthew 1:1-3")
	const reference = formatReference(bookName, chapter, startVerse, endVerse);

	// Join verses with spaces
	const verseText = verses.join(' ');

	return {
		bookId,
		reference,
		verseText
	};
}

/**
 * Like fetchRandomVerse, but re-rolls until the picked book is not in
 * `avoidBookIds` (the no-back-to-back neighbors for lazy gap-fill).
 * 66 books with ≤2 excluded gives ~97% success per try; capped at 20 tries
 * before accepting whatever was last drawn (spec: "Lazy Gap-Fill").
 */
export async function fetchRandomVerseAvoiding(
	avoidBookIds: string[] = []
): Promise<ApiVerse> {
	const avoid = new Set(avoidBookIds.filter(Boolean));
	let last: ApiVerse | null = null;
	for (let i = 0; i < 20; i++) {
		const v = await fetchRandomVerse();
		last = v;
		if (!avoid.has(v.bookId)) return v;
	}
	return last as ApiVerse;
}
