/**
 * MORPH-SPEC validate-css Command
 *
 * Validates that all CSS classes used in Razor files are defined in CSS files.
 * Helps catch missing CSS definitions before runtime.
 *
 * Usage:
 *   morph-spec validate-css [path]
 *   morph-spec validate-css src/MyApp.Web
 *   morph-spec validate-css --verbose
 *   morph-spec validate-css --generate-stub
 */

import chalk from 'chalk';
import { existsSync, writeFileSync } from 'fs';
import { resolve, join } from 'path';
import {
  validateCssClasses,
  formatValidationResults,
  generateCssStub
} from '../../lib/validators/css/css-validator.js';

/**
 * Execute the validate-css command
 * @param {string} path - Project path to validate
 * @param {Object} options - Command options
 */
export async function validateCssCommand(path, options = {}) {
  const projectPath = resolve(path || '.');
  const { verbose, generateStub, includeUtilities } = options;

  // Validate path exists
  if (!existsSync(projectPath)) {
    console.error(chalk.red(`\n Error: Path does not exist: ${projectPath}\n`));
    process.exit(1);
  }

  console.log(chalk.cyan('\n Validating CSS classes...\n'));
  console.log(chalk.gray(`  Path: ${projectPath}`));
  console.log('');

  try {
    // Run validation
    const results = await validateCssClasses(projectPath, {
      verbose,
      includeUtilities
    });

    // Output results
    const formatted = formatValidationResults(results, verbose);
    console.log(formatted);

    // Generate stub if requested
    if (generateStub && !results.valid) {
      const stubContent = generateCssStub(results);
      const stubPath = join(projectPath, 'missing-classes.css');

      writeFileSync(stubPath, stubContent, 'utf8');
      console.log(chalk.green(`\n Generated stub file: ${stubPath}\n`));
    }

    // Summary with colors
    if (results.valid) {
      console.log(chalk.green('\n All CSS classes are properly defined!\n'));
      process.exit(0);
    } else {
      console.log(chalk.yellow(`\n Found ${results.missingClasses.length} missing CSS class(es)\n`));

      // Suggestions
      console.log(chalk.cyan('Suggestions:'));
      console.log(chalk.gray('  1. Add the missing classes to your design-system.css'));
      console.log(chalk.gray('  2. Run with --generate-stub to create a template file'));
      console.log(chalk.gray('  3. If using utility frameworks (Tailwind), add --include-utilities\n'));

      process.exit(1);
    }
  } catch (error) {
    console.error(chalk.red(`\n Error: ${error.message}\n`));
    if (verbose) {
      console.error(error.stack);
    }
    process.exit(1);
  }
}
