/**
 * Misc handler group: skills, workflows, hooks, automations, patterns, darwin,
 * net, decompose, entangle, cas, kv, execute_nxl, publish_trace.
 * Extracted from mcp.ts (Phase 3 split).
 */
import { getFederation, getGraphEngine, } from '../helpers.js';
import { nexusEventBus } from '../../../../engines/event-bus.js';
import { nexusNetRelay } from '../../../../engines/nexusnet-relay.js';
import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
import { SkillCardRegistry } from '../../../../engines/skill-card.js';
import { summarizeExecution } from '../../../../phantom/index.js';
export async function handleMiscGroup(toolName, hctx, request, args, ctx) {
    switch (toolName) {
        case 'nexus_skill_register': {
            const graphEngine = getGraphEngine();
            const registry = new SkillCardRegistry(graphEngine);
            const card = request.params.arguments?.card;
            if (!card || !card.name || !card.trigger || !card.actions) {
                throw new McpError(ErrorCode.InvalidParams, 'Invalid SkillCard format. Must contain name, trigger, and actions.');
            }
            const id = registry.register(card);
            nexusEventBus.emit('skill.register', { name: card.name, id });
            return {
                content: [{
                        type: 'text',
                        text: `🎯 Skill Card "${card.name}" registered successfully!\nEntity ID: ${id}\nYAML serialized and stored in Graph Knowledge Engine.`
                    }]
            };
        }
        case 'nexus_skill_generate': {
            const name = String(request.params.arguments?.name ?? '');
            const instructions = String(request.params.arguments?.instructions ?? '');
            const riskClass = String(request.params.arguments?.riskClass ?? 'orchestrate');
            const scope = String(request.params.arguments?.scope ?? 'session');
            const artifact = hctx.getRuntime().generateSkill({ name, instructions, riskClass, scope, provenance: 'mcp:generate' });
            hctx.sessionDNA.recordSkillLearned(artifact.name);
            return {
                content: [{
                        type: 'text',
                        text: `🧠 Runtime skill generated\nID: ${artifact.skillId}\nName: ${artifact.name}\nRisk: ${artifact.riskClass}\nScope: ${artifact.scope}\nProvenance: ${artifact.provenance}`,
                    }],
            };
        }
        case 'nexus_skill_deploy': {
            const skillId = String(request.params.arguments?.skillId ?? '');
            const scope = String(request.params.arguments?.scope ?? 'session');
            const runtime = hctx.getRuntime();
            const known = runtime.listSkills().find((skill) => skill.skillId === skillId || skill.name === skillId);
            const artifact = known ? runtime.deploySkill(known.skillId, scope) : undefined;
            if (!artifact) {
                return { content: [{ type: 'text', text: `❌ Skill not found: ${skillId}` }] };
            }
            hctx.sessionDNA.recordSkill(artifact.name);
            return {
                content: [{
                        type: 'text',
                        text: `🚚 Runtime skill deployed\nID: ${artifact.skillId}\nName: ${artifact.name}\nScope: ${artifact.scope}\nRollout: ${artifact.rolloutStatus}`,
                    }],
            };
        }
        case 'nexus_skill_revoke': {
            const skillId = String(request.params.arguments?.skillId ?? '');
            const runtime = hctx.getRuntime();
            const known = runtime.listSkills().find((skill) => skill.skillId === skillId || skill.name === skillId);
            const artifact = known ? runtime.revokeSkill(known.skillId) : undefined;
            if (!artifact) {
                return { content: [{ type: 'text', text: `❌ Skill not found: ${skillId}` }] };
            }
            return {
                content: [{
                        type: 'text',
                        text: `🧯 Runtime skill revoked\nID: ${artifact.skillId}\nName: ${artifact.name}\nRollout: ${artifact.rolloutStatus}`,
                    }],
            };
        }
        case 'nexus_workflow_generate': {
            const name = String(request.params.arguments?.name ?? '');
            const description = String(request.params.arguments?.description ?? '');
            const domain = request.params.arguments?.domain ? String(request.params.arguments?.domain) : undefined;
            const scope = String(request.params.arguments?.scope ?? 'session');
            const artifact = hctx.getRuntime().generateWorkflow({ name, description, domain, scope });
            return {
                content: [{
                        type: 'text',
                        text: `🧭 Workflow generated\nID: ${artifact.workflowId}\nName: ${artifact.name}\nDomain: ${artifact.domain}\nScope: ${artifact.scope}`,
                    }],
            };
        }
        case 'nexus_workflow_deploy': {
            const workflowId = String(request.params.arguments?.workflowId ?? '');
            const scope = String(request.params.arguments?.scope ?? 'session');
            const runtime = hctx.getRuntime();
            const known = runtime.listWorkflows().find((workflow) => workflow.workflowId === workflowId || workflow.name === workflowId);
            const artifact = known ? runtime.deployWorkflow(known.workflowId, scope) : undefined;
            if (!artifact) {
                return { content: [{ type: 'text', text: `❌ Workflow not found: ${workflowId}` }] };
            }
            return {
                content: [{
                        type: 'text',
                        text: `🚚 Workflow deployed\nID: ${artifact.workflowId}\nName: ${artifact.name}\nScope: ${artifact.scope}\nRollout: ${artifact.rolloutStatus}`,
                    }],
            };
        }
        case 'nexus_workflow_run': {
            const workflowId = String(request.params.arguments?.workflowId ?? '');
            const goalOverride = request.params.arguments?.goal ? String(request.params.arguments.goal) : undefined;
            try {
                const execution = await hctx.getRuntime().runWorkflow(workflowId, goalOverride);
                return {
                    content: [{
                            type: 'text',
                            text: [
                                `🧭 Workflow Runtime — ${summarizeExecution(execution)}`,
                                `Run ID: ${execution.runId}`,
                                `Artifacts: ${execution.artifactsPath}`,
                                `Decision: ${execution.finalDecision?.action ?? 'none'}`,
                                `Workflows: ${execution.activeWorkflows.map((workflow) => workflow.name).join(', ') || 'none'}`,
                                `Result: ${execution.result}`,
                            ].join('\n'),
                        }],
                };
            }
            catch (error) {
                return { content: [{ type: 'text', text: `❌ Workflow runtime error: ${error.message}` }] };
            }
        }
        case 'nexus_hook_generate': {
            const name = String(request.params.arguments?.name ?? '');
            const description = String(request.params.arguments?.description ?? '');
            const trigger = String(request.params.arguments?.trigger ?? 'run.created');
            const riskClass = String(request.params.arguments?.riskClass ?? 'orchestrate');
            const scope = String(request.params.arguments?.scope ?? 'session');
            const artifact = hctx.getRuntime().generateHook({ name, description, trigger, riskClass, scope });
            return {
                content: [{
                        type: 'text',
                        text: `🪝 Hook generated\nID: ${artifact.hookId}\nName: ${artifact.name}\nTrigger: ${artifact.trigger}\nScope: ${artifact.scope}`,
                    }],
            };
        }
        case 'nexus_hook_deploy': {
            const hookId = String(request.params.arguments?.hookId ?? '');
            const scope = String(request.params.arguments?.scope ?? 'session');
            const runtime = hctx.getRuntime();
            const known = runtime.listHooks().find((hook) => hook.hookId === hookId || hook.name === hookId);
            const artifact = known ? runtime.deployHook(known.hookId, scope) : undefined;
            if (!artifact) {
                return { content: [{ type: 'text', text: `❌ Hook not found: ${hookId}` }] };
            }
            nexusEventBus.emit('hook.deploy', { hookId: artifact.hookId, scope: artifact.scope, status: artifact.rolloutStatus });
            return {
                content: [{
                        type: 'text',
                        text: `🪝 Hook deployed\nID: ${artifact.hookId}\nName: ${artifact.name}\nScope: ${artifact.scope}\nRollout: ${artifact.rolloutStatus}`,
                    }],
            };
        }
        case 'nexus_hook_revoke': {
            const hookId = String(request.params.arguments?.hookId ?? '');
            const runtime = hctx.getRuntime();
            const known = runtime.listHooks().find((hook) => hook.hookId === hookId || hook.name === hookId);
            const artifact = known ? runtime.revokeHook(known.hookId) : undefined;
            if (!artifact) {
                return { content: [{ type: 'text', text: `❌ Hook not found: ${hookId}` }] };
            }
            nexusEventBus.emit('hook.revoke', { hookId: artifact.hookId, status: artifact.rolloutStatus });
            return {
                content: [{
                        type: 'text',
                        text: `🧯 Hook revoked\nID: ${artifact.hookId}\nName: ${artifact.name}\nRollout: ${artifact.rolloutStatus}`,
                    }],
            };
        }
        case 'nexus_automation_generate': {
            const name = String(request.params.arguments?.name ?? '');
            const description = String(request.params.arguments?.description ?? '');
            const triggerMode = String(request.params.arguments?.triggerMode ?? 'event');
            const eventTrigger = request.params.arguments?.eventTrigger ? String(request.params.arguments?.eventTrigger) : undefined;
            const scope = String(request.params.arguments?.scope ?? 'session');
            const artifact = hctx.getRuntime().generateAutomation({ name, description, triggerMode, eventTrigger, scope });
            return {
                content: [{
                        type: 'text',
                        text: `🤖 Automation generated\nID: ${artifact.automationId}\nName: ${artifact.name}\nTrigger Mode: ${artifact.triggerMode}\nScope: ${artifact.scope}`,
                    }],
            };
        }
        case 'nexus_automation_deploy': {
            const automationId = String(request.params.arguments?.automationId ?? '');
            const scope = String(request.params.arguments?.scope ?? 'session');
            const runtime = hctx.getRuntime();
            const known = runtime.listAutomations().find((automation) => automation.automationId === automationId || automation.name === automationId);
            const artifact = known ? runtime.deployAutomation(known.automationId, scope) : undefined;
            if (!artifact) {
                return { content: [{ type: 'text', text: `❌ Automation not found: ${automationId}` }] };
            }
            nexusEventBus.emit('automation.deploy', { automationId: artifact.automationId, scope: artifact.scope, status: artifact.rolloutStatus });
            return {
                content: [{
                        type: 'text',
                        text: `🤖 Automation deployed\nID: ${artifact.automationId}\nName: ${artifact.name}\nScope: ${artifact.scope}\nRollout: ${artifact.rolloutStatus}`,
                    }],
            };
        }
        case 'nexus_automation_run': {
            const automationId = String(request.params.arguments?.automationId ?? '');
            const goalOverride = request.params.arguments?.goal ? String(request.params.arguments.goal) : undefined;
            try {
                const execution = await hctx.getRuntime().runAutomation(automationId, goalOverride);
                return {
                    content: [{
                            type: 'text',
                            text: [
                                `🤖 Automation Runtime — ${summarizeExecution(execution)}`,
                                `Run ID: ${execution.runId}`,
                                `Artifacts: ${execution.artifactsPath}`,
                                `Automations: ${execution.activeAutomations.map((automation) => automation.name).join(', ') || 'none'}`,
                                `Result: ${execution.result}`,
                            ].join('\n'),
                        }],
                };
            }
            catch (error) {
                return { content: [{ type: 'text', text: `❌ Automation runtime error: ${error.message}` }] };
            }
        }
        case 'nexus_automation_revoke': {
            const automationId = String(request.params.arguments?.automationId ?? '');
            const runtime = hctx.getRuntime();
            const known = runtime.listAutomations().find((automation) => automation.automationId === automationId || automation.name === automationId);
            const artifact = known ? runtime.revokeAutomation(known.automationId) : undefined;
            if (!artifact) {
                return { content: [{ type: 'text', text: `❌ Automation not found: ${automationId}` }] };
            }
            nexusEventBus.emit('automation.revoke', { automationId: artifact.automationId, status: artifact.rolloutStatus });
            return {
                content: [{
                        type: 'text',
                        text: `🧯 Automation revoked\nID: ${artifact.automationId}\nName: ${artifact.name}\nRollout: ${artifact.rolloutStatus}`,
                    }],
            };
        }
        case 'nexus_pattern_search': {
            const query = String(request.params.arguments?.query ?? '');
            const limit = Number(request.params.arguments?.limit ?? 6);
            const results = hctx.getOrchestrator().searchPatterns(query, limit);
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({
                            total: results.length,
                            patterns: results,
                        }, null, 2),
                    }],
            };
        }
        case 'nexus_pattern_list': {
            const limit = Number(request.params.arguments?.limit ?? 8);
            const results = hctx.getOrchestrator().listPatterns().slice(0, Math.max(1, limit));
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({
                            total: results.length,
                            patterns: results,
                        }, null, 2),
                    }],
            };
        }
        case 'nexus_knowledge_provenance': {
            const provenance = hctx.getOrchestrator().getKnowledgeFabricProvenance();
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify(provenance, null, 2),
                    }],
            };
        }
        case 'nexus_darwin_propose': {
            const hypothesis = String(request.params.arguments?.hypothesis ?? '');
            const targetFile = String(request.params.arguments?.targetFile ?? '');
            const approach = String(request.params.arguments?.approach ?? '');
            try {
                const cycle = hctx.getDarwinLoop(request.params.arguments ?? {}).propose(hypothesis, targetFile, approach);
                nexusEventBus.emit('darwin.cycle', { hypothesis: cycle.hypothesis, outcome: 'proposed' });
                return {
                    content: [{
                            type: 'text',
                            text: `🧬 Darwin Cycle Proposed Successfully\nID: ${cycle.id}\nWorktree Branch: ${cycle.worktreeBranch}\nStatus: ${cycle.outcome}\n\nProceed to implement and validate on this branch, then use nexus_darwin_review.`,
                        }],
                };
            }
            catch (err) {
                return {
                    content: [{
                            type: 'text',
                            text: `❌ Darwin Cycle Rejected: ${err.message}`,
                        }],
                };
            }
        }
        case 'nexus_darwin_review': {
            const cycleId = String(request.params.arguments?.cycleId ?? '');
            const action = String(request.params.arguments?.action ?? 'defer');
            const learnings = Array.isArray(request.params.arguments?.learnings)
                ? request.params.arguments?.learnings
                : [];
            try {
                const updated = await hctx.getDarwinLoop(request.params.arguments ?? {}).review(cycleId, action, learnings);
                nexusEventBus.emit('darwin.cycle', { hypothesis: updated.hypothesis, outcome: updated.outcome });
                return {
                    content: [{
                            type: 'text',
                            text: `🧬 Darwin Cycle ${cycleId} updated to: ${updated.outcome}.\nLearnings recorded: ${updated.learnings.length}`,
                        }],
                };
            }
            catch (err) {
                throw new McpError(ErrorCode.InvalidParams, err.message);
            }
        }
        case 'nexus_darwin_status': {
            const loop = hctx.getDarwinLoop(request.params.arguments ?? {});
            const pending = loop.getPending();
            if (pending.length === 0) {
                return {
                    content: [{ type: 'text', text: '🧬 Darwin Loop: No pending proposals.' }],
                };
            }
            const lines = pending.map((c) => `• [${c.id}] ${c.hypothesis.slice(0, 80)} — target: ${c.targetFile} — approach: ${c.approach.slice(0, 60)}`);
            return {
                content: [{
                        type: 'text',
                        text: `🧬 Darwin Loop — ${pending.length} pending proposal(s):\n\n${lines.join('\n')}`,
                    }],
            };
        }
        case 'nexus_net_publish': {
            const type = String(request.params.arguments?.type ?? 'knowledge');
            const content = String(request.params.arguments?.content ?? '');
            const tags = Array.isArray(request.params.arguments?.tags) ? request.params.arguments?.tags : [];
            try {
                const result = await nexusNetRelay.publish(type, { content, tags });
                nexusEventBus.emit('nexusnet.publish', { type, byteSize: result.bytes });
                return {
                    content: [{
                            type: 'text',
                            text: result.configured
                                ? `🌐 Published to NexusNet successfully.\nMessage ID: ${result.id}\nBytes: ${result.bytes}`
                                : `⚠️ NexusNet relay unconfigured.\nBuffered message ID: ${result.id}\nBytes: ${result.bytes}\nMode: ${result.mode}`,
                        }],
                };
            }
            catch (err) {
                return {
                    content: [{ type: 'text', text: `❌ NexusNet Publish Failed: ${err.message}` }],
                };
            }
        }
        case 'nexus_net_sync': {
            try {
                const messages = await nexusNetRelay.sync();
                nexusEventBus.emit('nexusnet.sync', { newItemsCount: messages.length });
                let text = `🌐 Synced with NexusNet. Found ${messages.length} new messages from other agents.\n`;
                messages.forEach((m, i) => {
                    text += `\n[${i + 1}] Type: ${m.type} | Agent: ${m.sourceId}\nContent: ${m.payload.content}\nTags: ${m.payload.tags.join(', ')}\n`;
                });
                return {
                    content: [{ type: 'text', text }],
                };
            }
            catch (err) {
                return {
                    content: [{ type: 'text', text: `❌ NexusNet Sync Failed: ${err.message}` }],
                };
            }
        }
        case 'nexus_assemble_context': {
            const files = Array.isArray(request.params.arguments?.files)
                ? request.params.arguments?.files
                : [];
            const reason = String(request.params.arguments?.reason ?? '');
            const lines = [
                `Reason: ${reason.replace(/\n/g, ' ').substring(0, 56).padEnd(58, ' ')}`,
                '─'.repeat(66)
            ];
            files.forEach((file, idx) => {
                const prefix = idx === files.length - 1 ? '└──' : '├──';
                const displayPath = file.length > 62 ? '...' + file.substring(file.length - 59) : file;
                lines.push(`${prefix} ${displayPath.padEnd(64, ' ')}`);
            });
            hctx.box('📂 CONTEXT ASSEMBLED', lines, '34');
            const text = `📂 Context Assembled. Reason: ${reason}\n\n` + files.map(f => `- ${f}`).join('\n');
            return { content: [{ type: 'text', text }] };
        }
        case 'nexus_publish_trace': {
            const taskId = String(request.params.arguments?.taskId ?? '');
            const goal = String(request.params.arguments?.goal ?? '');
            const findings = Array.isArray(request.params.arguments?.findings) ? request.params.arguments.findings : [];
            const confidence = Number(request.params.arguments?.confidence ?? 0.9);
            const trace = { taskId, goal, findings, confidence, timestamp: Date.now() };
            const result = await getFederation().publishTrace(trace);
            return {
                content: [{
                        type: 'text',
                        text: `🌐 Federated Trace Released!\nURL: ${result.url}\nID: ${result.id}\nTags: #federation, #gist, #trace`
                    }]
            };
        }
    }
    return undefined;
}
