/**
 * Discovery handler group: list_execution_presets, list_skills, list_specialists,
 * list_crews, rag_*, list_workflows, list_hooks, list_automations.
 * Extracted from mcp.ts (Phase 3 split).
 */
import { formatBullets, formatJsonDetails, collectFolderFiles, } from '../helpers.js';
import { listExecutionPresets } from '../../../../engines/execution-presets.js';
import { requireRuntime } from '../util/require-runtime.js';
import * as path from 'path';
export async function handleDiscoveryGroup(toolName, hctx, request, args, ctx) {
    const runtimeError = requireRuntime(hctx);
    if (runtimeError)
        return runtimeError;
    switch (toolName) {
        case 'nexus_list_execution_presets': {
            const presets = listExecutionPresets();
            return {
                content: [{
                        type: 'text',
                        text: [
                            'Execution presets ready.',
                            formatBullets(presets.map((preset) => `${preset.id}: ${preset.summary}`)),
                            formatJsonDetails('Structured details', presets),
                        ].join('\n\n'),
                    }],
            };
        }
        case 'nexus_list_skills': {
            const skills = hctx.getRuntime().listSkills();
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({
                            total: skills.length,
                            skills: skills.map((skill) => ({
                                skillId: skill.skillId,
                                name: skill.name,
                                scope: skill.scope,
                                rolloutStatus: skill.rolloutStatus,
                                riskClass: skill.riskClass,
                                catalogOrigin: skill.catalogOrigin,
                                catalogPath: skill.catalogPath,
                                catalogPriority: skill.catalogPriority,
                                summary: skill.instructions.slice(0, 220),
                            })),
                        }, null, 2),
                    }],
            };
        }
        case 'nexus_list_specialists': {
            const specialists = hctx.getRuntime().listSpecialists();
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({
                            total: specialists.length,
                            specialists: specialists.map((specialist) => ({
                                specialistId: specialist.specialistId,
                                name: specialist.name,
                                division: specialist.division,
                                authority: specialist.authority,
                                domains: specialist.domains,
                                recommendedSkills: specialist.recommendedSkills,
                                recommendedWorkflows: specialist.recommendedWorkflows,
                            })),
                        }, null, 2),
                    }],
            };
        }
        case 'nexus_list_crews': {
            const crews = hctx.getRuntime().listCrews();
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({
                            total: crews.length,
                            crews,
                        }, null, 2),
                    }],
            };
        }
        case 'nexus_rag_list_collections': {
            const collections = hctx.getOrchestrator().listRagCollections();
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({
                            total: collections.length,
                            collections,
                        }, null, 2),
                    }],
            };
        }
        case 'nexus_rag_create_collection': {
            const name = String(request.params.arguments?.name ?? '');
            const description = request.params.arguments?.description ? String(request.params.arguments.description) : undefined;
            const tags = Array.isArray(request.params.arguments?.tags)
                ? request.params.arguments.tags.map(String)
                : [];
            const scope = String(request.params.arguments?.scope ?? 'session') === 'project' ? 'project' : 'session';
            const collection = hctx.getOrchestrator().createRagCollection({ name, description, tags, scope });
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify(collection, null, 2),
                    }],
            };
        }
        case 'nexus_rag_ingest_collection': {
            const collectionId = String(request.params.arguments?.collectionId ?? '');
            const rawInputs = Array.isArray(request.params.arguments?.inputs)
                ? request.params.arguments.inputs
                : [];
            const inputs = [];
            for (const entry of rawInputs) {
                if (entry?.folderPath) {
                    // Expand folder into individual file entries (bounded to workspace root)
                    const folderAbs = path.resolve(String(entry.folderPath));
                    if (!hctx.isPackageLikeWorkspace(folderAbs)) {
                        inputs.push({
                            text: `[skipped] folder path outside workspace root: ${folderAbs}`,
                            label: 'security-skip',
                            tags: ['skipped'],
                        });
                        continue;
                    }
                    const folderGlob = entry?.folderGlob ? String(entry.folderGlob) : undefined;
                    const files = collectFolderFiles(folderAbs, folderGlob);
                    for (const f of files) {
                        inputs.push({
                            filePath: f,
                            label: entry?.label ? String(entry.label) : undefined,
                            tags: Array.isArray(entry?.tags) ? entry.tags.map(String) : [],
                        });
                    }
                }
                else {
                    inputs.push({
                        filePath: entry?.filePath ? String(entry.filePath) : undefined,
                        url: entry?.url ? String(entry.url) : undefined,
                        text: entry?.text ? String(entry.text) : undefined,
                        label: entry?.label ? String(entry.label) : undefined,
                        tags: Array.isArray(entry?.tags) ? entry.tags.map(String) : [],
                    });
                }
            }
            const result = await hctx.getOrchestrator().ingestRagCollection(collectionId, inputs);
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify(result, null, 2),
                    }],
            };
        }
        case 'nexus_rag_attach_collection': {
            const collectionId = String(request.params.arguments?.collectionId ?? '');
            const collection = hctx.getOrchestrator().attachRagCollection(collectionId);
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify(collection, null, 2),
                    }],
            };
        }
        case 'nexus_rag_detach_collection': {
            const collectionId = String(request.params.arguments?.collectionId ?? '');
            const collection = hctx.getOrchestrator().detachRagCollection(collectionId);
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify(collection, null, 2),
                    }],
            };
        }
        case 'nexus_rag_delete_collection': {
            const collectionId = String(request.params.arguments?.collectionId ?? '');
            const removed = hctx.getOrchestrator().deleteRagCollection(collectionId);
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({ collectionId, removed }, null, 2),
                    }],
            };
        }
        case 'nexus_list_workflows': {
            const workflows = hctx.getRuntime().listWorkflows();
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({
                            total: workflows.length,
                            workflows: workflows.map((workflow) => ({
                                workflowId: workflow.workflowId,
                                name: workflow.name,
                                scope: workflow.scope,
                                rolloutStatus: workflow.rolloutStatus,
                                domain: workflow.domain,
                                catalogOrigin: workflow.catalogOrigin,
                                catalogPath: workflow.catalogPath,
                                catalogPriority: workflow.catalogPriority,
                                summary: workflow.description,
                            })),
                        }, null, 2),
                    }],
            };
        }
        case 'nexus_list_hooks': {
            const hooks = hctx.getRuntime().listHooks();
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({
                            total: hooks.length,
                            hooks: hooks.map((hook) => ({
                                hookId: hook.hookId,
                                name: hook.name,
                                trigger: hook.trigger,
                                scope: hook.scope,
                                rolloutStatus: hook.rolloutStatus,
                                riskClass: hook.riskClass,
                                catalogOrigin: hook.catalogOrigin,
                                catalogPath: hook.catalogPath,
                                catalogPriority: hook.catalogPriority,
                                summary: hook.description,
                            })),
                        }, null, 2),
                    }],
            };
        }
        case 'nexus_list_automations': {
            const automations = hctx.getRuntime().listAutomations();
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({
                            total: automations.length,
                            automations: automations.map((automation) => ({
                                automationId: automation.automationId,
                                name: automation.name,
                                triggerMode: automation.triggerMode,
                                eventTrigger: automation.eventTrigger,
                                scope: automation.scope,
                                rolloutStatus: automation.rolloutStatus,
                                catalogOrigin: automation.catalogOrigin,
                                catalogPath: automation.catalogPath,
                                catalogPriority: automation.catalogPriority,
                                summary: automation.description,
                            })),
                        }, null, 2),
                    }],
            };
        }
    }
    return undefined;
}
