import { getMatches } from "../file-matching.js";
import { defineSource } from "../source.js";
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { z } from "zod";
import { matter } from "gray-matter-es";
import remarkParse from "remark-parse";
import { unified } from "unified";
//#region src/lib/sources/readme-file.ts
const readmeSchema = z.object({
	frontmatter: z.record(z.string(), z.unknown()).optional(),
	name: z.string()
});
/**
* Recursively extract plain text from mdast phrasing content.
*/
function extractText(nodes) {
	return nodes.map((node) => {
		if ("value" in node) return node.value;
		if ("children" in node) return extractText(node.children);
		return "";
	}).join("").trim();
}
/**
* Extract the text content of the first H1 heading from markdown.
*/
function extractFirstH1(markdown) {
	const tree = unified().use(remarkParse).parse(markdown);
	for (const node of tree.children) if (node.type === "heading" && node.depth === 1) {
		const text = extractText(node.children);
		if (text.length > 0) return text;
	}
}
/**
* Parse a README file's content.
* @param content - Raw file content (markdown).
* @returns Parsed metadata, or `undefined` if no H1 heading is found.
*/
function parse(content) {
	const { content: markdown, data } = matter(content);
	const name = extractFirstH1(markdown);
	if (!name) return void 0;
	return readmeSchema.parse({
		frontmatter: Object.keys(data).length > 0 ? data : void 0,
		name
	});
}
const readmeFileSource = defineSource({
	async discover(context) {
		return getMatches(context.options, ["README", "README.*"]);
	},
	key: "readmeFile",
	async parse(input, context) {
		const data = parse(await readFile(resolve(context.options.path, input), "utf8"));
		if (data !== void 0) return {
			data,
			source: input
		};
	},
	phase: 1
});
//#endregion
export { readmeFileSource };
