/**
 * Template Show Command - Display detailed information about a template
 */

import chalk from 'chalk';
import { logger } from '../../utils/logger.js';
import { getTemplateById, resolveTemplatePathById } from '../../core/templates/template-registry.js';
import { readFileSync, existsSync } from 'fs';

/**
 * Show template details command
 */
export async function templateShowCommand(templateId, options) {
  logger.header(`Template: ${templateId}`);
  logger.blank();

  try {
    const template = getTemplateById(templateId);

    if (!template) {
      logger.error(`Template not found: ${templateId}`);
      logger.dim('\n💡 Use `morph-spec template list` to see available templates');
      process.exit(1);
    }

    // Display template metadata
    logger.info(chalk.bold('📋 Metadata'));
    console.log(`  ID: ${chalk.cyan(template.id)}`);
    console.log(`  Name: ${chalk.green(template.name)}`);
    console.log(`  Path: ${chalk.dim(template.path)}`);
    console.log(`  Location: ${template.location === 'framework' ? chalk.cyan('framework') : chalk.yellow('stack')}`);
    console.log(`  Category: ${template.category}`);
    console.log(`  Phase: ${template.phase || 'N/A'}`);
    console.log(`  Required: ${template.required ? chalk.green('Yes') : chalk.dim('No')}`);
    console.log(`  Stack-Specific: ${template.stackSpecific ? chalk.yellow('Yes') : chalk.cyan('No (universal)')}`);

    if (template.stackSpecific && template.stacks) {
      console.log(`  Stacks: ${chalk.yellow(template.stacks.join(', '))}`);
    }

    console.log(`  Engine: ${template.engine === 'handlebars' ? chalk.blue('Handlebars') : chalk.dim('Custom')}`);

    if (template.deprecated) {
      console.log(`  ${chalk.red.bold('⚠️  DEPRECATED')}`);
    }

    if (template.autoGenerated) {
      console.log(`  ${chalk.dim('Auto-generated (not user-facing)')}`);
    }

    logger.blank();

    // Description
    if (template.description) {
      logger.info(chalk.bold('📝 Description'));
      console.log(`  ${template.description}`);
      logger.blank();
    }

    // Placeholders
    if (template.placeholders && template.placeholders.length > 0) {
      logger.info(chalk.bold('🔑 Variables'));
      template.placeholders.forEach(p => {
        console.log(`  ${chalk.cyan(`{{${p}}}`)}`);
      });
      logger.blank();
    }

    // Output name
    if (template.outputName) {
      logger.info(chalk.bold('📄 Output Name'));
      console.log(`  ${chalk.dim(template.outputName)}`);
      logger.blank();
    }

    // Resolve actual path
    if (options.showPath) {
      const projectPath = options.projectPath || process.cwd();
      const stackId = options.stack || 'blazor-azure';
      const resolvedPath = resolveTemplatePathById(templateId, projectPath, stackId);

      logger.info(chalk.bold('📂 Resolved Path'));
      if (resolvedPath) {
        console.log(`  ${chalk.green(resolvedPath)}`);
        console.log(`  ${chalk.dim(`(${existsSync(resolvedPath) ? 'exists' : 'not found'})`)}`);
      } else {
        console.log(`  ${chalk.red('Not found in framework/ or stack/')}`);
      }
      logger.blank();
    }

    // Show template preview
    if (options.preview) {
      const projectPath = options.projectPath || process.cwd();
      const stackId = options.stack || 'blazor-azure';
      const resolvedPath = resolveTemplatePathById(templateId, projectPath, stackId);

      if (resolvedPath && existsSync(resolvedPath)) {
        logger.info(chalk.bold('👁️  Preview (first 20 lines)'));
        logger.blank();

        const content = readFileSync(resolvedPath, 'utf-8');
        const lines = content.split('\n').slice(0, 20);

        lines.forEach((line, i) => {
          console.log(chalk.dim(`${String(i + 1).padStart(3)}  ${line}`));
        });

        if (content.split('\n').length > 20) {
          logger.blank();
          logger.dim(`  ... (${content.split('\n').length - 20} more lines)`);
        }

        logger.blank();
      } else {
        logger.warn('Template file not found - cannot preview');
      }
    }

    // Show usage hint
    if (template.engine === 'handlebars') {
      logger.info(chalk.bold('💡 Usage Hint'));
      console.log(chalk.dim(`  morph-spec template render ${templateId} output.md '{"FEATURE_NAME":"my-feature"}'`));
      logger.blank();
    }

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