export interface FrontmatterResult {
	data: Record<string, string | string[]>;
	content: string;
}

function parseScalar(raw: string): string {
	const trimmed = raw.trim();
	if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
		return trimmed.slice(1, -1);
	}
	return trimmed;
}

function parseList(raw: string): string[] {
	const trimmed = raw.trim();
	const inner = trimmed.startsWith('[') && trimmed.endsWith(']') ? trimmed.slice(1, -1) : trimmed;
	return inner
		.split(',')
		.map((item) => parseScalar(item))
		.filter(Boolean);
}

export function parseFrontmatter(raw: string): FrontmatterResult {
	const match = raw.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/);
	if (!match) {
		return { data: {}, content: raw.trim() };
	}

	const [, block, content] = match;
	const data: Record<string, string | string[]> = {};

	for (const line of block.split('\n')) {
		const separator = line.indexOf(':');
		if (separator === -1) continue;
		const key = line.slice(0, separator).trim();
		const value = line.slice(separator + 1).trim();
		data[key] = key === 'tags' ? parseList(value) : parseScalar(value);
	}

	return { data, content: content.trim() };
}
