import { access } from 'node:fs/promises';
import { basename, relative, resolve } from 'node:path';
import { appendKnownStray } from '../../config/sync-config.js';
import { CliError } from '../../errors/index.js';
import { toPosixPath } from '../../fs/paths.js';
import { adoptStrayToCanonical } from './adopt-stray.js';
export function isCursorSkillCandidate(candidate) {
    const providerPath = toPosixPath(candidate.report.providerPath);
    return (candidate.provider === 'cursor' &&
        candidate.mapping.contentType === 'skill' &&
        candidate.mapping.nativeRead &&
        (providerPath === '.cursor/skills' ||
            providerPath.startsWith('.cursor/skills/')));
}
export async function applyCursorSkillDisposition(scopeRoot, candidate, manifest, disposition, syncConfigPath, options = {}) {
    if (!isCursorSkillCandidate(candidate)) {
        throw new CliError(`Cannot apply a Cursor skill disposition to ${candidate.report.providerPath}.`);
    }
    if (disposition === 'adopt') {
        return adoptStrayToCanonical(scopeRoot, candidate, manifest, options);
    }
    await assertCursorOnlyNameAvailable(scopeRoot, candidate);
    await appendKnownStray(syncConfigPath, candidate.report.providerPath);
    return manifest;
}
async function assertCursorOnlyNameAvailable(scopeRoot, candidate) {
    const canonicalPath = resolve(scopeRoot, candidate.mapping.canonicalDir, basename(candidate.report.providerPath));
    if (!(await pathExists(canonicalPath))) {
        return;
    }
    throw new CliError(`Cannot keep ${candidate.report.providerPath} Cursor-only because canonical skill ${toPosixPath(relative(scopeRoot, canonicalPath))} has the same name. Rename one skill, then run the command again.`);
}
async function pathExists(path) {
    try {
        await access(path);
        return true;
    }
    catch {
        return false;
    }
}
