/**
 * ${VOCAB.factory} RAG Knowledge Base
 * Phase 1: RAG-Augmented Routing System
 * 
 * This module stores code patterns, best practices, and routing intelligence
 * for the ${VOCAB.factory} code generation system.
 */

export interface KnowledgeEntry {
  id: string;
  category: 'pattern' | 'component' | 'architecture' | 'styling' | 'api' | 'database' | 'security' | 'testing';
  tags: string[];
  title: string;
  description: string;
  content: string;
  examples?: string[];
  relatedEntries?: string[];
  complexity: 'low' | 'medium' | 'high';
  preferredModel?: string;
}

export const CODE_PATTERNS: KnowledgeEntry[] = [
  // React/Next.js Patterns
  {
    id: 'react-server-component',
    category: 'pattern',
    tags: ['react', 'nextjs', 'server-component', 'rsc'],
    title: 'React Server Component Pattern',
    description: 'Server-side rendered components with no client-side JavaScript',
    content: `
// Server Components are the default in Next.js 13+
// They run on the server and can directly access databases

import { prisma } from '@/lib/db';

export default async function ServerComponent() {
  const data = await prisma.model.findMany();
  return <div>{data.map(item => <p key={item.id}>{item.name}</p>)}</div>;
}
    `,
    complexity: 'low',
    preferredModel: 'claude-sonnet-4.6'
  },
  {
    id: 'react-client-component',
    category: 'pattern',
    tags: ['react', 'nextjs', 'client-component', 'interactivity'],
    title: 'React Client Component Pattern',
    description: 'Interactive components with useState, useEffect, event handlers',
    content: `
'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';

export function ClientComponent() {
  const [data, setData] = useState([]);
  
  useEffect(() => {
    fetch('/api/data').then(r => r.json()).then(setData);
  }, []);
  
  return (
    <motion.div animate={{ opacity: 1 }}>
      {/* Interactive content */}
    </motion.div>
  );
}
    `,
    complexity: 'medium',
    preferredModel: 'claude-sonnet-4.6'
  },
  {
    id: 'api-route-pattern',
    category: 'api',
    tags: ['nextjs', 'api', 'route', 'rest'],
    title: 'Next.js API Route Pattern',
    description: 'Server-side API endpoints with proper error handling',
    content: `
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

export const dynamic = 'force-dynamic';

export async function GET(request: NextRequest) {
  try {
    const data = await prisma.model.findMany();
    return NextResponse.json(data);
  } catch (error) {
    console.error('API Error:', error);
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const created = await prisma.model.create({ data: body });
    return NextResponse.json(created, { status: 201 });
  } catch (error) {
    console.error('API Error:', error);
    return NextResponse.json({ error: 'Bad Request' }, { status: 400 });
  }
}
    `,
    complexity: 'medium',
    preferredModel: 'claude-sonnet-4.6'
  },
  {
    id: 'prisma-query-pattern',
    category: 'database',
    tags: ['prisma', 'database', 'query', 'orm'],
    title: 'Prisma Query Patterns',
    description: 'Common Prisma query patterns for CRUD operations',
    content: `
// Find with relations
const user = await prisma.user.findUnique({
  where: { id },
  include: { posts: true, profile: true }
});

// Upsert pattern
const result = await prisma.user.upsert({
  where: { email },
  update: { name },
  create: { email, name }
});

// Transaction
const [post, updateCount] = await prisma.$transaction([
  prisma.post.create({ data }),
  prisma.analytics.update({ where: { id: 1 }, data: { count: { increment: 1 } } })
]);
    `,
    complexity: 'medium',
    preferredModel: 'claude-sonnet-4.6'
  },
  {
    id: 'form-validation-pattern',
    category: 'pattern',
    tags: ['form', 'validation', 'zod', 'react-hook-form'],
    title: 'Form Validation with Zod',
    description: 'Type-safe form validation using Zod and react-hook-form',
    content: `
'use client';

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

const schema = z.object({
  email: z.string().email('Invalid email'),
  password: z.string().min(8, 'Password must be at least 8 characters'),
  name: z.string().min(2, 'Name required')
});

type FormData = z.infer<typeof schema>;

export function ValidatedForm() {
  const { register, handleSubmit, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(schema)
  });

  const onSubmit = (data: FormData) => {
    // Handle submission
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register('email')} />
      {errors.email && <span>{errors.email.message}</span>}
      {/* More fields */}
    </form>
  );
}
    `,
    complexity: 'medium',
    preferredModel: 'claude-sonnet-4.6'
  },
  {
    id: 'tailwind-glass-card',
    category: 'styling',
    tags: ['tailwind', 'css', 'glassmorphism', 'ui'],
    title: 'Glassmorphism Card Pattern',
    description: 'Modern glassmorphic card styling with Tailwind',
    content: `
// Tailwind glass card styling
<div className="glass-card p-6 bg-black/50 backdrop-blur-xl border border-white/10 rounded-xl shadow-lg">
  <h3 className="text-white font-semibold text-lg mb-2">Card Title</h3>
  <p className="text-gray-400">Card content with proper contrast</p>
</div>

// With gradient border
<div className="relative group">
  <div className="absolute inset-0 bg-gradient-to-r from-brand-deep to-brand-secondary rounded-xl blur opacity-25 group-hover:opacity-50 transition" />
  <div className="relative glass-card p-6 rounded-xl">
    Content here
  </div>
</div>
    `,
    complexity: 'low',
    preferredModel: 'claude-haiku-4.5'
  },
  {
    id: 'framer-motion-animation',
    category: 'pattern',
    tags: ['animation', 'framer-motion', 'react', 'ui'],
    title: 'Framer Motion Animation Patterns',
    description: 'Common animation patterns using Framer Motion',
    content: `
import { motion, AnimatePresence } from 'framer-motion';
import { useInView } from 'react-intersection-observer';

// Scroll-triggered animation
export function ScrollReveal({ children }) {
  const [ref, inView] = useInView({ triggerOnce: true, threshold: 0.1 });
  
  return (
    <motion.div
      ref={ref}
      initial={{ opacity: 0, y: 20 }}
      animate={inView ? { opacity: 1, y: 0 } : {}}
      transition={{ duration: 0.6 }}
    >
      {children}
    </motion.div>
  );
}

// Staggered list
const container = {
  hidden: { opacity: 0 },
  show: {
    opacity: 1,
    transition: { staggerChildren: 0.1 }
  }
};

const item = {
  hidden: { opacity: 0, x: -20 },
  show: { opacity: 1, x: 0 }
};
    `,
    complexity: 'medium',
    preferredModel: 'claude-sonnet-4.6'
  },
  {
    id: 'auth-session-pattern',
    category: 'security',
    tags: ['auth', 'nextauth', 'session', 'security'],
    title: 'NextAuth Session Pattern',
    description: 'Authentication and session management with NextAuth',
    content: `
// Server-side session check
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';

export default async function ProtectedPage() {
  const session = await getServerSession(authOptions);
  
  if (!session) {
    redirect('/login');
  }
  
  return <div>Welcome, {session.user.name}</div>;
}

// Client-side session hook
'use client';
import { useSession } from 'next-auth/react';
import { VOCAB } from '@/lib/white-label/constants';

export function UserMenu() {
  const { data: session, status } = useSession();
  
  if (status === 'loading') return <Skeleton />;
  if (!session) return <LoginButton />;
  
  return <Avatar user={session.user} />;
}
    `,
    complexity: 'high',
    preferredModel: 'claude-opus-4.6'
  },
  {
    id: 'error-boundary-pattern',
    category: 'pattern',
    tags: ['error', 'boundary', 'react', 'error-handling'],
    title: 'Error Boundary Pattern',
    description: 'React error boundaries for graceful error handling',
    content: `
// error.tsx - Next.js error boundary
'use client';

export default function Error({
  error,
  reset
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  return (
    <div className="flex flex-col items-center justify-center min-h-[400px]">
      <h2 className="text-2xl font-bold text-red-500 mb-4">Something went wrong</h2>
      <p className="text-gray-400 mb-6">{error.message}</p>
      <button onClick={reset} className="btn-primary">
        Try again
      </button>
    </div>
  );
}
    `,
    complexity: 'low',
    preferredModel: 'claude-haiku-4.5'
  },
  {
    id: 'complex-algorithm',
    category: 'pattern',
    tags: ['algorithm', 'logic', 'complex', 'reasoning'],
    title: 'Complex Algorithm Implementation',
    description: 'Multi-step algorithms requiring careful reasoning',
    content: 'Use o3/o4-mini for complex algorithmic problems that require step-by-step reasoning, mathematical proofs, or optimization problems.',
    complexity: 'high',
    preferredModel: 'o3'
  }
];

export const MODEL_CAPABILITIES: Record<string, {
  strengths: string[];
  weaknesses: string[];
  costTier: 'low' | 'medium' | 'high';
  speed: 'fast' | 'medium' | 'slow';
  contextWindow: number;
}> = {
  'claude-sonnet-4.6': {
    strengths: ['code generation', 'refactoring', 'documentation', 'balanced performance'],
    weaknesses: ['very complex algorithms'],
    costTier: 'medium',
    speed: 'medium',
    contextWindow: 200000
  },
  'claude-opus-4.6': {
    strengths: ['complex architecture', 'security review', 'nuanced decisions', 'multi-file changes'],
    weaknesses: ['simple tasks (overkill)'],
    costTier: 'high',
    speed: 'slow',
    contextWindow: 200000
  },
  'claude-haiku-4.5': {
    strengths: ['quick edits', 'simple components', 'styling', 'boilerplate'],
    weaknesses: ['complex logic', 'large codebase understanding'],
    costTier: 'low',
    speed: 'fast',
    contextWindow: 200000
  },
  'o3': {
    strengths: ['complex algorithms', 'mathematical reasoning', 'step-by-step logic'],
    weaknesses: ['simple tasks', 'cost'],
    costTier: 'high',
    speed: 'slow',
    contextWindow: 128000
  },
  'o4-mini': {
    strengths: ['algorithms', 'reasoning', 'balanced cost'],
    weaknesses: ['creative writing'],
    costTier: 'medium',
    speed: 'medium',
    contextWindow: 128000
  },
  'deepseek-v3.1': {
    strengths: ['code generation', 'long context', 'cost-effective'],
    weaknesses: ['complex architecture'],
    costTier: 'low',
    speed: 'fast',
    contextWindow: 64000
  },
  'gpt-4.1': {
    strengths: ['general purpose', 'instruction following', 'versatile'],
    weaknesses: ['specialized tasks'],
    costTier: 'medium',
    speed: 'medium',
    contextWindow: 128000
  },
  'gemini-2.5-pro': {
    strengths: ['multi-modal', 'long context', 'analysis'],
    weaknesses: ['code specificity'],
    costTier: 'medium',
    speed: 'medium',
    contextWindow: 1000000
  }
};

/**
 * Search the knowledge base for relevant entries
 */
export function searchKnowledgeBase(
  query: string,
  filters?: { category?: string; tags?: string[]; maxComplexity?: string }
): KnowledgeEntry[] {
  const queryLower = query.toLowerCase();
  const queryTerms = queryLower.split(/\s+/);
  
  return CODE_PATTERNS.filter(entry => {
    // Apply filters
    if (filters?.category && entry.category !== filters.category) return false;
    if (filters?.tags && !filters.tags.some(tag => entry.tags.includes(tag))) return false;
    if (filters?.maxComplexity) {
      const complexityOrder = ['low', 'medium', 'high'];
      if (complexityOrder.indexOf(entry.complexity) > complexityOrder.indexOf(filters.maxComplexity)) {
        return false;
      }
    }
    
    // Search in title, description, tags, content
    const searchableText = [
      entry.title,
      entry.description,
      ...entry.tags,
      entry.content
    ].join(' ').toLowerCase();
    
    // Check if any query term matches
    return queryTerms.some(term => searchableText.includes(term));
  }).sort((a, b) => {
    // Prioritize by relevance (title matches > tag matches > content matches)
    const aScore = queryTerms.filter(t => a.title.toLowerCase().includes(t)).length * 3 +
                   queryTerms.filter(t => a.tags.some(tag => tag.includes(t))).length * 2 +
                   queryTerms.filter(t => a.content.toLowerCase().includes(t)).length;
    const bScore = queryTerms.filter(t => b.title.toLowerCase().includes(t)).length * 3 +
                   queryTerms.filter(t => b.tags.some(tag => tag.includes(t))).length * 2 +
                   queryTerms.filter(t => b.content.toLowerCase().includes(t)).length;
    return bScore - aScore;
  });
}
