import {
	getStreamProcess,
	addStreamClient,
	removeStreamClient,
} from "$lib/server/streaming.js";

export async function GET({ url }) {
	const streamId = url.searchParams.get("id");

	if (!streamId) {
		return new Response("Missing stream ID", { status: 400 });
	}

	const stream = getStreamProcess(streamId);
	if (!stream || !stream.process || !stream.process.stdout) {
		return new Response("Stream not found", { status: 404 });
	}

	const clientId = Math.random().toString(36).substring(7);
	addStreamClient(streamId, clientId);

	// Create a web ReadableStream from the Node.js stream
	const nodeStream = stream.process.stdout;

	const webReadableStream = new ReadableStream({
		start(controller) {
			nodeStream.on("data", (chunk) => {
				controller.enqueue(chunk);
			});

			nodeStream.on("end", () => {
				controller.close();
			});

			nodeStream.on("error", () => {
				controller.close();
			});
		},
		cancel() {
			removeStreamClient(streamId, clientId);
		},
	});

	// Return the response with proper headers
	return new Response(webReadableStream, {
		status: 200,
		headers: {
			"Content-Type": "image/jpeg",
			"Cache-Control": "no-cache, no-store, must-revalidate",
			Pragma: "no-cache",
			Expires: "0",
			Connection: "keep-alive",
		},
	});
}
