1
import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
	getScenarioByNormalizedName,
	saveNewScenario,
	updateScenarioData
} from '$lib/server/database';
import { generateCareerArchetype } from '$lib/server/archetypeSelection';
import { allArchetypeData } from '$lib/server/archetypeData/all';
import { generateArchetypeData } from '$lib/server/archetypeGeneration';
import { checkSession } from '$lib/server/auth';

export const POST: RequestHandler = async ({ request, cookies }) => {
	const { careerName } = await request.json();

	if ((await checkSession(cookies.get('session') || '')) !== true) {
		throw error(401, 'Unauthorized');
	}

	const stream = new ReadableStream({
		async start(controller) {
			const encoder = new TextEncoder();

			const sendUpdate = (data: any) => {
				controller.enqueue(encoder.encode(JSON.stringify(data) + '\n'));
			};

			sendUpdate({ status: 'loading', message: 'Processing request...' });

			try {
				const scenario = await getScenarioByNormalizedName(careerName);

				if (!scenario) {
					// Throw error so the try/catch will handle it
					throw new Error(`No scenario found for career name: ${careerName}`);
				}

				sendUpdate({ status: 'done', message: 'Scenario found', scenarioId: scenario.$id });
			} catch (err) {
				sendUpdate({ status: 'loading', message: 'Determining archetype...' });

				let archetypeId: string;
				// Generate a new scenario if not found or if there's an error
				try {
					archetypeId = await generateCareerArchetype(careerName);
				} catch (genErr) {
					console.error('Error generating archetype:', genErr);
					throw error(500, 'Failed to generate archetype');
				}

				sendUpdate({ status: 'loading', message: 'Generating scenario data...' });

				// Get the archetype data
				const archetype = allArchetypeData.find((a) => a.id === archetypeId);
				if (!archetype) {
					throw error(500, 'Failed to find generated archetype');
				}

				// Generate the scenario data based on the archetype
				let newScenarioData, cachedImageUrlsPromises;
				try {
					const result = await generateArchetypeData(archetype, careerName);
					newScenarioData = result.output;
					cachedImageUrlsPromises = result.cachedImageUrlsPromise;
				} catch (dataErr) {
					console.error('Error generating archetype data:', dataErr);
					throw error(500, 'Failed to generate archetype data');
				}

				sendUpdate({ status: 'loading', message: 'Saving scenario...' });

				// Save the new scenario to the database
				try {
					const savedScenario = await saveNewScenario({
						normalizedName: careerName,
						archetype: archetype.id,
						rating: 5, // Assume perfect rating
						isActive: true,
						scenarioData: JSON.stringify(newScenarioData)
					});

					(async () => {
						// If there are any cached image URL updates pending, wait for those and update the scenario data in the database
						if (cachedImageUrlsPromises) {
							try {
								await cachedImageUrlsPromises;
								await updateScenarioData(savedScenario.$id, JSON.stringify(newScenarioData));
							} catch (updateErr) {
								console.error('Error updating scenario with cached image URLs:', updateErr);
								// Not throwing an error here since the scenario was successfully created, just logging the issue
							}
						}
					})().catch((err) => {
						console.error('Error in cached image URL update process:', err);
					});

					sendUpdate({
						status: 'done',
						message: 'Scenario created',
						scenarioId: savedScenario.$id
					});
				} catch (saveErr) {
					console.error('Error saving new scenario:', saveErr);
					throw error(500, 'Failed to save new scenario');
				}
			}
		}
	});

	return new Response(stream, {
		headers: {
			'Content-Type': 'application/x-ndjson', // Newline-delimited JSON format
			'Cache-Control': 'no-cache',
			Connection: 'keep-alive'
		}
	});
};

For immediate assistance, please email our customer support: [email protected]

Download RAW File