#!/usr/bin/env node

import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
  Tool,
} from '@modelcontextprotocol/sdk/types.js';
import { chromium, Browser, Page } from 'playwright';
import { nanoid } from 'nanoid';
import { APIKeyManager, APIKeyInfo } from './utils/api-key-manager.js';
import { CloudAIService } from './utils/cloud-ai-service.js';
import { LocalDebugEngine } from './engines/local-debug-engine.js';
import { DebugSession as BaseDebugSession } from './types.js';
import { tidewave } from './utils/tidewave-integration.js';
import { AuditEngine } from './engines/audit-engine.js';
import { VersionChecker } from './utils/version-checker.js';
import { CICDIntegration } from './utils/ci-cd-integration.js';

interface DebugSession {
  id: string;
  sessionId: string;
  browser: Browser;
  page: Page;
  url: string;
  framework: string;
  startTime: Date;
  state: any;
  events: any[];
}

/**
 * AI Debug Local MCP Server
 * 
 * Revolutionary local debugging with freemium cloud AI features.
 * 
 * Architecture:
 * - Runs locally (works with localhost apps)
 * - Basic debugging (free tier)
 * - Advanced AI analysis (paid tier with API key)
 * - Compiled binary distribution (IP protection)
 */
export class AIDebugLocalMCPServer {
  private server: Server;
  private sessions: Map<string, DebugSession> = new Map();
  private apiKeyManager: APIKeyManager;
  private cloudAI: CloudAIService;
  private localEngine: LocalDebugEngine;
  private auditEngine: AuditEngine;
  private versionChecker: VersionChecker;
  private cicdIntegration: CICDIntegration;

  constructor() {
    this.versionChecker = new VersionChecker();
    this.server = new Server(
      {
        name: 'ai-debug-local',
        version: '1.0.0',
      },
      {
        capabilities: {
          tools: {},
        },
      }
    );

    this.apiKeyManager = new APIKeyManager();
    this.cloudAI = new CloudAIService();
    this.localEngine = new LocalDebugEngine();
    this.auditEngine = new AuditEngine();
    this.cicdIntegration = new CICDIntegration();

    this.setupToolHandlers();
    this.initializeServices();
  }
  
  private async initializeServices() {
    // Initialize API key manager
    await this.apiKeyManager.initialize();
    
    // Set API key for cloud service if available
    const apiKey = process.env.AI_DEBUG_API_KEY;
    if (apiKey) {
      this.cloudAI.setApiKey(apiKey);
    }
  }

  private setupToolHandlers() {
    this.server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: [
          {
            name: 'inject_debugging',
            description: 'Inject AI debugging capabilities into a local web application. Launches a browser, navigates to your app, and injects revolutionary debugging code. Works with localhost and private applications.',
            inputSchema: {
              type: 'object',
              properties: {
                url: {
                  type: 'string',
                  description: 'URL of the web application to debug (e.g., http://localhost:3000)'
                },
                framework: {
                  type: 'string',
                  enum: ['auto', 'nextjs', 'remix', 'astro', 'nuxt', 'qwik', 'solidjs', 'sveltekit', 'rails', 'django', 'phoenix', 'react', 'vue', 'angular', 'svelte', 'flutter-web'],
                  description: 'Web framework to optimize for (auto-detect if not specified)',
                  default: 'auto'
                },
                headless: {
                  type: 'boolean',
                  description: 'Run browser in headless mode (default: false)',
                  default: false
                }
              },
              required: ['url']
            }
          },
          {
            name: 'monitor_realtime',
            description: 'Monitor real-time application events. FREE: Basic event collection. PREMIUM: AI-powered pattern analysis and insights.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                },
                duration: {
                  type: 'number',
                  description: 'Monitoring duration in seconds (default: 30)',
                  default: 30
                },
                aiAnalysis: {
                  type: 'boolean',
                  description: 'Enable AI-powered analysis (requires API key)',
                  default: false
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'simulate_user_action',
            description: 'Simulate user interactions in the local browser. FREE: Basic actions. PREMIUM: AI-optimized interaction patterns.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                },
                action: {
                  type: 'string',
                  enum: ['click', 'type', 'submit', 'scroll', 'hover'],
                  description: 'Type of user action'
                },
                selector: {
                  type: 'string',
                  description: 'CSS selector for target element'
                },
                value: {
                  type: 'string',
                  description: 'Value for type actions'
                }
              },
              required: ['sessionId', 'action', 'selector']
            }
          },
          {
            name: 'take_screenshot',
            description: 'Capture screenshots of your local application for visual debugging.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                },
                fullPage: {
                  type: 'boolean',
                  description: 'Capture full page (default: true)',
                  default: true
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'analyze_with_ai',
            description: 'PREMIUM: Get revolutionary AI insights about your application. Requires API key.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                },
                analysisType: {
                  type: 'string',
                  enum: ['performance', 'ux', 'accessibility', 'security', 'comprehensive'],
                  description: 'Type of AI analysis',
                  default: 'comprehensive'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'get_debug_report',
            description: 'Generate debugging report. FREE: Basic report. PREMIUM: AI-enhanced with insights and recommendations.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                },
                includeAI: {
                  type: 'boolean',
                  description: 'Include AI analysis (requires API key)',
                  default: false
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'close_session',
            description: 'Close debugging session and clean up browser resources.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'get_subscription_info',
            description: 'Get information about AI Debug subscription and API key status.',
            inputSchema: {
              type: 'object',
              properties: {},
              additionalProperties: false
            }
          },
          {
            name: 'run_audit',
            description: 'Run comprehensive audits on the web page for accessibility, performance, SEO, security, and best practices. Returns detailed scores and actionable recommendations.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                },
                categories: {
                  type: 'array',
                  items: {
                    type: 'string',
                    enum: ['all', 'accessibility', 'performance', 'seo', 'security', 'bestPractices']
                  },
                  description: 'Audit categories to run (default: all)',
                  default: ['all']
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'mock_network',
            description: 'Mock network responses to test different scenarios. Useful for testing error handling, slow responses, or specific data conditions.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                },
                action: {
                  type: 'string',
                  enum: ['add', 'remove', 'clear', 'list'],
                  description: 'Mock action to perform'
                },
                urlPattern: {
                  type: 'string',
                  description: 'URL pattern to mock (supports * wildcards)'
                },
                response: {
                  type: 'object',
                  properties: {
                    status: {
                      type: 'number',
                      description: 'HTTP status code (default: 200)'
                    },
                    body: {
                      description: 'Response body (string or JSON)'
                    },
                    headers: {
                      type: 'object',
                      description: 'Response headers'
                    },
                    delay: {
                      type: 'number',
                      description: 'Delay in milliseconds before responding'
                    }
                  }
                }
              },
              required: ['sessionId', 'action']
            }
          },
          {
            name: 'flutter_widget_tree',
            description: 'Get the Flutter widget tree for debugging Flutter Web applications. Shows widget hierarchy, properties, and render objects.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'flutter_performance',
            description: 'Get Flutter performance metrics including FPS, frame times, and widget build performance.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'flutter_inspect_widget',
            description: 'Inspect a specific Flutter widget by ID to see its properties and state.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                },
                widgetId: {
                  type: 'string',
                  description: 'Widget ID to inspect'
                },
                highlight: {
                  type: 'boolean',
                  description: 'Highlight the widget in the UI',
                  default: false
                }
              },
              required: ['sessionId', 'widgetId']
            }
          },
          {
            name: 'tidewave_query',
            description: 'Execute Tidewave AI-powered queries against Phoenix/Rails applications for enhanced debugging and testing. Access logs, execute SQL, trace processes, and more.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                },
                tool: {
                  type: 'string',
                  enum: ['logs', 'eval', 'sql', 'processes', 'documentation', 'dependencies'],
                  description: 'Tidewave tool to execute'
                },
                params: {
                  type: 'object',
                  description: 'Parameters for the Tidewave tool',
                  additionalProperties: true
                }
              },
              required: ['sessionId', 'tool']
            }
          },
          {
            name: 'debug_hydration',
            description: 'Detect SSR/CSR hydration mismatches that cause React, Next.js, Remix, and other framework errors. Shows server vs client HTML differences.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'analyze_bundles',
            description: 'Analyze JavaScript bundle sizes, loading patterns, and code coverage. Helps identify performance bottlenecks and unused code.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'track_route_changes',
            description: 'Monitor SPA route changes, navigation performance, and history state. Works with any client-side router.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'detect_problems',
            description: 'Automatically detect common web app problems: hydration errors, large bundles, slow routes, poor caching, and more.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'nextjs_page_info',
            description: 'Get Next.js page information including rendering type (SSR/SSG/ISR), data fetching methods, and app directory usage.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'nextjs_image_audit',
            description: 'Audit Next.js image optimization. Detects unoptimized images, suggests next/image usage, and identifies oversized images.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'nextjs_detect_issues',
            description: 'Detect Next.js specific problems: hydration errors, large RSC payloads, slow transitions, unnecessary SSR.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'rails_turbo_analysis',
            description: 'Analyze Rails Turbo/Hotwire performance: cache hit rates, frame loading, navigation timing.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'csrf_security_check',
            description: 'Check CSRF token configuration for Rails/Django apps. Detects missing tokens in forms and AJAX requests.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'stimulus_controllers',
            description: 'List and analyze Stimulus controllers in Rails applications. Shows actions, targets, and potential issues.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'meta_framework_info',
            description: 'Get information about detected meta-framework (Remix, Astro, Nuxt, Qwik, SolidJS, SvelteKit) including version, features, and build tool.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'remix_loader_analysis',
            description: 'Analyze Remix loader performance including execution times, data sizes, and caching behavior.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'astro_islands_audit',
            description: 'Audit Astro islands for hydration strategies, component usage, and performance optimization opportunities.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'nuxt_payload_analysis',
            description: 'Analyze Nuxt payload size, hydration state, and server-side data to identify optimization opportunities.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'qwik_resumability_check',
            description: 'Check Qwik resumability performance including serialized state size, QRL loading, and lazy execution metrics.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'vite_hmr_monitor',
            description: 'Monitor Vite HMR (Hot Module Replacement) events, update times, and errors during development.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'detect_meta_framework_issues',
            description: 'Detect framework-specific issues in Remix, Astro, Nuxt, Qwik, SolidJS, or SvelteKit applications.',
            inputSchema: {
              type: 'object',
              properties: {
                sessionId: {
                  type: 'string',
                  description: 'Debug session ID'
                }
              },
              required: ['sessionId']
            }
          },
          {
            name: 'init_ci_cd',
            description: 'Initialize CI/CD pipeline templates with AI debugging integration. Generates GitHub Actions, GitLab CI, or other CI/CD configurations with automated testing and debugging capabilities.',
            inputSchema: {
              type: 'object',
              properties: {
                projectDir: {
                  type: 'string',
                  description: 'Project directory path'
                },
                provider: {
                  type: 'string',
                  enum: ['github', 'gitlab', 'circleci', 'jenkins'],
                  description: 'CI/CD provider',
                  default: 'github'
                },
                appUrl: {
                  type: 'string',
                  description: 'Application URL for testing',
                  default: 'http://localhost:3000'
                },
                framework: {
                  type: 'string',
                  enum: ['auto', 'react', 'vue', 'angular', 'nextjs', 'phoenix', 'rails', 'node'],
                  description: 'Project framework (auto-detect if not specified)',
                  default: 'auto'
                },
                tools: {
                  type: 'array',
                  items: {
                    type: 'string',
                    enum: ['debug_page', 'performance_audit', 'run_accessibility_check', 'tidewave_query']
                  },
                  description: 'AI debugging tools to include in CI/CD',
                  default: ['debug_page', 'performance_audit']
                }
              },
              required: ['projectDir']
            }
          }
        ] as Tool[]
      };
    });

    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      try {
        switch (request.params.name) {
          case 'inject_debugging':
            return await this.injectDebugging(request.params.arguments);
          case 'monitor_realtime':
            return await this.monitorRealtime(request.params.arguments);
          case 'simulate_user_action':
            return await this.simulateUserAction(request.params.arguments);
          case 'take_screenshot':
            return await this.takeScreenshot(request.params.arguments);
          case 'analyze_with_ai':
            return await this.analyzeWithAI(request.params.arguments);
          case 'get_debug_report':
            return await this.getDebugReport(request.params.arguments);
          case 'close_session':
            return await this.closeSession(request.params.arguments);
          case 'get_subscription_info':
            return await this.getSubscriptionInfo();
          case 'run_audit':
            return await this.runAudit(request.params.arguments);
          case 'mock_network':
            return await this.mockNetwork(request.params.arguments);
          case 'flutter_widget_tree':
            return await this.getFlutterWidgetTree(request.params.arguments);
          case 'flutter_performance':
            return await this.getFlutterPerformance(request.params.arguments);
          case 'flutter_inspect_widget':
            return await this.inspectFlutterWidget(request.params.arguments);
          case 'tidewave_query':
            return await this.executeTidewaveQuery(request.params.arguments);
          case 'debug_hydration':
            return await this.debugHydration(request.params.arguments);
          case 'analyze_bundles':
            return await this.analyzeBundles(request.params.arguments);
          case 'track_route_changes':
            return await this.trackRouteChanges(request.params.arguments);
          case 'detect_problems':
            return await this.detectProblems(request.params.arguments);
          case 'nextjs_page_info':
            return await this.getNextJSPageInfo(request.params.arguments);
          case 'nextjs_image_audit':
            return await this.getNextJSImageAudit(request.params.arguments);
          case 'nextjs_detect_issues':
            return await this.detectNextJSIssues(request.params.arguments);
          case 'rails_turbo_analysis':
            return await this.analyzeTurbo(request.params.arguments);
          case 'csrf_security_check':
            return await this.checkCSRFSecurity(request.params.arguments);
          case 'stimulus_controllers':
            return await this.getStimulusControllers(request.params.arguments);
          case 'meta_framework_info':
            return await this.getMetaFrameworkInfo(request.params.arguments);
          case 'remix_loader_analysis':
            return await this.analyzeRemixLoaders(request.params.arguments);
          case 'astro_islands_audit':
            return await this.auditAstroIslands(request.params.arguments);
          case 'nuxt_payload_analysis':
            return await this.analyzeNuxtPayload(request.params.arguments);
          case 'qwik_resumability_check':
            return await this.checkQwikResumability(request.params.arguments);
          case 'vite_hmr_monitor':
            return await this.monitorViteHMR(request.params.arguments);
          case 'detect_meta_framework_issues':
            return await this.detectMetaFrameworkIssues(request.params.arguments);
          case 'init_ci_cd':
            return await this.initCICD(request.params.arguments);
          default:
            throw new Error(`Unknown tool: ${request.params.name}`);
        }
      } catch (error) {
        return this.createErrorResponse(error);
      }
    });
  }

  private async injectDebugging(args: any) {
    const { url, framework = 'auto', headless = false } = args;
    const sessionId = nanoid();

    try {
      // Launch local browser
      const browser = await chromium.launch({ 
        headless,
        devtools: !headless 
      });
      
      const page = await browser.newPage();
      await page.goto(url, { waitUntil: 'networkidle' });

      // Attach local engine to page
      await this.localEngine.attachToPage(page);
      
      // Detect Tidewave capabilities
      const tidewaveCapabilities = await tidewave.detectTidewave(url);
      
      // Detect framework
      let detectedFramework = framework;
      if (framework === 'auto') {
        detectedFramework = await this.localEngine.detectFramework(page);
        
        // If Tidewave detected, use its framework info
        if (tidewaveCapabilities) {
          detectedFramework = tidewaveCapabilities.framework === 'unknown' ? detectedFramework : tidewaveCapabilities.framework;
        }
      }

      // Inject our revolutionary debugging code (local version)
      await this.localEngine.injectDebugging(page, detectedFramework);

      // Capture initial state with Tidewave enhancement
      let state = await this.localEngine.captureState();
      if (tidewaveCapabilities) {
        state = await tidewave.enhanceDebugState(url, state);
      }

      // Store session
      const session: DebugSession = {
        id: sessionId,
        sessionId,
        browser,
        page,
        url,
        framework: detectedFramework,
        startTime: new Date(),
        state,
        events: []
      };

      this.sessions.set(sessionId, session);

      // Wait for initialization
      await page.waitForTimeout(1000);

      return {
        content: [{
          type: 'text',
          text: `🔬 **AI Debug Session Started**

**Session ID:** \`${sessionId}\`
**URL:** ${url}
**Framework:** ${detectedFramework}
**Browser:** Local browser launched

**🚀 Debugging Capabilities Injected:**
- ✅ Real-time event monitoring
- ✅ User interaction simulation  
- ✅ Visual debugging with screenshots
- ✅ Framework-specific hooks (${detectedFramework})
- ✅ Local performance analysis
${detectedFramework === 'flutter-web' ? `- ✅ Flutter widget tree inspection
- ✅ Flutter performance metrics (FPS, frame times)
- ✅ Flutter widget property inspection
- ✅ Flutter DevTools integration${this.localEngine.isFlutterConnected() ? ' (Connected!)' : ' (Attempting connection...)'}` : ''}

**💡 Available Features:**
- **FREE:** Basic debugging, screenshots, event monitoring
- **PREMIUM:** AI insights, advanced analysis, recommendations

**Next Steps:**
1. Use \`monitor_realtime\` to observe behavior
2. Use \`simulate_user_action\` to test interactions
3. Use \`analyze_with_ai\` for revolutionary AI insights (Premium)

${this.apiKeyManager.hasValidKey() ? 
  '🔑 **Premium features available** with your API key!' :
  '💡 **Upgrade:** Get API key at https://ai-debug.com/pricing for AI features'
}

**Local debugging is now active! 🎯**`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to inject debugging: ${error instanceof Error ? error.message : error}`);
    }
  }

  private async monitorRealtime(args: any) {
    const { sessionId, duration = 30, aiAnalysis = false } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    // Always do local monitoring
    const events = await this.localEngine.monitorEvents(session.page, duration);
    session.events.push(...events);
    
    // Get console messages with smart truncation
    const consoleMessages = this.localEngine.getConsoleMessages({
      maxTokens: 2000  // Reserve tokens for console output
    });

    let analysis = this.localEngine.basicAnalysis(events);

    // Premium AI analysis if requested and available
    if (aiAnalysis) {
      if (!this.apiKeyManager.hasValidKey()) {
        return this.createPremiumFeatureResponse('AI Analysis');
      }

      try {
        const aiInsights = await this.cloudAI.analyzeEvents(events);
        analysis = { ...analysis, ...aiInsights };
      } catch (error) {
        // Fallback to local analysis if cloud fails
        console.error('Cloud AI analysis failed, using local analysis');
      }
    }

    return {
      content: [{
        type: 'text',
        text: `📊 **Real-time Monitoring Complete** (${duration}s)

**Events Captured:** ${events.length}
**User Interactions:** ${events.filter(e => e.type === 'userInteraction').length}
**Network Requests:** ${events.filter(e => e.type === 'networkRequest').length}
**DOM Changes:** ${events.filter(e => e.type === 'domMutation').length}
**Errors:** ${events.filter(e => e.type === 'error').length}

**📈 Basic Analysis:**
- **Most Active Element:** ${analysis.mostActiveElement || 'N/A'}
- **Performance Score:** ${analysis.performanceScore || 'N/A'}/100
- **Error Rate:** ${analysis.errorRate || 0}%

${aiAnalysis && analysis.aiInsights ? 
  `**🧠 AI Insights:**\n${analysis.aiInsights.map((insight: string) => `💡 ${insight}`).join('\n')}` :
  '💡 **Enable AI analysis** with `aiAnalysis: true` for revolutionary insights!'
}

${events.filter(e => e.type === 'error').length > 0 ?
  `⚠️ **Errors Detected:**\n${events.filter(e => e.type === 'error').map(e => `- ${e.data.message}`).slice(0, 3).join('\n')}` :
  '✅ No errors detected'
}`
      }]
    };
  }

  private async simulateUserAction(args: any) {
    const { sessionId, action, selector, value } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    const result = await this.localEngine.simulateAction(session.page, action, selector, value);
    
    // Capture events triggered by the action
    const postActionEvents = await this.localEngine.captureRecentEvents(session.page, 2000);
    session.events.push(...postActionEvents);

    return {
      content: [{
        type: 'text',
        text: `🎯 **User Action Simulation**

**Action:** ${result.description}
**Success:** ${result.success ? '✅' : '❌'}
**Duration:** ${result.duration}ms

**📊 Response Analysis:**
- **Events Triggered:** ${postActionEvents.length}
- **DOM Changes:** ${postActionEvents.filter(e => e.type === 'domMutation').length}
- **Network Activity:** ${postActionEvents.filter(e => e.type === 'networkRequest').length}

${result.success ? 
  '✅ Action completed successfully' : 
  `❌ Action failed: ${result.error}`
}

${postActionEvents.length > 0 ?
  `**Recent Events:**\n${postActionEvents.slice(0, 3).map(e => `- ${e.type}: ${e.data.target || e.data.url || 'N/A'}`).join('\n')}` :
  '⚠️ No response detected - action may have been ignored'
}`
      }]
    };
  }

  private async takeScreenshot(args: any) {
    const { sessionId, fullPage = true } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    const screenshot = await session.page.screenshot({
      type: 'png',
      fullPage
    });

    return {
      content: [
        {
          type: 'text',
          text: `📸 **Screenshot Captured**

**Type:** ${fullPage ? 'Full page' : 'Viewport'}
**Timestamp:** ${new Date().toLocaleTimeString()}
**URL:** ${session.url}

*Visual debugging via local browser*`
        },
        {
          type: 'image',
          data: screenshot.toString('base64'),
          mimeType: 'image/png'
        }
      ]
    };
  }

  private async analyzeWithAI(args: any) {
    const { sessionId, analysisType = 'comprehensive' } = args;
    
    if (!this.apiKeyManager.hasValidKey()) {
      return this.createPremiumFeatureResponse('AI Analysis');
    }

    const session = this.sessions.get(sessionId);
    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      // Get current page state
      const pageState = await this.localEngine.extractPageState(session.page);
      
      // Send to cloud AI for revolutionary analysis
      const aiAnalysis = await this.cloudAI.comprehensiveAnalysis(
        session.events,
        pageState,
        analysisType
      );

      await this.apiKeyManager.recordUsage('ai_analysis');

      return {
        content: [{
          type: 'text',
          text: `🧠 **Revolutionary AI Analysis** (${analysisType})

## 🎯 Overall Assessment
**Health Score:** ${aiAnalysis.healthScore}/100
**User Experience:** ${aiAnalysis.uxScore}/100
**Performance:** ${aiAnalysis.performanceScore}/100

## 🔍 Key Findings
${aiAnalysis.findings.map((finding: any) => 
  `**${finding.severity.toUpperCase()}:** ${finding.title}\n   ${finding.description}`
).join('\n\n')}

## 💡 AI Recommendations
${aiAnalysis.recommendations.map((rec: any) => 
  `**${rec.priority}:** ${rec.title}\n   ${rec.description}\n   *Impact:* ${rec.impact}`
).join('\n\n')}

## ⚡ Quick Fixes
${aiAnalysis.quickFixes.map((fix: string) => `- ${fix}`).join('\n')}

## 🏗️ Framework-Specific Insights
${aiAnalysis.frameworkInsights.map((insight: string) => `💡 ${insight}`).join('\n')}

*Powered by revolutionary AI debugging engine*`
        }]
      };
    } catch (error) {
      throw new Error(`AI analysis failed: ${error instanceof Error ? error.message : error}`);
    }
  }

  private async getDebugReport(args: any) {
    const { sessionId, includeAI = false } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    // Always generate basic report
    const basicReport = this.localEngine.generateBasicReport(session);

    let aiEnhancements = null;
    if (includeAI) {
      if (!this.apiKeyManager.hasValidKey()) {
        return this.createPremiumFeatureResponse('AI-Enhanced Reports');
      }

      try {
        aiEnhancements = await this.cloudAI.enhanceReport(basicReport, session.events);
        await this.apiKeyManager.recordUsage('ai_report');
      } catch (error) {
        console.error('AI enhancement failed, using basic report');
      }
    }

    const duration = Math.round((Date.now() - session.startTime.getTime()) / 1000);

    return {
      content: [{
        type: 'text',
        text: `📋 **AI Debug Report** - Session ${sessionId}

## 🌐 Session Information
**URL:** ${session.url}
**Framework:** ${session.framework}
**Duration:** ${duration}s
**Events Captured:** ${session.events.length}

## 📊 Activity Summary
**User Interactions:** ${session.events.filter(e => e.type === 'userInteraction').length}
**Network Requests:** ${session.events.filter(e => e.type === 'networkRequest').length}
**DOM Changes:** ${session.events.filter(e => e.type === 'domMutation').length}
**Console Messages:** ${session.events.filter(e => e.type === 'console').length}
**Errors:** ${session.events.filter(e => e.type === 'error').length}

## 🔍 Basic Analysis
${basicReport.findings.map((finding: string) => `- ${finding}`).join('\n')}

${aiEnhancements ? `
## 🧠 AI-Enhanced Insights
**Performance Rating:** ${aiEnhancements.performanceRating}/10
**Code Quality:** ${aiEnhancements.codeQuality}/10
**User Experience:** ${aiEnhancements.uxRating}/10

**Key Recommendations:**
${aiEnhancements.recommendations.map((rec: string) => `💡 ${rec}`).join('\n')}

**Optimization Opportunities:**
${aiEnhancements.optimizations.map((opt: string) => `⚡ ${opt}`).join('\n')}
` : `
💡 **Upgrade for AI Insights:** Add \`includeAI: true\` and get revolutionary AI analysis!
🔗 **Get API Key:** https://ai-debug.com/pricing
`}

## 🕒 Recent Activity
${session.events.slice(-5).map(e => 
  `**${new Date(e.data.timestamp).toLocaleTimeString()}** - ${e.type}`
).join('\n')}

---
*Generated by AI Debug Local MCP Server*`
      }]
    };
  }

  private async closeSession(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    const duration = Math.round((Date.now() - session.startTime.getTime()) / 1000);
    const eventCount = session.events.length;

    await session.browser.close();
    this.sessions.delete(sessionId);

    return {
      content: [{
        type: 'text',
        text: `🔒 **Debug Session Closed**

**Session ID:** ${sessionId}
**Duration:** ${duration}s
**Events Captured:** ${eventCount}
**URL:** ${session.url}

Browser resources cleaned up successfully. ✅

*Session managed locally for complete privacy*`
      }]
    };
  }

  private async getSubscriptionInfo() {
    const keyStatus = this.apiKeyManager.getKeyStatus();
    const usage = this.apiKeyManager.getUsageStats();

    return {
      content: [{
        type: 'text',
        text: `💳 **AI Debug Subscription Status**

## 🔑 API Key Status
**Status:** ${keyStatus.valid ? '✅ Valid' : '❌ Invalid/Missing'}
**Tier:** ${keyStatus.tier || 'Free'}
${keyStatus.valid ? `**Expires:** ${keyStatus.expiresAt || 'Never'}` : ''}

## 📊 Usage Statistics
**This Month:**
- **AI Analysis:** ${usage.aiAnalysis}/${usage.limits.aiAnalysis === -1 ? '∞' : usage.limits.aiAnalysis}
- **AI Reports:** ${usage.aiReports}/${usage.limits.aiReports === -1 ? '∞' : usage.limits.aiReports}
- **Premium Features:** ${usage.premiumFeatures}/${usage.limits.premiumFeatures === -1 ? '∞' : usage.limits.premiumFeatures}

## 🚀 Available Features
**FREE Tier:**
- ✅ Local debugging and monitoring
- ✅ User action simulation  
- ✅ Screenshots and basic reports
- ✅ Framework detection

${keyStatus.valid ? `
**${keyStatus.tier?.toUpperCase()} Tier:**
- ✅ Revolutionary AI analysis
- ✅ AI-enhanced reports
- ✅ Advanced insights and recommendations
- ✅ Performance optimization suggestions
- ✅ Priority support
` : `
**PREMIUM Features (Requires API Key):**
- 🔒 Revolutionary AI analysis
- 🔒 AI-enhanced reports  
- 🔒 Advanced insights and recommendations
- 🔒 Performance optimization suggestions

**🔗 Upgrade:** https://ai-debug.com/pricing
`}

## 🔗 Quick Links
- **Dashboard:** https://ai-debug.com/dashboard
- **Documentation:** https://docs.ai-debug.com
- **Support:** https://ai-debug.com/support

*Revolutionary debugging technology for modern developers*`
      }]
    };
  }

  // Helper methods
  private createPremiumFeatureResponse(featureName: string) {
    return {
      content: [{
        type: 'text',
        text: `🔒 **Premium Feature: ${featureName}**

This feature requires an AI Debug API key.

**🚀 Why Upgrade?**
- 🧠 Revolutionary AI analysis powered by advanced algorithms
- 💡 Intelligent insights and recommendations  
- ⚡ Performance optimization suggestions
- 🔧 Framework-specific debugging intelligence
- 📊 Advanced reporting and analytics

**💳 Pricing:**
- **Pro:** $29/month - 100 AI analyses
- **Enterprise:** $299/month - Unlimited + priority support

**🔗 Get API Key:** https://ai-debug.com/pricing

**⚙️ Setup:**
1. Purchase API key at https://ai-debug.com/dashboard
2. Set environment variable: \`export AI_DEBUG_API_KEY=your_key\`
3. Restart your MCP server
4. Enjoy revolutionary AI debugging!

*Local debugging remains completely free forever.*`
      }]
    };
  }

  private async runAudit(args: any) {
    const { sessionId, categories = ['all'] } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    // Run the audit
    const auditResults = await this.auditEngine.performAudit(session.page, categories);
    
    // Calculate overall score
    const scores = Object.values(auditResults).map(r => r.score);
    const overallScore = Math.round(scores.reduce((a, b) => a + b, 0) / scores.length);
    
    // Count issues by severity
    const issueCounts = { error: 0, warning: 0, info: 0 };
    Object.values(auditResults).forEach(result => {
      result.issues.forEach(issue => {
        issueCounts[issue.severity]++;
      });
    });

    // Format the results
    let reportText = `🔍 **Comprehensive Audit Report**

**Overall Score:** ${overallScore}/100 ${getScoreEmoji(overallScore)}
**URL:** ${session.url}

**📊 Summary:**
- 🔴 Errors: ${issueCounts.error}
- 🟡 Warnings: ${issueCounts.warning}
- ℹ️ Info: ${issueCounts.info}

`;

    // Add results for each category
    for (const [category, result] of Object.entries(auditResults)) {
      reportText += `\n## ${getCategoryIcon(category)} ${formatCategoryName(category)} - ${result.score}/100\n\n`;
      
      if (result.issues.length > 0) {
        reportText += '**Issues:**\n';
        result.issues.forEach(issue => {
          const icon = issue.severity === 'error' ? '❌' : issue.severity === 'warning' ? '⚠️' : 'ℹ️';
          reportText += `${icon} ${issue.message}\n`;
        });
        reportText += '\n';
      }
      
      if (result.suggestions.length > 0) {
        reportText += '**Recommendations:**\n';
        result.suggestions.forEach(suggestion => {
          reportText += `💡 ${suggestion}\n`;
        });
      }
    }

    // Add AI insights if premium
    if (this.apiKeyManager.hasValidKey()) {
      reportText += `\n## 🧠 AI Insights (Premium)
✨ Based on the audit results, consider focusing on ${getTopPriority(auditResults)}
📈 Fixing all errors could improve your score by up to ${calculatePotentialImprovement(issueCounts)}%
🎯 Quick wins: Start with accessibility and performance optimizations`;
    } else {
      reportText += `\n💡 **Upgrade to Premium** for AI-powered insights and recommendations tailored to your specific issues.`;
    }

    return {
      content: [{
        type: 'text',
        text: reportText
      }]
    };

    function getScoreEmoji(score: number): string {
      if (score >= 90) return '🟢';
      if (score >= 70) return '🟡';
      if (score >= 50) return '🟠';
      return '🔴';
    }

    function getCategoryIcon(category: string): string {
      const icons: Record<string, string> = {
        accessibility: '♿',
        performance: '⚡',
        seo: '🔍',
        security: '🔒',
        bestPractices: '✅'
      };
      return icons[category] || '📋';
    }

    function formatCategoryName(category: string): string {
      const names: Record<string, string> = {
        accessibility: 'Accessibility',
        performance: 'Performance',
        seo: 'SEO',
        security: 'Security',
        bestPractices: 'Best Practices'
      };
      return names[category] || category;
    }

    function getTopPriority(results: Record<string, any>): string {
      let lowestScore = 100;
      let priority = '';
      
      for (const [category, result] of Object.entries(results)) {
        if (result.score < lowestScore) {
          lowestScore = result.score;
          priority = formatCategoryName(category);
        }
      }
      
      return priority || 'general improvements';
    }

    function calculatePotentialImprovement(counts: Record<string, number>): number {
      return Math.min(counts.error * 10 + counts.warning * 5, 50);
    }
  }

  private async mockNetwork(args: any) {
    const { sessionId, action, urlPattern, response } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    switch (action) {
      case 'add':
        if (!urlPattern) {
          throw new Error('URL pattern required for add action');
        }
        
        await this.localEngine.addNetworkMock(urlPattern, response || {});
        
        return {
          content: [{
            type: 'text',
            text: `🎭 **Network Mock Added**

**Pattern:** \`${urlPattern}\`
**Status:** ${response?.status || 200}
**Delay:** ${response?.delay ? `${response.delay}ms` : 'None'}

The following URLs will be intercepted:
${this.getMatchingExamples(urlPattern)}

**Active Mocks:** ${this.localEngine.getMockedUrls().length}

💡 **Usage Tips:**
- Test error scenarios with status codes like 404, 500
- Simulate slow networks with delay
- Mock specific JSON responses for edge cases`
          }]
        };

      case 'remove':
        if (!urlPattern) {
          throw new Error('URL pattern required for remove action');
        }
        
        const removed = this.localEngine.removeNetworkMock(urlPattern);
        
        return {
          content: [{
            type: 'text',
            text: removed 
              ? `✅ Removed mock for pattern: \`${urlPattern}\``
              : `❌ No mock found for pattern: \`${urlPattern}\``
          }]
        };

      case 'clear':
        this.localEngine.clearAllMocks();
        
        return {
          content: [{
            type: 'text',
            text: '🧹 All network mocks cleared'
          }]
        };

      case 'list':
        const mocks = this.localEngine.getMockedUrls();
        
        return {
          content: [{
            type: 'text',
            text: mocks.length > 0
              ? `📋 **Active Network Mocks:**\n${mocks.map(m => `- \`${m}\``).join('\n')}`
              : '📋 No active network mocks'
          }]
        };

      default:
        throw new Error(`Unknown mock action: ${action}`);
    }
  }

  private getMatchingExamples(pattern: string): string {
    const examples = [];
    
    if (pattern.includes('*')) {
      if (pattern === '*') {
        examples.push('- All requests');
      } else if (pattern.startsWith('*/')) {
        examples.push(`- Any domain with path ${pattern.substring(1)}`);
      } else if (pattern.endsWith('/*')) {
        examples.push(`- All paths under ${pattern.substring(0, pattern.length - 2)}`);
      } else {
        examples.push(`- URLs matching pattern ${pattern}`);
      }
    } else {
      examples.push(`- Exact URL: ${pattern}`);
    }
    
    return examples.join('\n');
  }

  private async getFlutterWidgetTree(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    if (session.framework !== 'flutter-web') {
      throw new Error('This tool only works with Flutter Web applications');
    }

    try {
      const widgetTree = await this.localEngine.getFlutterWidgetTree();
      
      if (!widgetTree) {
        return {
          content: [{
            type: 'text',
            text: `⚠️ **Flutter DevTools Not Connected**

Flutter was detected but DevTools connection failed.

**To enable Flutter debugging:**
1. Run your Flutter app in debug mode: \`flutter run -d chrome --web-port=8080\`
2. Look for "Observatory listening on" in the console
3. The debugger will automatically connect

**Alternative:** Use browser DevTools with Flutter Inspector extension.`
          }]
        };
      }

      // Format widget tree for display
      const formatWidget = (widget: any, indent: number = 0): string => {
        const spacing = '  '.repeat(indent);
        const props = widget.properties ? Object.entries(widget.properties)
          .map(([k, v]) => `${k}: ${JSON.stringify(v)}`)
          .join(', ') : '';
        
        let result = `${spacing}${widget.type}${props ? ` (${props})` : ''}`;
        
        if (widget.renderObject) {
          result += ` [${widget.renderObject.type}]`;
          if (widget.renderObject.size) {
            result += ` ${widget.renderObject.size.width}x${widget.renderObject.size.height}`;
          }
        }
        
        result += '\n';
        
        if (widget.children) {
          widget.children.forEach((child: any) => {
            result += formatWidget(child, indent + 1);
          });
        }
        
        return result;
      };

      return {
        content: [{
          type: 'text',
          text: `🎯 **Flutter Widget Tree**

\`\`\`
${formatWidget(widgetTree)}
\`\`\`

**Widget Count:** ${countWidgets(widgetTree)}
**Max Depth:** ${getMaxDepth(widgetTree)}

💡 **Tips:**
- Use \`flutter_inspect_widget\` to examine specific widgets
- Widget IDs are shown in square brackets
- RenderObject info shows actual rendered size`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to get Flutter widget tree: ${error instanceof Error ? error.message : error}`);
    }

    function countWidgets(widget: any): number {
      return 1 + (widget.children?.reduce((sum: number, child: any) => sum + countWidgets(child), 0) || 0);
    }

    function getMaxDepth(widget: any, depth: number = 0): number {
      const childDepths = widget.children?.map((child: any) => getMaxDepth(child, depth + 1)) || [];
      return Math.max(depth, ...childDepths);
    }
  }

  private async getFlutterPerformance(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    if (session.framework !== 'flutter-web') {
      throw new Error('This tool only works with Flutter Web applications');
    }

    try {
      const [perfData, memoryData] = await Promise.all([
        this.localEngine.getFlutterPerformance(),
        this.localEngine.getFlutterMemoryUsage()
      ]);

      return {
        content: [{
          type: 'text',
          text: `⚡ **Flutter Performance Metrics**

**🎬 Frame Performance:**
- **FPS:** ${perfData?.fps || 'N/A'} fps ${perfData?.fps < 30 ? '⚠️ Low FPS!' : perfData?.fps >= 60 ? '✅' : ''}
- **Frame Time:** ${perfData?.frameTime?.toFixed(2) || 'N/A'} ms
- **Widget Build Time:** ${perfData?.widgetBuildTime?.toFixed(2) || 'N/A'} ms
- **Raster Time:** ${perfData?.rasterTime?.toFixed(2) || 'N/A'} ms

**💾 Memory Usage:**
- **Used:** ${memoryData ? (memoryData.used / 1024 / 1024).toFixed(2) : 'N/A'} MB
- **Capacity:** ${memoryData ? (memoryData.capacity / 1024 / 1024).toFixed(2) : 'N/A'} MB
- **External:** ${memoryData ? (memoryData.external / 1024 / 1024).toFixed(2) : 'N/A'} MB

**📊 Performance Analysis:**
${getPerformanceAnalysis(perfData)}

**💡 Optimization Tips:**
${getOptimizationTips(perfData)}`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to get Flutter performance data: ${error instanceof Error ? error.message : error}`);
    }

    function getPerformanceAnalysis(perf: any): string {
      if (!perf) return '- No performance data available';
      
      const issues = [];
      if (perf.fps < 30) issues.push('- 🔴 Critical: FPS below 30, users will notice stuttering');
      else if (perf.fps < 60) issues.push('- 🟡 Warning: FPS below 60, some jank may be visible');
      
      if (perf.frameTime > 16.67) issues.push('- ⚠️ Frame time exceeds 16ms budget');
      if (perf.widgetBuildTime > 8) issues.push('- ⚠️ Widget builds taking too long');
      
      return issues.length > 0 ? issues.join('\n') : '- ✅ Performance looks good!';
    }

    function getOptimizationTips(perf: any): string {
      const tips = [];
      
      if (perf?.fps < 60) {
        tips.push('- Use const constructors where possible');
        tips.push('- Implement shouldRebuild in custom widgets');
        tips.push('- Avoid rebuilding large widget trees');
      }
      
      if (perf?.widgetBuildTime > 8) {
        tips.push('- Break down complex widgets into smaller ones');
        tips.push('- Use RepaintBoundary for expensive widgets');
        tips.push('- Cache computed values');
      }
      
      return tips.length > 0 ? tips.join('\n') : '- Performance is optimal';
    }
  }

  private async inspectFlutterWidget(args: any) {
    const { sessionId, widgetId, highlight = false } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    if (session.framework !== 'flutter-web') {
      throw new Error('This tool only works with Flutter Web applications');
    }

    try {
      if (highlight) {
        await this.localEngine.highlightFlutterWidget(widgetId);
      }

      const properties = await this.localEngine.inspectFlutterWidget(widgetId);
      
      if (!properties) {
        return {
          content: [{
            type: 'text',
            text: `❌ Widget with ID "${widgetId}" not found or no longer in tree`
          }]
        };
      }

      // Format properties for display
      const formatProperties = (props: any, indent: number = 0): string => {
        const spacing = '  '.repeat(indent);
        let result = '';
        
        for (const [key, value] of Object.entries(props)) {
          if (typeof value === 'object' && value !== null) {
            result += `${spacing}${key}:\n${formatProperties(value, indent + 1)}`;
          } else {
            result += `${spacing}${key}: ${value}\n`;
          }
        }
        
        return result;
      };

      return {
        content: [{
          type: 'text',
          text: `🔍 **Flutter Widget Inspector**

**Widget ID:** ${widgetId}
${highlight ? '✨ Widget highlighted in UI' : ''}

**Properties:**
\`\`\`
${formatProperties(properties)}
\`\`\`

💡 **Actions:**
- Set \`highlight: true\` to visually highlight this widget
- Use property values to understand widget state
- Check parent/child relationships in widget tree`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to inspect Flutter widget: ${error instanceof Error ? error.message : error}`);
    }
  }

  private async executeTidewaveQuery(args: any) {
    const { sessionId, tool, params = {} } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      // Check if the session has Tidewave capabilities
      if (!session.state.tidewave) {
        return {
          content: [{
            type: 'text',
            text: '❌ **Tidewave Not Available**\n\nThis application does not have Tidewave enabled. To use Tidewave features:\n\n**For Phoenix:**\n1. Add `{:tidewave, "~> 0.1.0"}` to your `mix.exs`\n2. Configure Tidewave in your Phoenix endpoint\n\n**For Rails:**\n1. Add `gem "tidewave_rails"` to your Gemfile\n2. Configure Tidewave in your Rails application\n\nThen restart your application and try again.'
          }]
        };
      }

      // Execute the Tidewave tool
      const result = await tidewave.executeTool(session.url, { tool, params });
      
      if (!result.success) {
        return {
          content: [{
            type: 'text',
            text: `❌ **Tidewave Error**\n\n${result.error}\n\n**Available Tools:** ${session.state.tidewave.available_tools.join(', ')}`
          }]
        };
      }

      // Format the response based on tool type
      let formattedResponse = '';
      
      switch (tool) {
        case 'logs':
          formattedResponse = this.formatTidewaveLogs(result.data);
          break;
        case 'sql':
          formattedResponse = this.formatTidewaveSQL(result.data);
          break;
        case 'processes':
          formattedResponse = this.formatTidewaveProcesses(result.data);
          break;
        case 'eval':
          formattedResponse = this.formatTidewaveEval(result.data);
          break;
        case 'documentation':
          formattedResponse = this.formatTidewaveDocumentation(result.data);
          break;
        case 'dependencies':
          formattedResponse = this.formatTidewaveDependencies(result.data);
          break;
        default:
          formattedResponse = `**${tool.toUpperCase()} Result:**\n\n\`\`\`json\n${JSON.stringify(result.data, null, 2)}\n\`\`\``;
      }

      const framework = session.state.tidewave.framework.toUpperCase();
      const executionTime = result.metadata?.execution_time ? ` (${result.metadata.execution_time}ms)` : '';
      
      return {
        content: [{
          type: 'text',
          text: `🌊 **Tidewave ${framework} Query**${executionTime}\n\n${formattedResponse}\n\n💡 **Available Tools:** ${session.state.tidewave.available_tools.join(', ')}`
        }]
      };

    } catch (error) {
      throw new Error(`Failed to execute Tidewave query: ${error instanceof Error ? error.message : error}`);
    }
  }

  private formatTidewaveLogs(logs: any): string {
    if (!logs || !Array.isArray(logs)) {
      return 'No logs available';
    }
    
    return `**Recent Application Logs:**\n\n${logs.map(log => 
      `\`[${log.timestamp}]\` **${log.level?.toUpperCase() || 'INFO'}** ${log.message}`
    ).join('\n')}`;
  }

  private formatTidewaveSQL(result: any): string {
    if (!result) return 'No SQL results';
    
    if (result.error) {
      return `❌ **SQL Error:** ${result.error}`;
    }
    
    if (!result.rows || result.rows.length === 0) {
      return '✅ **SQL executed successfully** (no rows returned)';
    }
    
    const headers = Object.keys(result.rows[0]);
    const tableHeader = `| ${headers.join(' | ')} |`;
    const tableSeparator = `|${headers.map(() => '---').join('|')}|`;
    const tableRows = result.rows.map((row: any) => 
      `| ${headers.map(h => row[h] || '').join(' | ')} |`
    );
    
    return `**SQL Query Results** (${result.rows.length} rows):\n\n${tableHeader}\n${tableSeparator}\n${tableRows.join('\n')}`;
  }

  private formatTidewaveProcesses(processes: any): string {
    if (!processes || !Array.isArray(processes)) {
      return 'No process information available';
    }
    
    return `**Application Processes:**\n\n${processes.map(proc => 
      `🔧 **${proc.name || 'Process'}** (PID: ${proc.pid})\n   Status: ${proc.status}\n   Memory: ${proc.memory_mb}MB\n   CPU: ${proc.cpu_percent}%`
    ).join('\n\n')}`;
  }

  private formatTidewaveEval(result: any): string {
    if (result.error) {
      return `❌ **Evaluation Error:** ${result.error}`;
    }
    
    return `**Code Evaluation Result:**\n\n\`\`\`\n${result.output || result.value || 'nil'}\n\`\`\``;
  }

  private formatTidewaveDocumentation(docs: any): string {
    if (!docs) return 'No documentation available';
    
    return `**Application Documentation:**\n\n${docs.content || JSON.stringify(docs, null, 2)}`;
  }

  private formatTidewaveDependencies(deps: any): string {
    if (!deps || !Array.isArray(deps)) {
      return 'No dependencies found';
    }
    
    return `**Project Dependencies:**\n\n${deps.map(dep => 
      `📦 **${dep.name}** v${dep.version}${dep.description ? `\n   ${dep.description}` : ''}`
    ).join('\n\n')}`;
  }

  private async debugHydration(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const issues = await this.localEngine.getHydrationIssues();
      
      if (issues.length === 0) {
        return {
          content: [{
            type: 'text',
            text: `✅ **No Hydration Issues Detected**

The application appears to be hydrating correctly!

**💡 Tips for preventing hydration issues:**
- Avoid using browser-only APIs during SSR
- Don't use Math.random() or Date.now() in render
- Ensure consistent data between server and client
- Check for conditional rendering based on window/document

Keep monitoring during development as hydration issues often appear with specific user interactions.`
          }]
        };
      }

      return {
        content: [{
          type: 'text',
          text: `⚠️ **Hydration Mismatches Detected**

Found **${issues.length}** hydration errors that need attention.

${issues.map((issue: any, i: number) => `
**Issue #${i + 1}: ${issue.element}**
- **Server HTML:** \`${issue.serverHTML}\`
- **Client HTML:** \`${issue.clientHTML}\`
- **Time:** ${new Date(issue.timestamp).toLocaleTimeString()}
${issue.stackTrace ? `- **Stack:** First seen at ${issue.stackTrace.split('\n')[1]?.trim() || 'unknown'}` : ''}
`).join('\n')}

**🔍 Common Causes:**
1. **Date/Time rendering** - Use consistent formatting
2. **Random values** - Move randomization to useEffect
3. **Browser APIs** - Check typeof window !== 'undefined'
4. **User state** - Ensure auth state matches on server/client

**🛠️ How to Fix:**
1. Make server and client render identical HTML
2. Move dynamic content to useEffect/componentDidMount
3. Use suppressHydrationWarning for unavoidable differences
4. Consider using dynamic imports for client-only components

**📚 Framework-Specific Docs:**
- Next.js: https://nextjs.org/docs/messages/react-hydration-error
- Remix: https://remix.run/docs/en/main/guides/gotchas#hydration
- Gatsby: https://www.gatsbyjs.com/docs/debugging-html-builds/`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to analyze hydration: ${error instanceof Error ? error.message : error}`);
    }
  }

  private async analyzeBundles(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const analysis = await this.localEngine.getBundleAnalysis();
      
      const formatSize = (bytes: number) => {
        if (bytes < 1024) return `${bytes}B`;
        if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
        return `${(bytes / 1024 / 1024).toFixed(2)}MB`;
      };

      return {
        content: [{
          type: 'text',
          text: `📦 **Bundle Analysis Report**

**📊 Overview:**
- **Total JS Size:** ${formatSize(analysis.totalSize)}
- **Lazy Loaded:** ${formatSize(analysis.lazyLoadedSize)} (${analysis.totalSize > 0 ? ((analysis.lazyLoadedSize / analysis.totalSize) * 100).toFixed(1) : 0}%)
- **Cache Hit Rate:** ${analysis.cacheHitRate.toFixed(1)}%
- **Bundle Count:** ${analysis.bundles.length}

${analysis.coverage ? `**📈 Code Coverage:**
- **Used:** ${formatSize(analysis.coverage.used)} (${analysis.coverage.percentage?.toFixed(1) || 0}%)
- **Total:** ${formatSize(analysis.coverage.total)}
- **Unused:** ${formatSize(analysis.coverage.total - analysis.coverage.used)} 🗑️` : ''}

**📦 Largest Bundles:**
${analysis.bundles.slice(0, 5).map((bundle: any, i: number) => 
  `${i + 1}. **${bundle.url.split('/').pop()}**
   - Size: ${formatSize(bundle.size)} ${bundle.gzipSize ? `(${formatSize(bundle.gzipSize)} gzipped)` : ''}
   - Load time: ${bundle.loadTime}ms
   - Cache: ${bundle.cacheStatus} ${bundle.cacheStatus === 'hit' ? '✅' : bundle.cacheStatus === 'miss' ? '⚠️' : '❌'}
   - ${bundle.isLazyLoaded ? '🔄 Lazy loaded' : '📦 Initial bundle'}
   ${bundle.coverage !== undefined ? `- Coverage: ${bundle.coverage.toFixed(1)}%` : ''}`
).join('\n\n')}

**💡 Optimization Recommendations:**
${this.getBundleRecommendations(analysis)}

**🛠️ Quick Wins:**
1. Enable compression (gzip/brotli)
2. Use HTTP/2 push for critical resources
3. Implement code splitting by route
4. Remove unused dependencies
5. Use dynamic imports for heavy libraries`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to analyze bundles: ${error instanceof Error ? error.message : error}`);
    }
  }

  private getBundleRecommendations(analysis: any): string {
    const recommendations = [];
    
    if (analysis.totalSize > 1024 * 1024 * 2) { // 2MB
      recommendations.push('⚠️ Total bundle size exceeds 2MB - consider aggressive code splitting');
    }
    
    if (analysis.lazyLoadedSize < analysis.totalSize * 0.3) {
      recommendations.push('📦 Less than 30% is lazy loaded - move more code to dynamic imports');
    }
    
    if (analysis.coverage && analysis.coverage.percentage < 50) {
      recommendations.push('🗑️ Over 50% of code is unused - audit dependencies and tree-shake');
    }
    
    if (analysis.cacheHitRate < 50) {
      recommendations.push('💾 Poor cache performance - implement content hashing and long-term caching');
    }
    
    const largeBundles = analysis.bundles.filter((b: any) => b.size > 500 * 1024);
    if (largeBundles.length > 0) {
      recommendations.push(`🎯 ${largeBundles.length} bundles over 500KB - split or optimize these first`);
    }
    
    return recommendations.length > 0 ? recommendations.join('\n') : '✅ Bundle sizes look reasonable!';
  }

  private async trackRouteChanges(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const routes = await this.localEngine.getRouteChanges();
      
      if (routes.length === 0) {
        return {
          content: [{
            type: 'text',
            text: `🛤️ **No Route Changes Detected**

No client-side navigation has occurred yet.

**💡 This tool tracks:**
- SPA route transitions (pushState/replaceState)
- Browser back/forward navigation
- Route change performance
- Navigation patterns

Navigate through your app to see route tracking in action!`
          }]
        };
      }

      const avgDuration = routes.reduce((sum: number, r: any) => sum + r.duration, 0) / routes.length;
      const slowRoutes = routes.filter((r: any) => r.duration > 1000);

      return {
        content: [{
          type: 'text',
          text: `🛤️ **Route Change Analysis**

**📊 Navigation Summary:**
- **Total Navigations:** ${routes.length}
- **Average Duration:** ${avgDuration.toFixed(0)}ms
- **Slow Transitions:** ${slowRoutes.length} (>1s)

**📍 Route History:**
${routes.slice(-10).reverse().map((route: any, i: number) => 
  `${i + 1}. **${route.type.toUpperCase()}** ${route.duration > 1000 ? '🐌' : '⚡'}
   From: \`${route.from.split('?')[0]}\`
   To: \`${route.to.split('?')[0]}\`
   Duration: ${route.duration}ms
   Time: ${new Date(route.timestamp).toLocaleTimeString()}`
).join('\n\n')}

**🎯 Performance Insights:**
${this.getRouteInsights(routes, avgDuration, slowRoutes)}

**💡 Optimization Tips:**
1. **Prefetch** critical data before navigation
2. **Show loading states** immediately on click
3. **Code split** by route to reduce bundle sizes
4. **Cache** API responses for instant navigation
5. **Optimize** data fetching with parallel requests`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to track routes: ${error instanceof Error ? error.message : error}`);
    }
  }

  private getRouteInsights(routes: any[], avgDuration: number, slowRoutes: any[]): string {
    const insights = [];
    
    if (avgDuration > 500) {
      insights.push(`⚠️ Average route change takes ${avgDuration.toFixed(0)}ms - target <300ms`);
    } else {
      insights.push(`✅ Good average navigation speed: ${avgDuration.toFixed(0)}ms`);
    }
    
    if (slowRoutes.length > 0) {
      const slowestRoute = slowRoutes.sort((a, b) => b.duration - a.duration)[0];
      insights.push(`🐌 Slowest route: ${slowestRoute.to} (${slowestRoute.duration}ms)`);
    }
    
    // Check for patterns
    const routeCounts: Record<string, number> = {};
    routes.forEach(r => {
      const path = r.to.split('?')[0];
      routeCounts[path] = (routeCounts[path] || 0) + 1;
    });
    
    const hotRoutes = Object.entries(routeCounts)
      .filter(([_, count]) => count > 2)
      .sort(([_, a], [__, b]) => b - a);
    
    if (hotRoutes.length > 0) {
      insights.push(`🔥 Most visited: ${hotRoutes[0][0]} (${hotRoutes[0][1]} times)`);
    }
    
    return insights.join('\n');
  }

  private async detectProblems(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const problems = await this.localEngine.detectCommonProblems();
      
      if (problems.length === 0) {
        return {
          content: [{
            type: 'text',
            text: `✅ **No Major Problems Detected!**

Your application appears to be running smoothly.

**🔍 What we checked:**
- ✅ Hydration consistency
- ✅ Bundle sizes
- ✅ Code usage efficiency
- ✅ Route performance
- ✅ Cache utilization

Keep this tool handy during development to catch issues early!`
          }]
        };
      }

      const severityEmoji = {
        high: '🔴',
        medium: '🟡',
        low: '🟠'
      };

      return {
        content: [{
          type: 'text',
          text: `🔍 **Detected ${problems.length} Potential Issues**

${problems.sort((a: any, b: any) => {
  const severityOrder: Record<string, number> = { high: 0, medium: 1, low: 2 };
  return severityOrder[a.severity] - severityOrder[b.severity];
}).map((problem: any, i: number) => 
  `**${i + 1}. ${severityEmoji[problem.severity as keyof typeof severityEmoji]} ${problem.problem}**
   
   **Issue:** ${problem.description}
   
   **Solution:** ${problem.solution}
   
   ---`
).join('\n\n')}

**🛠️ Next Steps:**
1. Address HIGH severity issues first
2. Use specific debug tools for detailed analysis:
   - \`debug_hydration\` for SSR issues
   - \`analyze_bundles\` for performance
   - \`track_route_changes\` for navigation
3. Re-run \`detect_problems\` after fixes

**💡 Pro Tip:** Run this check regularly during development to catch issues early!`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to detect problems: ${error instanceof Error ? error.message : error}`);
    }
  }

  private async getNextJSPageInfo(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const pageInfo = await this.localEngine.getNextJSPageInfo();
      const buildInfo = await this.localEngine.getNextJSBuildInfo();
      
      if (!pageInfo) {
        return {
          content: [{
            type: 'text',
            text: '❌ Not a Next.js application or Next.js not detected.'
          }]
        };
      }

      return {
        content: [{
          type: 'text',
          text: `⚡ **Next.js Page Information**

**📄 Current Page:**
- **Path:** \`${pageInfo.path}\`
- **Type:** ${pageInfo.type.toUpperCase()} ${this.getPageTypeEmoji(pageInfo.type)}
- **App Directory:** ${pageInfo.isAppDir ? 'Yes ✅' : 'No (Pages Router)'}
- **Has Layout:** ${pageInfo.hasLayout ? 'Yes' : 'No'}

**🔧 Data Fetching:**
${pageInfo.dataFetching.length > 0 
  ? pageInfo.dataFetching.map((method: any) => `- \`${method}\``).join('\n')
  : '- No server-side data fetching'}

**🏗️ Build Configuration:**
- **Build ID:** \`${buildInfo?.buildId || 'Unknown'}\`
- **Base Path:** ${buildInfo?.basePath || '/'}
- **Asset Prefix:** ${buildInfo?.assetPrefix || 'None'}
- **Preview Mode:** ${buildInfo?.isPreview ? 'Yes 🔍' : 'No'}

**💡 Recommendations:**
${this.getNextJSRecommendations(pageInfo)}`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to get Next.js info: ${error instanceof Error ? error.message : error}`);
    }
  }

  private getPageTypeEmoji(type: string): string {
    const emojis: Record<string, string> = {
      'static': '📄',
      'ssr': '🔄',
      'ssg': '🏗️',
      'isr': '♻️'
    };
    return emojis[type] || '❓';
  }

  private getNextJSRecommendations(pageInfo: any): string {
    const recommendations = [];
    
    if (pageInfo.type === 'ssr' && pageInfo.dataFetching.length === 0) {
      recommendations.push('• Consider using Static Generation (SSG) for better performance');
    }
    
    if (!pageInfo.isAppDir) {
      recommendations.push('• Consider migrating to App Directory for better features');
    }
    
    if (pageInfo.type === 'static' && pageInfo.dataFetching.includes('getServerSideProps' as any)) {
      recommendations.push('• Page has conflicting render methods');
    }
    
    return recommendations.length > 0 ? recommendations.join('\n') : '• Page is well configured ✅';
  }

  private async getNextJSImageAudit(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const imageIssues = await this.localEngine.getNextJSImageIssues();
      
      const highImpact = imageIssues.unoptimizedImages.filter((img: any) => 
        img.improvement.includes('High')
      );
      const mediumImpact = imageIssues.unoptimizedImages.filter((img: any) => 
        img.improvement.includes('Medium')
      );

      return {
        content: [{
          type: 'text',
          text: `🖼️ **Next.js Image Optimization Audit**

**📊 Overview:**
- **Total Images:** ${imageIssues.unoptimizedImages.length}
- **next/image Usage:** ${imageIssues.nextImageUsage.toFixed(1)}%
- **High Impact Issues:** ${highImpact.length}
- **Medium Impact Issues:** ${mediumImpact.length}

**🚨 Unoptimized Images:**
${imageIssues.unoptimizedImages.slice(0, 10).map((img: any, i: number) => 
  `**${i + 1}. ${img.improvement.includes('High') ? '🔴' : '🟡'} ${img.src.split('/').pop()}**
   - Format: ${img.format.toUpperCase()}
   - Displayed: ${img.displayed.width}x${img.displayed.height}
   - Actual: ${img.actual.width}x${img.actual.height}
   - ${img.improvement}`
).join('\n\n')}

${imageIssues.unoptimizedImages.length > 10 ? `*... and ${imageIssues.unoptimizedImages.length - 10} more*\n\n` : ''}
**💡 Optimization Guide:**
1. **Use next/image** for automatic optimization
2. **Specify dimensions** to prevent layout shift
3. **Use WebP/AVIF** formats for better compression
4. **Implement lazy loading** for below-fold images
5. **Configure image domains** in next.config.js

**📝 Example Migration:**
\`\`\`jsx
// Before
<img src="/hero.jpg" alt="Hero" />

// After
import Image from 'next/image'
<Image 
  src="/hero.jpg" 
  alt="Hero" 
  width={1200} 
  height={600}
  priority
/>
\`\`\``
        }]
      };
    } catch (error) {
      throw new Error(`Failed to audit images: ${error instanceof Error ? error.message : error}`);
    }
  }

  private async detectNextJSIssues(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const problems = await this.localEngine.detectNextJSProblems();
      
      if (problems.length === 0) {
        return {
          content: [{
            type: 'text',
            text: '✅ **No Next.js specific issues detected!**\n\nYour Next.js app is following best practices.'
          }]
        };
      }

      const severityEmoji: Record<string, string> = {
        high: '🔴',
        medium: '🟡', 
        low: '🟢'
      };

      return {
        content: [{
          type: 'text',
          text: `⚡ **Next.js Issue Detection**

**Found ${problems.length} Next.js Specific Issues:**

${problems.map((problem: any, i: number) => 
  `**${i + 1}. ${severityEmoji[problem.severity]} ${problem.problem}**
   
   **Issue:** ${problem.description}
   
   **Solution:** ${problem.solution}
   
   ---`
).join('\n\n')}

**📚 Next.js Resources:**
- [Performance Best Practices](https://nextjs.org/docs/pages/building-your-application/optimizing/performance)
- [Image Optimization](https://nextjs.org/docs/pages/building-your-application/optimizing/images)
- [App Router Migration](https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration)`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to detect Next.js issues: ${error instanceof Error ? error.message : error}`);
    }
  }

  private async analyzeTurbo(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const turboEvents = await this.localEngine.getTurboEvents();
      const controllers = await this.localEngine.getStimulusControllers();
      
      const visits = turboEvents.filter((e: any) => e.type === 'visit');
      const cacheMisses = turboEvents.filter((e: any) => e.type === 'cache-miss');
      const frameLoads = turboEvents.filter((e: any) => e.type === 'frame-load');
      
      const cacheHitRate = visits.length > 0 
        ? ((visits.length - cacheMisses.length) / visits.length * 100).toFixed(1)
        : 0;

      return {
        content: [{
          type: 'text',
          text: `🚄 **Rails Turbo/Hotwire Analysis**

**📊 Navigation Performance:**
- **Total Page Visits:** ${visits.length}
- **Cache Hit Rate:** ${cacheHitRate}%
- **Cache Misses:** ${cacheMisses.length}
- **Turbo Frames Loaded:** ${frameLoads.length}

**🎯 Stimulus Controllers:**
- **Total Controllers:** ${controllers.length}
${controllers.length > 0 ? controllers.slice(0, 5).map((c: any) => 
  `  - **${c.identifier}** on \`${c.element}\`
    Actions: ${c.actions.length > 0 ? c.actions.join(', ') : 'None'}
    Targets: ${c.targets.length > 0 ? c.targets.join(', ') : 'None'}`
).join('\n') : '  No Stimulus controllers found'}

**📈 Performance Insights:**
${this.getTurboInsights(cacheHitRate, cacheMisses.length, frameLoads.length)}

**💡 Optimization Tips:**
1. **Improve Cache Hit Rate:** Add \`data-turbo-permanent\` to persistent elements
2. **Use Turbo Frames:** Load partial page updates instead of full visits
3. **Prefetch Links:** Add \`data-turbo-prefetch\` for instant navigation
4. **Lazy Load Frames:** Use \`loading="lazy"\` on turbo-frame elements
5. **Monitor Console:** Check for Turbo-specific JavaScript errors`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to analyze Turbo: ${error instanceof Error ? error.message : error}`);
    }
  }

  private getTurboInsights(cacheHitRate: string | number, cacheMisses: number, frameLoads: number): string {
    const insights = [];
    
    if (Number(cacheHitRate) < 50) {
      insights.push('⚠️ Low cache hit rate indicates pages aren\'t being cached effectively');
    }
    
    if (cacheMisses > 10) {
      insights.push('⚠️ High number of cache misses may cause slower navigation');
    }
    
    if (frameLoads === 0) {
      insights.push('💡 Consider using Turbo Frames for partial page updates');
    }
    
    if (insights.length === 0) {
      insights.push('✅ Turbo is performing well');
    }
    
    return insights.join('\n');
  }

  private async checkCSRFSecurity(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const csrfIssues = await this.localEngine.getCSRFIssues();
      const forms = await this.localEngine.getFormSubmissions();
      
      const formsWithoutCSRF = forms.filter((f: any) => 
        !f.hasCSRF && ['POST', 'PUT', 'PATCH', 'DELETE'].includes(f.method.toUpperCase())
      );

      return {
        content: [{
          type: 'text',
          text: `🔒 **CSRF Security Check**

**⚠️ Security Issues Found:**
- **CSRF Token Failures:** ${csrfIssues.length}
- **Forms Without CSRF:** ${formsWithoutCSRF.length}
- **Total Forms Checked:** ${forms.length}

${csrfIssues.length > 0 ? `**🚨 Failed Requests:**
${csrfIssues.slice(0, 5).map((issue: any, i: number) => 
  `${i + 1}. **${issue.method}** to \`${issue.endpoint}\`
   Token Present: ${issue.hasToken ? 'Yes ❌' : 'No ❌'}
   Token Name: ${issue.tokenName}`
).join('\n\n')}\n\n` : ''}

${formsWithoutCSRF.length > 0 ? `**📝 Unprotected Forms:**
${formsWithoutCSRF.slice(0, 5).map((form: any, i: number) => 
  `${i + 1}. **${form.method}** to \`${form.action}\`
   ${form.hasFile ? '📎 Has file upload' : ''}`
).join('\n\n')}\n\n` : ''}

**🛡️ CSRF Protection Guide:**

**For Rails:**
\`\`\`erb
<!-- In layout -->
<%= csrf_meta_tags %>

<!-- In forms -->
<%= form_with model: @user do |f| %>
  <!-- CSRF token included automatically -->
<% end %>

<!-- For AJAX -->
headers: {
  'X-CSRF-Token': document.querySelector('[name="csrf-token"]').content
}
\`\`\`

**For Django:**
\`\`\`django
<!-- In forms -->
<form method="post">
  {% csrf_token %}
  <!-- form fields -->
</form>

<!-- For AJAX -->
headers: {
  'X-CSRFToken': getCookie('csrftoken')
}
\`\`\`

**🔍 Security Status:** ${csrfIssues.length === 0 && formsWithoutCSRF.length === 0 ? '✅ All forms protected' : '❌ Security improvements needed'}`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to check CSRF: ${error instanceof Error ? error.message : error}`);
    }
  }

  private async getStimulusControllers(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const controllers = await this.localEngine.getStimulusControllers();
      
      if (controllers.length === 0) {
        return {
          content: [{
            type: 'text',
            text: '❌ No Stimulus controllers found. This may not be a Rails app with Stimulus, or Stimulus hasn\'t been initialized yet.'
          }]
        };
      }

      // Group controllers by identifier
      const controllerMap = new Map<string, any[]>();
      controllers.forEach((c: any) => {
        if (!controllerMap.has(c.identifier)) {
          controllerMap.set(c.identifier, []);
        }
        controllerMap.get(c.identifier)?.push(c);
      });

      return {
        content: [{
          type: 'text',
          text: `🎮 **Stimulus Controllers Analysis**

**📊 Overview:**
- **Total Controllers:** ${controllers.length}
- **Unique Types:** ${controllerMap.size}
- **Most Used:** ${Array.from(controllerMap.entries()).sort((a, b) => b[1].length - a[1].length)[0]?.[0] || 'N/A'}

**🔧 Controller Details:**
${Array.from(controllerMap.entries()).map(([identifier, instances]) => 
  `**${identifier}** (${instances.length} instance${instances.length > 1 ? 's' : ''})
${instances.slice(0, 3).map((c: any, i: number) => 
  `  ${i + 1}. Element: \`${c.element}\`
     ${c.actions.length > 0 ? `Actions: ${c.actions.map((a: string) => `\`${a}\``).join(', ')}` : ''}
     ${c.targets.length > 0 ? `Targets: ${c.targets.map((t: string) => `\`${t}\``).join(', ')}` : ''}`
).join('\n')}
${instances.length > 3 ? `  *... and ${instances.length - 3} more*` : ''}`
).join('\n\n')}

**💡 Best Practices:**
1. **Naming:** Use descriptive controller names (e.g., \`dropdown-controller\`)
2. **Actions:** Follow the pattern \`event->controller#method\`
3. **Targets:** Define all DOM references as targets
4. **Values:** Use Stimulus values for configuration
5. **Lifecycle:** Implement \`connect()\` and \`disconnect()\` properly

**🐛 Common Issues to Check:**
- Duplicate controller registrations
- Missing target elements
- Incorrect action syntax
- Memory leaks from missing disconnect cleanup`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to analyze Stimulus: ${error instanceof Error ? error.message : error}`);
    }
  }

  private async getMetaFrameworkInfo(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const info = await this.localEngine.getMetaFrameworkInfo();
      
      if (!info || !info.framework) {
        return {
          content: [{
            type: 'text',
            text: '❌ No meta-framework detected. This may be a traditional SPA or server-rendered app.'
          }]
        };
      }

      const frameworkEmojis: Record<string, string> = {
        'remix': '🎸',
        'astro': '🚀',
        'nuxt': '💚',
        'qwik': '⚡',
        'solidjs': '⚛️',
        'sveltekit': '🧡'
      };

      return {
        content: [{
          type: 'text',
          text: `${frameworkEmojis[info.framework] || '🔧'} **${info.framework.charAt(0).toUpperCase() + info.framework.slice(1)} Framework Detected**

**📊 Framework Information:**
- **Framework:** ${info.framework}
- **Version:** ${info.version || 'Unknown'}
- **Build Tool:** ${info.buildTool || 'Unknown'} ${info.buildTool === 'vite' ? '⚡' : ''}

**✨ Detected Features:**
${info.features.map((f: string) => `- ${f}`).join('\n')}

**🛠️ Available Debugging Tools:**
${this.getFrameworkSpecificTools(info.framework)}

**💡 Quick Tips:**
${this.getFrameworkTips(info.framework)}`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to get meta-framework info: ${error instanceof Error ? error.message : error}`);
    }
  }

  private getFrameworkSpecificTools(framework: string): string {
    const tools: Record<string, string[]> = {
      'remix': [
        '`remix_loader_analysis` - Analyze loader performance',
        '`vite_hmr_monitor` - Monitor HMR updates'
      ],
      'astro': [
        '`astro_islands_audit` - Audit component hydration',
        '`vite_hmr_monitor` - Monitor HMR updates'
      ],
      'nuxt': [
        '`nuxt_payload_analysis` - Analyze payload size',
        '`vite_hmr_monitor` - Monitor HMR updates'
      ],
      'qwik': [
        '`qwik_resumability_check` - Check resumability performance'
      ],
      'solidjs': [
        '`detect_meta_framework_issues` - Detect SolidJS issues',
        '`vite_hmr_monitor` - Monitor HMR updates'
      ],
      'sveltekit': [
        '`detect_meta_framework_issues` - Detect SvelteKit issues',
        '`vite_hmr_monitor` - Monitor HMR updates'
      ]
    };
    
    return tools[framework]?.join('\n') || '- Use `detect_meta_framework_issues` for general analysis';
  }

  private getFrameworkTips(framework: string): string {
    const tips: Record<string, string> = {
      'remix': '- Use `defer()` for non-critical data\n- Enable single fetch for better performance',
      'astro': '- Use `client:idle` for non-critical components\n- Enable view transitions for SPA-like navigation',
      'nuxt': '- Use `useLazyFetch` for non-blocking data\n- Enable Nitro caching for API routes',
      'qwik': '- Keep serialized state minimal\n- Use `$()` for lazy-loaded code',
      'solidjs': '- Use `createResource` for async data\n- Avoid unnecessary reactivity',
      'sveltekit': '- Use `load` functions for data fetching\n- Enable prerendering where possible'
    };
    
    return tips[framework] || '- Check framework documentation for best practices';
  }

  private async analyzeRemixLoaders(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const loaderData = await this.localEngine.getRemixLoaderData();
      const routeModules = await this.localEngine.getRemixRouteModules();
      
      if (loaderData.length === 0) {
        return {
          content: [{
            type: 'text',
            text: '❌ No Remix loader data captured yet. Navigate through your app to collect loader performance data.'
          }]
        };
      }

      const avgDuration = loaderData.reduce((sum: number, d: any) => sum + d.duration, 0) / loaderData.length;
      const slowLoaders = loaderData.filter((d: any) => d.duration > 1000);
      const cachedLoaders = loaderData.filter((d: any) => d.cached);

      return {
        content: [{
          type: 'text',
          text: `🎸 **Remix Loader Performance Analysis**

**📊 Overview:**
- **Total Loader Calls:** ${loaderData.length}
- **Average Duration:** ${avgDuration.toFixed(0)}ms
- **Slow Loaders (>1s):** ${slowLoaders.length}
- **Cache Hit Rate:** ${loaderData.length > 0 ? ((cachedLoaders.length / loaderData.length) * 100).toFixed(1) : 0}%

**🐌 Slowest Loaders:**
${loaderData
  .sort((a: any, b: any) => b.duration - a.duration)
  .slice(0, 5)
  .map((d: any, i: number) => 
    `${i + 1}. **${d.route || 'Unknown Route'}**
   Duration: ${d.duration}ms ${d.duration > 2000 ? '🔴' : d.duration > 1000 ? '🟡' : '🟢'}
   Size: ${(d.size / 1024).toFixed(2)}KB
   Cached: ${d.cached ? 'Yes ✅' : 'No ❌'}`
  ).join('\n\n')}

**📁 Route Modules:**
- **Total Routes:** ${routeModules?.routes?.length || 0}
- **Current Route:** \`${routeModules?.currentRoute || 'Unknown'}\`

**💡 Optimization Tips:**
1. **Use \`defer()\`** for non-critical data
2. **Implement caching** with appropriate headers
3. **Parallelize data fetching** with Promise.all()
4. **Use database indexes** for slow queries
5. **Consider CDN caching** for static data`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to analyze Remix loaders: ${error instanceof Error ? error.message : error}`);
    }
  }

  private async auditAstroIslands(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const islands = await this.localEngine.getAstroIslands();
      
      if (islands.length === 0) {
        return {
          content: [{
            type: 'text',
            text: '❌ No Astro islands found. Make sure you\'re using interactive components with client directives.'
          }]
        };
      }

      const hydrationCounts: Record<string, number> = {};
      islands.forEach((island: any) => {
        const directive = island.hydrationDirective || 'none';
        hydrationCounts[directive] = (hydrationCounts[directive] || 0) + 1;
      });

      return {
        content: [{
          type: 'text',
          text: `🚀 **Astro Islands Audit**

**🏝️ Island Overview:**
- **Total Islands:** ${islands.length}
- **Eager Loading:** ${hydrationCounts['load'] || 0} islands
- **Idle Loading:** ${hydrationCounts['idle'] || 0} islands
- **Visible Loading:** ${hydrationCounts['visible'] || 0} islands
- **Media Query:** ${hydrationCounts['media'] || 0} islands
- **Client Only:** ${hydrationCounts['only'] || 0} islands

**📊 Hydration Strategy Breakdown:**
${Object.entries(hydrationCounts)
  .map(([strategy, count]) => {
    const percentage = ((count / islands.length) * 100).toFixed(1);
    const emoji = strategy === 'load' ? '⚡' : strategy === 'idle' ? '⏱️' : strategy === 'visible' ? '👁️' : '📱';
    return `${emoji} **client:${strategy}**: ${count} islands (${percentage}%)`;
  }).join('\n')}

**🔍 Island Details:**
${islands.slice(0, 10).map((island: any, i: number) => 
  `${i + 1}. **${island.component.split('/').pop()}**
   Hydration: \`client:${island.hydrationDirective || 'none'}\`
   Loading: ${island.loading}
   Props: ${Object.keys(island.props).length} props`
).join('\n\n')}

${islands.length > 10 ? `*... and ${islands.length - 10} more islands*\n\n` : ''}
**⚠️ Potential Issues:**
${this.getAstroIslandIssues(islands, hydrationCounts)}

**💡 Best Practices:**
1. Use \`client:idle\` for below-fold components
2. Use \`client:visible\` for heavy components
3. Minimize \`client:load\` usage
4. Consider static HTML for non-interactive content
5. Bundle similar components together`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to audit Astro islands: ${error instanceof Error ? error.message : error}`);
    }
  }

  private getAstroIslandIssues(islands: any[], hydrationCounts: Record<string, number>): string {
    const issues = [];
    
    if (hydrationCounts['load'] > 5) {
      issues.push('🔴 Too many islands with `client:load` - impacts initial load performance');
    }
    
    if (islands.length > 20) {
      issues.push('🟡 Large number of islands may increase JavaScript payload');
    }
    
    if (!hydrationCounts['visible'] && !hydrationCounts['idle'] && hydrationCounts['load'] > 3) {
      issues.push('🟡 Consider using `client:idle` or `client:visible` for better performance');
    }
    
    return issues.length > 0 ? issues.join('\n') : '✅ Island configuration looks good!';
  }

  private async analyzeNuxtPayload(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const payload = await this.localEngine.getNuxtPayload();
      
      if (!payload) {
        return {
          content: [{
            type: 'text',
            text: '❌ No Nuxt payload detected. Make sure this is a Nuxt 3 application.'
          }]
        };
      }

      return {
        content: [{
          type: 'text',
          text: `💚 **Nuxt Payload Analysis**

**📊 Payload Overview:**
- **Hydration Status:** ${payload.isHydrating ? 'In Progress ⏳' : 'Complete ✅'}
- **Server Rendered:** ${payload.serverRendered ? 'Yes ✅' : 'No ❌'}
- **Data Keys:** ${payload.data.length}
- **State Keys:** ${payload.state.length}
- **Has Errors:** ${payload.error ? 'Yes 🔴' : 'No ✅'}

**📦 Payload Contents:**
${payload.data.length > 0 ? `**Data Keys:**\n${payload.data.slice(0, 10).map((key: string) => `- \`${key}\``).join('\n')}` : ''}
${payload.data.length > 10 ? `\n*... and ${payload.data.length - 10} more*` : ''}

${payload.state.length > 0 ? `**State Keys:**\n${payload.state.slice(0, 10).map((key: string) => `- \`${key}\``).join('\n')}` : ''}
${payload.state.length > 10 ? `\n*... and ${payload.state.length - 10} more*` : ''}

${payload.error ? `**🔴 Error Details:**\n\`\`\`\n${JSON.stringify(payload.error, null, 2)}\n\`\`\`\n` : ''}

**⚠️ Potential Issues:**
${this.getNuxtPayloadIssues(payload)}

**💡 Optimization Tips:**
1. Use \`useLazyFetch\` for non-critical data
2. Implement \`transform\` to reduce payload size
3. Use \`pick\` to select only needed fields
4. Enable payload extraction for static hosting
5. Consider \`sharedPrerenderData\` for common data`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to analyze Nuxt payload: ${error instanceof Error ? error.message : error}`);
    }
  }

  private getNuxtPayloadIssues(payload: any): string {
    const issues = [];
    
    if (payload.data.length > 50) {
      issues.push('🔴 Large number of data keys may indicate over-fetching');
    }
    
    if (payload.state.length > 30) {
      issues.push('🟡 Many state keys - consider using stores more efficiently');
    }
    
    if (!payload.serverRendered && payload.data.length > 0) {
      issues.push('🟡 Client-side rendering with data - consider SSR for SEO');
    }
    
    if (payload.error) {
      issues.push('🔴 Error in payload - check error handling');
    }
    
    return issues.length > 0 ? issues.join('\n') : '✅ Payload structure looks healthy!';
  }

  private async checkQwikResumability(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const resumability = await this.localEngine.getQwikResumability();
      
      if (!resumability) {
        return {
          content: [{
            type: 'text',
            text: '❌ No Qwik resumability data found. Make sure this is a Qwik application.'
          }]
        };
      }

      const stateKB = (resumability.serializedState / 1024).toFixed(2);
      const isLarge = resumability.serializedState > 50000;

      return {
        content: [{
          type: 'text',
          text: `⚡ **Qwik Resumability Analysis**

**📊 Resumability Metrics:**
- **Serialized State Size:** ${stateKB}KB ${isLarge ? '🔴' : '✅'}
- **QRL Count:** ${resumability.qrlCount} lazy-loadable chunks
- **Symbols Loaded:** ${resumability.symbolsLoaded} on demand
- **Resume Time:** ${resumability.resumeTime}ms

**🎯 Performance Impact:**
${this.getQwikPerformanceAnalysis(resumability)}

**📦 State Breakdown:**
- **Per Component:** ~${resumability.qrlCount > 0 ? (resumability.serializedState / resumability.qrlCount / 1024).toFixed(2) : 0}KB average
- **Compression Potential:** ~${(parseFloat(stateKB) * 0.3).toFixed(2)}KB gzipped

**⚠️ Issues & Recommendations:**
${this.getQwikIssues(resumability)}

**💡 Best Practices:**
1. Keep component state minimal
2. Use \`noSerialize()\` for non-resumable data
3. Lazy load heavy components with \`$()\`
4. Use server-side stores for shared data
5. Implement progressive enhancement`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to check Qwik resumability: ${error instanceof Error ? error.message : error}`);
    }
  }

  private getQwikPerformanceAnalysis(resumability: any): string {
    const analysis = [];
    
    if (resumability.serializedState < 10000) {
      analysis.push('🚀 Excellent - Minimal state for instant resumability');
    } else if (resumability.serializedState < 50000) {
      analysis.push('✅ Good - Reasonable state size for fast resume');
    } else {
      analysis.push('⚠️ Large state may impact initial render performance');
    }
    
    if (resumability.symbolsLoaded === 0) {
      analysis.push('💯 Perfect - No JavaScript loaded until interaction');
    } else if (resumability.symbolsLoaded < 5) {
      analysis.push('✅ Minimal symbols loaded on initial render');
    } else {
      analysis.push('⚠️ Multiple symbols loaded - check lazy boundaries');
    }
    
    return analysis.join('\n');
  }

  private getQwikIssues(resumability: any): string {
    const issues = [];
    
    if (resumability.serializedState > 100000) {
      issues.push('🔴 Very large serialized state - move data to server');
    } else if (resumability.serializedState > 50000) {
      issues.push('🟡 Large serialized state - consider optimization');
    }
    
    if (resumability.qrlCount === 0) {
      issues.push('🟡 No QRLs detected - ensure proper Qwik syntax');
    }
    
    if (resumability.symbolsLoaded > 10) {
      issues.push('🔴 Too many symbols loaded initially');
    }
    
    return issues.length > 0 ? issues.join('\n') : '✅ Resumability is well optimized!';
  }

  private async monitorViteHMR(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const events = await this.localEngine.getViteHMREvents();
      const frameworkInfo = await this.localEngine.getMetaFrameworkInfo();
      
      if (!frameworkInfo?.buildTool || frameworkInfo.buildTool !== 'vite') {
        return {
          content: [{
            type: 'text',
            text: '❌ Vite not detected. This tool only works with Vite-powered applications.'
          }]
        };
      }

      const updateEvents = events.filter((e: any) => e.type === 'update');
      const errorEvents = events.filter((e: any) => e.type === 'error');
      const reloadEvents = events.filter((e: any) => e.type === 'full-reload');

      return {
        content: [{
          type: 'text',
          text: `⚡ **Vite HMR Monitor**

**📊 HMR Statistics:**
- **Total Events:** ${events.length}
- **Hot Updates:** ${updateEvents.length} ✅
- **Full Reloads:** ${reloadEvents.length} 🔄
- **Errors:** ${errorEvents.length} ${errorEvents.length > 0 ? '🔴' : '✅'}
- **Framework:** ${frameworkInfo.framework} + Vite

**📝 Recent HMR Events:**
${events.slice(-10).reverse().map((event: any, i: number) => {
  const icon = event.type === 'update' ? '✅' : event.type === 'error' ? '🔴' : '🔄';
  const time = new Date(event.timestamp).toLocaleTimeString();
  return `${i + 1}. ${icon} **${event.type}** at ${time}
   ${event.files ? `Files: ${event.files.join(', ')}` : ''}
   ${event.error ? `Error: ${event.error}` : ''}`;
}).join('\n\n')}

**⚠️ HMR Health:**
${this.getViteHMRHealth(events, updateEvents, errorEvents, reloadEvents)}

**💡 HMR Best Practices:**
1. Ensure components have proper HMR boundaries
2. Use \`import.meta.hot.accept()\` for custom HMR
3. Avoid side effects in module scope
4. Check for circular dependencies
5. Use \`vite-plugin-inspect\` for debugging`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to monitor Vite HMR: ${error instanceof Error ? error.message : error}`);
    }
  }

  private getViteHMRHealth(events: any[], updates: any[], errors: any[], reloads: any[]): string {
    const health = [];
    
    if (errors.length === 0 && reloads.length < updates.length / 2) {
      health.push('✅ HMR is working smoothly');
    }
    
    if (errors.length > 0) {
      health.push(`🔴 ${errors.length} HMR errors need attention`);
    }
    
    if (reloads.length > updates.length) {
      health.push('⚠️ Too many full reloads - check HMR boundaries');
    }
    
    if (events.length === 0) {
      health.push('💤 No HMR activity detected yet');
    }
    
    return health.length > 0 ? health.join('\n') : '✅ HMR system is healthy';
  }

  private async detectMetaFrameworkIssues(args: any) {
    const { sessionId } = args;
    const session = this.sessions.get(sessionId);

    if (!session) {
      throw new Error(`Debug session ${sessionId} not found`);
    }

    try {
      const problems = await this.localEngine.detectMetaFrameworkProblems();
      const frameworkInfo = await this.localEngine.getMetaFrameworkInfo();
      
      if (!frameworkInfo?.framework) {
        return {
          content: [{
            type: 'text',
            text: '❌ No meta-framework detected. Use framework-specific tools for traditional SPAs.'
          }]
        };
      }

      if (problems.length === 0) {
        return {
          content: [{
            type: 'text',
            text: `✅ **No ${frameworkInfo.framework} issues detected!**\n\nYour application is following best practices.`
          }]
        };
      }

      const severityEmoji: Record<string, string> = {
        high: '🔴',
        medium: '🟡',
        low: '🟢'
      };

      return {
        content: [{
          type: 'text',
          text: `🔍 **${frameworkInfo.framework.charAt(0).toUpperCase() + frameworkInfo.framework.slice(1)} Issue Detection**

**Found ${problems.length} Framework-Specific Issues:**

${problems.map((problem: any, i: number) => 
  `**${i + 1}. ${severityEmoji[problem.severity]} ${problem.problem}**
   
   **Issue:** ${problem.description}
   
   **Solution:** ${problem.solution}
   
   ---`
).join('\n\n')}

**📚 Framework Resources:**
${this.getFrameworkResources(frameworkInfo.framework)}`
        }]
      };
    } catch (error) {
      throw new Error(`Failed to detect meta-framework issues: ${error instanceof Error ? error.message : error}`);
    }
  }

  private getFrameworkResources(framework: string): string {
    const resources: Record<string, string> = {
      'remix': '- [Remix Performance](https://remix.run/docs/en/main/guides/performance)\n- [Data Loading](https://remix.run/docs/en/main/guides/data-loading)',
      'astro': '- [Astro Islands](https://docs.astro.build/en/concepts/islands/)\n- [Performance](https://docs.astro.build/en/concepts/why-astro/#performance)',
      'nuxt': '- [Data Fetching](https://nuxt.com/docs/getting-started/data-fetching)\n- [Performance](https://nuxt.com/docs/guide/concepts/rendering#performance)',
      'qwik': '- [Resumability](https://qwik.builder.io/docs/concepts/resumable/)\n- [Lazy Loading](https://qwik.builder.io/docs/concepts/progressive/)',
      'solidjs': '- [Performance](https://www.solidjs.com/guides/performance)\n- [Reactivity](https://www.solidjs.com/guides/reactivity)',
      'sveltekit': '- [Loading Data](https://kit.svelte.dev/docs/load)\n- [Performance](https://kit.svelte.dev/docs/performance)'
    };
    
    return resources[framework] || '- Check official documentation for best practices';
  }

  private async initCICD(args: any) {
    try {
      const {
        projectDir,
        provider = 'github',
        appUrl = 'http://localhost:3000',
        framework = 'auto',
        tools = ['debug_page', 'performance_audit']
      } = args;

      if (!projectDir) {
        throw new Error('Project directory is required');
      }

      // Auto-detect framework if not specified
      const detectedFramework = framework === 'auto' 
        ? await this.cicdIntegration.detectFramework(projectDir)
        : framework;

      // Configure CI/CD with Tidewave support for Phoenix/Rails
      const hasTidewave = detectedFramework === 'phoenix' || detectedFramework === 'rails';
      const config = {
        provider,
        appUrl,
        framework: detectedFramework,
        hasTidewave,
        tools: hasTidewave ? [...tools, 'tidewave_query'] : tools
      };

      const result = await this.cicdIntegration.initCI(projectDir, config);

      return {
        content: [{
          type: 'text',
          text: `✅ **CI/CD Integration Initialized**

**Framework**: ${result.framework}
**Provider**: ${provider}
**App URL**: ${appUrl}

**Generated Files**:
${result.files.map((f: string) => `- ${f}`).join('\n')}

**Included Tools**:
${config.tools.map((t: string) => `- ${t}`).join('\n')}

${hasTidewave ? '🌊 **Tidewave Integration**: Enabled for enhanced Phoenix/Rails debugging' : ''}

**Next Steps**:
1. Commit the generated CI/CD files to your repository
2. Push to trigger your first automated AI debugging run
3. Review the generated reports in your CI/CD dashboard

**Available NPM Scripts**:
- \`npm run ai-debug\` - Run AI debugging locally
- \`npm run ai-debug:ci\` - Run CI-optimized debugging
- \`npm run ai-debug:performance\` - Performance audit
- \`npm run ai-debug:accessibility\` - Accessibility check
${hasTidewave ? '- `npm run ai-debug:tidewave` - Tidewave Phoenix/Rails debugging' : ''}
`
        }]
      };

    } catch (error) {
      throw new Error(`Failed to initialize CI/CD: ${error instanceof Error ? error.message : error}`);
    }
  }

  private createErrorResponse(error: any) {
    const message = error instanceof Error ? error.message : String(error);
    
    return {
      content: [{
        type: 'text',
        text: `❌ **Error**

${message}

**🔗 Need Help?**
- **Documentation:** https://docs.ai-debug.com
- **Support:** https://ai-debug.com/support
- **GitHub Issues:** https://github.com/ai-debug/mcp-server/issues

*AI Debug Local MCP Server*`
      }]
    };
  }

  async run() {
    const transport = new StdioServerTransport();
    await this.server.connect(transport);
    
    console.error('🔬 AI Debug Local MCP Server ready!');
    console.error('🎯 Revolutionary local debugging activated');
    console.error('');
    
    if (this.apiKeyManager.hasValidKey()) {
      console.error('🔑 Premium features available with your API key');
    } else {
      console.error('💡 Free tier active - get API key for AI features');
      console.error('🔗 Upgrade: https://ai-debug.com/pricing');
    }
  }
}

// Auto-start if this file is run directly
if (import.meta.url === `file://${process.argv[1]}`) {
  const server = new AIDebugLocalMCPServer();
  server.run().catch(console.error);
}