import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { log } from '$lib/server/logger';
import { backendFetch } from '$lib/server/scraper';

/**
 * GET /api/audio/status/[slug]/[n]?voice=...
 * Proxies the audio generation status check to the backend's
 * GET /api/audio/status/{slug}/{n} endpoint.
 *
 * Possible responses passed through to the client:
 *   {"status":"done"}                                — audio ready; no url
 *   {"status":"pending"|"generating","task_id":"..."} — in progress
 *   {"status":"idle"}                                — no job yet
 *   {"status":"failed","error":"..."}                — last job failed
 *
 * When status is "done" the scraper's internal proxy URL is stripped — the
 * client must call GET /api/presign/audio to obtain a direct MinIO presigned
 * URL.  This avoids streaming audio through the Node.js server.
 */
export const GET: RequestHandler = async ({ params, url }) => {
	const { slug, n } = params;
	const chapter = parseInt(n, 10);
	if (!slug || !chapter || chapter < 1) {
		error(400, 'Invalid slug or chapter number');
	}

	const voice = url.searchParams.get('voice') ?? '';
	const qs = new URLSearchParams();
	if (voice) qs.set('voice', voice);

	const scraperRes = await backendFetch(
		`/api/audio/status/${slug}/${chapter}?${qs.toString()}`
	);

	if (!scraperRes.ok) {
		const text = await scraperRes.text().catch(() => '');
		log.error('audio', 'backend audio status check failed', {
			slug,
			chapter,
			status: scraperRes.status,
			body: text
		});
		error(scraperRes.status as Parameters<typeof error>[0], text || 'Status check failed');
	}

	const data = (await scraperRes.json()) as {
		status: string;
		task_id?: string;
		url?: string;
		error?: string;
	};

	// Strip the backend's internal proxy URL from "done" responses.
	// The client will call GET /api/presign/audio to get a direct MinIO URL,
	// avoiding streaming audio through the Node.js server.
	if (data.status === 'done') {
		delete data.url;
	}

	return new Response(JSON.stringify(data), {
		headers: { 'Content-Type': 'application/json' }
	});
};
