// ── cli/commandCatalog.ts ─────────────────────────────────────────────────────
// Single source of truth for all slash commands — descriptions, usage, subs,
// examples, section groupings, and (C2+) runtime dispatch handlers.
//
// Consumed by:
//   • cli/commandPalette.ts (interactive arrow-key palette)
//   • cli/aiden.ts           (Tab completer + /help handler + dispatch)
//   • core/pluginLoader.ts   (plugin command registration — C4)
// ─────────────────────────────────────────────────────────────────────────────

export interface CmdDetail {
  desc:      string
  usage?:    string
  subs?:     string[]
  examples?: string[]
  section?:  string
  // ── C2 additions ─────────────────────────────────────────────────────────────
  /** Runtime dispatch handler.  Populated by registerCoreCommands() in aiden.ts
   *  and by plugin register() calls.  args = parts.slice(1) (everything after
   *  the slash command name). */
  handler?:  (args: string[]) => Promise<void>
  /** Whether this entry was contributed by a plugin or shipped as core. */
  origin?:   'core' | 'plugin'
  /** Hint: safe to run in parallel with other commands (reserved for C4). */
  parallel?: boolean
}

export interface PaletteCommand {
  command:      string        // e.g. "/skills"
  description:  string        // one-line desc for palette display
  usage?:       string        // full usage signature
  subcommands?: PaletteCommand[]
  section?:     string        // grouping label
}

// ── Full command registry (static metadata) ───────────────────────────────────
// C2 adds the 6 commands that existed in /help display but were missing here.
// Handlers are NOT stored here — they are registered at runtime via
// registerCoreCommands() in cli/aiden.ts, which closes over module-scope state.

export const COMMAND_DETAIL: Record<string, CmdDetail> = {
  '/new':        { section: 'Session',   desc: 'Start a fresh session (clears local history).',                usage: '/new' },
  '/reset':      { section: 'Session',   desc: 'Alias for /new.',                                             usage: '/reset' },
  '/clear':      { section: 'Session',   desc: 'Clear the terminal screen.',                                  usage: '/clear' },
  '/history':    { section: 'Session',   desc: 'Show conversation history for this session.',                 usage: '/history' },
  '/stop':       { section: 'Session',   desc: 'Interrupt an in-flight LLM call.',                           usage: '/stop' },
  '/export':     { section: 'Session',   desc: 'Export conversation as Markdown or JSON.',                   usage: '/export md|json' },
  '/fork':       { section: 'Session',   desc: 'Branch current session under a new name.',                   usage: '/fork <name>' },
  '/checkpoint': { section: 'Session',   desc: 'Save a state snapshot.',                                     usage: '/checkpoint' },
  '/timing':     { section: 'Info',      desc: 'Show timing breakdown for the last response.',                usage: '/timing' },
  '/version':    { section: 'Info',      desc: 'Show current version and check for updates.',                 usage: '/version' },
  '/status':     { section: 'Info',      desc: 'Show server health, uptime, RAM.',                           usage: '/status' },
  '/tools':      { section: 'Info',      desc: 'All registered tools grouped by category.',                  usage: '/tools' },
  '/kit':        { section: 'Info',      desc: 'Toolkit categories — enable or disable tool groups.',        usage: '/kit' },
  '/providers':  { section: 'Info',      desc: 'Provider chain with rate-limit status.',                     usage: '/providers' },
  '/models':     { section: 'Info',      desc: 'Model assignments for each task type.',                      usage: '/models' },
  '/memory':     { section: 'Info',      desc: 'Conversation memory stats.',                                 usage: '/memory' },
  '/memsearch':  { section: 'Info',      desc: 'Search memories by keyword — Layer 1 progressive disclosure.',
    usage:    '/memsearch <query>',
    examples: ['/memsearch archon provider routing', '/memsearch phase 14 lazy loading'],
  },
  '/memtimeline':{ section: 'Info',      desc: 'Chronological context around a memory ID — Layer 2.',
    usage:    '/memtimeline <mem_id>',
    examples: ['/memtimeline mem_000001'],
  },
  '/memget':     { section: 'Info',      desc: 'Full detail for specific memory IDs — Layer 3.',
    usage:    '/memget <id1,id2,...>',
    examples: ['/memget mem_000001', '/memget mem_000001,mem_000002'],
  },
  '/goals':      { section: 'Info',      desc: 'Active goals queue.',                                        usage: '/goals' },
  '/skills':     { section: 'Info',      desc: 'Skill lifecycle manager.',
    subs:    ['search <q>', 'install <name>', 'list', 'check', 'update <name>', 'audit', 'remove <name>',
              'publish <name>', 'export <name>', 'import <source>', 'import-repo <owner/repo>',
              'validate [id]', 'source <name>', 'stats', 'recommend', 'test <name>',
              'enable <id>', 'disable <id>', 'approve <id>', 'reject <id>', 'explore <topic>',
              'review [<id>]'],
    examples: ['/skills list', '/skills search http', '/skills validate', '/skills import owner/repo',
               '/skills import-repo anthropics/skills', '/skills enable algorithmic-art'],
    usage: '/skills [list|search|install|enable|disable|validate|import|...] [args]',
  },
  // ── Gap 1 (C2): 3 Info commands previously missing from catalog ──────────────
  '/plugins':    { section: 'Info',      desc: 'Plugin manager — list loaded plugins or force reload.',
    subs:     ['list', 'reload'],
    examples: ['/plugins', '/plugins reload'],
    usage:    '/plugins [list|reload]',
  },
  '/profile':    { section: 'Info',      desc: 'View, edit, or clear the structured user profile (Honcho model).',
    subs:     ['edit', 'clear'],
    examples: ['/profile', '/profile edit', '/profile clear'],
    usage:    '/profile [edit|clear]',
  },
  '/failed':     { section: 'Info',      desc: 'Signal last exchange failed — triggers failure trace analysis + lesson.',
    usage:    '/failed [reason]',
    examples: ['/failed', '/failed wrong file was edited'],
  },
  '/lessons':    { section: 'Info',      desc: 'Browse permanent failure rules stored in LESSONS.md.',
    subs:     ['search <q>', 'web|shell|files|planning|provider|memory|skills|errors|general'],
    examples: ['/lessons', '/lessons search rate limit', '/lessons errors'],
    usage:    '/lessons [search <q>|<category>]',
  },
  '/teach':      { section: 'Info',      desc: 'Append a manual rule to LESSONS.md.',
    usage:    '/teach <rule text>',
    examples: ['/teach If rate limit hit, wait 60s before retry'],
  },
  '/focus':      { section: 'Info',      desc: 'Toggle zen mode — suppress tool traces and status output.',  usage: '/focus' },
  '/explore':    { section: 'Info',      desc: 'Capability browser.',
    subs:     ['tools', 'skills', 'providers'],
    examples: ['/explore tools', '/explore skills'],
    usage:    '/explore [tools|skills|providers]',
  },
  '/pulse':      { section: 'Info',      desc: 'Live system dashboard — uptime, RAM, providers, async tasks.', usage: '/pulse' },
  '/rewind':     { section: 'Info',      desc: 'Time-travel undo — mark a restore point, then jump back.',
    subs:     ['mark [label]', 'undo', '<n>'],
    examples: ['/rewind mark safe', '/rewind undo', '/rewind 2'],
    usage:    '/rewind [mark <label>|undo|<n>]',
  },
  '/pin':        { section: 'Info',      desc: 'Pin an exchange so it is never compacted.',
    subs:     ['[label]', 'list', 'unpin <idx>'],
    examples: ['/pin important fact', '/pin list', '/pin unpin 0'],
    usage:    '/pin [<label>|list|unpin <idx>]',
  },
  '/diff':       { section: 'Info',      desc: 'Filesystem changes since last commit (git status).',         usage: '/diff' },
  '/trust':      { section: 'Info',      desc: 'Per-tool approval levels.',
    subs:     ['list', 'set <tool> <0|1|2|3>', 'reset <tool>'],
    examples: ['/trust list', '/trust set web_search 2', '/trust reset web_search'],
    usage:    '/trust [list|set <tool> <level>|reset <tool>]',
  },
  '/timeline':   { section: 'Info',      desc: 'ASCII tree of all sessions with branching and message counts.', usage: '/timeline' },
  '/garden':     { section: 'Info',      desc: 'Memory layer explorer — all 9 memory stores at a glance.',
    subs:     ['semantic', 'entities', 'learning', 'facts'],
    examples: ['/garden', '/garden semantic', '/garden entities'],
    usage:    '/garden [semantic|entities|learning|facts]',
  },
  '/decision':   { section: 'Info',      desc: 'Per-turn reasoning trace from the decision log.',
    subs:     ['[N]', 'last', 'clear'],
    examples: ['/decision', '/decision 50', '/decision last', '/decision clear'],
    usage:    '/decision [<N>|last|clear]',
  },
  '/log':        { section: 'Core',      desc: 'Show recent log buffer entries.',
    usage:    '/log [N] [level]',
    examples: ['/log', '/log 50', '/log 20 error'],
  },
  '/save':       { section: 'Core',      desc: 'Save conversation to workspace/exports/ as Markdown.',
    usage:    '/save [filename]',
    examples: ['/save', '/save my-session'],
  },
  '/rerun':      { section: 'Core',      desc: 'Re-send the last user message.',                             usage: '/rerun' },
  '/name':       { section: 'Core',      desc: 'Give the current session a human-readable name.',
    usage:    '/name <label>',
    examples: ['/name debugging-auth-bug', '/name'],
  },
  '/stack':      { section: 'Core',      desc: 'Show active async task stack.',                              usage: '/stack' },
  '/halt':       { section: 'Core',      desc: 'Hard-stop all execution and LLM calls immediately.',         usage: '/halt' },
  '/yolo':       { section: 'Core',      desc: 'Toggle YOLO mode — auto-approve all tool calls.',           usage: '/yolo' },
  '/attach':     { section: 'Core',      desc: 'Queue a file as context prepended to the next message.',
    subs:     ['<path>', 'list', 'clear'],
    examples: ['/attach ./notes.txt', '/attach list', '/attach clear'],
    usage:    '/attach [<path>|list|clear]',
  },
  '/changelog':  { section: 'Core',      desc: 'Show recent git commits or workspace file changes.',
    usage:    '/changelog [N]',
    examples: ['/changelog', '/changelog 50'],
  },
  '/sessions':   { section: 'Info',      desc: 'List recent sessions.',                                      usage: '/sessions' },
  '/recipes':    { section: 'Info',      desc: 'List saved YAML prompt recipes.',                           usage: '/recipes' },
  '/analytics':  { section: 'Info',      desc: 'Token usage analytics over time.',                          usage: '/analytics' },
  '/budget':     { section: 'Info',      desc: 'Estimated token cost for this session.',                    usage: '/budget' },
  '/workspace':  { section: 'Info',      desc: 'Show current workspace path and contents.',                 usage: '/workspace' },
  '/model':      { section: 'Config',    desc: 'Switch the active LLM model.',                              usage: '/model <name>' },
  '/provider':   { section: 'Config',    desc: 'Manage API providers — list, add, remove, test.',
    usage:    '/provider [list|add|add-custom|remove|test]',
    subs:     ['list', 'add <type> <key>', 'add-custom <name> <baseUrl> [key]', 'remove <id>', 'test <id>'],
    examples: ['/provider list', '/provider add groq sk-xxx', '/provider test groq-1'],
  },
  '/primary':    { section: 'Config',    desc: 'Pin a provider to front of the chain.',                     usage: '/primary [list|<name>|reset]' },
  '/switch':     { section: 'Config',    desc: 'Alias for /primary — pin a provider to front of chain.',    usage: '/switch [list|<name>|reset]' },
  '/theme':      { section: 'Config',    desc: 'Change color theme.',
    usage:    '/theme <name>',
    examples: ['/theme default', '/theme mono', '/theme slate', '/theme ember'],
  },
  '/persona':    { section: 'Config',    desc: 'Switch response persona.',
    usage:    '/persona <name>',
    examples: ['/persona default', '/persona concise', '/persona technical'],
  },
  '/detail':     { section: 'Config',    desc: 'Cycle tool-trace detail level: off → tools → verbose.',     usage: '/detail' },
  '/depth':      { section: 'Config',    desc: 'Cycle reasoning depth: low → medium → high.',               usage: '/depth' },
  '/config':     { section: 'Config',    desc: 'Show current configuration snapshot.',                      usage: '/config' },
  '/quick':      { section: 'Power',     desc: 'Quick side question — no history, no tools.',               usage: '/quick <question>' },
  '/compact':    { section: 'Power',     desc: 'Manual context compression.',                               usage: '/compact' },
  '/async':      { section: 'Power',     desc: 'Run a task in the background.',                             usage: '/async <task>' },
  '/run':        { section: 'Power',     desc: 'Execute JS in the Aiden VM sandbox with full SDK access.',
    subs:     ['<file.js>', '- [desc]', 'examples', 'help', 'help <ns>'],
    examples: ['/run scripts/port_checker.js', '/run -', '/run examples', '/run help'],
    usage:    '/run <file.js> | - | examples | help [ns]',
  },
  '/spawn':      { section: 'Power',     desc: 'Delegate a sub-task to an isolated subagent.',
    subs:     ['<task>', 'list', 'kill <id>'],
    examples: ['/spawn summarise the logs', '/spawn list', '/spawn kill spawn_1234_abc'],
    usage:    '/spawn <task> | list | kill <id>',
  },
  '/swarm':      { section: 'Power',     desc: 'Run N parallel subagents and aggregate results.',
    subs:     ['<task>', '<task> --n=<N>', '<task> --strategy=vote|merge|best'],
    examples: ['/swarm research quantum computing', '/swarm write a haiku --n=5 --strategy=vote'],
    usage:    '/swarm <task> [--n=3] [--strategy=vote|merge|best]',
  },
  '/search':     { section: 'Power',     desc: 'Hybrid BM25 + semantic search over sessions and memory.',
    subs:     ['<query>', '<query> --top=N'],
    examples: ['/search market research', '/search authentication bug --top=10'],
    usage:    '/search <query> [--top=N]',
  },
  '/permissions': { section: 'Power',    desc: 'Permission system — view mode, reload config, browse audit log.',
    subs:     ['status', 'reload', 'audit', 'edit'],
    examples: ['/permissions', '/permissions reload', '/permissions audit', '/permissions edit'],
    usage:    '/permissions [status|reload|audit|edit]',
  },
  '/uninstall':  { section: 'Power',    desc: 'Uninstall Aiden from this system.',
    subs:     ['--keep-workspace', '--keep-config', '--yes'],
    examples: ['/uninstall', '/uninstall --keep-workspace', '/uninstall --yes'],
    usage:    '/uninstall [--keep-workspace] [--keep-config] [--yes]',
  },
  '/mcp':        { section: 'Power',     desc: 'Manage MCP (Model Context Protocol) server connections.',
    subs:     ['list', 'tools [server]', 'connect <name> <cmd>', 'disconnect <name>', 'call <server:tool> [json]'],
    examples: ['/mcp list', '/mcp tools github', '/mcp call github:list_issues {}'],
    usage:    '/mcp <subcommand> [args]',
  },
  '/cmd':        { section: 'Power',     desc: 'Run a Windows cmd.exe command and show stdout/exitCode.',
    examples: ['/cmd dir', '/cmd ipconfig /all'],
    usage:    '/cmd <command>',
  },
  '/ps':         { section: 'Power',     desc: 'Run a PowerShell command directly (no temp file).',
    examples: ['/ps Get-Process | Select-Object -First 5', '/ps $PSVersionTable'],
    usage:    '/ps <command>',
  },
  '/wsl':        { section: 'Power',     desc: 'Run a bash command inside WSL (auto-translates paths).',
    examples: ['/wsl uname -a', '/wsl ls -la /mnt/c/Users'],
    usage:    '/wsl <command> [--distro=<name>]',
  },
  '/refresh':    { section: 'Power',     desc: 'Check for Aiden updates and reload config.',                usage: '/refresh' },
  '/channels':   { section: 'Power',     desc: 'Show all channel adapters and their status.',
    subs:    ['restart <name>', 'test <name>'],
    usage:   '/channels [restart <name>|test <name>]',
    examples: ['/channels', '/channels restart discord', '/channels test slack'],
  },
  '/voice':      { section: 'Voice',     desc: 'Toggle voice mode — TTS reads every AI reply aloud.',
    subs:    ['on', 'off', 'status', 'providers', 'design', 'clone', 'reset'],
    usage:   '/voice [on|off|status|providers|design <desc>|clone <path>|reset]',
    examples: ['/voice', '/voice on', '/voice off', '/voice providers'],
  },
  '/speak':      { section: 'Voice',     desc: 'Speak text immediately using the TTS engine.',
    usage:    '/speak <text>',
    examples: ['/speak Hello, how can I help you today?'],
  },
  '/listen':     { section: 'Voice',     desc: 'Record microphone input, transcribe via STT, and send as message.',
    usage:    '/listen [seconds]',
    examples: ['/listen', '/listen 10'],
  },
  '/todo':       { section: 'Power',     desc: 'Manage a per-session task list.',
    subs:    ['add <text>', 'done <id>', 'remove <id>', 'list [all|pending|done]', 'clear'],
    usage:   '/todo [add <text>|done <id>|remove <id>|list [filter]|clear]',
    examples: ['/todo add Write unit tests', '/todo done 1', '/todo list pending', '/todo clear'],
  },
  '/cron':       { section: 'Power',     desc: 'Schedule recurring shell commands. Persists across sessions.',
    subs:    ['add <schedule> <command>', 'list', 'pause <id>', 'resume <id>', 'delete <id>', 'run <id>'],
    usage:   '/cron [add <schedule> -- <command>|list|pause|resume|delete|run <id>]',
    examples: ['/cron add every 5 minutes -- echo heartbeat', '/cron list', '/cron pause 1'],
  },
  '/vision':     { section: 'Power',     desc: 'Analyze an image with AI vision.',
    usage:   '/vision <path|url> [prompt]',
    examples: ['/vision screenshot.png', '/vision /tmp/photo.jpg What text is visible?'],
  },
  '/security':   { section: 'Power',     desc: 'Run AgentShield security scan.',                            usage: '/security' },
  '/debug':      { section: 'Power',     desc: 'Recent server log entries.',                                usage: '/debug' },
  '/private':    { section: 'Power',     desc: 'Toggle private mode — suppresses memory writes.',           usage: '/private' },
  '/learn':      { section: 'Power',     desc: 'Trigger active skill learning for a topic.',
    usage:    '/learn [<name>] [<description>]',
    examples: ['/learn TypeScript generics advanced patterns'],
  },
  // ── Gap 1 (C2): 3 Power commands previously missing from catalog ─────────────
  '/install':    { section: 'Power',     desc: 'Install a skill from the public registry (skills.taracod.com).',
    usage:    '/install <skill_name>',
    examples: ['/install http-client', '/install code-review'],
  },
  '/publish':    { section: 'Power',     desc: 'Publish a skill to the public registry (Pro — requires license key).',
    usage:    '/publish <skill_name> [--key=<license>]',
    examples: ['/publish my-skill', '/publish my-skill --key=abc123'],
  },
  '/sandbox':    { section: 'Power',     desc: 'Manage Docker sandbox mode (status / off / auto / strict / build).',
    subs:     ['status', 'off', 'auto', 'strict', 'build'],
    examples: ['/sandbox', '/sandbox strict', '/sandbox build'],
    usage:    '/sandbox [status|off|auto|strict|build]',
  },
  '/help':       { section: 'Meta',      desc: 'Show help overview, or search / get detail on a command.',
    subs:     ['search <q>', '<command>'],
    examples: ['/help', '/help search memory', '/help /skills'],
    usage:    '/help [search <q>|<command>]',
  },
  '/quit':       { section: 'Exit',      desc: 'Exit Aiden.',                                               usage: '/quit' },
  '/exit':       { section: 'Exit',      desc: 'Alias for /quit.',                                          usage: '/exit' },
  '/q':          { section: 'Exit',      desc: 'Alias for /quit.',                                          usage: '/q' },
}

// ── Runtime registry (C2) ─────────────────────────────────────────────────────
// Seeded from COMMAND_DETAIL at module load.  register() / unregister() mutate
// this map and bump _generation so downstream caches can invalidate.

let _generation = 0

/** Internal registry — DO NOT access directly; use list() / get(). */
const _registry: Map<string, CmdDetail> = new Map(Object.entries(COMMAND_DETAIL))

/**
 * Register (or replace) a slash command at runtime.
 * Bumps _generation so dropdown / palette caches know to rebuild.
 */
export function register(name: string, detail: CmdDetail): void {
  _registry.set(name, detail)
  _generation++
}

/**
 * Unregister a slash command at runtime.
 * No-ops silently if the name is not registered.
 */
export function unregister(name: string): void {
  if (_registry.delete(name)) _generation++
}

/** All registered commands as [name, detail] pairs (includes plugins). */
export function list(): Array<[string, CmdDetail]> {
  return Array.from(_registry.entries())
}

/** Look up a single command by exact name (e.g. '/skills'). */
export function get(name: string): CmdDetail | undefined {
  return _registry.get(name)
}

/** Monotonic counter — incremented on every register() / unregister() call.
 *  Consumers can cache against this value and rebuild when it changes. */
export function generation(): number {
  return _generation
}

// ── Flat list of command strings (used by Tab completer) ──────────────────────
// Derived from the static COMMAND_DETAIL so it is available synchronously
// before registerCoreCommands() runs.  Prefer commandCatalog.list() for
// anything that needs runtime-registered plugin commands.
export const COMMANDS: string[] = Object.keys(COMMAND_DETAIL)

// ── Catalog builder ───────────────────────────────────────────────────────────

/** Build a PaletteCommand array for the command palette.
 *  Uses the live _registry so plugin commands are included. */
export function getCatalog(): PaletteCommand[] {
  return list().map(([cmd, d]) => {
    const subcommands: PaletteCommand[] | undefined = d.subs?.map(sub => {
      const subcmd = sub.split(' ')[0]   // first token is the subcommand keyword
      return {
        command:     `${cmd} ${subcmd}`,
        description: sub,
        section:     d.section,
      }
    })
    return {
      command:     cmd,
      description: d.desc,
      usage:       d.usage,
      subcommands,
      section:     d.section,
    }
  })
}
