/**
 * MORPH-SPEC Generate Command
 * CLI wrapper for code generation operations
 */

import { mkdirSync, writeFileSync } from 'fs';
import { dirname } from 'path';
import ora from 'ora';
import chalk from 'chalk';
import { logger } from '../utils/logger.js';
import * as DesignSystemGenerator from '../lib/design-system-generator.js';

// ============================================================================
// Design System Subcommand
// ============================================================================

/**
 * Generate design system files (CSS + themes) from ui-design-system.md
 * @param {string} designSystemPath - Path to ui-design-system.md
 * @param {Object} options - CLI options
 */
export async function generateDesignSystemCommand(designSystemPath, options) {
  if (!designSystemPath) {
    logger.error('Design system file path required');
    logger.dim('  Usage: morph-spec generate design-system <ui-design-system.md>');
    logger.blank();
    logger.dim('  Example:');
    logger.dim('    morph-spec generate design-system .morph/project/outputs/my-feature/ui-design-system.md');
    process.exit(1);
  }

  logger.header('MORPH-SPEC Design System Generator');
  logger.blank();

  const spinner = ora('Parsing design system...').start();

  try {
    // Determine mode
    let mode = 'both';
    if (options.fluent && !options.mud) mode = 'fluent';
    if (options.mud && !options.fluent) mode = 'mud';

    // Generate design system
    const generated = DesignSystemGenerator.generateDesignSystem(designSystemPath, {
      mode,
      namespace: options.namespace || 'YourProject.Themes'
    });

    spinner.succeed('Design system parsed!');
    logger.blank();

    // Display stats
    logger.header('Parsed Design System:');
    logger.info(`Primary Colors: ${chalk.cyan(generated.stats.primaryColors)}`);
    logger.info(`Neutral Colors: ${chalk.cyan(generated.stats.neutralColors)}`);
    logger.info(`Semantic Colors: ${chalk.cyan(generated.stats.semanticColors)}`);
    logger.info(`Font Sizes: ${chalk.cyan(generated.stats.fontSizes)}`);
    logger.info(`Spacing Values: ${chalk.cyan(generated.stats.spacingValues)}`);
    logger.blank();

    if (options.dryRun) {
      logger.warn('Dry run - files not written');
      logger.blank();
      logger.header('Would generate:');
      logger.dim('  - wwwroot/css/design-system.css');
      if (generated.fluentTheme) logger.dim('  - Themes/FluentDesignTheme.cs');
      if (generated.mudTheme) logger.dim('  - Themes/MudDesignTheme.cs');
      logger.blank();
      return;
    }

    // Write files
    const writeSpinner = ora('Writing files...').start();

    // Write CSS
    const cssPath = options.cssOutput || 'wwwroot/css/design-system.css';
    mkdirSync(dirname(cssPath), { recursive: true });
    writeFileSync(cssPath, generated.css);
    writeSpinner.text = `Created ${cssPath}`;

    // Write Fluent theme
    if (generated.fluentTheme) {
      const fluentPath = options.fluentOutput || 'Themes/FluentDesignTheme.cs';
      mkdirSync(dirname(fluentPath), { recursive: true });
      writeFileSync(fluentPath, generated.fluentTheme);
      writeSpinner.text = `Created ${fluentPath}`;
    }

    // Write MudBlazor theme
    if (generated.mudTheme) {
      const mudPath = options.mudOutput || 'Themes/MudDesignTheme.cs';
      mkdirSync(dirname(mudPath), { recursive: true });
      writeFileSync(mudPath, generated.mudTheme);
      writeSpinner.text = `Created ${mudPath}`;
    }

    writeSpinner.succeed('Files generated!');
    logger.blank();

    // List generated files
    logger.header('Generated Files:');
    logger.success(`  ✓ ${cssPath}`);
    if (generated.fluentTheme) logger.success(`  ✓ ${options.fluentOutput || 'Themes/FluentDesignTheme.cs'}`);
    if (generated.mudTheme) logger.success(`  ✓ ${options.mudOutput || 'Themes/MudDesignTheme.cs'}`);
    logger.blank();

    // Next steps
    logger.header('Next Steps:');
    logger.dim('  1. Reference design-system.css in your layout');
    logger.dim('  2. Register theme in Program.cs');
    logger.dim('  3. Apply theme to your components');
    logger.blank();

  } catch (error) {
    spinner.fail('Generation failed');
    logger.error(error.message);
    process.exit(1);
  }
}

// ============================================================================
// Main Generate Command (router for future subcommands)
// ============================================================================

/**
 * Main generate command router
 * Future: Could add more generation commands here
 */
export async function generateCommand(subcommand, args, options) {
  switch (subcommand) {
    case 'design-system':
      await generateDesignSystemCommand(args[0], options);
      break;

    // Future: Add more generation commands
    // case 'component':
    //   await generateComponentCommand(args[0], options);
    //   break;

    default:
      logger.error(`Unknown subcommand: ${subcommand}`);
      logger.blank();
      logger.info('Available subcommands:');
      logger.dim('  design-system    Generate CSS + theme files from ui-design-system.md');
      logger.blank();
      logger.dim('Run "morph-spec generate --help" for more information');
      process.exit(1);
  }
}
