// engine/marketplace-fetcher/local-source.ts — SPEC-681: Discover and symlink ~/.claude/skills/
// Skills from the local source are symlinked (not copied) into .claude/skills/.
import { readdir, mkdir, symlink, access } from 'node:fs/promises';
import { join, resolve } from 'node:path';
import { homedir } from 'node:os';
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const LOCAL_SKILLS_DIR = join(homedir(), '.claude', 'skills');
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function targetSkillsDir(projectPath) {
    return join(projectPath, '.claude', 'skills');
}
/** Strip the .md extension to get the skill name. */
function toSkillName(filename) {
    return filename.replace(/\.md$/, '');
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
 * Discover all .md files in ~/.claude/skills/ and symlink them into .claude/skills/.
 * Returns [] if ~/.claude/skills/ does not exist (fresh user — Scenario 8).
 * Never throws.
 */
export async function fetchLocalSkills(projectPath) {
    // Check if ~/.claude/skills/ exists — if not, return empty (Scenario 8)
    try {
        await access(LOCAL_SKILLS_DIR);
    }
    catch {
        return [];
    }
    let entries;
    try {
        const dirEntries = await readdir(LOCAL_SKILLS_DIR);
        entries = dirEntries.filter((f) => f.endsWith('.md'));
    }
    catch {
        return [];
    }
    const targetDir = targetSkillsDir(projectPath);
    await mkdir(targetDir, { recursive: true });
    const results = [];
    for (const filename of entries) {
        const skillName = toSkillName(filename);
        const sourcePath = resolve(join(LOCAL_SKILLS_DIR, filename));
        const destPath = join(targetDir, filename);
        let created;
        try {
            await symlink(sourcePath, destPath);
            created = true;
        }
        catch (err) {
            // EEXIST means symlink already exists — not an error
            if (err.code !== 'EEXIST') {
                continue;
            }
            // Already linked — not newly created
            created = false;
        }
        results.push({
            skillName,
            source: 'local',
            installedPath: destPath,
            created,
        });
    }
    return results;
}
//# sourceMappingURL=local-source.js.map