/**
 * MORPH-SPEC Detectors - Main Orchestrator
 *
 * Coordinates all detection modules to build a complete picture of the project.
 */

import { detectStructure } from './structure-detector.js';
import { detectConfig } from './config-detector.js';
import { analyzeConversation } from './conversation-analyzer.js';
import { generateStandards } from './standards-generator.js';

/**
 * Main detection orchestrator
 * @param {string} projectPath - Path to project root
 * @param {Object} options - Detection options
 * @returns {Promise<Object>} Detection results
 */
export async function detectProject(projectPath, options = {}) {
  const results = {
    path: projectPath,
    timestamp: new Date().toISOString(),
    structure: null,
    config: null,
    conversation: null,
    inferred: null
  };

  try {
    // 1. Detect structure (stack, architecture, patterns)
    if (options.structure !== false) {
      results.structure = await detectStructure(projectPath);
    }

    // 2. Detect config (technologies, dependencies, versions)
    if (options.config !== false) {
      results.config = await detectConfig(projectPath);
    }

    // 3. Analyze conversation history (if available)
    if (options.conversation !== false) {
      results.conversation = await analyzeConversation(projectPath);
    }

    // 4. Generate inferred standards
    if (options.generateStandards !== false) {
      results.inferred = await generateStandards(results);
    }

    return results;
  } catch (error) {
    throw new Error(`Detection failed: ${error.message}`);
  }
}

/**
 * Get detection summary
 * @param {Object} results - Detection results
 * @returns {string} Human-readable summary
 */
export function getDetectionSummary(results) {
  const { structure, config } = results;

  const lines = [
    '## Detection Summary',
    '',
    '### Stack',
    `- **Type**: ${structure?.stack || 'unknown'}`,
    `- **Architecture**: ${structure?.architecture || 'unknown'}`,
    `- **UI Library**: ${structure?.uiLibrary || 'none'}`,
    '',
    '### Technologies',
    `- **Language**: ${config?.language || 'unknown'}`,
    `- **Version**: ${config?.version || 'unknown'}`,
    `- **Package Manager**: ${config?.packageManager || 'unknown'}`,
    '',
    '### Patterns Detected',
    ...(structure?.patterns || []).map(p => `- ${p}`),
    '',
    '### Recommendations',
    ...(results.inferred?.recommendations || []).map(r => `- ${r}`)
  ];

  return lines.join('\n');
}
