import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getRandomVersesFromBook } from '$lib/server/xml-bible';

interface VerseOption {
	text: string;
	isImposter: boolean;
	ref: string;
}

export const GET: RequestHandler = async () => {
	try {
		// Select two different random books (1-66)
		let book1Num = Math.floor(Math.random() * 66) + 1;
		let book2Num = Math.floor(Math.random() * 66) + 1;
		while (book2Num === book1Num) {
			book2Num = Math.floor(Math.random() * 66) + 1;
		}

		// Randomly decide which is majority
		const majorityBookNum = Math.random() < 0.5 ? book1Num : book2Num;
		const imposterBookNum = majorityBookNum === book1Num ? book2Num : book1Num;

		// Get 3 random verses from majority book
		const options: VerseOption[] = [];
		for (let i = 0; i < 3; i++) {
			const verseData = getRandomVersesFromBook(majorityBookNum, 1);
			if (!verseData) {
				throw new Error('Failed to get majority verse');
			}
			options.push({
				text: verseData.verses[0],
				isImposter: false,
				ref: `${verseData.bookName} ${verseData.chapter}:${verseData.startVerse}`
			});
		}

		// Get 1 random verse from imposter book
		const imposterVerseData = getRandomVersesFromBook(imposterBookNum, 1);
		if (!imposterVerseData) {
			throw new Error('Failed to get imposter verse');
		}
		options.push({
			text: imposterVerseData.verses[0],
			isImposter: true,
			ref: `${imposterVerseData.bookName} ${imposterVerseData.chapter}:${imposterVerseData.startVerse}`
		});

		// Fisher-Yates shuffle
		for (let i = options.length - 1; i > 0; i--) {
			const j = Math.floor(Math.random() * (i + 1));
			[options[i], options[j]] = [options[j], options[i]];
		}

		const verses = options.map(o => o.text);
		const refs = options.map(o => o.ref);
		const imposterIndex = options.findIndex(o => o.isImposter);

		return json({
			verses,
			refs,
			imposterIndex
		});
	} catch (error) {
		console.error('Imposter API error:', error);
		return json({ error: 'Failed to generate imposter game' }, { status: 500 });
	}
};