export const prerender = true;

import fs from 'node:fs';
import Vips from 'wasm-vips';
import path from 'node:path/posix';
import chalk from 'chalk';
import dayjs from 'dayjs';

var imageTypes = [
	'.bmp',
	'.ico',
	'.cur',
	'.gif',
	'.heif',
	'.heic',
	'.jpeg',
	'.jpg',
	'.jpe',
	'.jp2',
	'.j2k',
	'.jpx',
	'.jpf',
	'.jpm',
	'.jpx-bgr',
	'.jpx-bgx',
	'.jxr',
	'.hdp',
	'.wdp',
	'.png',
	'.tiff',
	'.tif'
];

export async function GET({ url }) {
	/**
	 * @param {string} source - decode the source asset path
	 */
	const source = path.join('./', decodeURI(url.pathname));
	// IF asset is image
	if (imageTypes.includes(path.parse(path.parse(source).name).ext)) {
		console.log(
			chalk.green(`${dayjs().format('HH:mm:ss')} [image] optimizing ${path.parse(source).name}`)
		);
		const vips = await Vips();
		/**
		 * @param {Buffer} image
		 */
		let image;
		if (source.startsWith('__http')) {
			const http = source.replace('__', '').replace('__/', '://');
			const url = `${path.parse(http).dir}/${path.parse(http).name}`;
			const res = await fetch(url);
			if (res.ok) {
				image = await res.arrayBuffer();
			} else {
				image = await (await fetch('/og/image/null/null')).arrayBuffer();
			}
		} else {
			image = fs.readFileSync(path.join('./', path.parse(source).dir, path.parse(source).name));
		}
		return new Response(vips.Image.newFromBuffer(image).webpsaveBuffer({ Q: 80 }));
	}
	return new Response(fs.readFileSync(source));
}
