/**
 * Template List Command - List all available templates with filtering
 */

import chalk from 'chalk';
import { logger } from '../../utils/logger.js';
import {
  getAllTemplates,
  getTemplatesByCategory,
  getTemplatesByPhase,
  getTemplatesByStack,
  getRequiredTemplates,
  getRegistryStats
} from '../../core/templates/template-registry.js';

/**
 * Format template for display
 */
function formatTemplate(template) {
  const { id, name, category, phase, required, stackSpecific, location, engine, deprecated } = template;

  const badges = [];
  if (required) badges.push(chalk.green('[REQUIRED]'));
  if (deprecated) badges.push(chalk.red('[DEPRECATED]'));
  if (stackSpecific) badges.push(chalk.yellow('[STACK-SPECIFIC]'));
  else badges.push(chalk.cyan('[UNIVERSAL]'));
  if (engine === 'handlebars') badges.push(chalk.blue('[HBS]'));

  const badgeStr = badges.join(' ');

  return {
    id: chalk.bold(id),
    name,
    location: location === 'framework' ? chalk.cyan('framework') : chalk.yellow('stack'),
    category: chalk.dim(category),
    phase: chalk.dim(phase || 'N/A'),
    badges: badgeStr
  };
}

/**
 * List templates command
 */
export async function templateListCommand(options) {
  logger.header('MORPH-SPEC Templates');
  logger.blank();

  try {
    let templates;

    // Apply filters
    if (options.category) {
      templates = getTemplatesByCategory(options.category);
      logger.dim(`Category: ${options.category}`);
    } else if (options.phase) {
      templates = getTemplatesByPhase(options.phase);
      logger.dim(`Phase: ${options.phase}`);
    } else if (options.stack) {
      templates = getTemplatesByStack(options.stack);
      logger.dim(`Stack: ${options.stack}`);
    } else if (options.required) {
      templates = getRequiredTemplates(options.stack);
      logger.dim('Required templates only');
    } else {
      templates = getAllTemplates();
      logger.dim('All templates');
    }

    logger.blank();

    if (templates.length === 0) {
      logger.warn('No templates found matching criteria');
      return;
    }

    // Group by location if not filtered
    if (!options.category && !options.phase) {
      const frameworkTemplates = templates.filter(t => t.location === 'framework');
      const stackTemplates = templates.filter(t => t.location === 'stack');

      if (frameworkTemplates.length > 0) {
        logger.info(chalk.bold.cyan(`\n📦 Universal Templates (${frameworkTemplates.length})`));
        frameworkTemplates.forEach(t => {
          const formatted = formatTemplate(t);
          console.log(`  ${formatted.id.padEnd(30)} ${formatted.name.padEnd(40)} ${formatted.badges}`);
        });
      }

      if (stackTemplates.length > 0) {
        logger.info(chalk.bold.yellow(`\n📦 Stack-Specific Templates (${stackTemplates.length})`));
        stackTemplates.forEach(t => {
          const formatted = formatTemplate(t);
          const stacks = t.stacks ? chalk.dim(`(${t.stacks.join(', ')})`) : '';
          console.log(`  ${formatted.id.padEnd(30)} ${formatted.name.padEnd(40)} ${stacks} ${formatted.badges}`);
        });
      }
    } else {
      // Flat list
      templates.forEach(t => {
        const formatted = formatTemplate(t);
        console.log(`  ${formatted.id.padEnd(30)} ${formatted.name.padEnd(40)} ${formatted.location.padEnd(15)} ${formatted.badges}`);
      });
    }

    // Show statistics
    if (!options.category && !options.phase && !options.stack && !options.required) {
      logger.blank();
      const stats = getRegistryStats();
      logger.info(chalk.bold('\n📊 Statistics'));
      console.log(`  Total Templates: ${chalk.green(stats.total)}`);
      console.log(`  Framework: ${chalk.cyan(stats.framework)}`);
      console.log(`  Blazor-Azure: ${chalk.yellow(stats.blazorAzure)}`);
      console.log(`  Next.js-Supabase: ${chalk.yellow(stats.nextjsSupabase)}`);
      console.log(`  Required: ${chalk.green(stats.required)}`);
      console.log(`  Optional: ${chalk.dim(stats.optional)}`);
    }

    logger.blank();

    // Show usage hint
    logger.dim('💡 Use `morph-spec template show <id>` to see template details');
    logger.blank();

  } catch (error) {
    logger.error(`Failed to list templates: ${error.message}`);
    process.exit(1);
  }
}
