/**
 * Standards Generator - Generates inferred-standards.md from detection results
 */

/**
 * Generate inferred standards
 * @param {Object} detectionResults - Results from all detectors
 * @returns {Promise<Object>} Generated standards
 */
export async function generateStandards(detectionResults) {
  const { structure, config, conversation } = detectionResults;

  const standards = {
    markdown: generateMarkdown(structure, config, conversation),
    recommendations: generateRecommendations(structure, config, conversation),
    gaps: identifyGaps(structure, config)
  };

  return standards;
}

/**
 * Generate markdown content for inferred-standards.md
 */
function generateMarkdown(structure, config, conversation) {
  const sections = [];

  // Header
  sections.push(`# Inferred Standards (Auto-generated)`);
  sections.push(``);
  sections.push(`> ⚠️ This file is auto-generated by MORPH-SPEC detection system.`);
  sections.push(`> Manual edits will be overwritten. Create custom standards in \`overrides.md\`.`);
  sections.push(``);
  sections.push(`**Generated:** ${new Date().toISOString()}`);
  sections.push(``);
  sections.push(`---`);
  sections.push(``);

  // Stack Summary
  sections.push(`## 🎯 Project Stack`);
  sections.push(``);
  sections.push(`- **Type**: ${structure?.stack || 'unknown'}`);
  sections.push(`- **Language**: ${config?.language || 'unknown'}`);
  sections.push(`- **Version**: ${config?.version || 'unknown'}`);
  sections.push(`- **Architecture**: ${structure?.architecture || 'unknown'}`);
  if (structure?.uiLibrary) {
    sections.push(`- **UI Library**: ${structure.uiLibrary}`);
  }
  sections.push(``);

  // Technologies
  if (config?.technologies?.length > 0) {
    sections.push(`## 🛠️ Technologies Detected`);
    sections.push(``);
    config.technologies.forEach(tech => {
      sections.push(`- ${tech}`);
    });
    sections.push(``);
  }

  // Patterns
  if (structure?.patterns?.length > 0) {
    sections.push(`## 📐 Patterns in Use`);
    sections.push(``);
    structure.patterns.forEach(pattern => {
      sections.push(`- ${pattern}`);
    });
    sections.push(``);
  }

  // Coding Standards (inferred)
  sections.push(`## 💻 Inferred Coding Standards`);
  sections.push(``);
  sections.push(generateCodingStandards(structure, config));
  sections.push(``);

  // Architecture Patterns
  if (structure?.architecture !== 'unknown') {
    sections.push(`## 🏗️ Architecture Pattern`);
    sections.push(``);
    sections.push(generateArchitectureSection(structure));
    sections.push(``);
  }

  // Dependencies
  if (config?.dependencies?.length > 0) {
    sections.push(`## 📦 Key Dependencies`);
    sections.push(``);
    const importantDeps = filterImportantDependencies(config.dependencies);
    importantDeps.slice(0, 10).forEach(dep => {
      sections.push(`- ${dep}`);
    });
    if (config.dependencies.length > 10) {
      sections.push(`- ... and ${config.dependencies.length - 10} more`);
    }
    sections.push(``);
  }

  // User Preferences (from conversation)
  if (conversation?.preferences && Object.keys(conversation.preferences).some(k => conversation.preferences[k])) {
    sections.push(`## 🎨 User Preferences (from past decisions)`);
    sections.push(``);
    Object.entries(conversation.preferences).forEach(([key, value]) => {
      if (value) {
        sections.push(`- **${formatKey(key)}**: ${value}`);
      }
    });
    sections.push(``);
  }

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

/**
 * Generate coding standards section
 */
function generateCodingStandards(structure, config) {
  if (config?.language === 'csharp') {
    return `### C# / .NET Conventions

Based on detected patterns in your codebase:

- **Naming**: PascalCase for classes, camelCase for variables
- **Async**: Methods with \`Async\` suffix
- **DI**: Constructor injection (${structure.patterns.includes('Dependency Injection') ? '✅ detected' : '⚠️ not detected'})
- **Tests**: ${structure.patterns.includes('Unit Tests') ? '✅ Present' : '⚠️ Not detected'}

**Recommendation**: Refer to \`.morph/standards/coding.md\` for complete .NET standards.`;
  }

  if (config?.language === 'javascript') {
    return `### JavaScript / TypeScript Conventions

Based on detected patterns in your codebase:

- **Package Manager**: ${config.packageManager}
- **Framework**: ${config.technologies.join(', ')}

**Recommendation**: Refer to framework standards for JavaScript best practices.`;
  }

  return 'No specific coding standards inferred. Check framework standards for guidance.';
}

/**
 * Generate architecture section
 */
function generateArchitectureSection(structure) {
  const { architecture } = structure;

  const descriptions = {
    'clean-architecture': `### Clean Architecture

Your project follows Clean Architecture pattern:

- ✅ **Domain** layer detected (core business logic)
- ✅ **Application** layer detected (use cases)
- ✅ **Infrastructure** layer detected (implementations)

**Key principles**:
- Domain has no dependencies
- Application depends on Domain
- Infrastructure implements Application interfaces`,

    'cqrs': `### CQRS Pattern

Your project uses Command Query Responsibility Segregation:

- ✅ **Commands** detected (write operations)
- ✅ **Queries** detected (read operations)

**Key principles**:
- Separate read and write models
- Commands return void or Task
- Queries return data`,

    'mvc': `### MVC Pattern

Your project uses Model-View-Controller pattern:

- ✅ **Controllers** detected
- ✅ **Models** detected
- ✅ **Views** detected`
  };

  return descriptions[architecture] || `Architecture: ${architecture}`;
}

/**
 * Generate recommendations
 */
function generateRecommendations(structure, config, conversation) {
  const recommendations = [];

  // Recommend based on stack
  if (structure?.stack === 'blazor') {
    if (!structure.uiLibrary) {
      recommendations.push('Consider adding Fluent UI Blazor or MudBlazor for consistent UI components');
    }

    if (!structure.patterns.includes('AI Agents') && config?.technologies?.includes('Microsoft Agent Framework')) {
      recommendations.push('Setup detected Agent Framework but no agents found - check .morph/standards/agent-framework-setup.md');
    }
  }

  // Recommend tests
  if (!structure?.patterns?.includes('Unit Tests')) {
    recommendations.push('No unit tests detected - consider adding test project');
  }

  // Recommend DI
  if (!structure?.patterns?.includes('Dependency Injection')) {
    recommendations.push('Consider implementing Dependency Injection pattern');
  }

  // Architecture recommendations
  if (structure?.architecture === 'unknown' && structure?.folders?.hasServices) {
    recommendations.push('Service layer detected but no clear architecture - consider Clean Architecture or CQRS');
  }

  return recommendations;
}

/**
 * Identify gaps between framework and project
 */
function identifyGaps(structure, config) {
  const gaps = [];

  // Check for missing patterns
  const expectedPatterns = {
    blazor: ['Service Layer', 'Repository Pattern', 'Dependency Injection'],
    nextjs: ['API Routes', 'Components'],
  };

  const expected = expectedPatterns[structure?.stack];
  if (expected) {
    expected.forEach(pattern => {
      if (!structure?.patterns?.includes(pattern)) {
        gaps.push(`Missing: ${pattern}`);
      }
    });
  }

  return gaps;
}

/**
 * Filter important dependencies
 */
function filterImportantDependencies(deps) {
  const important = deps.filter(dep => {
    // Framework packages
    if (dep.includes('Microsoft.') || dep.includes('System.')) return true;
    // UI libraries
    if (dep.includes('Blazor') || dep.includes('FluentUI') || dep.includes('Mud')) return true;
    // Common tools
    if (dep.includes('Hangfire') || dep.includes('Serilog') || dep.includes('AutoMapper')) return true;
    // AI/ML
    if (dep.includes('Agents') || dep.includes('AI') || dep.includes('OpenAI')) return true;
    return false;
  });

  return important.length > 0 ? important : deps;
}

/**
 * Format key for display
 */
function formatKey(key) {
  return key
    .replace(/([A-Z])/g, ' $1')
    .replace(/^./, str => str.toUpperCase())
    .trim();
}
