import fs from 'fs';
import path from 'path';
/**
 * Parse SKILL.md frontmatter (YAML between --- delimiters) and body content.
 */
function parseFrontmatter(content) {
    const match = content.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
    if (!match) {
        throw new Error('SKILL.md must have YAML frontmatter between --- delimiters');
    }
    const rawMeta = match[1];
    const body = match[2].trim();
    const meta = {};
    for (const line of rawMeta.split('\n')) {
        const colonIdx = line.indexOf(':');
        if (colonIdx === -1)
            continue;
        const key = line.slice(0, colonIdx).trim();
        let value = line.slice(colonIdx + 1).trim();
        if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
            value = value.slice(1, -1);
        }
        meta[key] = value;
    }
    return { meta, body };
}
/**
 * Load a single skill from its directory (expects SKILL.md inside).
 */
export function loadSkill(skillDir) {
    const skillPath = path.join(skillDir, 'SKILL.md');
    const content = fs.readFileSync(skillPath, 'utf-8');
    const { meta, body } = parseFrontmatter(content);
    return {
        name: meta.name,
        type: meta.type,
        description: meta.description,
        server: meta.server || undefined,
        instructions: body,
    };
}
/**
 * Load all skills from the skills/ directory.
 * Returns empty array if directory doesn't exist.
 */
export function loadSkills(skillsDir) {
    if (!fs.existsSync(skillsDir)) {
        return [];
    }
    const entries = fs.readdirSync(skillsDir, { withFileTypes: true });
    const skills = [];
    for (const entry of entries) {
        if (!entry.isDirectory())
            continue;
        const skillMdPath = path.join(skillsDir, entry.name, 'SKILL.md');
        if (!fs.existsSync(skillMdPath))
            continue;
        skills.push(loadSkill(path.join(skillsDir, entry.name)));
    }
    return skills;
}
