/**
 * @fileoverview Diff Display - Shows diff between current and generated configs
 * @module morph-spec/ui/diff-display
 */

import { diffLines } from 'diff';
import chalk from 'chalk';

/**
 * Display diff between two text strings
 * @param {string} oldContent - Original content
 * @param {string} newContent - New content
 * @param {string} filename - Filename for display
 */
export function displayDiff(oldContent, newContent, filename) {
  console.log(chalk.bold(`\n📝 Changes in ${filename}:\n`));

  const diff = diffLines(oldContent, newContent);

  diff.forEach(part => {
    const color = part.added ? chalk.green : part.removed ? chalk.red : chalk.gray;
    const prefix = part.added ? '+ ' : part.removed ? '- ' : '  ';

    part.value.split('\n').forEach((line, index) => {
      if (line || index < part.value.split('\n').length - 1) {
        console.log(color(prefix + line));
      }
    });
  });

  console.log(); // Empty line after diff
}

/**
 * Display side-by-side summary of changes
 * @param {Object} oldConfig - Old config object
 * @param {Object} newConfig - New config object
 */
export function displayConfigSummary(oldConfig, newConfig) {
  console.log(chalk.bold('\n📊 Configuration Summary:\n'));

  const fields = [
    { key: 'name', label: 'Project Name' },
    { key: 'type', label: 'Project Type' },
    { key: 'description', label: 'Description' },
    { key: 'stack.backend.tech', label: 'Backend' },
    { key: 'stack.frontend.tech', label: 'Frontend' },
    { key: 'stack.database.tech', label: 'Database' },
    { key: 'architecture', label: 'Architecture' }
  ];

  fields.forEach(({ key, label }) => {
    const oldValue = getNestedValue(oldConfig, key) || chalk.gray('(not set)');
    const newValue = getNestedValue(newConfig, key) || chalk.gray('(not set)');

    const changed = oldValue !== newValue;
    const color = changed ? chalk.yellow : chalk.white;

    console.log(
      color(`  ${label.padEnd(20)}: `) +
      chalk.dim(String(oldValue).padEnd(30)) +
      chalk.bold(' → ') +
      color(newValue)
    );
  });

  console.log();
}

/**
 * Get nested value from object by dot notation key
 * @param {Object} obj - Object to query
 * @param {string} key - Dot notation key (e.g., 'stack.backend.tech')
 * @returns {any} Value or null
 */
function getNestedValue(obj, key) {
  if (!obj) return null;

  const keys = key.split('.');
  let current = obj;

  for (const k of keys) {
    if (current && typeof current === 'object' && k in current) {
      current = current[k];
    } else {
      return null;
    }
  }

  return current;
}
