/**
 * Troubleshooting Documentation Template
 * Generates common issues and solutions based on technology stack
 */

import { DocumentationIntent } from '../../../types/workflow';
import { DocumentationTemplate, TemplateContext } from './base-template';

export class TroubleshootingTemplate extends DocumentationTemplate {
  canHandle(intent: DocumentationIntent): boolean {
    return intent.type === 'troubleshooting';
  }

  generate(context: TemplateContext): string {
    const { intent } = context;

    let content = `# Troubleshooting`;

    if (intent.scope) {
      content += `: ${this.capitalize(intent.scope)}`;
    }

    content += '\n\n';

    // Generate scope-specific troubleshooting
    if (intent.scope === 'authentication') {
      content += this.generateAuthTroubleshooting(context);
    } else if (intent.scope === 'database') {
      content += this.generateDatabaseTroubleshooting(context);
    } else if (intent.scope === 'api') {
      content += this.generateApiTroubleshooting(context);
    } else {
      // General troubleshooting
      content += this.generateGeneralTroubleshooting(context);
    }

    // Add technology-specific issues if requested
    if (intent.includeCommonIssues) {
      content += '\n\n' + this.generateTechnologySpecificIssues(context);
    }

    content += this.generateFooter(context);

    return content;
  }

  private generateAuthTroubleshooting(context: TemplateContext): string {
    const { extendedWorkflow } = context;
    const provider = extendedWorkflow?.auth?.provider || 'authentication';

    let content = `Common authentication issues and their solutions.\n\n`;

    // CORS issues (common across all auth providers)
    content += `## CORS Errors\n\n`;
    content += `### Problem\n`;
    content += `When making authenticated requests from your frontend, you may encounter CORS errors:\n\n`;
    content += '```\n';
    content += `Access to fetch at 'http://localhost:3001/api/users' from origin 'http://localhost:5173'\n`;
    content += `has been blocked by CORS policy\n`;
    content += '```\n\n';

    content += `### Solution\n\n`;
    content += `The backend is configured with CORS middleware in \`backend/src/index.ts\`. Ensure your frontend URL is included in the allowed origins:\n\n`;
    content += '**backend/src/index.ts:**\n';
    content += '```typescript\n';
    content += `import cors from 'cors';\n\n`;
    content += `app.use(cors({\n`;
    content += `  origin: process.env.FRONTEND_URL || 'http://localhost:5173',\n`;
    content += `  credentials: true\n`;
    content += `}));\n`;
    content += '```\n\n';

    content += `**Environment Variable:**\n`;
    content += `Set \`FRONTEND_URL\` in your \`.env\` file:\n`;
    content += '```\n';
    content += `FRONTEND_URL=http://localhost:5173\n`;
    content += '```\n\n';

    content += `### Common Causes\n`;
    content += `1. **Credentials not included**: Add \`credentials: true\` to CORS config (already configured)\n`;
    content += `2. **Wrong origin**: Check \`FRONTEND_URL\` matches your dev server port\n`;
    content += `3. **Preflight requests**: Ensure backend handles OPTIONS requests (Express cors handles this)\n\n`;

    // Provider-specific issues
    if (provider === 'clerk') {
      content += this.generateClerkTroubleshooting(context);
    } else if (provider === 'auth0') {
      content += this.generateAuth0Troubleshooting(context);
    }

    return content;
  }

  private generateClerkTroubleshooting(_context: TemplateContext): string {
    let content = `## Clerk-Specific Issues\n\n`;

    content += `### Invalid API Key\n\n`;
    content += `**Problem:** Backend fails to start with "Invalid Clerk API Key"\n\n`;
    content += `**Solution:**\n`;
    content += `1. Check \`CLERK_SECRET_KEY\` is set in \`backend/.env\`\n`;
    content += `2. Verify the key starts with \`sk_\` (secret key, not publishable key)\n`;
    content += `3. Ensure key is from the correct Clerk application\n\n`;

    content += `**Environment Variables:**\n`;
    content += '```bash\n';
    content += `# backend/.env\n`;
    content += `CLERK_SECRET_KEY=sk_test_xxxxx  # NOT pk_test_xxxxx\n\n`;
    content += `# frontend/.env\n`;
    content += `VITE_CLERK_PUBLISHABLE_KEY=pk_test_xxxxx\n`;
    content += '```\n\n';

    content += `### Session Not Found\n\n`;
    content += `**Problem:** User appears logged in on frontend but backend returns 401\n\n`;
    content += `**Solution:**\n`;
    content += `1. Ensure \`credentials: true\` is set in CORS config\n`;
    content += `2. Check frontend is using \`credentials: 'include'\` in fetch requests\n`;
    content += `3. Verify both frontend and backend are on same domain or use proper CORS configuration\n\n`;

    content += `**Frontend fetch example:**\n`;
    content += '```typescript\n';
    content += `const response = await fetch('http://localhost:3001/api/users', {\n`;
    content += `  credentials: 'include', // ✅ Required for cookie-based auth\n`;
    content += `  headers: {\n`;
    content += `    'Content-Type': 'application/json'\n`;
    content += `  }\n`;
    content += `});\n`;
    content += '```\n\n';

    return content;
  }

  private generateAuth0Troubleshooting(_context: TemplateContext): string {
    let content = `## Auth0-Specific Issues\n\n`;

    content += `### JWT Verification Failed\n\n`;
    content += `**Problem:** Backend returns "Invalid token" or "JWT verification failed"\n\n`;
    content += `**Solution:**\n`;
    content += `1. Check \`AUTH0_DOMAIN\` matches your Auth0 tenant domain\n`;
    content += `2. Verify \`AUTH0_AUDIENCE\` matches the API identifier in Auth0\n`;
    content += `3. Ensure frontend is requesting tokens for the correct audience\n\n`;

    return content;
  }

  private generateDatabaseTroubleshooting(context: TemplateContext): string {
    const { extendedWorkflow } = context;
    const dbType = extendedWorkflow?.technology?.database?.type || 'postgresql';

    let content = `Common database issues and their solutions.\n\n`;

    content += `## Connection Errors\n\n`;
    content += `### Problem\n`;
    content += `Backend fails to connect to database with errors like:\n`;
    content += '```\n';
    content += `Error: connect ECONNREFUSED 127.0.0.1:5432\n`;
    content += '```\n\n';

    content += `### Solution\n\n`;
    content += `1. **Check database is running:**\n`;
    content += '```bash\n';
    if (dbType === 'postgresql') {
      content += `# Using Docker\n`;
      content += `docker ps | grep postgres\n\n`;
      content += `# Or check PostgreSQL service status\n`;
      content += `brew services list | grep postgresql\n`;
    }
    content += '```\n\n';

    content += `2. **Verify DATABASE_URL:**\n`;
    content += `Check \`backend/.env\` has correct connection string:\n`;
    content += '```\n';
    if (dbType === 'postgresql') {
      content += `DATABASE_URL=postgresql://user:password@localhost:5432/dbname\n`;
    } else if (dbType === 'mysql') {
      content += `DATABASE_URL=mysql://user:password@localhost:3306/dbname\n`;
    }
    content += '```\n\n';

    content += `3. **Run migrations:**\n`;
    content += '```bash\n';
    content += `cd backend\n`;
    content += `npm run prisma:migrate\n`;
    content += '```\n\n';

    content += `## Migration Errors\n\n`;
    content += `### Problem\n`;
    content += `Prisma migrations fail or database schema is out of sync\n\n`;
    content += `### Solution\n\n`;
    content += `1. **Reset database (development only):**\n`;
    content += '```bash\n';
    content += `cd backend\n`;
    content += `npx prisma migrate reset\n`;
    content += '```\n\n';

    content += `2. **Generate Prisma Client:**\n`;
    content += '```bash\n';
    content += `npx prisma generate\n`;
    content += '```\n\n';

    return content;
  }

  private generateApiTroubleshooting(_context: TemplateContext): string {
    let content = `Common API issues and their solutions.\n\n`;

    content += `## 404 Not Found\n\n`;
    content += `### Problem\n`;
    content += `API endpoint returns 404 even though it exists\n\n`;
    content += `### Solution\n`;
    content += `1. Check the API path matches the frontend request\n`;
    content += `2. Verify backend server is running on expected port\n`;
    content += `3. Ensure \`/api\` prefix is included if configured\n\n`;

    content += `## 500 Internal Server Error\n\n`;
    content += `### Problem\n`;
    content += `API returns 500 status code\n\n`;
    content += `### Solution\n`;
    content += `1. Check backend console for error logs\n`;
    content += `2. Verify database is connected and migrations are run\n`;
    content += `3. Check request body matches expected schema\n\n`;

    return content;
  }

  private generateGeneralTroubleshooting(context: TemplateContext): string {
    let content = `Common issues and their solutions.\n\n`;

    // Event-driven architecture issues (if events are configured)
    const hasEvents = context.extendedWorkflow?.events && Object.keys(context.extendedWorkflow.events).length > 0;
    const hasRedis = context.extendedWorkflow?.technology?.cache?.provider?.includes('redis');
    if (hasEvents && hasRedis) {
      content += this.generateEventDrivenTroubleshooting(context);
    }

    // Environment setup issues
    content += this.generateEnvironmentIssues(context);

    // Port conflicts
    content += this.generatePortConflictIssues(context);

    // Development server issues
    content += `## Development Server Issues\n\n`;
    content += `### Frontend not starting\n\n`;
    content += `**Problem:** Vite dev server fails to start or shows errors\n\n`;
    content += `**Solutions:**\n`;
    content += `1. Clear node_modules and reinstall:\n`;
    content += '```bash\n';
    content += `cd frontend\n`;
    content += `rm -rf node_modules package-lock.json\n`;
    content += `npm install\n`;
    content += '```\n\n';
    content += `2. Check Node.js version:\n`;
    content += '```bash\n';
    content += `node --version  # Should be 18.x or higher\n`;
    content += '```\n\n';
    content += `3. Clear Vite cache:\n`;
    content += '```bash\n';
    content += `rm -rf node_modules/.vite\n`;
    content += '```\n\n';

    content += `### Backend not starting\n\n`;
    content += `**Problem:** Express server fails to start\n\n`;
    content += `**Solutions:**\n`;
    content += `1. Check database connection:\n`;
    content += '```bash\n';
    content += `# Verify DATABASE_URL is set\n`;
    content += `cat backend/.env | grep DATABASE_URL\n`;
    content += '```\n\n';
    content += `2. Run migrations:\n`;
    content += '```bash\n';
    content += `cd backend\n`;
    content += `npm run prisma:migrate\n`;
    content += `npm run prisma:generate\n`;
    content += '```\n\n';
    content += `3. Check for TypeScript errors:\n`;
    content += '```bash\n';
    content += `cd backend\n`;
    content += `npx tsc --noEmit\n`;
    content += '```\n\n';

    // Docker issues
    content += this.generateDockerIssues(context);

    // Dependency issues
    content += this.generateDependencyIssues(context);

    // Performance issues
    content += this.generatePerformanceIssues(context);

    return content;
  }

  private generateEventDrivenTroubleshooting(_context: TemplateContext): string {
    let content = `## Event-Driven Architecture Issues\n\n`;

    content += `### Events Not Being Emitted\n\n`;
    content += `**Problem:** Events are not being published to the event bus after API operations\n\n`;
    content += `**Solutions:**\n`;
    content += `1. Check Redis connection:\n`;
    content += '```bash\n';
    content += `# Verify Redis is running\n`;
    content += `docker ps | grep redis\n\n`;
    content += `# Test connection\n`;
    content += `redis-cli ping  # Should return "PONG"\n`;
    content += '```\n\n';
    content += `2. Verify \`REDIS_URL\` in backend/.env:\n`;
    content += '```bash\n';
    content += `# For local Redis\n`;
    content += `REDIS_URL=redis://localhost:6379\n\n`;
    content += `# For Upstash Redis\n`;
    content += `REDIS_URL=rediss://...upstash.io:6379\n`;
    content += '```\n\n';
    content += `3. Check event bus initialization:\n`;
    content += '```bash\n';
    content += `# Look for this in backend logs:\n`;
    content += `[Event Bus] Connected to Redis\n`;
    content += `[Event Bus] Initialized\n`;
    content += '```\n\n';
    content += `4. Verify event emission in API endpoint:\n`;
    content += '```typescript\n';
    content += `// backend/src/routes/users.ts\n`;
    content += `const user = await prisma.user.create({ data });\n`;
    content += `await emitEventWithContext(req, "user_created", { userId: user.id });\n`;
    content += `// Check console for: [Event Emitter] Emitted user_created\n`;
    content += '```\n\n';

    content += `### Events Not Being Received by Handlers\n\n`;
    content += `**Problem:** Event handlers are not processing events\n\n`;
    content += `**Solutions:**\n`;
    content += `1. Check subscriber initialization in backend logs:\n`;
    content += '```bash\n';
    content += `[Subscriber] Initialized user_created handler\n`;
    content += `[Subscriber] Initialized user_updated handler\n`;
    content += '```\n\n';
    content += `2. Verify event handler is registered:\n`;
    content += '```typescript\n';
    content += `// backend/src/events/subscriber-initializer.ts should include:\n`;
    content += `await eventBus.subscribe("user_created", async (event) => {\n`;
    content += `  await handleUserCreatedHandler(event);\n`;
    content += `});\n`;
    content += '```\n\n';
    content += `3. Check for errors in event handler:\n`;
    content += '```bash\n';
    content += `# Look for errors in console:\n`;
    content += `[UserCreatedHandler] Error processing event: ...\n`;
    content += '```\n\n';
    content += `4. Test event bus manually:\n`;
    content += '```typescript\n';
    content += `// Temporary test code\n`;
    content += `import { getEventBus } from "./events/event-bus";\n\n`;
    content += `const eventBus = getEventBus();\n`;
    content += `await eventBus.publish("test_event", { message: "Hello" });\n`;
    content += '```\n\n';

    content += `### WebSocket Clients Not Receiving Real-time Updates\n\n`;
    content += `**Problem:** Frontend doesn't receive real-time events via WebSocket\n\n`;
    content += `**Solutions:**\n`;
    content += `1. Check WebSocket connection in browser console:\n`;
    content += '```javascript\n';
    content += `// Should see:\n`;
    content += `[WebSocket] Connected\n`;
    content += `[WebSocket] Connection confirmed: client_...\n`;
    content += '```\n\n';
    content += `2. Verify WebSocket server initialization in backend logs:\n`;
    content += '```bash\n';
    content += `[WebSocket] Client connected: client_...\n`;
    content += `[WebSocket] Heartbeat started\n`;
    content += '```\n\n';
    content += `3. Check event bridge is connecting events to WebSocket:\n`;
    content += '```bash\n';
    content += `# Backend logs should show:\n`;
    content += `[Event Bridge] Initializing event bridge...\n`;
    content += `[Event Bridge] Event bridge initialized\n`;
    content += `[WebSocket] Broadcasted user_created to N clients\n`;
    content += '```\n\n';
    content += `4. Verify frontend is subscribing to events:\n`;
    content += '```typescript\n';
    content += `// frontend/src/App.tsx or component\n`;
    content += `import { useEvent } from "./hooks/useEvents";\n\n`;
    content += `useEvent("user_created", (payload) => {\n`;
    content += `  console.log("Received user_created:", payload);\n`;
    content += `});\n`;
    content += '```\n\n';
    content += `5. Check WebSocket subscriptions:\n`;
    content += '```bash\n';
    content += `# Browser console should show:\n`;
    content += `[WebSocket] Client client_... subscribed to: ["user_created"]\n`;
    content += '```\n\n';

    content += `### Redis Connection Errors\n\n`;
    content += `**Problem:** "ECONNREFUSED" or "Redis connection failed"\n\n`;
    content += `**Solutions:**\n`;
    content += `1. **Start Redis locally:**\n`;
    content += '```bash\n';
    content += `# Using Docker\n`;
    content += `docker run -d -p 6379:6379 redis:7-alpine\n\n`;
    content += `# Or using Homebrew\n`;
    content += `brew services start redis\n`;
    content += '```\n\n';
    content += `2. **Check Redis is accessible:**\n`;
    content += '```bash\n';
    content += `redis-cli ping\n`;
    content += `# Should return: PONG\n`;
    content += '```\n\n';
    content += `3. **For Upstash Redis:**\n`;
    content += `- Verify \`REDIS_URL\` includes full connection string with password\n`;
    content += `- Check Upstash dashboard for connection details\n`;
    content += `- Ensure URL starts with \`rediss://\` (with SSL) not \`redis://\`\n\n`;

    content += `### Event Handler Errors Don't Crash Server\n\n`;
    content += `**This is expected behavior:** Event handlers are designed to fail gracefully.\n\n`;
    content += `**How it works:**\n`;
    content += `- Event emission is non-blocking\n`;
    content += `- Handler errors are logged but don't affect API responses\n`;
    content += `- Events are still received by other subscribers\n\n`;
    content += `**Debugging failed handlers:**\n`;
    content += '```bash\n';
    content += '# Check logs for handler errors:\n';
    content += 'grep "Handler] Error" backend/logs/*.log\n\n';
    content += '# Add logging in your handler:\n';
    content += 'export async function handleUserCreatedHandler(event) {\n';
    content += '  console.log("[Debug] Handler input:", event);\n';
    content += '  try {\n';
    content += '    // Your logic\n';
    content += '  } catch (error) {\n';
    content += '    console.error("[Handler Error]", error);\n';
    content += '    throw error;  // Re-throw for event bus error handling\n';
    content += '  }\n';
    content += '}\n';
    content += '```\n\n';

    content += `### WebSocket Connection Drops\n\n`;
    content += `**Problem:** WebSocket disconnects frequently or doesn't reconnect\n\n`;
    content += `**Solutions:**\n`;
    content += `1. Check heartbeat is working (backend logs):\n`;
    content += '```bash\n';
    content += `[WebSocket] Heartbeat started\n`;
    content += '```\n\n';
    content += `2. Verify automatic reconnection (browser console):\n`;
    content += '```javascript\n';
    content += `[WebSocket] Disconnected\n`;
    content += `[WebSocket] Reconnecting in 1000ms (attempt 1)\n`;
    content += `[WebSocket] Connected\n`;
    content += '```\n\n';
    content += `3. Check firewall/proxy settings:\n`;
    content += `- WebSocket connections may be blocked by corporate proxies\n`;
    content += `- Try accessing from different network\n\n`;
    content += `4. Increase heartbeat interval if network is unstable:\n`;
    content += '```typescript\n';
    content += `// backend/src/websocket/server.ts\n`;
    content += `realtimeServer.startHeartbeat(60000);  // 60 seconds instead of 30\n`;
    content += '```\n\n';

    return content;
  }

  private generateEnvironmentIssues(_context: TemplateContext): string {
    let content = `## Environment Setup Issues\n\n`;

    content += `### Node.js Version Mismatch\n\n`;
    content += `**Problem:** Application fails with syntax errors or unexpected behavior\n\n`;
    content += `**Solution:**\n`;
    content += `1. Check current Node.js version:\n`;
    content += '```bash\n';
    content += `node --version\n`;
    content += '```\n\n';
    content += `2. Install correct version (18.x or higher):\n`;
    content += '```bash\n';
    content += `# Using nvm (recommended)\n`;
    content += `nvm install 18\n`;
    content += `nvm use 18\n\n`;
    content += `# Or download from nodejs.org\n`;
    content += '```\n\n';

    content += `### Missing Environment Variables\n\n`;
    content += `**Problem:** Application crashes with "undefined" environment variables\n\n`;
    content += `**Solution:**\n`;
    content += `1. Copy example environment files:\n`;
    content += '```bash\n';
    content += `cp backend/.env.example backend/.env\n`;
    content += `cp frontend/.env.example frontend/.env\n`;
    content += '```\n\n';
    content += `2. Fill in required values:\n`;
    content += '```bash\n';
    content += `# backend/.env\n`;
    content += `DATABASE_URL=postgresql://...\n`;
    content += `PORT=3001\n\n`;
    content += `# frontend/.env\n`;
    content += `VITE_API_URL=http://localhost:3001\n`;
    content += '```\n\n';
    content += `3. Restart development servers after changing .env files\n\n`;

    content += `### npm vs yarn Conflicts\n\n`;
    content += `**Problem:** Lock file conflicts or dependency issues\n\n`;
    content += `**Solution:**\n`;
    content += `Pick one package manager and stick with it:\n`;
    content += `- If using npm: Delete \`yarn.lock\`, keep \`package-lock.json\`\n`;
    content += `- If using yarn: Delete \`package-lock.json\`, keep \`yarn.lock\`\n`;
    content += `- Never mix npm and yarn in the same project\n\n`;

    return content;
  }

  private generatePortConflictIssues(_context: TemplateContext): string {
    let content = `## Port Already in Use\n\n`;

    content += `### Problem\n`;
    content += `Error: "Port 3001 is already in use" or "EADDRINUSE"\n\n`;

    content += `### Solution\n\n`;
    content += `**Option 1: Kill the process using the port**\n`;
    content += '```bash\n';
    content += `# Find process using port 3001\n`;
    content += `lsof -i :3001\n\n`;
    content += `# Kill the process (replace PID with actual process ID)\n`;
    content += `kill -9 PID\n`;
    content += '```\n\n';

    content += `**Option 2: Use a different port**\n`;
    content += '```bash\n';
    content += `# backend/.env\n`;
    content += `PORT=3002  # Change to any available port\n`;
    content += '```\n\n';

    content += `**Common port conflicts:**\n`;
    content += `- \`3001\`: Backend server\n`;
    content += `- \`5173\`: Frontend dev server (Vite)\n`;
    content += `- \`5432\`: PostgreSQL\n`;
    content += `- \`3306\`: MySQL\n\n`;

    return content;
  }

  private generateDockerIssues(_context: TemplateContext): string {
    let content = `## Docker Issues\n\n`;

    content += `### Containers Not Starting\n\n`;
    content += `**Problem:** \`docker compose up\` fails or containers exit immediately\n\n`;
    content += `**Solutions:**\n`;
    content += `1. Check container logs:\n`;
    content += '```bash\n';
    content += `docker compose logs backend\n`;
    content += `docker compose logs frontend\n`;
    content += `docker compose logs postgres\n`;
    content += '```\n\n';
    content += `2. Rebuild containers:\n`;
    content += '```bash\n';
    content += `docker compose down\n`;
    content += `docker compose build --no-cache\n`;
    content += `docker compose up\n`;
    content += '```\n\n';
    content += `3. Check for port conflicts:\n`;
    content += '```bash\n';
    content += `docker compose ps\n`;
    content += `lsof -i :3001  # Backend port\n`;
    content += `lsof -i :5432  # PostgreSQL port\n`;
    content += '```\n\n';

    content += `### Database Container Issues\n\n`;
    content += `**Problem:** Backend can't connect to database in Docker\n\n`;
    content += `**Solutions:**\n`;
    content += `1. Use correct hostname in DATABASE_URL:\n`;
    content += '```bash\n';
    content += `# ❌ Wrong (when running in Docker)\n`;
    content += `DATABASE_URL=postgresql://user:pass@localhost:5432/db\n\n`;
    content += `# ✅ Correct (use service name from docker-compose.yml)\n`;
    content += `DATABASE_URL=postgresql://user:pass@postgres:5432/db\n`;
    content += '```\n\n';
    content += `2. Wait for database to be ready:\n`;
    content += '```bash\n';
    content += `# Check if postgres is ready\n`;
    content += `docker compose exec postgres pg_isready\n`;
    content += '```\n\n';

    content += `### Volume Permission Issues\n\n`;
    content += `**Problem:** Permission denied errors in Docker containers\n\n`;
    content += `**Solution:**\n`;
    content += '```bash\n';
    content += `# Reset volume permissions\n`;
    content += `docker compose down -v  # WARNING: Deletes all data\n`;
    content += `docker compose up\n`;
    content += '```\n\n';

    return content;
  }

  private generateDependencyIssues(_context: TemplateContext): string {
    let content = `## Dependency Issues\n\n`;

    content += `### Peer Dependency Warnings\n\n`;
    content += `**Problem:** npm shows peer dependency warnings during install\n\n`;
    content += `**Solution:**\n`;
    content += `- Usually safe to ignore if application works\n`;
    content += `- If issues occur, try:\n`;
    content += '```bash\n';
    content += `npm install --legacy-peer-deps\n`;
    content += '```\n\n';

    content += `### Module Not Found\n\n`;
    content += `**Problem:** "Cannot find module" errors\n\n`;
    content += `**Solutions:**\n`;
    content += `1. Install missing dependency:\n`;
    content += '```bash\n';
    content += `npm install <package-name>\n`;
    content += '```\n\n';
    content += `2. Clear cache and reinstall:\n`;
    content += '```bash\n';
    content += `rm -rf node_modules package-lock.json\n`;
    content += `npm cache clean --force\n`;
    content += `npm install\n`;
    content += '```\n\n';
    content += `3. Check import paths are correct:\n`;
    content += '```typescript\n';
    content += `// ❌ Wrong\n`;
    content += `import { foo } from './Foo'  // Missing file extension\n\n`;
    content += `// ✅ Correct\n`;
    content += `import { foo } from './Foo.js'\n`;
    content += '```\n\n';

    return content;
  }

  private generatePerformanceIssues(_context: TemplateContext): string {
    let content = `## Performance Issues\n\n`;

    content += `### Slow Development Server\n\n`;
    content += `**Problem:** Hot reload is slow or Vite server is sluggish\n\n`;
    content += `**Solutions:**\n`;
    content += `1. Exclude node_modules from file watchers:\n`;
    content += '```javascript\n';
    content += `// vite.config.ts\n`;
    content += `export default {\n`;
    content += `  server: {\n`;
    content += `    watch: {\n`;
    content += `      ignored: ['**/node_modules/**']\n`;
    content += `    }\n`;
    content += `  }\n`;
    content += `}\n`;
    content += '```\n\n';
    content += `2. Clear Vite cache:\n`;
    content += '```bash\n';
    content += `rm -rf node_modules/.vite\n`;
    content += '```\n\n';

    content += `### High Memory Usage\n\n`;
    content += `**Problem:** Node.js process consumes excessive memory\n\n`;
    content += `**Solutions:**\n`;
    content += `1. Increase Node memory limit:\n`;
    content += '```bash\n';
    content += `# In package.json scripts\n`;
    content += `"dev": "NODE_OPTIONS='--max-old-space-size=4096' vite"\n`;
    content += '```\n\n';
    content += `2. Check for memory leaks:\n`;
    content += `- Look for unsubscribed event listeners\n`;
    content += `- Check for unclosed database connections\n`;
    content += `- Review large array/object accumulations\n\n`;

    content += `### Slow Database Queries\n\n`;
    content += `**Problem:** API endpoints are slow due to database\n\n`;
    content += `**Solutions:**\n`;
    content += `1. Add database indexes:\n`;
    content += '```prisma\n';
    content += `model User {\n`;
    content += `  id    String @id\n`;
    content += `  email String @unique  // Automatically indexed\n`;
    content += `  \n`;
    content += `  @@index([email])  // Add index manually\n`;
    content += `}\n`;
    content += '```\n\n';
    content += `2. Use \`select\` to fetch only needed fields:\n`;
    content += '```typescript\n';
    content += `// ❌ Fetches all fields\n`;
    content += `const users = await prisma.user.findMany();\n\n`;
    content += `// ✅ Fetches only needed fields\n`;
    content += `const users = await prisma.user.findMany({\n`;
    content += `  select: { id: true, email: true }\n`;
    content += `});\n`;
    content += '```\n\n';

    return content;
  }

  private generateTechnologySpecificIssues(context: TemplateContext): string {
    const { extendedWorkflow } = context;
    let content = `## Technology-Specific Issues\n\n`;

    // React-specific issues
    if (extendedWorkflow?.technology?.frontend?.framework === 'react') {
      content += this.generateReactIssues(context);
    }

    // Express-specific issues
    if (extendedWorkflow?.technology?.backend?.framework === 'express') {
      content += this.generateExpressIssues(context);
    }

    // Prisma-specific issues
    if (extendedWorkflow?.technology?.backend?.orm === 'prisma') {
      content += this.generatePrismaIssues(context);
    }

    return content;
  }

  private generateReactIssues(_context: TemplateContext): string {
    let content = `### React Common Issues\n\n`;

    content += `#### Hooks Rules Violation\n\n`;
    content += `**Problem:** "Rendered more hooks than during the previous render" or "Hooks can only be called inside function components"\n\n`;
    content += `**Solution:**\n`;
    content += `- Never call hooks inside loops, conditions, or nested functions\n`;
    content += `- Always call hooks at the top level of your component\n`;
    content += '```typescript\n';
    content += `// ❌ Wrong\n`;
    content += `function MyComponent() {\n`;
    content += `  if (condition) {\n`;
    content += `    const [state, setState] = useState(0);  // Conditional hook\n`;
    content += `  }\n`;
    content += `}\n\n`;
    content += `// ✅ Correct\n`;
    content += `function MyComponent() {\n`;
    content += `  const [state, setState] = useState(0);\n`;
    content += `  if (condition) {\n`;
    content += `    // Use state here\n`;
    content += `  }\n`;
    content += `}\n`;
    content += '```\n\n';

    content += `#### Infinite Re-render Loop\n\n`;
    content += `**Problem:** "Too many re-renders" error\n\n`;
    content += `**Solutions:**\n`;
    content += '```typescript\n';
    content += `// ❌ Wrong: Sets state during render\n`;
    content += `function MyComponent() {\n`;
    content += `  const [count, setCount] = useState(0);\n`;
    content += `  setCount(count + 1);  // Causes infinite loop\n`;
    content += `}\n\n`;
    content += `// ✅ Correct: Use useEffect for side effects\n`;
    content += `function MyComponent() {\n`;
    content += `  const [count, setCount] = useState(0);\n`;
    content += `  useEffect(() => {\n`;
    content += `    setCount(count + 1);\n`;
    content += `  }, []);  // Empty deps = run once\n`;
    content += `}\n`;
    content += '```\n\n';

    content += `#### Stale Closure in useEffect\n\n`;
    content += `**Problem:** useEffect uses old values from previous renders\n\n`;
    content += `**Solution:**\n`;
    content += '```typescript\n';
    content += `// ❌ Wrong: Missing dependency\n`;
    content += `useEffect(() => {\n`;
    content += `  console.log(count);  // Uses stale value\n`;
    content += `}, []);  // count not in dependencies\n\n`;
    content += `// ✅ Correct: Include all dependencies\n`;
    content += `useEffect(() => {\n`;
    content += `  console.log(count);  // Always uses current value\n`;
    content += `}, [count]);\n`;
    content += '```\n\n';

    content += `#### Hydration Mismatch\n\n`;
    content += `**Problem:** "Hydration failed" or "Text content does not match"\n\n`;
    content += `**Solutions:**\n`;
    content += `- Don't use browser-only APIs during initial render:\n`;
    content += '```typescript\n';
    content += `// ❌ Wrong\n`;
    content += `function MyComponent() {\n`;
    content += `  return <div>{window.innerWidth}</div>;  // Undefined on server\n`;
    content += `}\n\n`;
    content += `// ✅ Correct\n`;
    content += `function MyComponent() {\n`;
    content += `  const [width, setWidth] = useState(0);\n`;
    content += `  useEffect(() => {\n`;
    content += `    setWidth(window.innerWidth);  // Only on client\n`;
    content += `  }, []);\n`;
    content += `  return <div>{width || 'Loading...'}</div>;\n`;
    content += `}\n`;
    content += '```\n\n';

    content += `#### Key Prop Warning\n\n`;
    content += `**Problem:** "Each child in a list should have a unique key prop"\n\n`;
    content += `**Solution:**\n`;
    content += '```typescript\n';
    content += `// ❌ Wrong: Using index as key\n`;
    content += `items.map((item, index) => <Item key={index} {...item} />)\n\n`;
    content += `// ✅ Correct: Use stable unique ID\n`;
    content += `items.map(item => <Item key={item.id} {...item} />)\n`;
    content += '```\n\n';

    return content;
  }

  private generateExpressIssues(_context: TemplateContext): string {
    let content = `### Express Common Issues\n\n`;

    content += `#### Middleware Order\n\n`;
    content += `**Problem:** Middleware not executing or routes not working\n\n`;
    content += `**Solution:** Middleware order matters in Express:\n`;
    content += '```typescript\n';
    content += `// ✅ Correct order\n`;
    content += `app.use(cors());           // 1. CORS first\n`;
    content += `app.use(express.json());   // 2. Body parsers\n`;
    content += `app.use(authMiddleware);   // 3. Auth middleware\n`;
    content += `app.use('/api', routes);   // 4. Routes last\n`;
    content += `app.use(errorHandler);     // 5. Error handler last\n`;
    content += '```\n\n';

    content += `#### Async/Await Error Handling\n\n`;
    content += `**Problem:** Unhandled promise rejections crash the server\n\n`;
    content += `**Solution:** Wrap async route handlers:\n`;
    content += '```typescript\n';
    content += `// ❌ Wrong: Errors not caught\n`;
    content += `app.get('/users', async (req, res) => {\n`;
    content += `  const users = await db.users.findMany();  // If this fails, crashes\n`;
    content += `  res.json(users);\n`;
    content += `});\n\n`;
    content += `// ✅ Correct: Proper error handling\n`;
    content += `app.get('/users', async (req, res, next) => {\n`;
    content += `  try {\n`;
    content += `    const users = await db.users.findMany();\n`;
    content += `    res.json(users);\n`;
    content += `  } catch (error) {\n`;
    content += `    next(error);  // Pass to error handler\n`;
    content += `  }\n`;
    content += `});\n`;
    content += '```\n\n';

    content += `#### Response Already Sent\n\n`;
    content += `**Problem:** "Cannot set headers after they are sent to the client"\n\n`;
    content += `**Solutions:**\n`;
    content += `- Only send one response per request\n`;
    content += `- Use return after sending response:\n`;
    content += '```typescript\n';
    content += `// ❌ Wrong: Multiple responses\n`;
    content += `app.get('/data', (req, res) => {\n`;
    content += `  if (!req.query.id) {\n`;
    content += `    res.status(400).json({ error: 'Missing ID' });\n`;
    content += `  }\n`;
    content += `  res.json({ data: 'value' });  // Still executes!\n`;
    content += `});\n\n`;
    content += `// ✅ Correct: Return after response\n`;
    content += `app.get('/data', (req, res) => {\n`;
    content += `  if (!req.query.id) {\n`;
    content += `    return res.status(400).json({ error: 'Missing ID' });\n`;
    content += `  }\n`;
    content += `  res.json({ data: 'value' });\n`;
    content += `});\n`;
    content += '```\n\n';

    content += `#### CORS Not Working\n\n`;
    content += `**Problem:** CORS errors despite using cors middleware\n\n`;
    content += `**Solutions:**\n`;
    content += '```typescript\n';
    content += `// ❌ Wrong: CORS after routes\n`;
    content += `app.use('/api', routes);\n`;
    content += `app.use(cors());  // Too late!\n\n`;
    content += `// ✅ Correct: CORS before routes\n`;
    content += `app.use(cors({\n`;
    content += `  origin: process.env.FRONTEND_URL,\n`;
    content += `  credentials: true\n`;
    content += `}));\n`;
    content += `app.use('/api', routes);\n`;
    content += '```\n\n';

    return content;
  }

  private generatePrismaIssues(_context: TemplateContext): string {
    let content = `### Prisma Common Issues\n\n`;

    content += `#### Client Not Generated\n\n`;
    content += `**Problem:** "Cannot find module '@prisma/client'"\n\n`;
    content += `**Solution:**\n`;
    content += '```bash\n';
    content += `cd backend\n`;
    content += `npx prisma generate\n`;
    content += '```\n\n';
    content += `**Note:** Run \`prisma generate\` after every schema change\n\n`;

    content += `#### Migration Failed\n\n`;
    content += `**Problem:** Migration fails with constraint errors\n\n`;
    content += `**Solutions:**\n`;
    content += `1. Reset database (development only):\n`;
    content += '```bash\n';
    content += `npx prisma migrate reset\n`;
    content += '```\n\n';
    content += `2. Create migration without applying:\n`;
    content += '```bash\n';
    content += `npx prisma migrate dev --create-only\n`;
    content += `# Edit migration file if needed\n`;
    content += `npx prisma migrate dev\n`;
    content += '```\n\n';

    content += `#### Type Errors After Schema Change\n\n`;
    content += `**Problem:** TypeScript errors after updating Prisma schema\n\n`;
    content += `**Solution:**\n`;
    content += '```bash\n';
    content += `# Always run both commands\n`;
    content += `npx prisma generate      # Regenerate types\n`;
    content += `npx prisma migrate dev   # Apply changes\n`;
    content += '```\n\n';

    return content;
  }
}
