import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
const FRONTMATTER_DELIMITER = "---";
/**
 * Parse a markdown file that has YAML frontmatter.
 *
 * Expected format:
 * ```
 * ---
 * name: "..."
 * description: "..."
 * accessType: always
 * isEnabled: true
 * createdAt: "..."
 * ---
 *
 * The body content goes here.
 * ```
 */
export function parseSkillFile(raw) {
    const trimmed = raw.trimStart();
    if (!trimmed.startsWith(FRONTMATTER_DELIMITER)) {
        return null;
    }
    const afterFirstDelimiter = trimmed.slice(FRONTMATTER_DELIMITER.length);
    const endIndex = afterFirstDelimiter.indexOf(`\n${FRONTMATTER_DELIMITER}`);
    if (endIndex === -1) {
        return null;
    }
    const yamlStr = afterFirstDelimiter.slice(0, endIndex).trim();
    const content = afterFirstDelimiter
        .slice(endIndex + FRONTMATTER_DELIMITER.length + 1)
        .trimStart();
    let frontmatter;
    try {
        frontmatter = parseYaml(yamlStr) ?? {};
    }
    catch {
        return null;
    }
    if (typeof frontmatter.name !== "string" || !frontmatter.name) {
        return null;
    }
    return {
        name: frontmatter.name,
        description: typeof frontmatter.description === "string"
            ? frontmatter.description
            : "",
        accessType: frontmatter.accessType === "always" ? "always" : "on_demand",
        isEnabled: frontmatter.isEnabled !== false,
        createdAt: typeof frontmatter.createdAt === "string"
            ? frontmatter.createdAt
            : undefined,
        content,
    };
}
/**
 * Serialize a skill fact back to a markdown file string with YAML frontmatter.
 */
export function serializeSkillFile(fact) {
    const frontmatter = {
        name: fact.name,
        description: fact.description,
        accessType: fact.accessType,
        isEnabled: fact.isEnabled,
    };
    if (fact.createdAt) {
        frontmatter.createdAt = fact.createdAt;
    }
    const yamlStr = stringifyYaml(frontmatter).trimEnd();
    return `---\n${yamlStr}\n---\n\n${fact.content}\n`;
}
/**
 * Convert a fact name to a safe file name (kebab-case, no special chars).
 */
export function factNameToFileName(name) {
    return (name
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, "-")
        .replace(/^-+|-+$/g, "")
        .slice(0, 60) || "fact");
}
//# sourceMappingURL=parser.js.map