/**
 * Conversation Analyzer - Analyzes Claude Code conversation history for user preferences
 *
 * Note: This is a basic implementation. Full conversation analysis would require
 * access to Claude Code's message history API or local cache.
 */

import { existsSync, readFileSync } from 'fs';
import { join } from 'path';

/**
 * Analyze conversation history
 * @param {string} projectPath - Project root path
 * @returns {Promise<Object>} Conversation analysis results
 */
export async function analyzeConversation(projectPath) {
  const result = {
    preferences: {},
    decisions: [],
    patterns: [],
    available: false
  };

  // Check if .morph/project/context exists (past decisions)
  const contextPath = join(projectPath, '.morph', 'project', 'context');
  if (existsSync(contextPath)) {
    result.available = true;

    // Read decisions-history.md if exists
    const decisionsFile = join(contextPath, 'decisions-history.md');
    if (existsSync(decisionsFile)) {
      const content = readFileSync(decisionsFile, 'utf8');
      result.decisions = extractDecisions(content);
    }
  }

  // Check .morph/project/outputs/*/decisions.md
  const outputsPath = join(projectPath, '.morph', 'project', 'outputs');
  if (existsSync(outputsPath)) {
    const { readdirSync } = await import('fs');
    const features = readdirSync(outputsPath, { withFileTypes: true })
      .filter(dirent => dirent.isDirectory())
      .map(dirent => dirent.name);

    for (const feature of features) {
      const decisionsFile = join(outputsPath, feature, 'decisions.md');
      if (existsSync(decisionsFile)) {
        const content = readFileSync(decisionsFile, 'utf8');
        result.decisions.push(...extractDecisions(content));
      }
    }
  }

  // Extract patterns from decisions
  result.patterns = inferPatternsFromDecisions(result.decisions);

  // Extract preferences
  result.preferences = extractPreferences(result.decisions);

  return result;
}

/**
 * Extract decisions from markdown
 */
function extractDecisions(markdown) {
  const decisions = [];
  const lines = markdown.split('\n');

  let currentDecision = null;

  for (const line of lines) {
    // Look for decision headings
    if (line.match(/^##\s+Decision/i) || line.match(/^###\s+ADR/i)) {
      if (currentDecision) {
        decisions.push(currentDecision);
      }
      currentDecision = { text: '', category: 'unknown', confidence: 0.5 };
    }

    if (currentDecision) {
      currentDecision.text += line + '\n';

      // Categorize
      if (line.includes('UI') || line.includes('component') || line.includes('Fluent') || line.includes('Mud')) {
        currentDecision.category = 'ui-ux';
        currentDecision.confidence = 0.8;
      } else if (line.includes('pattern') || line.includes('architecture') || line.includes('CQRS')) {
        currentDecision.category = 'architecture';
        currentDecision.confidence = 0.8;
      } else if (line.includes('Azure') || line.includes('Container') || line.includes('deployment')) {
        currentDecision.category = 'azure';
        currentDecision.confidence = 0.8;
      } else if (line.includes('class') || line.includes('method') || line.includes('naming')) {
        currentDecision.category = 'coding';
        currentDecision.confidence = 0.8;
      }
    }
  }

  if (currentDecision) {
    decisions.push(currentDecision);
  }

  return decisions;
}

/**
 * Infer patterns from decisions
 */
function inferPatternsFromDecisions(decisions) {
  const patterns = [];

  for (const decision of decisions) {
    const text = decision.text.toLowerCase();

    if (text.includes('always use') || text.includes('sempre usar')) {
      patterns.push(`Pattern: ${decision.text.split('\n')[0].substring(0, 60)}...`);
    }

    if (text.includes('never') || text.includes('nunca')) {
      patterns.push(`Anti-pattern: ${decision.text.split('\n')[0].substring(0, 60)}...`);
    }
  }

  return patterns;
}

/**
 * Extract user preferences
 */
function extractPreferences(decisions) {
  const preferences = {
    uiLibrary: null,
    architecture: null,
    testing: null,
    deployment: null
  };

  for (const decision of decisions) {
    const text = decision.text.toLowerCase();

    if (text.includes('fluent ui') && !text.includes('not')) {
      preferences.uiLibrary = 'Fluent UI';
    } else if (text.includes('mudblazor') && !text.includes('not')) {
      preferences.uiLibrary = 'MudBlazor';
    }

    if (text.includes('clean architecture')) {
      preferences.architecture = 'Clean Architecture';
    } else if (text.includes('cqrs')) {
      preferences.architecture = 'CQRS';
    }

    if (text.includes('container apps')) {
      preferences.deployment = 'Azure Container Apps';
    } else if (text.includes('app service')) {
      preferences.deployment = 'Azure App Service';
    }
  }

  return preferences;
}
