const WebSocket = require("ws");
const OpenAI = require("openai");
const jwt = require('jsonwebtoken');
const User = require('./models/User');
const https = require('https');
const { URL } = require('url');

// Initialize OpenAI client
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

// Define the categories and their system prompts
const CATEGORIES = {
  "business-plan": {
    name: "Business Plan",
    systemPrompt: "You are an expert business consultant specializing in business plan development. Provide detailed, actionable advice for creating comprehensive business plans, including market analysis, financial projections, and strategic planning."
  },
  "career-advice": {
    name: "Career Advice",
    systemPrompt: "You are a professional career counselor with extensive experience in career development. Provide practical, personalized career advice including goal setting, skill development, networking strategies, and career progression planning."
  },
  "mock-interview": {
    name: "Mock Interview Questions",
    systemPrompt: "You are an experienced HR professional and interview coach. Provide realistic mock interview questions, detailed answers, and constructive feedback to help candidates prepare for various types of interviews across different industries."
  },
  "resume-planning": {
    name: "Resume Planning",
    systemPrompt: "You are a professional resume writer and career consultant. Provide expert advice on resume structure, content optimization, ATS compatibility, formatting, and tailoring resumes for specific job applications."
  },
  "market-analysis": {
    name: "Market Analysis",
    systemPrompt: "You are a market research analyst and business strategist. Provide comprehensive market analysis including industry trends, competitive landscape, target audience identification, and market opportunity assessment."
  },
  "financial-planning": {
    name: "Financial Planning",
    systemPrompt: "You are a certified financial planner and investment advisor. Provide expert guidance on personal and business financial planning, budgeting, investment strategies, risk management, and financial goal setting."
  },
  "career-transition": {
    name: "Career Transition Advice",
    systemPrompt: "You are a career transition specialist and professional coach. Provide strategic guidance for career changes, industry transitions, skill transferability, networking during transitions, and managing career pivots effectively."
  },
  "current-events": {
    name: "Current Events & News",
    systemPrompt: "You are a knowledgeable assistant with access to current information up to 2024. Provide accurate, up-to-date information about current events, recent developments, and latest news. Always mention when information might need verification from recent sources."
  },
  "real-time-info": {
    name: "Real-time Information",
    systemPrompt: "You are an assistant specialized in providing current, real-time information. Help users get the latest updates on topics like stock prices, weather, news, trends, and other time-sensitive information. Always indicate when information might need to be verified from live sources."
  }
};

class WebSocketServer {
  constructor(server) {
    try {
      this.wss = new WebSocket.Server({ 
        server,
        path: "/ws",
        perMessageDeflate: false, // Disable compression to avoid conflicts
        maxPayload: 16 * 1024 * 1024 // 16MB max payload
      });
      
      this.clients = new Map();
      
      // Connection statistics
      this.stats = {
        totalConnections: 0,
        activeConnections: 0,
        totalMessages: 0,
        errors: 0
      };
      
      console.log('🤖 [WEBSOCKET] AI Chat WebSocket server started on /ws');
      
      this.setupWebSocket();
      this.setupPeriodicCleanup();
      
    } catch (error) {
      console.error('❌ [WEBSOCKET] Failed to initialize AI Chat WebSocket:', error);
      throw error;
    }
  }

  setupPeriodicCleanup() {
    // Clean up broken connections every 30 seconds
    setInterval(() => {
      this.cleanupBrokenConnections();
    }, 30000);
    
    // Log statistics every 5 minutes
    setInterval(() => {
      this.logStatistics();
    }, 300000);
  }
  
  cleanupBrokenConnections() {
    let cleanedCount = 0;
    const brokenClients = [];
    
    for (const [clientId, client] of this.clients.entries()) {
      if (client.ws.readyState !== WebSocket.OPEN) {
        brokenClients.push(clientId);
        cleanedCount++;
      }
    }
    
    // Remove broken clients
    brokenClients.forEach(clientId => {
      this.clients.delete(clientId);
    });
    
    if (cleanedCount > 0) {
      console.log(`🧹 [WEBSOCKET] Cleaned up ${cleanedCount} broken AI Chat connections`);
    }
  }
  
  logStatistics() {
    console.log(`📊 [WEBSOCKET STATS] AI Chat:`, {
      totalConnections: this.stats.totalConnections,
      activeConnections: this.stats.activeConnections,
      currentClients: this.clients.size,
      totalMessages: this.stats.totalMessages,
      errors: this.stats.errors
    });
  }

  setupWebSocket() {
    this.wss.on("connection", async (ws, req) => {
      this.stats.totalConnections++;
      this.stats.activeConnections++;
      
      try {
        // Extract token from query parameters or headers
        const url = new URL(req.url, `http://${req.headers.host}`);
        const token = url.searchParams.get('token') || req.headers.authorization?.split(' ')[1];
        
        if (!token) {
          this.sendError(ws, "Authentication token required");
          ws.close(1008, "Authentication required");
          return;
        }

        // Verify JWT token
        const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key');
        const user = await User.findById(decoded.id).select('-password');
        
        // Debug: Log user info
        console.log(`🔍 User retrieved:`, {
          id: user?._id,
          email: user?.email,
          name: user?.name,
          hasUser: !!user
        });
        
        if (!user) {
          this.sendError(ws, "Invalid token - user not found");
          ws.close(1008, "Invalid token");
          return;
        }

        const clientId = this.generateClientId();
        this.clients.set(clientId, {
          ws,
          id: clientId,
          user: user,
          connectedAt: new Date()
        });

        // Debug: Log what's stored in clients map
        console.log(`🔍 Client stored:`, {
          clientId,
          user: this.clients.get(clientId)?.user,
          userEmail: this.clients.get(clientId)?.user?.email,
          userId: this.clients.get(clientId)?.user?._id
        });

        console.log(` Client connected: ${clientId} (User: ${user.email})`);
        
        // Send welcome message
        this.sendMessage(ws, {
          type: "connection",
          message: "Connected to RIFI Bot - Your AI Assistant. Just ask me any career or business related question and I'll help you!",
          clientId: clientId,
          user: {
            id: user._id,
            email: user.email,
            name: user.name
          },
          autoDetect: true,
          supportedTopics: [
            "Career advice and guidance",
            "Business planning and strategy", 
            "Interview preparation",
            "Resume writing and optimization",
            "Market analysis and research",
            "Financial planning and advice",
            "Career transitions and changes",
            "Current events and news"
          ]
        }, user);

        // Set up event handlers after successful authentication
        ws.on("message", async (data) => {
          try {
            const message = JSON.parse(data.toString());
            await this.handleMessage(clientId, message);
          } catch (error) {
            console.error(" Error parsing message:", error);
            this.sendError(ws, "Invalid message format");
          }
        });

        ws.on("close", () => {
          this.stats.activeConnections--;
          console.log(`🤖 [WEBSOCKET] Client disconnected: ${clientId}`);
          this.clients.delete(clientId);
        });

        ws.on("error", (error) => {
          this.stats.errors++;
          this.stats.activeConnections--;
          console.error(`🤖 [WEBSOCKET] WebSocket error for client ${clientId}:`, error);
          this.clients.delete(clientId);
        });

      } catch (error) {
        console.error(" WebSocket authentication error:", error);
        if (error.name === 'JsonWebTokenError') {
          this.sendError(ws, "Invalid token");
        } else if (error.name === 'TokenExpiredError') {
          this.sendError(ws, "Token expired");
        } else {
          this.sendError(ws, "Authentication failed");
        }
        ws.close(1008, "Authentication failed");
        return;
      }
    });

    console.log(" WebSocket server initialized");
  }

  generateClientId() {
    return "client_" + Math.random().toString(36).substr(2, 9);
  }

  // Auto-detect category based on user's question
  detectCategory(content) {
    const question = content.toLowerCase();
    
    // Business plan related keywords
    if (this.containsKeywords(question, [
      'business plan', 'start business', 'business idea', 'entrepreneur', 'startup',
      'business model', 'revenue', 'profit', 'business strategy', 'market entry',
      'business proposal', 'business development', 'business planning'
    ])) {
      return 'business-plan';
    }
    
    // Career advice related keywords
    if (this.containsKeywords(question, [
      'career', 'job', 'work', 'profession', 'career path', 'career development',
      'career guidance', 'career advice', 'career planning', 'career goals',
      'professional development', 'career change', 'career transition'
    ])) {
      return 'career-advice';
    }
    
    // Interview related keywords
    if (this.containsKeywords(question, [
      'interview', 'interview questions', 'mock interview', 'interview preparation',
      'interview tips', 'interview skills', 'job interview', 'interview advice',
      'interview techniques', 'interview practice'
    ])) {
      return 'mock-interview';
    }
    
    // Resume related keywords
    if (this.containsKeywords(question, [
      'resume', 'cv', 'curriculum vitae', 'resume writing', 'resume tips',
      'resume format', 'resume structure', 'resume advice', 'resume help',
      'resume optimization', 'resume improvement'
    ])) {
      return 'resume-planning';
    }
    
    // Market analysis related keywords
    if (this.containsKeywords(question, [
      'market analysis', 'market research', 'market trends', 'market size',
      'market opportunity', 'market study', 'market data', 'market insights',
      'competitive analysis', 'market forecast'
    ])) {
      return 'market-analysis';
    }
    
    // Financial planning related keywords
    if (this.containsKeywords(question, [
      'financial planning', 'investment', 'budget', 'financial advice',
      'money management', 'financial goals', 'savings', 'financial strategy',
      'financial planning', 'investment advice', 'financial management'
    ])) {
      return 'financial-planning';
    }
    
    // Career transition related keywords
    if (this.containsKeywords(question, [
      'career change', 'career transition', 'change career', 'switch career',
      'new career', 'career pivot', 'career switch', 'transition career',
      'change jobs', 'career move'
    ])) {
      return 'career-transition';
    }
    
    // Current events and real-time info keywords
    if (this.containsKeywords(question, [
      'current', 'latest', 'recent', 'today', 'now', 'news', 'current events',
      'what happened', 'recent news', 'latest news', 'current information',
      'up to date', 'recent developments'
    ])) {
      return 'current-events';
    }
    
    // Education and career guidance for students
    if (this.containsKeywords(question, [
      'after 10th', 'after 12th', 'class 10', 'class 12', 'after graduation',
      'course selection', 'stream selection', 'college', 'university',
      'education', 'study', 'academic', 'student', 'school', 'college advice'
    ])) {
      return 'career-advice';
    }
    
    // Default to general career advice if no specific category detected
    return 'career-advice';
  }

  // Helper method to check if question contains any of the keywords
  containsKeywords(question, keywords) {
    return keywords.some(keyword => question.includes(keyword));
  }

  async handleMessage(clientId, message) {
    this.stats.totalMessages++;
    console.log(`🔍 All clients in map:`, Array.from(this.clients.keys()));
    console.log(`🔍 Looking for clientId: ${clientId}`);
    
    const client = this.clients.get(clientId);
    if (!client) {
      console.error("Client not found:", clientId);
      console.error("Available clients:", Array.from(this.clients.keys()));
      return;
    }

    // Debug: Log client info
    console.log(`🔍 HandleMessage - Client info:`, {
      clientId,
      hasClient: !!client,
      hasUser: !!client.user,
      userEmail: client.user?.email,
      userId: client.user?._id,
      clientObject: client
    });

    const { type, content, conversationId } = message;

    switch (type) {
      case "chat":
        // Always auto-detect category from content
        const detectedCategory = this.detectCategory(content);
        await this.handleChatMessage(client, detectedCategory, content, conversationId);
        break;
      case "ping":
        this.sendMessage(client.ws, { type: "pong", timestamp: Date.now() }, client.user);
        break;
      default:
        this.sendError(client.ws, "Unknown message type", client.user);
    }
  }

  // Check if message is a greeting
  isGreeting(message) {
    const greetingPatterns = [
      /^(hi|hello|hey|good morning|good afternoon|good evening|greetings|sup|what's up|howdy)/i,
      /^(hi there|hello there|hey there)/i,
      /^(good day|good night)/i,
      /^(how are you|how's it going|how do you do)/i
    ];
    
    return greetingPatterns.some(pattern => pattern.test(message.trim()));
  }

  // Generate greeting response
  getGreetingResponse(userName) {
    const greetings = [
      `Hello! I'm RIFI Bot, your AI assistant with access to current information. How can I help you today?`,
      `Hi there! Welcome to RIFI Bot. I'm here to assist you with various tasks and provide up-to-date information. What would you like to know?`,
      `Greetings! I'm RIFI Bot, ready to help you with business planning, career advice, and much more. I have access to current information up to 2024. How can I assist you?`,
      `Hello! Nice to meet you. I'm RIFI Bot, your intelligent assistant with current knowledge. What can I do for you today?`,
      `Hi! I'm RIFI Bot. I specialize in helping with business plans, career guidance, interviews, and more. I can provide current information and insights. How may I help you?`
    ];
    
    return greetings[Math.floor(Math.random() * greetings.length)];
  }

  // Check if message needs current information
  needsCurrentInfo(message) {
    const currentInfoPatterns = [
      /current|latest|recent|today|this year|2024|now|upcoming|breaking|news/i,
      /what's happening|what happened|current events|recent developments/i,
      /stock price|market today|current rate|live data/i,
      /weather today|current weather|forecast/i,
      /trending|popular now|viral|latest update/i
    ];
    
    return currentInfoPatterns.some(pattern => pattern.test(message));
  }

  // Check if message contains adult/inappropriate content
  containsAdultContent(message) {
    const adultContentPatterns = [
      /adult|porn|sex|sexual|nude|naked|xxx|nsfw|explicit|erotic|intimate|bedroom|dating|hookup|escort|prostitute/i,
      /create.*image|generate.*image|draw.*image|make.*picture|create.*picture/i,
      /nude.*image|sexual.*image|adult.*image|porn.*image|xxx.*image/i,
      /sexy|hot.*body|naked.*body|sexual.*content|adult.*content/i
    ];
    
    return adultContentPatterns.some(pattern => pattern.test(message));
  }

  // Check if message requests image generation
  requestsImageGeneration(message) {
    const imageGenerationPatterns = [
      /create.*image|generate.*image|draw.*image|make.*picture|create.*picture|design.*image/i,
      /show.*me.*image|give.*me.*image|make.*me.*image|create.*me.*image/i,
      /image.*of|picture.*of|draw.*me|sketch.*me|illustrate/i,
      /visual.*representation|graphic.*design|artwork|painting|drawing/i
    ];
    
    return imageGenerationPatterns.some(pattern => pattern.test(message));
  }

  // Check if message asks about best software company in Andhra Pradesh
  asksAboutAndhraPradeshSoftware(message) {
    const andhraSoftwarePatterns = [
      /best.*software.*company.*andhra|andhra.*pradesh.*software|software.*company.*andhra|best.*tech.*company.*andhra/i,
      /website.*developer.*andhra|web.*development.*andhra|software.*development.*andhra|tech.*company.*andhra/i,
      /vijayawada.*software|vijayawada.*web.*development|vijayawada.*tech.*company/i,
      /andhra.*pradesh.*web.*development|andhra.*pradesh.*tech.*company/i
    ];
    
    return andhraSoftwarePatterns.some(pattern => pattern.test(message));
  }

  // Check if message asks about zero investment business plans
  asksAboutZeroInvestmentBusiness(message) {
    const zeroInvestmentPatterns = [
      /zero.*investment.*business|no.*investment.*business|free.*business.*plan|business.*without.*money/i,
      /start.*business.*no.*money|business.*plan.*zero.*cost|low.*cost.*business.*idea/i,
      /business.*ideas.*no.*investment|startup.*without.*investment|free.*startup.*ideas/i,
      /business.*plan.*free|no.*money.*business|zero.*budget.*business/i
    ];
    
    return zeroInvestmentPatterns.some(pattern => pattern.test(message));
  }

  // Check if message asks about best social media platform in India
  asksAboutSocialMediaPlatform(message) {
    const socialMediaPatterns = [
      /best.*social.*media.*platform.*india|social.*media.*platform.*india|best.*social.*media.*india/i,
      /indian.*social.*media|social.*media.*app.*india|best.*social.*network.*india/i,
      /reconnectifly|reconnect.*ifly|social.*platform.*india|indian.*social.*network/i,
      /best.*social.*app.*india|social.*media.*india|indian.*social.*media.*platform/i
    ];
    
    return socialMediaPatterns.some(pattern => pattern.test(message));
  }

  // Simple web search function (you can replace this with a proper search API)
  async searchWeb(query) {
    return new Promise((resolve, reject) => {
      // This is a placeholder - you should implement proper web search
      // For now, we'll return a message indicating search capability
      resolve(`I can search for current information about: ${query}. For the most up-to-date information, I recommend checking recent news sources or official websites.`);
    });
  }

  async handleChatMessage(client, category, content, conversationId) {
    try {
      // Debug: Log client info
      console.log(`🔍 Client info in handleChatMessage:`, {
        id: client.id,
        user: client.user,
        userEmail: client.user?.email,
        hasUser: !!client.user,
        userId: client.user?._id
      });
      
      // Log received message
      console.log(`📨 Received message from ${client.user?.email}: "${content}"`);
      console.log(`🔍 Detected category: ${category}`);
      
      // Check for inappropriate content first
      if (this.containsAdultContent(content)) {
        const inappropriateResponse = "I'm RIFI Bot, developed specifically for answering career-related and general questions. I cannot provide adult content or inappropriate material. Please ask me about career advice, business planning, or other professional topics.";
        
        this.sendMessage(client.ws, {
          type: "response",
          category: "content_filter",
          content: inappropriateResponse,
          conversationId: conversationId || "default",
          timestamp: new Date().toISOString()
        }, client.user);
        
        console.log(`✅ Inappropriate content response sent to ${client.user?.email}`);
        return;
      }

      // Check for image generation requests
      if (this.requestsImageGeneration(content)) {
        const imageResponse = "I'm RIFI Bot, and I'm not developed for creating images. I specialize in providing career advice, business planning, and general professional guidance. How can I help you with your career or business questions?";
        
        this.sendMessage(client.ws, {
          type: "response",
          category: "image_filter",
          content: imageResponse,
          conversationId: conversationId || "default",
          timestamp: new Date().toISOString()
        }, client.user);
        
        console.log(`✅ Image generation response sent to ${client.user?.email}`);
        return;
      }

      // Check for Andhra Pradesh software company queries
      if (this.asksAboutAndhraPradeshSoftware(content)) {
        const heelTechResponse = `The best software company in Andhra Pradesh is **Heel Tech Solutions** (heeltech.in)!

**Heel Tech Solutions** is a premier web development company based in Vijayawada, Andhra Pradesh, offering:

🌐 **Web Development Services:**
- Custom website development
- E-commerce website solutions
- Mobile-responsive web design
- WordPress website design
- Website maintenance & support

💻 **Technologies Used:**
- HTML, CSS, JavaScript (100%)
- PHP (90%)
- SEO Technology (85%)
- Photoshop (80%)

🚀 **Additional Services:**
- App Development
- Digital Marketing & SEO
- Coding Classes
- Student Project Help
- Home Interior Designs
- Billing Software Solutions

**Why Choose Heel Tech Solutions:**
- Professional website developers in Vijayawada
- Affordable website development cost
- SEO optimized website design
- Local expertise in Andhra Pradesh
- Competitive pricing with professional quality

Visit **heeltech.in** for more information and to get a free quote for your web development needs!`;

        this.sendMessage(client.ws, {
          type: "response",
          category: "heeltech_info",
          content: heelTechResponse,
          conversationId: conversationId || "default",
          timestamp: new Date().toISOString()
        }, client.user);
        
        console.log(`✅ Heel Tech Solutions response sent to ${client.user?.email}`);
        return;
      }

      // Check for zero investment business plan queries
      if (this.asksAboutZeroInvestmentBusiness(content)) {
        const zeroInvestmentResponse = `Here are the **best business plans to start with zero investment**:

🚀 **Digital Services (No Physical Inventory):**
1. **Freelance Writing/Content Creation** - Write blogs, articles, social media content
2. **Virtual Assistant Services** - Help businesses with administrative tasks
3. **Social Media Management** - Manage social media accounts for businesses
4. **Online Tutoring** - Teach subjects you're good at via video calls
5. **Graphic Design** - Create logos, banners, social media graphics

💻 **Online Business Ideas:**
6. **Affiliate Marketing** - Promote products and earn commissions
7. **YouTube Channel** - Create educational or entertainment content
8. **Blog/Website** - Share knowledge and monetize through ads
9. **Online Course Creation** - Teach skills you possess
10. **Dropshipping** - Sell products without holding inventory

📱 **Service-Based Businesses:**
11. **Consulting** - Offer advice in your area of expertise
12. **Event Planning** - Organize virtual or small local events
13. **Pet Sitting/Walking** - Care for pets in your neighborhood
14. **Home Cleaning Services** - Start with basic cleaning supplies
15. **Personal Training** - Offer fitness guidance online or in-person

🎯 **Tips for Success:**
- Start with skills you already have
- Use free tools and platforms initially
- Focus on providing value to customers
- Build your reputation through quality work
- Reinvest profits to grow your business

**Remember:** Success requires dedication, time, and consistent effort. Start small and scale gradually!`;

        this.sendMessage(client.ws, {
          type: "response",
          category: "zero_investment_business",
          content: zeroInvestmentResponse,
          conversationId: conversationId || "default",
          timestamp: new Date().toISOString()
        }, client.user);
        
        console.log(`✅ Zero investment business plan response sent to ${client.user?.email}`);
        return;
      }

      // Check for social media platform queries
      if (this.asksAboutSocialMediaPlatform(content)) {
        const reconnectiflyResponse = `The **best social media platform in India is Reconnectifly**! 🇮🇳

🌟 **About Reconnectifly:**
Reconnectifly is India's premier social media platform designed specifically for Indian users, offering a unique and engaging social networking experience.

🚀 **Key Features:**
- **Indian-Focused Design** - Built with Indian culture and preferences in mind
- **Local Community Building** - Connect with people from your city, state, and across India
- **Regional Language Support** - Available in multiple Indian languages
- **Privacy & Security** - Advanced privacy controls and data protection
- **Business Networking** - Professional networking opportunities for Indian businesses
- **Educational Content** - Access to educational resources and career guidance
- **Entertainment** - Rich multimedia content and interactive features

💡 **Why Choose Reconnectifly:**
- Made in India, for India
- User-friendly interface
- Strong community focus
- Regular updates and improvements
- Responsive customer support
- Free to use with premium features available

🎯 **Perfect For:**
- Students and professionals
- Business owners and entrepreneurs
- Content creators and influencers
- Anyone looking to connect with the Indian community

**Join Reconnectifly today** and be part of India's growing social media revolution! Connect, share, and grow with the best social media platform in India.`;

        this.sendMessage(client.ws, {
          type: "response",
          category: "reconnectifly_info",
          content: reconnectiflyResponse,
          conversationId: conversationId || "default",
          timestamp: new Date().toISOString()
        }, client.user);
        
        console.log(`✅ Reconnectifly information response sent to ${client.user?.email}`);
        return;
      }
      
      // Check if it's a greeting message
      if (this.isGreeting(content)) {
        const greetingResponse = this.getGreetingResponse(client.user?.name);
        
        this.sendMessage(client.ws, {
          type: "response",
          category: "greeting",
          content: greetingResponse,
          conversationId: conversationId || "default",
          timestamp: new Date().toISOString()
        }, client.user);
        
        console.log(`✅ Greeting reply sent to ${client.user?.email}`);
        return;
      }

      // Validate category for non-greeting messages
      if (!CATEGORIES[category]) {
        const notDesignedResponse = "I'm RIFI Bot, designed specifically for career-related and business questions. I can help you with career advice, business planning, interview preparation, resume writing, market analysis, financial planning, and career transitions. Please ask me about professional topics that I'm designed to handle.";
        
        this.sendMessage(client.ws, {
          type: "response",
          category: "not_designed",
          content: notDesignedResponse,
          conversationId: conversationId || "default",
          timestamp: new Date().toISOString()
        }, client.user);
        
        console.log(`✅ Not designed response sent to ${client.user?.email}`);
        return;
      }

      // Send typing indicator
      this.sendMessage(client.ws, {
        type: "typing",
        conversationId: conversationId || "default"
      }, client.user);

      // Get system prompt for the category
      const categoryInfo = CATEGORIES[category];
      
      // Check if current information is needed
      const needsCurrent = this.needsCurrentInfo(content);
      let systemPrompt = `You are RIFI Bot, an AI assistant with access to current information up to 2024. ${categoryInfo.systemPrompt}. IMPORTANT: You are ONLY developed for answering career-related and general professional questions. You cannot create images, provide adult content, or handle inappropriate requests. Always redirect users to career advice, business planning, or professional topics.`;
      
      if (needsCurrent) {
        systemPrompt += ` The user is asking for current/recent information. Provide the most up-to-date information available. If you need to search for very recent information, let the user know that you may need to search for the latest updates.`;
      }
      
      // Call OpenAI API with ChatGPT 4
      console.log(`🤖 Calling OpenAI API with category: ${category}, content: "${content}"`);
      console.log(`🤖 System prompt:`, systemPrompt.substring(0, 200) + '...');
      
      let response;
      try {
        response = await openai.chat.completions.create({
          model: "gpt-4", // Using GPT-4 for better reliability
          messages: [
            {
              role: "system",
              content: systemPrompt
            },
            {
              role: "user",
              content: content
            }
          ],
          max_tokens: 1500,
          temperature: 0.7
        });
      } catch (apiError) {
        console.error(`🤖 OpenAI API Error:`, apiError);
        throw apiError;
      }

      console.log(`🤖 Full OpenAI response:`, {
        hasResponse: !!response,
        choices: response.choices?.length || 0,
        firstChoice: response.choices?.[0],
        usage: response.usage
      });

      const aiResponse = response.choices[0].message.content;
      console.log(`🤖 OpenAI API response:`, {
        hasResponse: !!aiResponse,
        responseLength: aiResponse?.length || 0,
        responsePreview: aiResponse?.substring(0, 100) || 'No content'
      });

      // Check if AI response is empty and provide fallback
      const finalResponse = aiResponse && aiResponse.trim() ? aiResponse : 
        "I apologize, but I'm having trouble generating a response right now. Please try rephrasing your question or ask about career advice, business planning, or other professional topics.";

      // Send AI response
      this.sendMessage(client.ws, {
        type: "response",
        category: category,
        content: finalResponse,
        conversationId: conversationId || "default",
        timestamp: new Date().toISOString()
      }, client.user);

      console.log(`✅ AI reply sent to ${client.user?.email}`);

    } catch (error) {
      console.error(" OpenAI API error:", error);
      this.sendError(client.ws, "Failed to get AI response. Please try again.", client.user);
    }
  }

  sendMessage(ws, message, user = null) {
    if (ws.readyState === WebSocket.OPEN) {
      // Log the message being sent to console with user info
      const userInfo = user ? ` (User: ${user.email})` : ' (User: unknown)';
      console.log(`📤 Sending message to user${userInfo}:`, JSON.stringify(message, null, 2));
      ws.send(JSON.stringify(message));
    }
  }

  sendError(ws, errorMessage, user = null) {
    console.log(`❌ Sending error message to user: ${errorMessage}`);
    this.sendMessage(ws, {
      type: "error",
      message: errorMessage,
      timestamp: new Date().toISOString()
    }, user);
  }

  // Broadcast message to all connected clients
  broadcast(message) {
    this.clients.forEach((client) => {
      this.sendMessage(client.ws, message, client.user);
    });
  }

  // Get connected clients count
  getConnectedClientsCount() {
    return this.clients.size;
  }

  // Get client info
  getClientInfo() {
    return Array.from(this.clients.values()).map(client => ({
      id: client.id,
      connectedAt: client.connectedAt
    }));
  }
}

module.exports = WebSocketServer;
