/**
 * Command Registry - Auto-Discovery System
 *
 * Metadata-driven command loading eliminates hardcoded imports.
 * Enables dynamic command registration and discovery.
 *
 * @module command-registry
 */

/**
 * Command Metadata Registry
 *
 * Maps command names to their module paths and metadata.
 * Auto-discovered from src/commands/{category}/ structure.
 */
export const commandMetadata = {
  // Feature Management
  'create-story': {
    category: 'feature',
    description: 'Create a new user story with acceptance criteria',
    module: () => import('../../commands/feature/create-story.js'),
    exportName: 'createStoryCommand',
  },
  'shard-spec': {
    category: 'feature',
    description: 'Shard a large spec into manageable chunks',
    module: () => import('../../commands/feature/shard-spec.js'),
    exportName: 'shardSpecCommand',
  },
  'sprint-status': {
    category: 'feature',
    description: 'Show sprint progress and completion status',
    module: () => import('../../commands/feature/sprint-status.js'),
    exportName: 'sprintStatusCommand',
  },

  // State Management
  'state': {
    category: 'state',
    description: 'Manage feature state (init, get, set, list)',
    module: () => import('../../commands/state/state.js'),
    exportName: 'stateCommand',
  },
  'advance-phase': {
    category: 'state',
    description: 'Advance feature to next phase with validation',
    module: () => import('../../commands/state/advance-phase.js'),
    exportName: 'advancePhaseCommand',
  },
  'rollback-phase': {
    category: 'state',
    description: 'Rollback feature to previous phase',
    module: () => import('../../commands/state/rollback-phase.js'),
    exportName: 'rollbackPhaseCommand',
  },
  'approve': {
    category: 'state',
    description: 'Approve or reject approval gates',
    module: () => import('../../commands/state/approve.js'),
    exportName: 'approveCommand',
  },
  'validate-phase': {
    category: 'state',
    description: 'Validate phase transition requirements',
    module: () => import('../../commands/state/validate-phase.js'),
    exportName: 'validatePhaseCommand',
  },

  // Generation
  'generate': {
    category: 'generation',
    description: 'Generate design system files from spec',
    module: () => import('../../commands/generation/generate.js'),
    exportName: 'generateCommand',
  },
  'generate-context': {
    category: 'generation',
    description: 'Generate CONTEXT.md for LLM agents',
    module: () => import('../../commands/generation/generate-context.js'),
    exportName: 'generateContextCommand',
  },

  // Validation
  'validate-blazor': {
    category: 'validation',
    description: 'Validate Blazor components and patterns',
    module: () => import('../../commands/validation/validate-blazor.js'),
    exportName: 'validateBlazorCommand',
  },
  'validate-blazor-state': {
    category: 'validation',
    description: 'Validate Blazor state management patterns',
    module: () => import('../../commands/validation/validate-blazor-state.js'),
    exportName: 'validateBlazorStateCommand',
  },
  'validate-css': {
    category: 'validation',
    description: 'Validate CSS classes and design system',
    module: () => import('../../commands/validation/validate-css.js'),
    exportName: 'validateCssCommand',
  },
  'analyze-blazor-concurrency': {
    category: 'validation',
    description: 'Analyze Blazor concurrency issues',
    module: () => import('../../commands/validation/analyze-blazor-concurrency.js'),
    exportName: 'analyzeBlazorConcurrencyCommand',
  },
  'lint-fluent': {
    category: 'validation',
    description: 'Lint Fluent UI Blazor usage',
    module: () => import('../../commands/validation/lint-fluent.js'),
    exportName: 'lintFluentCommand',
  },

  // Templates
  'template-list': {
    category: 'templates',
    description: 'List available templates',
    module: () => import('../../commands/templates/template-list.js'),
    exportName: 'templateListCommand',
  },
  'template-show': {
    category: 'templates',
    description: 'Show template details and preview',
    module: () => import('../../commands/templates/template-show.js'),
    exportName: 'templateShowCommand',
  },
  'template-render': {
    category: 'templates',
    description: 'Render template with variables',
    module: () => import('../../commands/templates/template-render.js'),
    exportName: 'templateRenderCommand',
  },
  'template-customize': {
    category: 'templates',
    description: 'Customize template for stack',
    module: () => import('../../commands/templates/template-customize.js'),
    exportName: 'templateCustomizeCommand',
  },
  'template-validate': {
    category: 'templates',
    description: 'Validate template structure',
    module: () => import('../../commands/templates/template-validate.js'),
    exportName: 'templateValidateCommand',
  },

  // Project
  'init': {
    category: 'project',
    description: 'Initialize MORPH-SPEC in current directory',
    module: () => import('../../commands/project/init.js'),
    exportName: 'initCommand',
  },
  'doctor': {
    category: 'project',
    description: 'Check project health and configuration',
    module: () => import('../../commands/project/doctor.js'),
    exportName: 'doctorCommand',
  },
  'detect': {
    category: 'project',
    description: 'Auto-detect project stack and configuration',
    module: () => import('../../commands/project/detect.js'),
    exportName: 'detectCommand',
  },
  'detect-workflow': {
    category: 'project',
    description: 'Detect appropriate workflow for request',
    module: () => import('../../commands/project/detect-workflow.js'),
    exportName: 'detectWorkflowCommand',
  },
  'detect-agents': {
    category: 'project',
    description: 'Detect required agents for request',
    module: () => import('../../commands/project/detect-agents.js'),
    exportName: 'detectAgentsCommand',
  },
  'sync': {
    category: 'project',
    description: 'Sync standards from framework',
    module: () => import('../../commands/project/sync.js'),
    exportName: 'syncCommand',
  },
  'update': {
    category: 'project',
    description: 'Update MORPH-SPEC framework',
    module: () => import('../../commands/project/update.js'),
    exportName: 'updateCommand',
  },

  // Learning
  'capture-pattern': {
    category: 'learning',
    description: 'Capture learned pattern to memory',
    module: () => import('../../commands/learning/capture-pattern.js'),
    exportName: 'capturePatternCommand',
  },
  'search-patterns': {
    category: 'learning',
    description: 'Search learned patterns',
    module: () => import('../../commands/learning/search-patterns.js'),
    exportName: 'searchPatternsCommand',
  },

  // Tasks
  'task': {
    category: 'tasks',
    description: 'Manage tasks (done, start, next)',
    module: () => import('../../commands/tasks/task.js'),
    exportName: 'taskCommand',
  },

  // Agents
  'spawn-team': {
    category: 'agents',
    description: 'Spawn agent team for feature',
    module: () => import('../../commands/agents/spawn-team.js'),
    exportName: 'spawnTeamCommand',
  },

  // Utils
  'troubleshoot': {
    category: 'utils',
    description: 'Troubleshoot common errors',
    module: () => import('../../commands/utils/troubleshoot.js'),
    exportName: 'troubleshootCommand',
  },
  'session-summary': {
    category: 'utils',
    description: 'Generate session summary and recap',
    module: () => import('../../commands/utils/session-summary.js'),
    exportName: 'sessionSummaryCommand',
  },
  'migrate-state': {
    category: 'utils',
    description: 'Migrate state to new version',
    module: () => import('../../commands/utils/migrate-state.js'),
    exportName: 'migrateStateCommand',
  },
  'upgrade': {
    category: 'utils',
    description: 'Upgrade project to latest framework',
    module: () => import('../../commands/utils/upgrade.js'),
    exportName: 'upgradeCommand',
  },
};

/**
 * Load command dynamically
 *
 * @param {string} commandName - Command name (e.g., 'init', 'template-list')
 * @returns {Promise<Function>} Command function
 */
export async function loadCommand(commandName) {
  const meta = commandMetadata[commandName];

  if (!meta) {
    const availableCommands = Object.keys(commandMetadata).join(', ');
    throw new Error(`Unknown command: ${commandName}\n\nAvailable: ${availableCommands}`);
  }

  const module = await meta.module();
  const commandFn = module[meta.exportName] || module.default;

  if (!commandFn) {
    throw new Error(`Command '${commandName}' module does not export '${meta.exportName}'`);
  }

  return commandFn;
}

/**
 * Get all command names
 *
 * @returns {string[]} Array of command names
 */
export function getAllCommandNames() {
  return Object.keys(commandMetadata);
}

/**
 * Get commands by category
 *
 * @param {string} category - Category name
 * @returns {string[]} Array of command names in category
 */
export function getCommandsByCategory(category) {
  return Object.entries(commandMetadata)
    .filter(([_, meta]) => meta.category === category)
    .map(([name, _]) => name);
}

/**
 * Get all categories
 *
 * @returns {string[]} Array of unique category names
 */
export function getAllCategories() {
  const categories = new Set();
  Object.values(commandMetadata).forEach(meta => categories.add(meta.category));
  return Array.from(categories).sort();
}
