/**
 * V3 CLI Completions Command
 * Shell completions for bash, zsh, fish, powershell
 *
 * Created with ruv.io
 */

import type { Command, CommandContext, CommandResult } from '../types.js';
import { output } from '../output.js';

// Get all top-level commands for completions
const TOP_LEVEL_COMMANDS = [
  'swarm', 'agent', 'task', 'session', 'config', 'memory', 'workflow',
  'hive-mind', 'hooks', 'daemon', 'neural', 'security', 'performance',
  'providers', 'plugins', 'deployment', 'claims', 'embeddings',
  'doctor', 'completions', 'help', 'version'
];

// Swarm subcommands
const SWARM_SUBCOMMANDS = ['init', 'status', 'scale', 'destroy', 'monitor', 'optimize'];

// Agent subcommands
const AGENT_SUBCOMMANDS = ['spawn', 'terminate', 'status', 'list', 'pool', 'health', 'update'];

// Task subcommands
const TASK_SUBCOMMANDS = ['create', 'status', 'list', 'complete', 'cancel'];

// Memory subcommands
const MEMORY_SUBCOMMANDS = ['store', 'retrieve', 'search', 'list', 'delete', 'stats', 'configure', 'cleanup', 'compress', 'export', 'import'];

// Hive-mind subcommands
const HIVE_MIND_SUBCOMMANDS = ['init', 'spawn', 'status', 'task', 'join', 'leave', 'consensus', 'broadcast', 'memory', 'optimize-memory', 'shutdown'];

// Hooks subcommands
const HOOKS_SUBCOMMANDS = ['pre-edit', 'post-edit', 'pre-command', 'post-command', 'pre-task', 'post-task', 'route', 'explain', 'pretrain', 'build-agents', 'metrics', 'transfer', 'list', 'intelligence'];

// Generate bash completion script
function generateBashCompletion(): string {
  return `# claude-flow bash completion
# Generated by claude-flow completions bash
# Add this to ~/.bashrc or ~/.bash_completion

_claude_flow_completions() {
    local cur prev words cword
    _init_completion -n : || return

    local commands="${TOP_LEVEL_COMMANDS.join(' ')}"

    # Subcommand completions
    local swarm_commands="${SWARM_SUBCOMMANDS.join(' ')}"
    local agent_commands="${AGENT_SUBCOMMANDS.join(' ')}"
    local task_commands="${TASK_SUBCOMMANDS.join(' ')}"
    local memory_commands="${MEMORY_SUBCOMMANDS.join(' ')}"
    local hive_mind_commands="${HIVE_MIND_SUBCOMMANDS.join(' ')}"
    local hooks_commands="${HOOKS_SUBCOMMANDS.join(' ')}"

    case "\${words[1]}" in
        swarm)
            COMPREPLY=( $(compgen -W "\${swarm_commands}" -- "\${cur}") )
            return 0
            ;;
        agent)
            COMPREPLY=( $(compgen -W "\${agent_commands}" -- "\${cur}") )
            return 0
            ;;
        task)
            COMPREPLY=( $(compgen -W "\${task_commands}" -- "\${cur}") )
            return 0
            ;;
        memory)
            COMPREPLY=( $(compgen -W "\${memory_commands}" -- "\${cur}") )
            return 0
            ;;
        hive-mind|hive)
            COMPREPLY=( $(compgen -W "\${hive_mind_commands}" -- "\${cur}") )
            return 0
            ;;
        hooks)
            COMPREPLY=( $(compgen -W "\${hooks_commands}" -- "\${cur}") )
            return 0
            ;;
        neural)
            COMPREPLY=( $(compgen -W "train status patterns predict optimize" -- "\${cur}") )
            return 0
            ;;
        security)
            COMPREPLY=( $(compgen -W "scan cve threats audit secrets" -- "\${cur}") )
            return 0
            ;;
        performance)
            COMPREPLY=( $(compgen -W "benchmark profile metrics optimize bottleneck" -- "\${cur}") )
            return 0
            ;;
        plugins)
            COMPREPLY=( $(compgen -W "list install uninstall toggle info create" -- "\${cur}") )
            return 0
            ;;
        deployment|deploy)
            COMPREPLY=( $(compgen -W "deploy status rollback history environments logs" -- "\${cur}") )
            return 0
            ;;
        claims)
            COMPREPLY=( $(compgen -W "list check grant revoke roles policies" -- "\${cur}") )
            return 0
            ;;
        embeddings)
            COMPREPLY=( $(compgen -W "generate search compare collections index providers" -- "\${cur}") )
            return 0
            ;;
        daemon)
            COMPREPLY=( $(compgen -W "start stop status trigger enable" -- "\${cur}") )
            return 0
            ;;
        providers)
            COMPREPLY=( $(compgen -W "list configure test models usage" -- "\${cur}") )
            return 0
            ;;
        doctor)
            COMPREPLY=( $(compgen -W "--fix --component --verbose" -- "\${cur}") )
            return 0
            ;;
    esac

    if [[ \${cword} -eq 1 ]]; then
        COMPREPLY=( $(compgen -W "\${commands}" -- "\${cur}") )
        return 0
    fi
}

complete -F _claude_flow_completions claude-flow
complete -F _claude_flow_completions npx\\ @claude-flow/cli@v3alpha
`;
}

// Generate zsh completion script
function generateZshCompletion(): string {
  return `#compdef claude-flow
# claude-flow zsh completion
# Generated by claude-flow completions zsh
# Add to ~/.zfunc/_claude-flow or ~/.zsh/completions/_claude-flow

_claude_flow() {
    local -a commands
    local -a subcommands

    commands=(
        'swarm:Multi-agent swarm orchestration'
        'agent:Agent lifecycle management'
        'task:Task creation and management'
        'session:Session management'
        'config:Configuration management'
        'memory:Memory operations with AgentDB'
        'workflow:Workflow automation'
        'hive-mind:Queen-led consensus coordination'
        'hooks:Self-learning automation hooks'
        'daemon:Background service management'
        'neural:Neural pattern training'
        'security:Security scanning and CVE detection'
        'performance:Performance profiling'
        'providers:AI provider management'
        'plugins:Plugin management'
        'deployment:Deployment management'
        'claims:Claims-based authorization'
        'embeddings:Vector embeddings'
        'doctor:System diagnostics'
        'completions:Shell completion scripts'
        'help:Show help'
        'version:Show version'
    )

    _arguments -C \\
        '1: :->command' \\
        '2: :->subcommand' \\
        '*:: :->args' && return

    case $state in
        command)
            _describe -t commands 'claude-flow commands' commands
            ;;
        subcommand)
            case $words[2] in
                swarm)
                    subcommands=(
                        'init:Initialize swarm'
                        'status:Show swarm status'
                        'scale:Scale agent count'
                        'destroy:Shutdown swarm'
                        'monitor:Real-time monitoring'
                        'optimize:Optimize topology'
                    )
                    ;;
                agent)
                    subcommands=(
                        'spawn:Create new agent'
                        'terminate:Stop agent'
                        'status:Check agent status'
                        'list:List all agents'
                        'pool:Manage agent pool'
                        'health:Health check'
                        'update:Update agent config'
                    )
                    ;;
                task)
                    subcommands=(
                        'create:Create new task'
                        'status:Check task status'
                        'list:List all tasks'
                        'complete:Mark task complete'
                        'cancel:Cancel task'
                    )
                    ;;
                memory)
                    subcommands=(
                        'store:Store data'
                        'retrieve:Retrieve data'
                        'search:Semantic search'
                        'list:List entries'
                        'delete:Delete entry'
                        'stats:Show statistics'
                        'configure:Configure backend'
                        'cleanup:Clean stale data'
                        'compress:Compress storage'
                        'export:Export to file'
                        'import:Import from file'
                    )
                    ;;
                hive-mind|hive)
                    subcommands=(
                        'init:Initialize hive mind'
                        'spawn:Spawn worker agents'
                        'status:Show hive status'
                        'task:Submit task'
                        'join:Join agent to hive'
                        'leave:Remove agent'
                        'consensus:Consensus management'
                        'broadcast:Broadcast message'
                        'memory:Shared memory'
                        'optimize-memory:Optimize patterns'
                        'shutdown:Shutdown hive'
                    )
                    ;;
                hooks)
                    subcommands=(
                        'pre-edit:Before file editing'
                        'post-edit:After file editing'
                        'pre-command:Before command execution'
                        'post-command:After command execution'
                        'pre-task:Before task start'
                        'post-task:After task completion'
                        'route:Route task to agent'
                        'explain:Explain routing'
                        'pretrain:Bootstrap intelligence'
                        'build-agents:Generate agent configs'
                        'metrics:Show metrics'
                        'transfer:Transfer learning'
                        'list:List hooks'
                        'intelligence:Neural intelligence commands'
                    )
                    ;;
                neural)
                    subcommands=(
                        'train:Train neural patterns'
                        'status:Check neural status'
                        'patterns:Manage patterns'
                        'predict:Make predictions'
                        'optimize:Optimize models'
                    )
                    ;;
                security)
                    subcommands=(
                        'scan:Security scan'
                        'cve:CVE detection'
                        'threats:Threat modeling'
                        'audit:Security audit'
                        'secrets:Secrets scanning'
                    )
                    ;;
                performance)
                    subcommands=(
                        'benchmark:Run benchmarks'
                        'profile:Profile code'
                        'metrics:Show metrics'
                        'optimize:Optimize performance'
                        'bottleneck:Find bottlenecks'
                    )
                    ;;
                plugins)
                    subcommands=(
                        'list:List plugins'
                        'install:Install plugin'
                        'uninstall:Remove plugin'
                        'toggle:Enable/disable'
                        'info:Plugin details'
                        'create:Scaffold plugin'
                    )
                    ;;
                deployment|deploy)
                    subcommands=(
                        'deploy:Deploy to environment'
                        'status:Deployment status'
                        'rollback:Rollback version'
                        'history:Deployment history'
                        'environments:List environments'
                        'logs:View logs'
                    )
                    ;;
                claims)
                    subcommands=(
                        'list:List claims'
                        'check:Check permission'
                        'grant:Grant claim'
                        'revoke:Revoke claim'
                        'roles:Manage roles'
                        'policies:Manage policies'
                    )
                    ;;
                embeddings)
                    subcommands=(
                        'generate:Generate embeddings'
                        'search:Semantic search'
                        'compare:Compare vectors'
                        'collections:Manage collections'
                        'index:Index operations'
                        'providers:Embedding providers'
                    )
                    ;;
                daemon)
                    subcommands=(
                        'start:Start daemon'
                        'stop:Stop daemon'
                        'status:Daemon status'
                        'trigger:Trigger event'
                        'enable:Enable feature'
                    )
                    ;;
                providers)
                    subcommands=(
                        'list:List providers'
                        'configure:Configure provider'
                        'test:Test connection'
                        'models:Available models'
                        'usage:Usage statistics'
                    )
                    ;;
            esac
            _describe -t subcommands 'subcommands' subcommands
            ;;
    esac
}

_claude_flow "$@"
`;
}

// Generate fish completion script
function generateFishCompletion(): string {
  return `# claude-flow fish completion
# Generated by claude-flow completions fish
# Save to ~/.config/fish/completions/claude-flow.fish

# Disable file completion by default
complete -c claude-flow -f

# Top-level commands
${TOP_LEVEL_COMMANDS.map(cmd => `complete -c claude-flow -n "__fish_use_subcommand" -a "${cmd}"`).join('\n')}

# Swarm subcommands
${SWARM_SUBCOMMANDS.map(sub => `complete -c claude-flow -n "__fish_seen_subcommand_from swarm" -a "${sub}"`).join('\n')}

# Agent subcommands
${AGENT_SUBCOMMANDS.map(sub => `complete -c claude-flow -n "__fish_seen_subcommand_from agent" -a "${sub}"`).join('\n')}

# Task subcommands
${TASK_SUBCOMMANDS.map(sub => `complete -c claude-flow -n "__fish_seen_subcommand_from task" -a "${sub}"`).join('\n')}

# Memory subcommands
${MEMORY_SUBCOMMANDS.map(sub => `complete -c claude-flow -n "__fish_seen_subcommand_from memory" -a "${sub}"`).join('\n')}

# Hive-mind subcommands
${HIVE_MIND_SUBCOMMANDS.map(sub => `complete -c claude-flow -n "__fish_seen_subcommand_from hive-mind hive" -a "${sub}"`).join('\n')}

# Hooks subcommands
${HOOKS_SUBCOMMANDS.map(sub => `complete -c claude-flow -n "__fish_seen_subcommand_from hooks" -a "${sub}"`).join('\n')}

# Neural subcommands
complete -c claude-flow -n "__fish_seen_subcommand_from neural" -a "train status patterns predict optimize"

# Security subcommands
complete -c claude-flow -n "__fish_seen_subcommand_from security" -a "scan cve threats audit secrets"

# Performance subcommands
complete -c claude-flow -n "__fish_seen_subcommand_from performance" -a "benchmark profile metrics optimize bottleneck"

# Plugins subcommands
complete -c claude-flow -n "__fish_seen_subcommand_from plugins" -a "list install uninstall toggle info create"

# Deployment subcommands
complete -c claude-flow -n "__fish_seen_subcommand_from deployment deploy" -a "deploy status rollback history environments logs"

# Claims subcommands
complete -c claude-flow -n "__fish_seen_subcommand_from claims" -a "list check grant revoke roles policies"

# Embeddings subcommands
complete -c claude-flow -n "__fish_seen_subcommand_from embeddings" -a "generate search compare collections index providers"

# Daemon subcommands
complete -c claude-flow -n "__fish_seen_subcommand_from daemon" -a "start stop status trigger enable"

# Providers subcommands
complete -c claude-flow -n "__fish_seen_subcommand_from providers" -a "list configure test models usage"
`;
}

// Generate PowerShell completion script
function generatePowerShellCompletion(): string {
  return `# claude-flow PowerShell completion
# Generated by claude-flow completions powershell
# Add to $PROFILE or save to a separate file and dot-source it

$script:ClaudeFlowCommands = @(
    '${TOP_LEVEL_COMMANDS.join("',\n    '")}'
)

$script:SubCommands = @{
    'swarm' = @('${SWARM_SUBCOMMANDS.join("', '")}')
    'agent' = @('${AGENT_SUBCOMMANDS.join("', '")}')
    'task' = @('${TASK_SUBCOMMANDS.join("', '")}')
    'memory' = @('${MEMORY_SUBCOMMANDS.join("', '")}')
    'hive-mind' = @('${HIVE_MIND_SUBCOMMANDS.join("', '")}')
    'hive' = @('${HIVE_MIND_SUBCOMMANDS.join("', '")}')
    'hooks' = @('${HOOKS_SUBCOMMANDS.join("', '")}')
    'neural' = @('train', 'status', 'patterns', 'predict', 'optimize')
    'security' = @('scan', 'cve', 'threats', 'audit', 'secrets')
    'performance' = @('benchmark', 'profile', 'metrics', 'optimize', 'bottleneck')
    'plugins' = @('list', 'install', 'uninstall', 'toggle', 'info', 'create')
    'deployment' = @('deploy', 'status', 'rollback', 'history', 'environments', 'logs')
    'deploy' = @('deploy', 'status', 'rollback', 'history', 'environments', 'logs')
    'claims' = @('list', 'check', 'grant', 'revoke', 'roles', 'policies')
    'embeddings' = @('generate', 'search', 'compare', 'collections', 'index', 'providers')
    'daemon' = @('start', 'stop', 'status', 'trigger', 'enable')
    'providers' = @('list', 'configure', 'test', 'models', 'usage')
}

Register-ArgumentCompleter -Native -CommandName claude-flow -ScriptBlock {
    param($wordToComplete, $commandAst, $cursorPosition)

    $tokens = $commandAst.ToString().Split(' ')
    $command = $tokens[1]

    if ($tokens.Count -eq 2) {
        # Complete top-level commands
        $script:ClaudeFlowCommands | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
            [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
        }
    }
    elseif ($tokens.Count -eq 3 -and $script:SubCommands.ContainsKey($command)) {
        # Complete subcommands
        $script:SubCommands[$command] | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
            [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
        }
    }
}
`;
}

// Bash subcommand
const bashCommand: Command = {
  name: 'bash',
  description: 'Generate bash completion script',
  action: async (ctx: CommandContext): Promise<CommandResult> => {
    const script = generateBashCompletion();
    output.writeln(script);
    return { success: true };
  }
};

// Zsh subcommand
const zshCommand: Command = {
  name: 'zsh',
  description: 'Generate zsh completion script',
  action: async (ctx: CommandContext): Promise<CommandResult> => {
    const script = generateZshCompletion();
    output.writeln(script);
    return { success: true };
  }
};

// Fish subcommand
const fishCommand: Command = {
  name: 'fish',
  description: 'Generate fish completion script',
  action: async (ctx: CommandContext): Promise<CommandResult> => {
    const script = generateFishCompletion();
    output.writeln(script);
    return { success: true };
  }
};

// PowerShell subcommand
const powershellCommand: Command = {
  name: 'powershell',
  aliases: ['pwsh'],
  description: 'Generate PowerShell completion script',
  action: async (ctx: CommandContext): Promise<CommandResult> => {
    const script = generatePowerShellCompletion();
    output.writeln(script);
    return { success: true };
  }
};

// Main completions command
export const completionsCommand: Command = {
  name: 'completions',
  description: 'Generate shell completion scripts',
  subcommands: [bashCommand, zshCommand, fishCommand, powershellCommand],
  options: [],
  examples: [
    { command: 'claude-flow completions bash > ~/.bash_completion.d/claude-flow', description: 'Install bash completions' },
    { command: 'claude-flow completions zsh > ~/.zfunc/_claude-flow', description: 'Install zsh completions' },
    { command: 'claude-flow completions fish > ~/.config/fish/completions/claude-flow.fish', description: 'Install fish completions' },
    { command: 'claude-flow completions powershell >> $PROFILE', description: 'Install PowerShell completions' }
  ],
  action: async (): Promise<CommandResult> => {
    output.writeln();
    output.writeln(output.bold('Shell Completions'));
    output.writeln();
    output.writeln('Generate shell completion scripts for tab completion support.');
    output.writeln();
    output.writeln('Supported shells:');
    output.printList([
      `${output.highlight('bash')}       - Bash completion`,
      `${output.highlight('zsh')}        - Zsh completion`,
      `${output.highlight('fish')}       - Fish completion`,
      `${output.highlight('powershell')} - PowerShell completion`
    ]);
    output.writeln();
    output.writeln('Installation:');
    output.writeln();
    output.writeln(output.bold('Bash:'));
    output.writeln(output.dim('  claude-flow completions bash > ~/.bash_completion.d/claude-flow'));
    output.writeln(output.dim('  source ~/.bash_completion.d/claude-flow'));
    output.writeln();
    output.writeln(output.bold('Zsh:'));
    output.writeln(output.dim('  mkdir -p ~/.zfunc'));
    output.writeln(output.dim('  claude-flow completions zsh > ~/.zfunc/_claude-flow'));
    output.writeln(output.dim('  # Add to ~/.zshrc: fpath=(~/.zfunc $fpath); autoload -Uz compinit && compinit'));
    output.writeln();
    output.writeln(output.bold('Fish:'));
    output.writeln(output.dim('  claude-flow completions fish > ~/.config/fish/completions/claude-flow.fish'));
    output.writeln();
    output.writeln(output.bold('PowerShell:'));
    output.writeln(output.dim('  claude-flow completions powershell >> $PROFILE'));

    return { success: true };
  }
};

export default completionsCommand;
