import { join } from 'node:path';
import { WORKFLOW_AGENTS, WORKFLOW_SCRIPTS, WORKFLOW_TEMPLATES, } from '../../init/tools/shared/skill-manifest.js';
function matchesTarget(tool, target) {
    switch (target.kind) {
        case 'name':
            return tool.name === target.name;
        case 'pack':
            return tool.pack === target.pack;
        case 'all':
            return true;
    }
}
async function removeTool(tool, scopeRoot, dryRun, deps) {
    if (dryRun)
        return;
    if (tool.type === 'agent') {
        const agentPath = join(scopeRoot, '.agents', 'agents', `${tool.name}.md`);
        await deps.removeFile(agentPath);
    }
    else {
        const skillPath = join(scopeRoot, '.agents', 'skills', tool.name);
        await deps.removeDirectory(skillPath);
    }
}
async function removePackCompanionAssets(pack, scope, scopeRoot, dryRun, deps) {
    if (dryRun || pack !== 'workflows' || scope !== 'user') {
        return;
    }
    for (const agent of WORKFLOW_AGENTS) {
        await deps.removeFile(join(scopeRoot, '.agents', 'agents', agent));
    }
    for (const template of WORKFLOW_TEMPLATES) {
        await deps.removeFile(join(scopeRoot, '.oat', 'templates', template));
    }
    for (const script of WORKFLOW_SCRIPTS) {
        await deps.removeFile(join(scopeRoot, '.oat', 'scripts', script));
    }
}
export async function removeTools(target, scopes, cwd, home, dryRun, deps) {
    const removed = [];
    const assetsRoot = await deps.resolveAssetsRoot();
    for (const scope of scopes) {
        const scopeRoot = await deps.resolveScopeRoot(scope, cwd, home);
        const tools = await deps.scanTools({ scope, scopeRoot, assetsRoot });
        const matched = tools.filter((t) => matchesTarget(t, target));
        for (const tool of matched) {
            await removeTool(tool, scopeRoot, dryRun, deps);
            removed.push({ name: tool.name, type: tool.type, scope: tool.scope });
        }
        if (target.kind !== 'name') {
            const matchedPacks = new Set(matched
                .map((tool) => tool.pack)
                .filter((pack) => pack !== 'custom'));
            for (const pack of matchedPacks) {
                await removePackCompanionAssets(pack, scope, scopeRoot, dryRun, deps);
            }
        }
    }
    const notInstalled = [];
    if (target.kind === 'name' && removed.length === 0) {
        notInstalled.push(target.name);
    }
    return { removed, notInstalled };
}
