/**
 * Scan-and-reconcile olam skill symlinks after npm install.
 *
 * Source of truth: $(npm root -g)/@pleri/olam-cli/plugin/skills/olam-*
 * Deployed location: ~/.claude/skills/olam-*
 *
 * Rules (T22/OQ29):
 *   - For each olam-* dir in npm source not in deployed: create symlink
 *   - For each olam-* symlink in deployed pointing into npm package:
 *       if target file exists → leave alone
 *       if dangling → remove
 *   - Never touch non-olam-* entries (collision-safety per T7/T10)
 */
import * as fs from 'node:fs';
import * as path from 'node:path';
const realFs = {
    readdirSync: (p) => fs.readdirSync(p),
    existsSync: (p) => fs.existsSync(p),
    lstatSync: (p) => fs.lstatSync(p),
    readlinkSync: (p) => fs.readlinkSync(p),
    symlinkSync: (t, l) => fs.symlinkSync(t, l),
    unlinkSync: (p) => fs.unlinkSync(p),
    mkdirSync: (p, o) => { fs.mkdirSync(p, o); },
};
export function reconcileSkillSymlinks(npmSkillsDir, claudeSkillsDir, _fs = realFs) {
    const added = [];
    const removed = [];
    const kept = [];
    _fs.mkdirSync(claudeSkillsDir, { recursive: true });
    const sourceSkills = _fs.existsSync(npmSkillsDir)
        ? _fs.readdirSync(npmSkillsDir).filter((d) => d.startsWith('olam-'))
        : [];
    // Add missing symlinks (EEXIST race: another process may win between existsSync and symlinkSync)
    for (const skill of sourceSkills) {
        const linkPath = path.join(claudeSkillsDir, skill);
        const target = path.join(npmSkillsDir, skill);
        if (!_fs.existsSync(linkPath)) {
            try {
                _fs.symlinkSync(target, linkPath);
                added.push(skill);
            }
            catch (e) {
                if (e.code !== 'EEXIST')
                    throw e;
                kept.push(skill); // concurrent write won the race
            }
        }
    }
    // Clean dangling symlinks (only olam-* entries)
    const deployedEntries = _fs.existsSync(claudeSkillsDir)
        ? _fs.readdirSync(claudeSkillsDir).filter((d) => d.startsWith('olam-'))
        : [];
    for (const entry of deployedEntries) {
        const linkPath = path.join(claudeSkillsDir, entry);
        let isSymlink = false;
        try {
            isSymlink = _fs.lstatSync(linkPath).isSymbolicLink();
        }
        catch {
            continue;
        }
        if (!isSymlink)
            continue;
        const target = _fs.readlinkSync(linkPath);
        // Only manage symlinks that point into an npm package root
        if (!target.includes('@pleri/olam-cli')) {
            kept.push(entry);
            continue;
        }
        if (_fs.existsSync(target)) {
            kept.push(entry);
        }
        else {
            _fs.unlinkSync(linkPath);
            removed.push(entry);
        }
    }
    return { added, removed, kept };
}
//# sourceMappingURL=symlink-reconcile.js.map