/**
 * MORPH-SPEC Complexity Analyzer Library
 *
 * Analyzes user requests and classifies them into workflows:
 * - fast-track: Trivial changes (bug fixes, small adjustments)
 * - standard: Medium features (simple additions, improvements)
 * - full-morph: Complex features (new subsystems, architecture)
 *
 * Used both by CLI commands and internal automation.
 */

// ============================================================================
// COMPLEXITY THRESHOLDS
// ============================================================================

export const COMPLEXITY_THRESHOLDS = {
  'fast-track': {
    maxFiles: 3,
    maxLines: 50,
    maxComponents: 0,
    requiresInfrastructure: false,
    requiresArchitecturalDecisions: false,
    description: 'Bug fixes, small adjustments, edge cases, hotfixes'
  },
  'standard': {
    maxFiles: 10,
    maxLines: 500,
    maxComponents: 2,
    requiresInfrastructure: false,
    requiresArchitecturalDecisions: false, // Only tactical decisions
    description: 'Simple features, refactorings, incremental improvements'
  },
  'full-morph': {
    maxFiles: Infinity,
    maxLines: Infinity,
    maxComponents: Infinity,
    requiresInfrastructure: true, // Can have infrastructure
    requiresArchitecturalDecisions: true, // Strategic decisions
    description: 'Complex features, new subsystems, architectural changes'
  }
};

// ============================================================================
// KEYWORD DETECTION
// ============================================================================

/**
 * Keywords that indicate different complexity levels
 */
const COMPLEXITY_KEYWORDS = {
  trivial: [
    'bug', 'fix', 'corrigir', 'ajustar', 'typo', 'correção',
    'edge case', 'hotfix', 'urgente', 'rápido', 'quick',
    'cor', 'color', 'texto', 'text', 'label', 'validação',
    'mensagem', 'message', 'css', 'style', 'espaçamento'
  ],

  infrastructure: [
    'azure', 'bicep', 'deploy', 'infra', 'infrastructure',
    'container', 'kubernetes', 'k8s', 'database', 'sql',
    'storage', 'queue', 'service bus', 'redis', 'cosmos'
  ],

  architectural: [
    'sistema', 'system', 'arquitetura', 'architecture',
    'pattern', 'cqrs', 'event sourcing', 'microservice',
    'subsistema', 'subsystem', 'integração', 'integration',
    'autenticação', 'authentication', 'autorização', 'authorization'
  ],

  newComponents: [
    'novo', 'new', 'criar', 'create', 'adicionar', 'add',
    'implementar', 'implement', 'desenvolver', 'develop',
    'componente', 'component', 'serviço', 'service',
    'tela', 'screen', 'página', 'page', 'formulário', 'form'
  ]
};

// ============================================================================
// ANALYSIS FUNCTIONS
// ============================================================================

/**
 * Detect keywords in user input
 * @param {string} userInput - User request
 * @param {Array<string>} keywords - Keywords to search for
 * @returns {number} Count of keyword matches
 */
function detectKeywords(userInput, keywords) {
  const lowerInput = userInput.toLowerCase();
  return keywords.filter(keyword => lowerInput.includes(keyword)).length;
}

/**
 * Estimate code impact from user input
 * @param {string} userInput - User request
 * @returns {Object} Estimated impact
 */
export function estimateCodeImpact(userInput) {
  const lowerInput = userInput.toLowerCase();

  // Trivial indicators
  const trivialCount = detectKeywords(lowerInput, COMPLEXITY_KEYWORDS.trivial);
  if (trivialCount > 0) {
    return {
      estimatedFiles: 1,
      estimatedLines: 10,
      estimatedComponents: 0,
      confidence: 'high'
    };
  }

  // Count indicators of new components
  const newComponentCount = detectKeywords(lowerInput, COMPLEXITY_KEYWORDS.newComponents);

  // Multiple components/features mentioned (separated by "e", "and", or commas)
  const separators = [' e ', ' and ', ','];
  const hasSeparator = separators.some(sep => lowerInput.includes(sep));

  if (hasSeparator) {
    // Split by any separator
    let parts = [lowerInput];
    for (const sep of separators) {
      parts = parts.flatMap(part => part.split(sep));
    }
    parts = parts.filter(p => p.trim().length > 0);

    // If we found multiple parts, estimate high complexity
    if (parts.length > 1) {
      return {
        estimatedFiles: Math.min(parts.length * 3, 15),
        estimatedLines: Math.min(parts.length * 200, 1000),
        estimatedComponents: Math.min(parts.length, 5),
        confidence: 'medium'
      };
    }
  }

  // New component indicators
  if (newComponentCount > 0) {
    return {
      estimatedFiles: 5,
      estimatedLines: 200,
      estimatedComponents: 1,
      confidence: 'medium'
    };
  }

  // Default to standard complexity
  return {
    estimatedFiles: 5,
    estimatedLines: 150,
    estimatedComponents: 1,
    confidence: 'low'
  };
}

/**
 * Detect if request involves infrastructure
 * @param {string} userInput - User request
 * @returns {boolean} True if infrastructure is involved
 */
export function detectInfrastructure(userInput) {
  const infraCount = detectKeywords(userInput, COMPLEXITY_KEYWORDS.infrastructure);
  return infraCount > 0;
}

/**
 * Detect if request involves architectural decisions
 * @param {string} userInput - User request
 * @returns {boolean} True if architectural decisions are involved
 */
export function detectArchitecturalDecisions(userInput) {
  const archCount = detectKeywords(userInput, COMPLEXITY_KEYWORDS.architectural);
  return archCount > 0;
}

/**
 * Classify workflow based on analysis
 * @param {Object} impact - Code impact estimation
 * @param {boolean} hasInfrastructure - Has infrastructure
 * @param {boolean} hasArchitecturalDecisions - Has architectural decisions
 * @returns {string} Workflow type: "fast-track" | "standard" | "full-morph"
 */
export function classifyWorkflow(impact, hasInfrastructure, hasArchitecturalDecisions) {
  const { estimatedFiles, estimatedLines, estimatedComponents } = impact;

  // Full MORPH: Infrastructure or architectural decisions
  if (hasInfrastructure || hasArchitecturalDecisions) {
    return 'full-morph';
  }

  // Full MORPH: Large code impact
  if (estimatedFiles > COMPLEXITY_THRESHOLDS.standard.maxFiles ||
      estimatedLines > COMPLEXITY_THRESHOLDS.standard.maxLines ||
      estimatedComponents > COMPLEXITY_THRESHOLDS.standard.maxComponents) {
    return 'full-morph';
  }

  // Fast Track: Trivial changes
  if (estimatedFiles <= COMPLEXITY_THRESHOLDS['fast-track'].maxFiles &&
      estimatedLines <= COMPLEXITY_THRESHOLDS['fast-track'].maxLines &&
      estimatedComponents <= COMPLEXITY_THRESHOLDS['fast-track'].maxComponents) {
    return 'fast-track';
  }

  // Default: Standard workflow
  return 'standard';
}

/**
 * Analyze request complexity - Main entry point
 * @param {string} userInput - User request
 * @param {Object} options - Options
 * @param {string} options.forceWorkflow - Force specific workflow
 * @returns {Object} Complete analysis
 */
export function analyzeRequestComplexity(userInput, options = {}) {
  // Check for forced workflow
  if (options.forceWorkflow) {
    return {
      workflow: options.forceWorkflow,
      forced: true,
      reason: 'Manually overridden by user'
    };
  }

  // Analyze request
  const impact = estimateCodeImpact(userInput);
  const hasInfrastructure = detectInfrastructure(userInput);
  const hasArchitecturalDecisions = detectArchitecturalDecisions(userInput);

  const workflow = classifyWorkflow(impact, hasInfrastructure, hasArchitecturalDecisions);

  // Build reason
  let reason = `Estimated ${impact.estimatedFiles} files, ${impact.estimatedLines} lines, ${impact.estimatedComponents} components`;
  if (hasInfrastructure) reason += ', requires infrastructure';
  if (hasArchitecturalDecisions) reason += ', requires architectural decisions';

  return {
    workflow,
    forced: false,
    impact,
    hasInfrastructure,
    hasArchitecturalDecisions,
    confidence: impact.confidence,
    reason,
    thresholds: COMPLEXITY_THRESHOLDS[workflow]
  };
}

/**
 * Get workflow phases
 * @param {string} workflow - Workflow type
 * @returns {Array<string>} List of phases to execute
 */
export function getWorkflowPhases(workflow) {
  switch (workflow) {
    case 'fast-track':
      return ['quick-analysis', 'implement'];

    case 'standard':
      return ['proposal', 'design', 'tasks', 'implement'];

    case 'full-morph':
      return ['context', 'proposal', 'setup', 'uiux', 'design', 'clarify', 'tasks', 'implement', 'sync'];

    default:
      return ['context', 'proposal', 'setup', 'uiux', 'design', 'clarify', 'tasks', 'implement', 'sync'];
  }
}

/**
 * Get workflow description
 * @param {string} workflow - Workflow type
 * @returns {string} Human-readable description
 */
export function getWorkflowDescription(workflow) {
  switch (workflow) {
    case 'fast-track':
      return 'Fast Track: Quick fixes without formal spec (1 pause, no outputs)';

    case 'standard':
      return 'Standard: Medium complexity with simplified workflow (2-3 pauses, minimal outputs)';

    case 'full-morph':
      return 'Full MORPH: Complete 8-phase workflow with all outputs';

    default:
      return 'Unknown workflow';
  }
}
