/**
 * ${VOCAB.factory} Prompt Analyzer
 * Phase 1: RAG-Augmented Routing System
 * 
 * Analyzes user prompts to determine:
 * - Task type (create, edit, debug, explain, optimize)
 * - Complexity level (low, medium, high)
 * - Domain (frontend, backend, database, infrastructure)
 * - Required patterns from knowledge base
 */

import { searchKnowledgeBase, KnowledgeEntry, MODEL_CAPABILITIES } from './knowledge-base';
import { VOCAB } from '@/lib/white-label/constants';

export interface PromptAnalysis {
  taskType: 'create' | 'edit' | 'debug' | 'explain' | 'optimize' | 'refactor' | 'test';
  complexity: 'low' | 'medium' | 'high';
  domain: ('frontend' | 'backend' | 'database' | 'infrastructure' | 'styling' | 'security')[];
  detectedPatterns: string[];
  suggestedModel: string;
  confidence: number;
  relevantKnowledge: KnowledgeEntry[];
  estimatedTokens: number;
  reasoning: string;
}

const TASK_INDICATORS: Record<string, string[]> = {
  create: ['create', 'build', 'make', 'generate', 'add', 'implement', 'new', 'write'],
  edit: ['edit', 'modify', 'change', 'update', 'adjust', 'tweak'],
  debug: ['fix', 'debug', 'error', 'bug', 'issue', 'problem', 'broken', 'not working', 'failing'],
  explain: ['explain', 'why', 'how does', 'what is', 'understand', 'describe'],
  optimize: ['optimize', 'improve', 'faster', 'performance', 'speed up', 'efficient'],
  refactor: ['refactor', 'clean up', 'reorganize', 'restructure', 'simplify'],
  test: ['test', 'unit test', 'e2e', 'testing', 'coverage', 'spec']
};

const DOMAIN_INDICATORS: Record<string, string[]> = {
  frontend: ['component', 'page', 'ui', 'button', 'form', 'modal', 'layout', 'react', 'nextjs', 'client'],
  backend: ['api', 'endpoint', 'route', 'server', 'handler', 'middleware', 'webhook'],
  database: ['database', 'prisma', 'query', 'schema', 'model', 'migration', 'seed', 'sql'],
  infrastructure: ['deploy', 'docker', 'env', 'config', 'ci/cd', 'build', 'production'],
  styling: ['css', 'style', 'tailwind', 'design', 'color', 'animation', 'responsive', 'dark mode'],
  security: ['auth', 'authentication', 'authorization', 'session', 'token', 'password', 'encrypt', 'secure']
};

const COMPLEXITY_INDICATORS = {
  high: [
    'complex', 'advanced', 'multi', 'entire', 'full', 'complete system',
    'architecture', 'integration', 'migration', 'real-time', 'websocket',
    'algorithm', 'optimize across', 'scale', 'enterprise'
  ],
  medium: [
    'with validation', 'with error handling', 'connected to', 'using prisma',
    'authenticated', 'paginated', 'searchable', 'filterable', 'sortable'
  ],
  low: [
    'simple', 'basic', 'quick', 'small', 'just', 'only', 'single', 'static'
  ]
};

/**
 * Analyze a user prompt and determine routing information
 */
export function analyzePrompt(prompt: string): PromptAnalysis {
  const promptLower = prompt.toLowerCase();
  
  // Detect task type
  const taskType = detectTaskType(promptLower);
  
  // Detect domains
  const domain = detectDomains(promptLower);
  
  // Detect complexity
  const complexity = detectComplexity(promptLower, domain);
  
  // Detect patterns
  const detectedPatterns = detectPatterns(promptLower);
  
  // Search knowledge base
  const relevantKnowledge = searchKnowledgeBase(prompt, {
    tags: detectedPatterns.slice(0, 3) // Use top 3 patterns as filters
  }).slice(0, 5); // Get top 5 results
  
  // Estimate tokens
  const estimatedTokens = estimateTokens(prompt, relevantKnowledge);
  
  // Select model
  const { model, confidence, reasoning } = selectModel(taskType, complexity, domain, estimatedTokens);
  
  return {
    taskType,
    complexity,
    domain,
    detectedPatterns,
    suggestedModel: model,
    confidence,
    relevantKnowledge,
    estimatedTokens,
    reasoning
  };
}

function detectTaskType(prompt: string): PromptAnalysis['taskType'] {
  for (const [type, indicators] of Object.entries(TASK_INDICATORS)) {
    if (indicators.some(ind => prompt.includes(ind))) {
      return type as PromptAnalysis['taskType'];
    }
  }
  return 'create'; // Default to create
}

function detectDomains(prompt: string): PromptAnalysis['domain'] {
  const domains: PromptAnalysis['domain'] = [];
  
  for (const [domain, indicators] of Object.entries(DOMAIN_INDICATORS)) {
    if (indicators.some(ind => prompt.includes(ind))) {
      domains.push(domain as PromptAnalysis['domain'][number]);
    }
  }
  
  return domains.length > 0 ? domains : ['frontend']; // Default to frontend
}

function detectComplexity(prompt: string, domains: string[]): PromptAnalysis['complexity'] {
  // Check high complexity indicators
  if (COMPLEXITY_INDICATORS.high.some(ind => prompt.includes(ind))) {
    return 'high';
  }
  
  // Check low complexity indicators
  if (COMPLEXITY_INDICATORS.low.some(ind => prompt.includes(ind))) {
    return 'low';
  }
  
  // Multi-domain tasks are usually medium+
  if (domains.length >= 3) {
    return 'high';
  }
  
  if (domains.length >= 2 || COMPLEXITY_INDICATORS.medium.some(ind => prompt.includes(ind))) {
    return 'medium';
  }
  
  return 'medium'; // Default to medium
}

function detectPatterns(prompt: string): string[] {
  const patterns: string[] = [];
  
  // Pattern detection based on keywords
  const patternMap: Record<string, string[]> = {
    'react': ['component', 'react', 'jsx', 'tsx'],
    'nextjs': ['next', 'page', 'app router', 'server component'],
    'api': ['api', 'endpoint', 'route', 'rest'],
    'prisma': ['prisma', 'database', 'model', 'query'],
    'form': ['form', 'input', 'validation', 'submit'],
    'auth': ['auth', 'login', 'session', 'protected'],
    'animation': ['animation', 'animate', 'motion', 'transition'],
    'tailwind': ['tailwind', 'css', 'style', 'class']
  };
  
  for (const [pattern, keywords] of Object.entries(patternMap)) {
    if (keywords.some(kw => prompt.includes(kw))) {
      patterns.push(pattern);
    }
  }
  
  return patterns;
}

function estimateTokens(prompt: string, knowledge: KnowledgeEntry[]): number {
  // Base: prompt tokens (rough estimate: 4 chars per token)
  let tokens = Math.ceil(prompt.length / 4);
  
  // Add knowledge context
  for (const entry of knowledge) {
    tokens += Math.ceil(entry.content.length / 4);
  }
  
  // Response estimate (usually 2-4x input for code generation)
  tokens *= 3;
  
  return tokens;
}

function selectModel(
  taskType: string,
  complexity: string,
  domains: string[],
  estimatedTokens: number
): { model: string; confidence: number; reasoning: string } {
  let reasoning: string[] = [];
  
  // Security tasks always get Opus
  if (domains.includes('security') && (taskType === 'create' || taskType === 'refactor')) {
    return {
      model: 'claude-opus-4.6',
      confidence: 0.95,
      reasoning: 'Security-critical task requires careful review - using Opus for maximum accuracy'
    };
  }
  
  // Complex algorithmic tasks get o3/o4-mini
  if (complexity === 'high' && taskType === 'optimize') {
    reasoning.push('High complexity optimization task');
    return {
      model: 'o4-mini',
      confidence: 0.85,
      reasoning: 'Complex optimization requiring step-by-step reasoning'
    };
  }
  
  // Simple styling/UI tasks get Haiku
  if (complexity === 'low' && (domains.includes('styling') || domains.length === 1 && domains[0] === 'frontend')) {
    reasoning.push('Simple UI/styling task');
    return {
      model: 'claude-haiku-4.5',
      confidence: 0.9,
      reasoning: 'Simple frontend task - using fast, cost-effective Haiku'
    };
  }
  
  // Debug tasks benefit from reasoning models
  if (taskType === 'debug' && complexity !== 'low') {
    return {
      model: 'claude-sonnet-4.6',
      confidence: 0.88,
      reasoning: 'Debugging requires understanding context and tracing issues - using Sonnet'
    };
  }
  
  // Multi-domain or high complexity
  if (domains.length >= 3 || complexity === 'high') {
    reasoning.push('Multi-domain or high complexity task');
    return {
      model: 'claude-opus-4.6',
      confidence: 0.9,
      reasoning: 'Complex multi-domain task requiring architectural understanding'
    };
  }
  
  // Large context requirements
  if (estimatedTokens > 50000) {
    return {
      model: 'gemini-2.5-pro',
      confidence: 0.82,
      reasoning: 'Large context window needed for extensive code generation'
    };
  }
  
  // Default: Sonnet for balanced performance
  return {
    model: 'claude-sonnet-4.6',
    confidence: 0.85,
    reasoning: 'Standard code generation task - using balanced Sonnet model'
  };
}

/**
 * Get a brief summary of the analysis for logging/display
 */
export function summarizeAnalysis(analysis: PromptAnalysis): string {
  return `[${analysis.taskType.toUpperCase()}] ${analysis.complexity} complexity | ` +
         `Domains: ${analysis.domain.join(', ')} | ` +
         `Model: ${analysis.suggestedModel} (${Math.round(analysis.confidence * 100)}% confidence) | ` +
         `~${analysis.estimatedTokens} tokens`;
}
