import fs from 'node:fs';
import path from 'node:path';
import { configDir } from '../config.js';
/** Parse a minimal YAML frontmatter block for name/description. */
function parseFrontmatter(text) {
    const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
    if (!m)
        return { body: text };
    const fm = m[1];
    const get = (key) => {
        const line = fm.match(new RegExp(`^${key}:\\s*(.*)$`, 'm'));
        return line ? line[1].trim().replace(/^["']|["']$/g, '') : undefined;
    };
    return { name: get('name'), description: get('description'), body: text.slice(m[0].length) };
}
function skillsInDir(dir) {
    let entries;
    try {
        entries = fs.readdirSync(dir, { withFileTypes: true });
    }
    catch {
        return [];
    }
    const skills = [];
    for (const entry of entries) {
        // Skill dirs may be symlinks (e.g. .cursor/skills -> .claude/skills entries).
        if (!entry.isDirectory() && !entry.isSymbolicLink())
            continue;
        const file = path.join(dir, entry.name, 'SKILL.md');
        let text;
        try {
            text = fs.readFileSync(file, 'utf8');
        }
        catch {
            continue;
        }
        const { name, description, body } = parseFrontmatter(text);
        const firstLine = body.split('\n').find((l) => l.trim().length > 0) ?? '';
        skills.push({
            name: name ?? entry.name,
            description: description ?? firstLine.replace(/^#+\s*/, '').slice(0, 200),
            file,
        });
    }
    return skills;
}
/**
 * Discover skills the way the other harnesses do, deduped by name
 * (project beats global; earlier dirs beat later ones):
 *   .cheapcode/skills/ then .claude/skills/ then .cursor/skills/ in the project,
 *   then ~/.config/cheapcode/skills/ globally.
 */
export function discoverSkills(cwd) {
    const dirs = [
        path.join(cwd, '.cheapcode', 'skills'),
        path.join(cwd, '.claude', 'skills'),
        path.join(cwd, '.cursor', 'skills'),
        path.join(configDir(), 'skills'),
    ];
    const byName = new Map();
    for (const dir of dirs) {
        for (const skill of skillsInDir(dir)) {
            if (!byName.has(skill.name))
                byName.set(skill.name, skill);
        }
    }
    return [...byName.values()];
}
export function skillsPromptSection(skills) {
    if (skills.length === 0)
        return null;
    const list = skills
        .map((s) => `- ${s.name}: ${s.description}\n  (read with read_file: ${s.file})`)
        .join('\n');
    return `## Skills

Skills are canonical procedures for specific kinds of tasks. When a task matches a skill below, read its SKILL.md with read_file FIRST and follow it before improvising.

${list}`;
}
