export const csr = false;
export const prerender = true;

import fs from 'node:fs';
import path from 'node:path/posix';
import fm from 'front-matter';
import { marked } from 'marked';
import { mangle } from 'marked-mangle';
import { gfmHeadingId } from 'marked-gfm-heading-id';
import { markedHighlight } from 'marked-highlight';
import hljs from 'highlight.js';
import hljsSvelte from 'highlightjs-svelte';
import markedKatex from 'marked-katex-extension';
import dayjs from 'dayjs';
import DOMPurify from 'isomorphic-dompurify';
import Vips from 'wasm-vips';
import { JSDOM } from 'jsdom';
import md5 from 'md5';

marked.use(
	mangle(),
	gfmHeadingId(),
	markedKatex({
		output: 'mathml'
	}),
	markedHighlight({
		langPrefix: 'hljs language-',
		highlight(code, lang) {
			const language = hljs.getLanguage(lang) ? lang : 'plaintext';
			hljsSvelte(hljs);
			return hljs.highlight(code, { language }).value;
		}
	})
);

export async function load({ fetch, url, params }) {
	const slug = params.slug + '.md';
	const raw = fs.readFileSync(slug, { encoding: 'utf-8' });
	const name = path.parse(slug).name;
	const frontmatter = fm(raw);
	const title = marked
		.lexer(frontmatter.body)
		.find((token) => token.type === 'heading' && token.depth === 1).text;
	marked.use({
		renderer: {
			heading(text, level) {
				if (level === 1) {
					return `
							<h1>
								${text || 'null'}
							</h1>
							${dayjs(frontmatter.attributes.date).format('YYYY/MM/DD')}
						`;
				} else {
					return `<h${level}>${text}</h${level}>`;
				}
			},
			image(href, title, text) {
				/**
				 * @param {string} href - The link of image.
				 */
				if (href.startsWith('http://') || href.startsWith('https://') || href.startsWith('//')) {
					href =
						'/__' +
						(href.startsWith('//')
							? 'https' + href.replace('//', '__')
							: href.replace('://', '__/')) +
						'.webp';
				} else {
					href =
						'/' +
						path.relative(
							path.resolve('./'),
							path.resolve('./', path.parse(params.slug).dir, href + '.webp')
						);
				}
				return `<img title="${text}" alt="${text}" src="${href}" loading="lazy" />`;
			}
		}
	});
	const dom = DOMPurify.sanitize(await addImageInfo(marked.parse(frontmatter.body)));
	return {
		slug: params.slug,
		name: name,
		title: title || 'null',
		raw: raw,
		fm: frontmatter.attributes,
		body: {
			raw: frontmatter.body,
			dom: dom
		}
	};
	async function addImageInfo(dom) {
		const jsdom = new JSDOM(dom);
		const images = Array.from(jsdom.window.document.querySelectorAll('img'));
		const vips = await Vips();
		for (const image of images) {
			const res = await fetch(image.src);
			if (res.ok) {
				const vipsImage = vips.Image.newFromBuffer(await res.arrayBuffer());
				image.width = vipsImage.width;
				image.height = vipsImage.height;
				if (vipsImage.width / vipsImage.height < 1) {
					if (md5(image.alt).charCodeAt(0) > 5) {
						image.style.float = 'right';
					} else {
						image.style.float = 'left';
					}
					image.style.padding = '1rem';
					image.style.width = 'fit-content';
					image.style.maxWidth = '50%';
					image.style.height = 'fit-content';
				} else {
					image.style.width = '100%';
				}
			}
		}
		return jsdom.window.document.documentElement.outerHTML;
	}
}
