class ContextManager {
  constructor() {
    this.contexts = new Map(); // sessionId -> context
    this.defaultTtl = 30 * 60 * 1000; // 30 minutes
  }

  /**
   * Store query context for a session
   */
  storeContext(sessionId, parsedQuery, sqlResult = null) {
    const context = {
      ...parsedQuery,
      timestamp: Date.now(),
      sqlResult: sqlResult,
      refinements: []
    };
    
    this.contexts.set(sessionId, context);
    return context;
  }

  /**
   * Get context for a session
   */
  getContext(sessionId) {
    const context = this.contexts.get(sessionId);
    
    // Check if context has expired
    if (context && (Date.now() - context.timestamp) > this.defaultTtl) {
      this.contexts.delete(sessionId);
      return null;
    }
    
    return context;
  }

  /**
   * Update context with refinements
   */
  updateContext(sessionId, refinement) {
    const existingContext = this.getContext(sessionId);
    
    if (!existingContext) {
      return null;
    }

    // Update context with new refinements
    const updatedContext = {
      ...existingContext,
      ...refinement,
      refinements: [...existingContext.refinements, refinement],
      timestamp: Date.now()
    };

    this.contexts.set(sessionId, updatedContext);
    return updatedContext;
  }

  /**
   * Check if query is a follow-up/refinement
   */
  isFollowUpQuery(query) {
    const followUpIndicators = [
      'summarise by', 'group by', 'summarize by',
      'filter', 'show', 'exclude',
      'apartments only', 'villas only', 'commercial only',
      'weekly', 'monthly', 'yearly',
      'details', 'more info', 'expand',
      'breakdown', 'drill down', 'further'
    ];

    const queryLower = query.toLowerCase();
    
    // More specific patterns for follow-up queries
    const specificPatterns = [
      /^show.*only$/,
      /^filter.*only$/,
      /^exclude.*only$/,
      /^apartments only$/,
      /^villas only$/,
      /^commercial only$/
    ];
    
    // Check specific patterns first
    const hasSpecificPattern = specificPatterns.some(pattern => pattern.test(queryLower));
    
    // Check general indicators but exclude standalone "only" and "show" when it's part of a longer query
    const hasGeneralIndicator = followUpIndicators.some(indicator => {
      if (indicator === 'only' || indicator === 'show') {
        return false; // Skip these as they're too generic
      }
      return queryLower.includes(indicator);
    });
    
    return hasSpecificPattern || hasGeneralIndicator;
  }

  /**
   * Extract refinements from follow-up query
   */
  extractRefinements(query) {
    const queryLower = query.toLowerCase();
    const refinements = {};

    // Time grouping refinements
    if (queryLower.includes('summarise by week') || queryLower.includes('summarize by week') || queryLower.includes('group by week')) {
      refinements.grouping = 'weekly';
    } else if (queryLower.includes('summarise by month') || queryLower.includes('summarize by month') || queryLower.includes('group by month')) {
      refinements.grouping = 'monthly';
    } else if (queryLower.includes('summarise by year') || queryLower.includes('summarize by year') || queryLower.includes('group by year')) {
      refinements.grouping = 'yearly';
    } else if (queryLower.includes('weekly') && !queryLower.includes('month')) {
      refinements.grouping = 'weekly';
    } else if (queryLower.includes('monthly')) {
      refinements.grouping = 'monthly';
    }

    // Property type filters
    if (queryLower.includes('apartments only') || queryLower.includes('apartment only')) {
      refinements.property_filter = 'flat';
    } else if (queryLower.includes('villas only') || queryLower.includes('villa only')) {
      refinements.property_filter = 'villa';
    } else if (queryLower.includes('commercial only')) {
      refinements.property_filter = 'commercial';
    } else if (queryLower.includes('residential only')) {
      refinements.property_filter = 'residential';
    }

    // Room type filters
    if (queryLower.includes('3bhk') || queryLower.includes('3 bhk')) {
      refinements.room_filter = '3 b/r';
    } else if (queryLower.includes('2bhk') || queryLower.includes('2 bhk')) {
      refinements.room_filter = '2 b/r';
    } else if (queryLower.includes('1bhk') || queryLower.includes('1 bhk')) {
      refinements.room_filter = '1 b/r';
    } else if (queryLower.includes('studio')) {
      refinements.room_filter = 'studio';
    }

    // Area filters
    if (queryLower.includes('top 5 areas')) {
      refinements.limit = 5;
    } else if (queryLower.includes('top 10 areas')) {
      refinements.limit = 10;
    }

    return refinements;
  }

  /**
   * Clear context for a session
   */
  clearContext(sessionId) {
    this.contexts.delete(sessionId);
  }

  /**
   * Clean up expired contexts
   */
  cleanup() {
    const now = Date.now();
    for (const [sessionId, context] of this.contexts.entries()) {
      if (now - context.timestamp > this.defaultTtl) {
        this.contexts.delete(sessionId);
      }
    }
  }
}

module.exports = ContextManager;
