/**
 * Template Customize Command - Copy a framework template to project for customization
 */

import { copyFileSync, existsSync, mkdirSync } from 'fs';
import { join, dirname } from 'path';
import chalk from 'chalk';
import { logger } from '../../utils/logger.js';
import { getTemplateById, resolveTemplatePathById } from '../../core/templates/template-registry.js';

/**
 * Customize template command - copies framework template to project .morph/templates/
 */
export async function templateCustomizeCommand(templateId, options) {
  logger.header(`Customizing Template: ${templateId}`);
  logger.blank();

  try {
    // 1. Validate template exists
    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);
    }

    // 2. Check if template is framework (universal)
    if (template.location !== 'framework') {
      logger.warn(`Template "${templateId}" is already stack-specific`);
      logger.dim(`  Located at: stacks/${template.stacks?.[0]}/.morph/templates/${template.path}`);
      logger.dim('\n  You can edit it directly or copy to another stack.');
      process.exit(0);
    }

    // 3. Resolve source path (framework template)
    const projectPath = options.projectPath || process.cwd();
    const sourcePath = resolveTemplatePathById(templateId, projectPath);

    if (!sourcePath) {
      logger.error(`Framework template file not found for ${templateId}`);
      process.exit(1);
    }

    // 4. Determine destination (stack-specific or project-local)
    const stackId = options.stack || 'blazor-azure';
    const destDir = options.local
      ? join(projectPath, '.morph/templates', dirname(template.path))
      : join(projectPath, 'stacks', stackId, '.morph/templates', dirname(template.path));

    const destPath = options.local
      ? join(projectPath, '.morph/templates', template.path)
      : join(projectPath, 'stacks', stackId, '.morph/templates', template.path);

    // 5. Check if already exists
    if (existsSync(destPath) && !options.force) {
      logger.warn('Template already customized at this location');
      logger.dim(`  ${destPath}`);
      logger.dim('\n  Use --force to overwrite');
      process.exit(1);
    }

    // 6. Copy template
    logger.dim(`Source: ${sourcePath}`);
    logger.dim(`Destination: ${destPath}`);
    logger.blank();

    mkdirSync(destDir, { recursive: true });
    copyFileSync(sourcePath, destPath);

    logger.success('✅ Template copied for customization');
    logger.blank();

    // 7. Show next steps
    logger.info(chalk.bold('📝 Next Steps'));
    console.log(chalk.dim('  1. Edit the template file:'));
    console.log(chalk.cyan(`     ${destPath}`));
    console.log(chalk.dim('\n  2. Template will now be used instead of framework version'));
    console.log(chalk.dim('     (Stack-specific templates take precedence)'));
    console.log(chalk.dim('\n  3. Test rendering:'));
    console.log(chalk.cyan(`     morph-spec template render ${templateId} output.md '{"FEATURE_NAME":"test"}'`));

    if (!options.local) {
      console.log(chalk.dim('\n  4. To share across stacks, use --local flag'));
    }

    logger.blank();

    // 8. Show warning about updates
    logger.warn('⚠️  Customized templates won\'t receive framework updates');
    logger.dim('   To get updates: delete customized version and re-run this command');
    logger.blank();

  } catch (error) {
    logger.error(`Failed to customize template: ${error.message}`);
    if (options.verbose) {
      console.error(error.stack);
    }
    process.exit(1);
  }
}
