/**
 * Template Validate Command - Validate Handlebars templates
 */

import chalk from 'chalk';
import { logger } from '../../utils/logger.js';
import { validateTemplate, validateAllTemplates, formatValidationResults, summarizeValidation } from '../../core/templates/template-validator.js';

/**
 * Validate template(s) command
 */
export async function templateValidateCommand(templateId, options) {
  const projectPath = options.projectPath || process.cwd();

  if (templateId) {
    // Validate single template
    logger.header(`Validating Template: ${templateId}`);
    logger.blank();

    const result = validateTemplate(templateId, projectPath);

    // Display results
    if (result.errors.length === 0 && result.warnings.length === 0) {
      logger.success(`✅ Template is valid`);
      logger.blank();

      if (result.info.length > 0 && options.verbose) {
        logger.info(chalk.bold('ℹ️  Information'));
        result.info.forEach(info => console.log(chalk.dim(`  ${info}`)));
        logger.blank();
      }
    } else {
      if (result.errors.length > 0) {
        logger.error(chalk.bold('❌ Errors'));
        result.errors.forEach(error => console.log(chalk.red(`  - ${error}`)));
        logger.blank();
      }

      if (result.warnings.length > 0) {
        logger.warn(chalk.bold('⚠️  Warnings'));
        result.warnings.forEach(warning => console.log(chalk.yellow(`  - ${warning}`)));
        logger.blank();
      }

      if (result.info.length > 0 && options.verbose) {
        logger.info(chalk.bold('ℹ️  Information'));
        result.info.forEach(info => console.log(chalk.dim(`  ${info}`)));
        logger.blank();
      }

      if (result.errors.length > 0) {
        process.exit(1);
      }
    }
  } else {
    // Validate all templates
    logger.header('Validating All Templates');
    logger.blank();

    const validationOptions = {
      skipDeprecated: !options.includeDeprecated,
      category: options.category,
      technology: options.technology,
    };

    const results = validateAllTemplates(projectPath, validationOptions);
    const summary = summarizeValidation(results);

    // Display results
    const formatted = formatValidationResults(results, {
      showInfo: options.verbose,
      showValid: options.showValid,
    });

    console.log(formatted);
    logger.blank();

    // Exit with error if any templates have errors
    if (summary.hasErrors > 0) {
      logger.error(`${summary.hasErrors} template(s) failed validation`);
      process.exit(1);
    } else if (summary.hasWarnings > 0) {
      logger.warn(`${summary.hasWarnings} template(s) have warnings`);
      if (options.strict) {
        process.exit(1);
      }
    } else {
      logger.success(`All templates are valid! ✅`);
    }
  }
}
