import { join } from 'path';
import ora from 'ora';
import chalk from 'chalk';
import { logger } from '../utils/logger.js';
import { detectProject, getDetectionSummary } from '../../detectors/index.js';
import { ensureDir, writeFile } from '../utils/file-copier.js';

export async function detectCommand(options) {
  const targetPath = options.path || process.cwd();

  logger.header('MORPH-SPEC Project Detection');
  logger.dim(`Analyzing: ${targetPath}`);
  logger.blank();

  const spinner = ora('Detecting project structure...').start();

  try {
    // Run detection
    const results = await detectProject(targetPath, {
      structure: true,
      config: true,
      conversation: true,
      generateStandards: true
    });

    spinner.succeed('Detection complete!');
    logger.blank();

    // Display summary
    logger.header('Detection Results');
    logger.blank();

    // Stack
    logger.info(`Stack: ${chalk.cyan(results.structure.stack)}`);
    logger.info(`Architecture: ${chalk.cyan(results.structure.architecture)}`);
    if (results.structure.uiLibrary) {
      logger.info(`UI Library: ${chalk.cyan(results.structure.uiLibrary)}`);
    }
    logger.blank();

    // Technologies
    if (results.config.technologies.length > 0) {
      logger.header('Technologies:');
      results.config.technologies.forEach(tech => {
        logger.dim(`  - ${tech}`);
      });
      logger.blank();
    }

    // Patterns
    if (results.structure.patterns.length > 0) {
      logger.header('Patterns:');
      results.structure.patterns.forEach(pattern => {
        logger.dim(`  - ${pattern}`);
      });
      logger.blank();
    }

    // Recommendations
    if (results.inferred.recommendations.length > 0) {
      logger.header('Recommendations:');
      results.inferred.recommendations.forEach(rec => {
        logger.warn(`  ⚠ ${rec}`);
      });
      logger.blank();
    }

    // Save results if requested
    if (options.save !== false) {
      spinner.start('Saving detection results...');

      const outputDir = join(targetPath, '.morph', 'project', 'context');
      await ensureDir(outputDir);

      // Save detection log
      const logPath = join(outputDir, 'detection-log.md');
      const summary = getDetectionSummary(results);
      await writeFile(logPath, summary);

      // Save inferred standards
      const standardsDir = join(targetPath, '.morph', 'project', 'standards');
      await ensureDir(standardsDir);

      const standardsPath = join(standardsDir, 'inferred.md');
      await writeFile(standardsPath, results.inferred.markdown);

      spinner.succeed('Results saved!');
      logger.dim(`  - ${logPath}`);
      logger.dim(`  - ${standardsPath}`);
    }

    // Verbose output
    if (options.verbose) {
      logger.blank();
      logger.header('Detailed Results (JSON):');
      console.log(JSON.stringify(results, null, 2));
    }

  } catch (error) {
    spinner.fail('Detection failed');
    logger.error(error.message);
    process.exit(1);
  }
}
