import fs from 'node:fs/promises';
import path from 'node:path';
async function pathExists(target) {
    try {
        await fs.access(target);
        return true;
    }
    catch {
        return false;
    }
}
export async function loadAcodeConfig(configPath) {
    if (!configPath || !(await pathExists(configPath))) {
        return {};
    }
    const raw = await fs.readFile(configPath, 'utf-8');
    const parsed = JSON.parse(raw);
    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
        return {};
    }
    return parsed;
}
function parseYamlStringValue(raw) {
    const trimmed = raw.trim();
    if (!trimmed) {
        return undefined;
    }
    if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
        return trimmed.slice(1, -1).trim();
    }
    return trimmed;
}
function fallbackNameFromDirectory(directory) {
    return path.basename(directory).replace(/\.skill$/, '').replace(/[-_]/g, ' ');
}
async function readSkillMetadata(directory) {
    const skillFile = path.join(directory, 'SKILL.md');
    if (!(await pathExists(skillFile))) {
        return null;
    }
    const raw = (await fs.readFile(skillFile, 'utf-8')).replace(/^\uFEFF/, '');
    const metadata = {};
    if (raw.startsWith('---')) {
        const end = raw.indexOf('\n---', 3);
        if (end >= 0) {
            for (const line of raw.slice(3, end).split(/\r?\n/)) {
                const match = line.match(/^\s*(name|description)\s*:\s*(.*)$/);
                if (!match) {
                    continue;
                }
                const value = parseYamlStringValue(match[2] ?? '');
                if (value) {
                    metadata[match[1]] = value;
                }
            }
        }
    }
    return {
        name: metadata.name || fallbackNameFromDirectory(directory),
        description: metadata.description,
        directory,
    };
}
export async function loadAcodeSkills(skillsDir) {
    if (!skillsDir || !(await pathExists(skillsDir))) {
        return [];
    }
    const entries = await fs.readdir(skillsDir, { withFileTypes: true });
    const skills = [];
    for (const entry of entries) {
        if (entry.name.startsWith('.') || (!entry.isDirectory() && !entry.isSymbolicLink())) {
            continue;
        }
        const metadata = await readSkillMetadata(path.join(skillsDir, entry.name));
        if (metadata) {
            skills.push(metadata);
        }
    }
    return skills;
}
