> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mixus.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Code Generation

> Generate, review, and optimize code with AI assistance across multiple programming languages and frameworks

Accelerate your development workflow with AI-powered code generation. From writing functions and classes to complete applications, mixus helps you code faster, smarter, and more efficiently across dozens of programming languages and frameworks.

## Overview

Code generation in mixus combines advanced AI models with deep understanding of programming languages, frameworks, and best practices. Whether you're prototyping a new feature, solving a complex algorithm, or building an entire application, mixus provides intelligent code assistance that understands context, follows conventions, and produces production-ready code.

## Supported Languages and Frameworks

### Programming Languages

#### Fully Supported Languages

Languages with comprehensive generation capabilities:

```text Primary Language Support theme={null}
🔥 Tier 1 Languages (Advanced AI Models):
├── 🐍 Python: Frameworks, data science, web development
├── 💻 JavaScript/TypeScript: Frontend, backend, full-stack
├── ☕ Java: Enterprise, Spring, Android development
├── 🌐 Go: Microservices, system programming, cloud native
├── 🦀 Rust: System programming, WebAssembly, performance
├── 🚀 C#: .NET, Unity, enterprise applications
├── 🏃 Swift: iOS, macOS, server-side development
└── 💎 Ruby: Rails, web development, automation

🔧 Tier 2 Languages (Strong Support):
├── 🌊 C++: High-performance, embedded, gaming
├── 📱 Kotlin: Android, multiplatform development
├── 🐘 PHP: Web development, CMS, e-commerce
├── 🔍 Scala: Big data, functional programming
├── ⚡ Dart: Flutter, mobile development
├── 🎯 R: Data analysis, statistics, visualization
└── 🔬 MATLAB: Scientific computing, engineering
```

#### Framework Expertise

Deep integration with popular frameworks and libraries:

```json Framework Support Matrix theme={null}
{
  "web_frameworks": {
    "frontend": {
      "react": "advanced",
      "vue": "advanced", 
      "angular": "advanced",
      "svelte": "intermediate",
      "next_js": "advanced",
      "nuxt": "intermediate"
    },
    "backend": {
      "express": "advanced",
      "django": "advanced",
      "flask": "advanced",
      "spring_boot": "advanced",
      "rails": "advanced",
      "laravel": "intermediate"
    }
  },
  "mobile_frameworks": {
    "react_native": "advanced",
    "flutter": "advanced",
    "ionic": "intermediate",
    "xamarin": "intermediate"
  },
  "data_science": {
    "pandas": "advanced",
    "numpy": "advanced", 
    "tensorflow": "advanced",
    "pytorch": "advanced",
    "scikit_learn": "advanced"
  },
  "cloud_platforms": {
    "aws": "advanced",
    "gcp": "advanced",
    "azure": "advanced",
    "kubernetes": "intermediate"
  }
}
```

### Code Generation Types

#### Function and Method Generation

Create functions with proper signatures, documentation, and error handling:

```python Function Generation Example theme={null}
# Input: "Create a function to validate email addresses with regex"

import re
from typing import bool

def validate_email(email: str) -> bool:
    """
    Validates an email address using regex pattern.
    
    Args:
        email (str): The email address to validate
        
    Returns:
        bool: True if email is valid, False otherwise
        
    Examples:
        >>> validate_email("user@example.com")
        True
        >>> validate_email("invalid-email")
        False
    """
    if not email or not isinstance(email, str):
        return False
    
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email.strip()))

# Additional utility function for batch validation
def validate_emails(emails: list[str]) -> dict[str, bool]:
    """Validate multiple email addresses at once."""
    return {email: validate_email(email) for email in emails}
```

#### Class and Object Generation

Generate complete classes with methods, properties, and inheritance:

```typescript Class Generation Example theme={null}
// Input: "Create a TypeScript class for a shopping cart with items and calculations"

interface CartItem {
  id: string;
  name: string;
  price: number;
  quantity: number;
  discount?: number;
}

interface CartTotals {
  subtotal: number;
  tax: number;
  discount: number;
  total: number;
}

class ShoppingCart {
  private items: Map<string, CartItem> = new Map();
  private taxRate: number = 0.08; // 8% default tax rate

  constructor(taxRate?: number) {
    if (taxRate !== undefined) {
      this.taxRate = taxRate;
    }
  }

  /**
   * Add an item to the cart or update quantity if it exists
   */
  addItem(item: Omit<CartItem, 'quantity'>, quantity: number = 1): void {
    const existingItem = this.items.get(item.id);
    
    if (existingItem) {
      existingItem.quantity += quantity;
    } else {
      this.items.set(item.id, { ...item, quantity });
    }
  }

  /**
   * Remove an item from the cart
   */
  removeItem(itemId: string): boolean {
    return this.items.delete(itemId);
  }

  /**
   * Update the quantity of an item
   */
  updateQuantity(itemId: string, quantity: number): void {
    if (quantity <= 0) {
      this.removeItem(itemId);
      return;
    }

    const item = this.items.get(itemId);
    if (item) {
      item.quantity = quantity;
    }
  }

  /**
   * Calculate cart totals including tax and discounts
   */
  calculateTotals(): CartTotals {
    let subtotal = 0;
    let totalDiscount = 0;

    for (const item of this.items.values()) {
      const itemTotal = item.price * item.quantity;
      subtotal += itemTotal;
      
      if (item.discount) {
        totalDiscount += itemTotal * (item.discount / 100);
      }
    }

    const discountedSubtotal = subtotal - totalDiscount;
    const tax = discountedSubtotal * this.taxRate;
    const total = discountedSubtotal + tax;

    return {
      subtotal,
      tax,
      discount: totalDiscount,
      total
    };
  }

  /**
   * Get all items in the cart
   */
  getItems(): CartItem[] {
    return Array.from(this.items.values());
  }

  /**
   * Clear all items from the cart
   */
  clear(): void {
    this.items.clear();
  }

  /**
   * Get the number of unique items in the cart
   */
  getItemCount(): number {
    return this.items.size;
  }

  /**
   * Get the total quantity of all items
   */
  getTotalQuantity(): number {
    return Array.from(this.items.values())
      .reduce((total, item) => total + item.quantity, 0);
  }
}

export { ShoppingCart, type CartItem, type CartTotals };
```

#### API and Endpoint Generation

Create RESTful APIs with proper routing, validation, and error handling:

```javascript API Generation Example theme={null}
// Input: "Create a Node.js Express API for user management with CRUD operations"

const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { body, param, validationResult } = require('express-validator');
const rateLimit = require('express-rate-limit');

const router = express.Router();

// Rate limiting
const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests per windowMs
  message: 'Too many requests from this IP, please try again later.'
});

router.use(apiLimiter);

// Validation middleware
const validateUser = [
  body('email').isEmail().normalizeEmail(),
  body('password').isLength({ min: 8 }).matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/),
  body('firstName').trim().isLength({ min: 1 }),
  body('lastName').trim().isLength({ min: 1 }),
  body('role').optional().isIn(['user', 'admin'])
];

const validateUserUpdate = [
  body('email').optional().isEmail().normalizeEmail(),
  body('firstName').optional().trim().isLength({ min: 1 }),
  body('lastName').optional().trim().isLength({ min: 1 }),
  body('role').optional().isIn(['user', 'admin'])
];

const validateId = [
  param('id').isMongoId()
];

// Error handling middleware
const handleValidationErrors = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({
      success: false,
      message: 'Validation errors',
      errors: errors.array()
    });
  }
  next();
};

// Authentication middleware
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({
      success: false,
      message: 'Access token required'
    });
  }

  jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
    if (err) {
      return res.status(403).json({
        success: false,
        message: 'Invalid or expired token'
      });
    }
    req.user = user;
    next();
  });
};

// Routes

/**
 * GET /users
 * Get all users with pagination
 */
router.get('/users', authenticateToken, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const skip = (page - 1) * limit;

    const users = await User.find({}, '-password')
      .skip(skip)
      .limit(limit)
      .sort({ createdAt: -1 });

    const total = await User.countDocuments();

    res.json({
      success: true,
      data: {
        users,
        pagination: {
          current: page,
          pages: Math.ceil(total / limit),
          total
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: 'Error fetching users',
      error: error.message
    });
  }
});

/**
 * GET /users/:id
 * Get a specific user by ID
 */
router.get('/users/:id', 
  validateId, 
  handleValidationErrors, 
  authenticateToken, 
  async (req, res) => {
    try {
      const user = await User.findById(req.params.id, '-password');
      
      if (!user) {
        return res.status(404).json({
          success: false,
          message: 'User not found'
        });
      }

      res.json({
        success: true,
        data: user
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: 'Error fetching user',
        error: error.message
      });
    }
  }
);

/**
 * POST /users
 * Create a new user
 */
router.post('/users', 
  validateUser, 
  handleValidationErrors, 
  async (req, res) => {
    try {
      const { email, password, firstName, lastName, role = 'user' } = req.body;

      // Check if user already exists
      const existingUser = await User.findOne({ email });
      if (existingUser) {
        return res.status(409).json({
          success: false,
          message: 'User with this email already exists'
        });
      }

      // Hash password
      const saltRounds = 12;
      const hashedPassword = await bcrypt.hash(password, saltRounds);

      // Create user
      const user = new User({
        email,
        password: hashedPassword,
        firstName,
        lastName,
        role
      });

      await user.save();

      // Remove password from response
      const userResponse = user.toObject();
      delete userResponse.password;

      res.status(201).json({
        success: true,
        message: 'User created successfully',
        data: userResponse
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: 'Error creating user',
        error: error.message
      });
    }
  }
);

/**
 * PUT /users/:id
 * Update a user
 */
router.put('/users/:id',
  validateId,
  validateUserUpdate,
  handleValidationErrors,
  authenticateToken,
  async (req, res) => {
    try {
      const updates = req.body;
      
      // Remove password from updates (use separate endpoint for password changes)
      delete updates.password;

      const user = await User.findByIdAndUpdate(
        req.params.id,
        updates,
        { new: true, runValidators: true }
      ).select('-password');

      if (!user) {
        return res.status(404).json({
          success: false,
          message: 'User not found'
        });
      }

      res.json({
        success: true,
        message: 'User updated successfully',
        data: user
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: 'Error updating user',
        error: error.message
      });
    }
  }
);

/**
 * DELETE /users/:id
 * Delete a user
 */
router.delete('/users/:id',
  validateId,
  handleValidationErrors,
  authenticateToken,
  async (req, res) => {
    try {
      const user = await User.findByIdAndDelete(req.params.id);

      if (!user) {
        return res.status(404).json({
          success: false,
          message: 'User not found'
        });
      }

      res.json({
        success: true,
        message: 'User deleted successfully'
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: 'Error deleting user',
        error: error.message
      });
    }
  }
);

module.exports = router;
```

## Advanced Code Generation Features

### Context-Aware Generation

#### Project Structure Analysis

AI analyzes your existing codebase to maintain consistency:

```text Project Analysis Process theme={null}
🔍 Codebase Analysis:
├── 📁 File Structure: Understanding project organization
├── 🎨 Code Style: Detecting formatting and naming conventions
├── 📦 Dependencies: Analyzing imported libraries and frameworks
├── 🏗️ Architecture: Identifying design patterns and structure
├── 🔧 Configuration: Reading build tools and environment setup
└── 📝 Documentation: Understanding existing comments and docs

🎯 Generation Adaptation:
├── ✅ Match existing naming conventions
├── ✅ Follow established patterns and architecture
├── ✅ Use compatible dependencies and versions
├── ✅ Maintain consistent code style
├── ✅ Generate appropriate documentation
└── ✅ Respect project-specific constraints
```

#### Smart Imports and Dependencies

Automatic management of imports and package dependencies:

```python Smart Import Management theme={null}
# AI automatically analyzes and includes necessary imports

# Before generation - AI detects project uses:
# - FastAPI for web framework
# - Pydantic for data validation
# - SQLAlchemy for database
# - Custom models in ./models directory

from typing import List, Optional
from datetime import datetime
from fastapi import APIRouter, HTTPException, Depends, status
from pydantic import BaseModel, Field, validator
from sqlalchemy.orm import Session

# AI detects custom imports from project structure
from ..database import get_db
from ..models.user import User
from ..schemas.user import UserCreate, UserUpdate, UserResponse
from ..utils.auth import get_current_user, verify_password, hash_password

router = APIRouter(prefix="/users", tags=["users"])

# Generated code follows project patterns...
```

### Code Optimization

#### Performance Optimization

AI generates efficient, optimized code with performance considerations:

```python Performance-Optimized Code Generation theme={null}
# Input: "Create a function to find common elements in multiple large lists"

from typing import List, Set, TypeVar
from collections import Counter

T = TypeVar('T')

def find_common_elements_optimized(lists: List[List[T]], min_occurrences: int = None) -> List[T]:
    """
    Find common elements across multiple lists with optimal performance.
    
    Time Complexity: O(n * m) where n is total elements, m is number of lists
    Space Complexity: O(k) where k is unique elements
    
    Args:
        lists: List of lists to find common elements in
        min_occurrences: Minimum number of lists an element must appear in
                        (defaults to all lists)
    
    Returns:
        List of elements that appear in at least min_occurrences lists
    """
    if not lists:
        return []
    
    if min_occurrences is None:
        min_occurrences = len(lists)
    
    # Early return for single list
    if len(lists) == 1:
        return lists[0] if min_occurrences <= 1 else []
    
    # Convert to sets for O(1) lookup and remove duplicates
    sets = [set(lst) for lst in lists]
    
    # Start with the smallest set to minimize iterations
    smallest_set = min(sets, key=len)
    
    # Count occurrences across all sets
    element_counts = Counter()
    for element in smallest_set:
        count = sum(1 for s in sets if element in s)
        if count >= min_occurrences:
            element_counts[element] = count
    
    # Return elements sorted by frequency (most common first)
    return [element for element, count in element_counts.most_common()]

# Alternative implementation for very large datasets
def find_common_elements_memory_efficient(
    lists: List[List[T]], 
    min_occurrences: int = None
) -> List[T]:
    """Memory-efficient version using generators for large datasets."""
    if not lists or (min_occurrences and min_occurrences > len(lists)):
        return []
    
    if min_occurrences is None:
        min_occurrences = len(lists)
    
    # Use first list as base, convert others to sets for fast lookup
    base_list = lists[0]
    other_sets = [set(lst) for lst in lists[1:]]
    
    common_elements = []
    for element in base_list:
        # Count in how many lists this element appears
        count = 1 + sum(1 for s in other_sets if element in s)
        
        if count >= min_occurrences and element not in common_elements:
            common_elements.append(element)
    
    return common_elements
```

#### Security-First Code Generation

AI automatically includes security best practices:

```javascript Security-Aware Code Generation theme={null}
// Input: "Create a user authentication system with login and registration"

const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');
const validator = require('validator');
const csrf = require('csurf');

const router = express.Router();

// Security middleware
router.use(helmet()); // Set security headers
router.use(csrf()); // CSRF protection

// Rate limiting for auth endpoints
const authLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 5, // limit each IP to 5 requests per windowMs for auth
  message: {
    error: 'Too many authentication attempts, please try again later.',
    retryAfter: '15 minutes'
  },
  standardHeaders: true,
  legacyHeaders: false,
});

// Input validation and sanitization
const validateRegistration = (req, res, next) => {
  const { email, password, firstName, lastName } = req.body;
  const errors = [];

  // Email validation
  if (!email || !validator.isEmail(email)) {
    errors.push('Valid email address is required');
  }

  // Password strength validation
  if (!password || password.length < 8) {
    errors.push('Password must be at least 8 characters long');
  }
  
  if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/.test(password)) {
    errors.push('Password must contain uppercase, lowercase, number, and special character');
  }

  // Name validation
  if (!firstName || !validator.isAlpha(firstName.replace(/\s/g, ''))) {
    errors.push('Valid first name is required');
  }
  
  if (!lastName || !validator.isAlpha(lastName.replace(/\s/g, ''))) {
    errors.push('Valid last name is required');
  }

  if (errors.length > 0) {
    return res.status(400).json({
      success: false,
      message: 'Validation failed',
      errors
    });
  }

  // Sanitize inputs
  req.body.email = validator.normalizeEmail(email);
  req.body.firstName = validator.escape(firstName.trim());
  req.body.lastName = validator.escape(lastName.trim());

  next();
};

// Secure password hashing with timing attack protection
const hashPassword = async (password) => {
  const saltRounds = 12; // High cost factor
  return await bcrypt.hash(password, saltRounds);
};

// Secure password comparison with timing attack protection
const comparePassword = async (password, hash) => {
  return await bcrypt.compare(password, hash);
};

// Generate secure JWT tokens
const generateTokens = (userId) => {
  const accessToken = jwt.sign(
    { userId, type: 'access' },
    process.env.JWT_ACCESS_SECRET,
    { 
      expiresIn: '15m',
      issuer: 'mixus-app',
      audience: 'mixus-users'
    }
  );

  const refreshToken = jwt.sign(
    { userId, type: 'refresh' },
    process.env.JWT_REFRESH_SECRET,
    { 
      expiresIn: '7d',
      issuer: 'mixus-app',
      audience: 'mixus-users'
    }
  );

  return { accessToken, refreshToken };
};

/**
 * POST /register
 * Secure user registration with comprehensive validation
 */
router.post('/register', authLimiter, validateRegistration, async (req, res) => {
  try {
    const { email, password, firstName, lastName } = req.body;

    // Check if user already exists (prevent email enumeration)
    const existingUser = await User.findOne({ email });
    if (existingUser) {
      // Use same response time to prevent timing attacks
      await new Promise(resolve => setTimeout(resolve, 100));
      return res.status(409).json({
        success: false,
        message: 'Registration failed. Please try again.'
      });
    }

    // Hash password securely
    const hashedPassword = await hashPassword(password);

    // Create user with secure defaults
    const user = new User({
      email,
      password: hashedPassword,
      firstName,
      lastName,
      role: 'user', // Default role
      isEmailVerified: false,
      loginAttempts: 0,
      accountLocked: false,
      createdAt: new Date(),
      lastLoginAt: null
    });

    await user.save();

    // Generate email verification token
    const verificationToken = jwt.sign(
      { userId: user._id, email: user.email },
      process.env.EMAIL_VERIFICATION_SECRET,
      { expiresIn: '24h' }
    );

    // Send verification email (implement email service)
    // await emailService.sendVerificationEmail(email, verificationToken);

    // Log security event
    console.log(`New user registration: ${email} from IP: ${req.ip}`);

    res.status(201).json({
      success: true,
      message: 'Registration successful. Please check your email for verification.',
      data: {
        userId: user._id,
        email: user.email,
        requiresEmailVerification: true
      }
    });

  } catch (error) {
    console.error('Registration error:', error);
    res.status(500).json({
      success: false,
      message: 'Registration failed. Please try again.'
    });
  }
});

/**
 * POST /login
 * Secure user authentication with brute force protection
 */
router.post('/login', authLimiter, async (req, res) => {
  try {
    const { email, password } = req.body;

    // Input validation
    if (!email || !password) {
      return res.status(400).json({
        success: false,
        message: 'Email and password are required'
      });
    }

    // Find user with secure lookup
    const user = await User.findOne({ 
      email: validator.normalizeEmail(email) 
    });

    // Consistent timing to prevent user enumeration
    const isValidPassword = user ? 
      await comparePassword(password, user.password) : 
      await bcrypt.compare(password, '$2b$12$invalidhash'); // Dummy hash

    if (!user || !isValidPassword) {
      // Log failed attempt
      if (user) {
        user.loginAttempts = (user.loginAttempts || 0) + 1;
        user.lastFailedLogin = new Date();
        
        // Lock account after 5 failed attempts
        if (user.loginAttempts >= 5) {
          user.accountLocked = true;
          user.lockUntil = new Date(Date.now() + 30 * 60 * 1000); // 30 minutes
        }
        
        await user.save();
      }

      return res.status(401).json({
        success: false,
        message: 'Invalid credentials'
      });
    }

    // Check if account is locked
    if (user.accountLocked && user.lockUntil > new Date()) {
      return res.status(423).json({
        success: false,
        message: 'Account temporarily locked. Please try again later.',
        lockUntil: user.lockUntil
      });
    }

    // Check email verification
    if (!user.isEmailVerified) {
      return res.status(403).json({
        success: false,
        message: 'Please verify your email address before logging in.'
      });
    }

    // Successful login - reset failed attempts and update login info
    user.loginAttempts = 0;
    user.accountLocked = false;
    user.lockUntil = null;
    user.lastLoginAt = new Date();
    user.lastLoginIP = req.ip;
    await user.save();

    // Generate secure tokens
    const { accessToken, refreshToken } = generateTokens(user._id);

    // Set secure HTTP-only cookie for refresh token
    res.cookie('refreshToken', refreshToken, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'strict',
      maxAge: 7 * 24 * 60 * 60 * 1000 // 7 days
    });

    // Log successful login
    console.log(`Successful login: ${email} from IP: ${req.ip}`);

    res.json({
      success: true,
      message: 'Login successful',
      data: {
        accessToken,
        user: {
          id: user._id,
          email: user.email,
          firstName: user.firstName,
          lastName: user.lastName,
          role: user.role
        }
      }
    });

  } catch (error) {
    console.error('Login error:', error);
    res.status(500).json({
      success: false,
      message: 'Login failed. Please try again.'
    });
  }
});

module.exports = router;
```

## Code Quality and Standards

### Automated Code Review

#### Code Quality Checks

AI performs comprehensive code quality analysis:

```text Automated Code Review Features theme={null}
🔍 Code Quality Analysis:
├── 📏 Complexity Analysis
│   ├── Cyclomatic complexity measurement
│   ├── Nesting depth analysis
│   ├── Function length assessment
│   └── Class size evaluation
├── 🎨 Style Consistency
│   ├── Naming convention compliance
│   ├── Formatting and indentation
│   ├── Comment quality and placement
│   └── Import organization
├── 🔒 Security Scanning
│   ├── Common vulnerability patterns
│   ├── Input validation checks
│   ├── Authentication/authorization flaws
│   └── Data exposure risks
├── 🚀 Performance Analysis
│   ├── Algorithmic efficiency
│   ├── Memory usage patterns
│   ├── Database query optimization
│   └── Caching opportunities
└── 📝 Documentation Review
    ├── Function/method documentation
    ├── Type annotation completeness
    ├── Usage example accuracy
    └── API documentation consistency
```

#### Best Practice Enforcement

Automatic application of industry standards and best practices:

```python Best Practice Code Generation theme={null}
# AI automatically applies Python best practices

from typing import Optional, List, Dict, Any
from dataclasses import dataclass
from abc import ABC, abstractmethod
import logging
from datetime import datetime

# Configure logging with best practices
logger = logging.getLogger(__name__)

@dataclass
class User:
    """User data class with proper type hints and validation."""
    id: int
    email: str
    first_name: str
    last_name: str
    created_at: datetime
    is_active: bool = True
    metadata: Optional[Dict[str, Any]] = None
    
    def __post_init__(self) -> None:
        """Validate user data after initialization."""
        if not self.email or '@' not in self.email:
            raise ValueError("Invalid email address")
        
        if not self.first_name.strip():
            raise ValueError("First name cannot be empty")
            
        if not self.last_name.strip():
            raise ValueError("Last name cannot be empty")

class UserRepository(ABC):
    """Abstract base class defining user repository interface."""
    
    @abstractmethod
    async def create_user(self, user_data: Dict[str, Any]) -> User:
        """Create a new user."""
        pass
    
    @abstractmethod
    async def get_user_by_id(self, user_id: int) -> Optional[User]:
        """Retrieve user by ID."""
        pass
    
    @abstractmethod
    async def update_user(self, user_id: int, updates: Dict[str, Any]) -> Optional[User]:
        """Update user information."""
        pass
    
    @abstractmethod
    async def delete_user(self, user_id: int) -> bool:
        """Delete user by ID."""
        pass

class DatabaseUserRepository(UserRepository):
    """Database implementation of user repository."""
    
    def __init__(self, db_connection: Any) -> None:
        self.db = db_connection
    
    async def create_user(self, user_data: Dict[str, Any]) -> User:
        """
        Create a new user in the database.
        
        Args:
            user_data: Dictionary containing user information
            
        Returns:
            Created User object
            
        Raises:
            ValueError: If user data is invalid
            DatabaseError: If database operation fails
        """
        try:
            # Validate required fields
            required_fields = ['email', 'first_name', 'last_name']
            missing_fields = [field for field in required_fields if not user_data.get(field)]
            
            if missing_fields:
                raise ValueError(f"Missing required fields: {missing_fields}")
            
            # Sanitize and prepare data
            sanitized_data = {
                'email': user_data['email'].lower().strip(),
                'first_name': user_data['first_name'].strip(),
                'last_name': user_data['last_name'].strip(),
                'created_at': datetime.utcnow(),
                'is_active': user_data.get('is_active', True),
                'metadata': user_data.get('metadata', {})
            }
            
            # Execute database operation with proper error handling
            result = await self.db.execute(
                """
                INSERT INTO users (email, first_name, last_name, created_at, is_active, metadata)
                VALUES (%(email)s, %(first_name)s, %(last_name)s, %(created_at)s, %(is_active)s, %(metadata)s)
                RETURNING id, email, first_name, last_name, created_at, is_active, metadata
                """,
                sanitized_data
            )
            
            user_record = await result.fetchone()
            if not user_record:
                raise DatabaseError("Failed to create user")
            
            logger.info(f"Created user with ID: {user_record['id']}")
            
            return User(
                id=user_record['id'],
                email=user_record['email'],
                first_name=user_record['first_name'],
                last_name=user_record['last_name'],
                created_at=user_record['created_at'],
                is_active=user_record['is_active'],
                metadata=user_record['metadata']
            )
            
        except Exception as e:
            logger.error(f"Error creating user: {str(e)}", exc_info=True)
            raise

    async def get_user_by_id(self, user_id: int) -> Optional[User]:
        """
        Retrieve a user by their ID.
        
        Args:
            user_id: The ID of the user to retrieve
            
        Returns:
            User object if found, None otherwise
        """
        try:
            if not isinstance(user_id, int) or user_id <= 0:
                raise ValueError("User ID must be a positive integer")
            
            result = await self.db.execute(
                """
                SELECT id, email, first_name, last_name, created_at, is_active, metadata
                FROM users 
                WHERE id = %(user_id)s AND is_active = true
                """,
                {'user_id': user_id}
            )
            
            user_record = await result.fetchone()
            if not user_record:
                return None
            
            return User(
                id=user_record['id'],
                email=user_record['email'],
                first_name=user_record['first_name'],
                last_name=user_record['last_name'],
                created_at=user_record['created_at'],
                is_active=user_record['is_active'],
                metadata=user_record['metadata']
            )
            
        except Exception as e:
            logger.error(f"Error retrieving user {user_id}: {str(e)}", exc_info=True)
            raise
```

## Integration with Development Tools

### IDE Integration

#### Code Completion and Suggestions

AI provides intelligent code completion within your development environment:

```text IDE Integration Features theme={null}
💻 Development Environment Support:
├── 🔧 VS Code Extension
│   ├── Real-time code suggestions
│   ├── Inline documentation generation
│   ├── Error detection and fixes
│   └── Refactoring recommendations
├── 💎 JetBrains IDEs
│   ├── IntelliJ IDEA, PyCharm, WebStorm support
│   ├── Context-aware completions
│   ├── Code quality inspections
│   └── Automated testing generation
├── 🌐 Web-based Editors
│   ├── GitHub Codespaces integration
│   ├── CodeSandbox support
│   ├── Replit compatibility
│   └── Online code review tools
└── 📱 Mobile Development
    ├── Android Studio integration
    ├── Xcode support (via plugins)
    ├── Flutter development tools
    └── React Native workflows
```

### Version Control Integration

#### Git Workflow Enhancement

AI assists with version control best practices:

```bash Git Integration Examples theme={null}
# AI-generated commit messages
git commit -m "feat(auth): implement secure user authentication with JWT

- Add user registration with email verification
- Implement login with brute force protection
- Add refresh token rotation mechanism
- Include comprehensive input validation
- Add rate limiting for auth endpoints

Closes #123
Breaking change: Authentication now requires email verification"

# AI-generated pull request descriptions
# Title: Implement User Authentication System
# 
# ## Summary
# This PR implements a comprehensive user authentication system with security best practices.
#
# ## Changes
# - ✅ User registration with email verification
# - ✅ Secure login with JWT tokens
# - ✅ Brute force protection
# - ✅ Rate limiting
# - ✅ Input validation and sanitization
#
# ## Testing
# - Unit tests for all auth functions
# - Integration tests for API endpoints
# - Security testing for common vulnerabilities
#
# ## Breaking Changes
# - Authentication now requires email verification
# - Password requirements have been strengthened
```

## Best Practices

### Code Generation Workflow

1. **Start with Clear Requirements**
   ```text Effective Prompt Structure theme={null}
   ```

📋 Optimal Code Generation Prompts:
├── 🎯 Clear Objective: "Create a user authentication system"
├── 🔧 Technical Specs: "Using Node.js, Express, JWT, MongoDB"
├── 🔒 Security Requirements: "Include rate limiting and input validation"
├── 📊 Performance Needs: "Handle 1000+ concurrent users"
├── 🎨 Style Preferences: "Follow Airbnb JavaScript style guide"
└── 📝 Documentation Level: "Include JSDoc comments and examples"

````

2. **Iterative Refinement**
   ```text Code Improvement Process
🔄 Refinement Workflow:
   ├── 1️⃣ Generate initial implementation
   ├── 2️⃣ Review and identify improvements
   ├── 3️⃣ Request specific optimizations
   ├── 4️⃣ Add error handling and edge cases
   ├── 5️⃣ Enhance documentation and comments
   ├── 6️⃣ Optimize for performance
   └── 7️⃣ Add comprehensive tests
````

3. **Quality Assurance**
   ```text Code Quality Checklist theme={null}
   ```

✅ Pre-deployment Checklist:
├── 🔍 Code review and AI analysis
├── 🧪 Automated testing coverage
├── 🔒 Security vulnerability scan
├── 🚀 Performance benchmark testing
├── 📝 Documentation completeness
├── 🎨 Code style consistency
└── 🌐 Cross-platform compatibility

```

## Troubleshooting

### Common Generation Issues

#### Incomplete or Incorrect Code
**Problem**: Generated code doesn't meet requirements or has errors  
**Solutions**:
- Provide more specific and detailed requirements
- Include example inputs/outputs and expected behavior
- Specify the exact technologies and versions to use
- Break complex requests into smaller, focused tasks
- Review and refine prompts for clarity

#### Integration Problems
**Problem**: Generated code doesn't integrate well with existing codebase  
**Solutions**:
- Share relevant existing code context
- Specify coding conventions and style guides
- Provide information about project architecture
- Include dependency and configuration details
- Request code that matches existing patterns

#### Performance Issues
**Problem**: Generated code is slow or inefficient  
**Solutions**:
- Specify performance requirements upfront
- Request algorithmic complexity analysis
- Ask for optimization suggestions
- Include expected data sizes and usage patterns
- Request benchmarking and profiling guidance

## Related Features

- [AI Tools Reference](/ai-tools/reference) - Complete overview of all AI development tools
- [Code Review Tools](/ai-tools/code-review) - AI-powered code analysis and suggestions
- [Documentation Generation](/ai-tools/documentation) - Automated code documentation
- [Testing Assistance](/ai-tools/testing) - AI-generated tests and test strategies

## What's Next?

Ready to accelerate your development with AI-powered code generation? Here are your next steps:

1. **[Set up integrations](/integrations/setup)** for development tools
2. **[Review AI tools reference](/ai-tools/reference)** for advanced techniques
3. **[Explore code generation features](/ai-tools/code-generation)** for your projects
4. **[Explore team collaboration features](/multiplayer/overview)** for shared development

---

*Need help with code generation? Contact our [support team](/support/contact).* 
```
