// tools/manage-plugins-handler.ts — Handler for manage_plugins tool (SPEC-085 AC-09, SPEC-603, SPEC-604)
import { t, ti } from '../i18n/index.js';
import { searchPlugins } from '../engine/plugin-installer/plugin-catalog.js';
import { cleanupPluginArtifacts } from '../engine/plugin-installer/artifact-scanner.js';
import { discoverPlugins, installPlugin, activatePlugin, deactivatePlugin, uninstallPlugin, readPluginState, loadPluginModule, generatePluginDocs, getPluginToolCount, getPluginWorkerCount, getPluginAnalyzerCount, getPluginTemplateCount, } from '../engine/plugins/index.js';
function text(content) {
    return { content: [{ type: 'text', text: content }] };
}
function resolveProjectPath(input) {
    /* v8 ignore next -- process.cwd() fallback never reached when projectPath is always provided */
    return input.projectPath ?? process.cwd();
}
const DATA_DIR = 'data';
async function handleList(input) {
    const projectPath = resolveProjectPath(input);
    const plugins = await discoverPlugins(projectPath);
    const state = await readPluginState(DATA_DIR);
    const items = plugins.map((p) => {
        const persisted = state.plugins.find((s) => s.manifest.id === p.manifest.id);
        const currentState = persisted?.state ?? p.state;
        return {
            id: p.manifest.id,
            name: p.manifest.name,
            version: p.manifest.version,
            state: currentState,
            toolCount: getPluginToolCount(p.manifest.id),
            workerCount: getPluginWorkerCount(p.manifest.id),
            analyzerCount: getPluginAnalyzerCount(p.manifest.id),
            templateCount: getPluginTemplateCount(p.manifest.id),
        };
    });
    if (items.length === 0) {
        return text(t('tools.manage_plugins.noPlugins'));
    }
    return text(JSON.stringify({ plugins: items }, null, 2));
}
async function handleInstall(input) {
    if (!input.pluginPath) {
        return {
            content: [{ type: 'text', text: t('tools.manage_plugins.pluginPathRequired') }],
            isError: true,
        };
    }
    const projectPath = resolveProjectPath(input);
    const reg = await installPlugin(input.pluginPath, projectPath, DATA_DIR);
    return text(ti('tools.manage_plugins.installSuccess', {
        name: reg.manifest.name,
        id: reg.manifest.id,
        version: reg.manifest.version,
    }));
}
async function handleActivate(input) {
    if (!input.pluginId) {
        return {
            content: [
                { type: 'text', text: ti('tools.manage_plugins.pluginIdRequired', { action: 'activate' }) },
            ],
            isError: true,
        };
    }
    const projectPath = resolveProjectPath(input);
    const builtInTools = new Set(); // Would be populated from server
    const reg = await activatePlugin(input.pluginId, projectPath, DATA_DIR, builtInTools);
    if (reg.state === 'error') {
        return {
            content: [
                {
                    type: 'text',
                    text: ti('tools.manage_plugins.activateError', { error: reg.error ?? 'unknown error' }),
                },
            ],
            isError: true,
        };
    }
    return text(ti('tools.manage_plugins.activateSuccess', { name: reg.manifest.name }));
}
async function handleDeactivate(input) {
    if (!input.pluginId) {
        return {
            content: [
                {
                    type: 'text',
                    text: ti('tools.manage_plugins.pluginIdRequired', { action: 'deactivate' }),
                },
            ],
            isError: true,
        };
    }
    const reg = await deactivatePlugin(input.pluginId, DATA_DIR);
    return text(ti('tools.manage_plugins.deactivateSuccess', { name: reg.manifest.name }));
}
async function handleUninstall(input) {
    if (!input.pluginId) {
        return {
            content: [
                {
                    type: 'text',
                    text: ti('tools.manage_plugins.pluginIdRequired', { action: 'uninstall' }),
                },
            ],
            isError: true,
        };
    }
    const projectPath = resolveProjectPath(input);
    await uninstallPlugin(input.pluginId, projectPath, DATA_DIR);
    // SPEC-604: cleanup plugin artifacts from .claude/rules/, .claude/skills/, .claude/hooks/
    const cleaned = await cleanupPluginArtifacts(input.pluginId, projectPath);
    const baseMsg = ti('tools.manage_plugins.uninstallSuccess', { id: input.pluginId });
    const cleanupReport = cleaned.length > 0
        ? `\nCleaned ${String(cleaned.length)} artifact(s): ${cleaned.join(', ')}`
        : '';
    return text(baseMsg + cleanupReport);
}
async function handleInfo(input) {
    if (!input.pluginId) {
        return {
            content: [
                { type: 'text', text: ti('tools.manage_plugins.pluginIdRequired', { action: 'info' }) },
            ],
            isError: true,
        };
    }
    const state = await readPluginState(DATA_DIR);
    const reg = state.plugins.find((p) => p.manifest.id === input.pluginId);
    if (!reg) {
        return {
            content: [
                { type: 'text', text: ti('tools.manage_plugins.pluginNotFound', { id: input.pluginId }) },
            ],
            isError: true,
        };
    }
    let mod;
    try {
        const projectPath = resolveProjectPath(input);
        mod = await loadPluginModule(projectPath, reg.manifest);
    }
    catch {
        /* v8 ignore next -- defensive: module may not be loadable at runtime */
    }
    const docs = generatePluginDocs(reg.manifest, mod);
    return text(docs);
}
async function handleSearch(input) {
    const results = await searchPlugins(input.keyword, input.stackFilter);
    if (results.length === 0) {
        return text(t('tools.manage_plugins.noPlugins'));
    }
    const lines = ['## Plugin Search Results', ''];
    for (const plugin of results) {
        lines.push(`### ${plugin.displayName} (\`${plugin.id}\`)`);
        lines.push(`- **Tier**: ${plugin.tier}`);
        lines.push(`- **Stacks**: ${plugin.stacks.length > 0 ? plugin.stacks.join(', ') : 'all'}`);
        lines.push(`- ${plugin.description}`);
        lines.push('');
    }
    return text(lines.join('\n'));
}
async function handleUpdate(input) {
    if (!input.pluginId) {
        return {
            content: [
                {
                    type: 'text',
                    text: ti('tools.manage_plugins.pluginIdRequired', { action: 'update' }),
                },
            ],
            isError: true,
        };
    }
    if (!input.pluginPath) {
        return {
            content: [{ type: 'text', text: t('tools.manage_plugins.pluginPathRequired') }],
            isError: true,
        };
    }
    const projectPath = resolveProjectPath(input);
    // Update strategy: uninstall (with artifact cleanup) then reinstall
    await uninstallPlugin(input.pluginId, projectPath, DATA_DIR);
    await cleanupPluginArtifacts(input.pluginId, projectPath);
    const reg = await installPlugin(input.pluginPath, projectPath, DATA_DIR);
    return text(`Plugin "${reg.manifest.name}" updated successfully to version ${reg.manifest.version}.`);
}
/**
 * Routes manage_plugins actions to the appropriate handler.
 */
export async function handleManagePlugins(input) {
    switch (input.action) {
        case 'search':
            return handleSearch(input);
        case 'list':
            return handleList(input);
        case 'install':
            return handleInstall(input);
        case 'activate':
            return handleActivate(input);
        case 'deactivate':
            return handleDeactivate(input);
        case 'uninstall':
            return handleUninstall(input);
        case 'info':
            return handleInfo(input);
        case 'update':
            return handleUpdate(input);
    }
}
//# sourceMappingURL=manage-plugins-handler.js.map