All files / src/modules/recommendations/services personalization.service.ts

0% Statements 0/287
0% Branches 0/111
0% Functions 0/70
0% Lines 0/252

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User, UserDocument } from '../../../database/schemas/user.schema';
import { UserInteraction, UserInteractionDocument } from '../../../database/schemas/user-interaction.schema';
import { Product, ProductDocument } from '../../../database/schemas/product.schema';
 
export interface UserProfile {
  userId: string;
  preferenceVector: number[];
  preferredCategories: string[];
  preferredBrands: string[];
  preferredColors: string[];
  preferredStyles: string[];
  budgetRange: { min: number; max: number };
  sizePreferences: Record<string, string>;
  behaviorPatterns: {
    shoppingFrequency: string;
    averageSessionDuration: number;
    preferredShoppingTimes: number[];
    devicePreference: string;
    pricesensitivity: number;
  };
  personalityTraits: {
    adventurous: number; // 0-1 scale
    practical: number;
    trendy: number;
    qualityFocused: number;
    budgetConscious: number;
  };
  personalizationFactors: string[];
  lastUpdated: Date;
}
 
export interface ProductScore {
  productId: string;
  score: number;
  reasoning: string;
  confidence: number;
  factors: Array<{
    factor: string;
    weight: number;
    contribution: number;
  }>;
}
 
@Injectable()
export class PersonalizationService {
  private readonly logger = new Logger(PersonalizationService.name);
 
  constructor(
    @InjectModel(User.name) private userModel: Model<UserDocument>,
    @InjectModel(UserInteraction.name) private interactionModel: Model<UserInteractionDocument>,
    @InjectModel(Product.name) private productModel: Model<ProductDocument>,
  ) {}
 
  async buildUserProfile(userId: string): Promise<UserProfile> {
    try {
      const user = await this.userModel.findById(userId);
      Iif (!user) {
        throw new Error('User not found');
      }
 
      // Get user interactions for behavior analysis
      const interactions = await this.interactionModel
        .find({ userId })
        .sort({ timestamp: -1 })
        .limit(1000); // Last 1000 interactions
 
      // Build preference vector from interactions and explicit preferences
      const preferenceVector = await this.buildPreferenceVector(user, interactions);
      
      // Extract preferred categories, brands, colors, styles
      const preferences = this.extractPreferences(user, interactions);
      
      // Analyze behavior patterns
      const behaviorPatterns = this.analyzeBehaviorPatterns(interactions);
      
      // Calculate personality traits
      const personalityTraits = this.calculatePersonalityTraits(user, interactions);
      
      // Determine budget range
      const budgetRange = this.calculateBudgetRange(user, interactions);
 
      return {
        userId,
        preferenceVector,
        preferredCategories: preferences.categories,
        preferredBrands: preferences.brands,
        preferredColors: preferences.colors,
        preferredStyles: preferences.styles,
        budgetRange,
        sizePreferences: user.preferences?.sizes || {},
        behaviorPatterns,
        personalityTraits,
        personalizationFactors: this.getPersonalizationFactors(user, interactions),
        lastUpdated: new Date(),
      };
    } catch (error) {
      this.logger.error(`Error building user profile for ${userId}`, error);
      throw error;
    }
  }
 
  async scoreProducts(userId: string, products: any[]): Promise<ProductScore[]> {
    try {
      const userProfile = await this.buildUserProfile(userId);
      
      const scoredProducts = await Promise.all(
        products.map(async (product) => {
          const productDoc = await this.productModel.findById(product.productId || product._id);
          Iif (!productDoc) {
            return {
              productId: product.productId || product._id,
              score: 0,
              reasoning: 'Product not found',
              confidence: 0,
              factors: [],
            };
          }
 
          return this.calculatePersonalizationScore(userProfile, productDoc);
        }),
      );
 
      return scoredProducts.sort((a, b) => b.score - a.score);
    } catch (error) {
      this.logger.error(`Error scoring products for user ${userId}`, error);
      throw error;
    }
  }
 
  private async buildPreferenceVector(
    user: UserDocument,
    interactions: UserInteractionDocument[],
  ): Promise<number[]> {
    // Create a 100-dimensional preference vector
    const vector = new Array(100).fill(0);
 
    // Weight factors
    const weights = {
      explicitPreferences: 0.4,
      interactionHistory: 0.3,
      purchaseHistory: 0.2,
      timeDecay: 0.1,
    };
 
    // Explicit preferences from user profile
    Iif (user.preferences) {
      this.addExplicitPreferencesToVector(vector, user.preferences, weights.explicitPreferences);
    }
 
    // Interaction-based preferences
    this.addInteractionPreferencesToVector(vector, interactions, weights.interactionHistory);
 
    // Purchase history (high-value interactions)
    const purchases = interactions.filter(i => i.actionType === 'purchase');
    this.addInteractionPreferencesToVector(vector, purchases, weights.purchaseHistory);
 
    // Apply time decay to make recent preferences more important
    this.applyTimeDecay(vector, interactions, weights.timeDecay);
 
    // Normalize vector
    return this.normalizeVector(vector);
  }
 
  private addExplicitPreferencesToVector(
    vector: number[],
    preferences: any,
    weight: number,
  ): void {
    // Map categories to vector dimensions (0-19)
    const categoryMap = {
      'fashion': [0, 1, 2, 3],
      'beauty': [4, 5, 6, 7],
      'electronics': [8, 9, 10, 11],
      'home': [12, 13, 14, 15],
      'sports': [16, 17, 18, 19],
    };
 
    preferences.categories?.forEach((category: string) => {
      const dimensions = categoryMap[category.toLowerCase()] || [];
      dimensions.forEach(dim => {
        vector[dim] += weight;
      });
    });
 
    // Map colors to vector dimensions (20-39)
    const colorMap = {
      'black': 20, 'white': 21, 'red': 22, 'blue': 23, 'green': 24,
      'yellow': 25, 'pink': 26, 'purple': 27, 'orange': 28, 'brown': 29,
      'gray': 30, 'navy': 31, 'beige': 32, 'gold': 33, 'silver': 34,
    };
 
    preferences.colors?.forEach((color: string) => {
      const dim = colorMap[color.toLowerCase()];
      Iif (dim !== undefined) {
        vector[dim] += weight;
      }
    });
 
    // Map styles to vector dimensions (40-59)
    const styleMap = {
      'casual': 40, 'formal': 41, 'sporty': 42, 'elegant': 43, 'trendy': 44,
      'classic': 45, 'bohemian': 46, 'minimalist': 47, 'vintage': 48, 'modern': 49,
    };
 
    preferences.styles?.forEach((style: string) => {
      const dim = styleMap[style.toLowerCase()];
      Iif (dim !== undefined) {
        vector[dim] += weight;
      }
    });
  }
 
  private addInteractionPreferencesToVector(
    vector: number[],
    interactions: UserInteractionDocument[],
    weight: number,
  ): void {
    interactions.forEach(interaction => {
      // Weight different interaction types
      const actionWeights = {
        'view': 0.1,
        'click': 0.3,
        'wishlist': 0.5,
        'purchase': 1.0,
        'share': 0.4,
      };
 
      const actionWeight = actionWeights[interaction.actionType] || 0.1;
      const interactionWeight = weight * actionWeight;
 
      // Add to vector based on interaction context
      Iif ((interaction.context as any)?.category) {
        this.addCategoryToVector(vector, (interaction.context as any).category, interactionWeight);
      }
    });
  }
 
  private addCategoryToVector(vector: number[], category: string, weight: number): void {
    const categoryMap = {
      'fashion': [0, 1, 2, 3],
      'beauty': [4, 5, 6, 7],
      'electronics': [8, 9, 10, 11],
      'home': [12, 13, 14, 15],
      'sports': [16, 17, 18, 19],
    };
 
    const dimensions = categoryMap[category.toLowerCase()] || [];
    dimensions.forEach(dim => {
      vector[dim] += weight;
    });
  }
 
  private applyTimeDecay(
    vector: number[],
    interactions: UserInteractionDocument[],
    weight: number,
  ): void {
    const now = new Date();
    const maxAge = 365 * 24 * 60 * 60 * 1000; // 1 year in milliseconds
 
    interactions.forEach(interaction => {
      const age = now.getTime() - interaction.timestamp.getTime();
      const decayFactor = Math.exp(-age / maxAge); // Exponential decay
      
      // Apply decay to relevant vector dimensions
      for (let i = 0; i < vector.length; i++) {
        vector[i] *= (1 + decayFactor * weight);
      }
    });
  }
 
  private normalizeVector(vector: number[]): number[] {
    const magnitude = Math.sqrt(vector.reduce((sum, val) => sum + val * val, 0));
    return magnitude > 0 ? vector.map(val => val / magnitude) : vector;
  }
 
  private extractPreferences(
    user: UserDocument,
    interactions: UserInteractionDocument[],
  ): {
    categories: string[];
    brands: string[];
    colors: string[];
    styles: string[];
  } {
    // Start with explicit preferences
    const preferences = {
      categories: [...(user.preferences?.categories || [])],
      brands: [...(user.preferences?.brands || [])],
      colors: [...(user.preferences?.colors || [])],
      styles: [...(user.preferences?.styles || [])],
    };
 
    // Extract implicit preferences from interactions
    const categoryCount = new Map<string, number>();
    const brandCount = new Map<string, number>();
 
    interactions.forEach(interaction => {
      Iif ((interaction.context as any)?.category) {
        const category = (interaction.context as any).category;
        categoryCount.set(category, (categoryCount.get(category) || 0) + 1);
      }
    });
 
    // Add top categories from interactions
    const topCategories = Array.from(categoryCount.entries())
      .sort(([, a], [, b]) => b - a)
      .slice(0, 5)
      .map(([category]) => category);
 
    topCategories.forEach(category => {
      Iif (!preferences.categories.includes(category)) {
        preferences.categories.push(category);
      }
    });
 
    return preferences;
  }
 
  private analyzeBehaviorPatterns(interactions: UserInteractionDocument[]): {
    shoppingFrequency: string;
    averageSessionDuration: number;
    preferredShoppingTimes: number[];
    devicePreference: string;
    pricesensitivity: number;
  } {
    Iif (interactions.length === 0) {
      return {
        shoppingFrequency: 'unknown',
        averageSessionDuration: 0,
        preferredShoppingTimes: [],
        devicePreference: 'unknown',
        pricesensitivity: 0.5,
      };
    }
 
    // Calculate shopping frequency
    const daysBetweenSessions = this.calculateShoppingFrequency(interactions);
    const shoppingFrequency = this.categorizeFrequency(daysBetweenSessions);
 
    // Calculate average session duration
    const sessionDurations = this.calculateSessionDurations(interactions);
    const averageSessionDuration = sessionDurations.reduce((sum, duration) => sum + duration, 0) / sessionDurations.length;
 
    // Find preferred shopping times
    const hourCounts = new Array(24).fill(0);
    interactions.forEach(interaction => {
      const hour = interaction.timestamp.getHours();
      hourCounts[hour]++;
    });
    
    const preferredShoppingTimes = hourCounts
      .map((count, hour) => ({ hour, count }))
      .sort((a, b) => b.count - a.count)
      .slice(0, 3)
      .map(({ hour }) => hour);
 
    // Determine device preference
    const deviceCounts = new Map<string, number>();
    interactions.forEach(interaction => {
      const device = (interaction.context as any)?.deviceType || 'unknown';
      deviceCounts.set(device, (deviceCounts.get(device) || 0) + 1);
    });
    
    const devicePreference = Array.from(deviceCounts.entries())
      .sort(([, a], [, b]) => b - a)[0]?.[0] || 'unknown';
 
    // Calculate price sensitivity (0 = price insensitive, 1 = very price sensitive)
    const pricesensitivity = this.calculatePriceSensitivity(interactions);
 
    return {
      shoppingFrequency,
      averageSessionDuration,
      preferredShoppingTimes,
      devicePreference,
      pricesensitivity,
    };
  }
 
  private calculatePersonalityTraits(
    user: UserDocument,
    interactions: UserInteractionDocument[],
  ): {
    adventurous: number;
    practical: number;
    trendy: number;
    qualityFocused: number;
    budgetConscious: number;
  } {
    // Default values
    const traits = {
      adventurous: 0.5,
      practical: 0.5,
      trendy: 0.5,
      qualityFocused: 0.5,
      budgetConscious: 0.5,
    };
 
    Iif (interactions.length === 0) return traits;
 
    // Analyze interaction patterns to infer personality traits
    const categoryDiversity = this.calculateCategoryDiversity(interactions);
    const brandLoyalty = this.calculateBrandLoyalty(interactions);
    const priceVariability = this.calculatePriceVariability(interactions);
 
    // Adventurous: high category diversity, low brand loyalty
    traits.adventurous = Math.min(1, categoryDiversity * 0.7 + (1 - brandLoyalty) * 0.3);
 
    // Practical: consistent categories, moderate prices
    traits.practical = Math.min(1, (1 - categoryDiversity) * 0.5 + (1 - priceVariability) * 0.5);
 
    // Trendy: recent interactions with new products
    traits.trendy = this.calculateTrendiness(interactions);
 
    // Quality focused: higher average prices, brand loyalty
    traits.qualityFocused = Math.min(1, brandLoyalty * 0.6 + (1 - traits.budgetConscious) * 0.4);
 
    // Budget conscious: price sensitivity, coupon usage
    traits.budgetConscious = this.calculateBudgetConsciousness(interactions);
 
    return traits;
  }
 
  private calculateBudgetRange(
    user: UserDocument,
    interactions: UserInteractionDocument[],
  ): { min: number; max: number } {
    // Start with explicit budget preferences
    Iif (user.preferences?.budgetRange) {
      return user.preferences.budgetRange;
    }
 
    // Infer from interaction history
    const purchaseInteractions = interactions.filter(i => 
      i.actionType === 'purchase' && (i.metadata as any)?.totalAmount
    );
 
    Iif (purchaseInteractions.length === 0) {
      return { min: 0, max: 1000 }; // Default range
    }
 
    const amounts = purchaseInteractions.map(i => (i.metadata as any).totalAmount);
    amounts.sort((a, b) => a - b);
 
    const min = amounts[Math.floor(amounts.length * 0.1)] || 0; // 10th percentile
    const max = amounts[Math.floor(amounts.length * 0.9)] || 1000; // 90th percentile
 
    return { min, max };
  }
 
  private getPersonalizationFactors(
    user: UserDocument,
    interactions: UserInteractionDocument[],
  ): string[] {
    const factors = [];
 
    Iif (user.preferences?.categories?.length) factors.push('category-preferences');
    Iif (user.preferences?.brands?.length) factors.push('brand-preferences');
    Iif (user.preferences?.colors?.length) factors.push('color-preferences');
    Iif (user.preferences?.styles?.length) factors.push('style-preferences');
    Iif (user.measurements) factors.push('body-measurements');
    Iif (user.profile?.location) factors.push('location');
    Iif (interactions.length > 10) factors.push('interaction-history');
    Iif (interactions.filter(i => i.actionType === 'purchase').length > 0) factors.push('purchase-history');
 
    return factors;
  }
 
  private calculatePersonalizationScore(
    userProfile: UserProfile,
    product: ProductDocument,
  ): ProductScore {
    const factors: Array<{ factor: string; weight: number; contribution: number }> = [];
    let totalScore = 0;
 
    // Category match (weight: 0.25)
    Iif (userProfile.preferredCategories.includes(product.category.main)) {
      const contribution = 0.8;
      factors.push({ factor: 'category-match', weight: 0.25, contribution });
      totalScore += 0.25 * contribution;
    }
 
    // Brand preference (weight: 0.15)
    Iif (userProfile.preferredBrands.includes(product.brand)) {
      const contribution = 0.9;
      factors.push({ factor: 'brand-preference', weight: 0.15, contribution });
      totalScore += 0.15 * contribution;
    }
 
    // Price range match (weight: 0.2)
    const productPrice = product.variants[0]?.price?.current || 0;
    Iif (productPrice >= userProfile.budgetRange.min && productPrice <= userProfile.budgetRange.max) {
      const contribution = 0.7;
      factors.push({ factor: 'price-range', weight: 0.2, contribution });
      totalScore += 0.2 * contribution;
    }
 
    // Style match (weight: 0.15)
    const styleMatch = this.calculateStyleMatch(userProfile.preferredStyles, product);
    Iif (styleMatch > 0) {
      factors.push({ factor: 'style-match', weight: 0.15, contribution: styleMatch });
      totalScore += 0.15 * styleMatch;
    }
 
    // Personality trait alignment (weight: 0.15)
    const personalityMatch = this.calculatePersonalityMatch(userProfile.personalityTraits, product);
    factors.push({ factor: 'personality-match', weight: 0.15, contribution: personalityMatch });
    totalScore += 0.15 * personalityMatch;
 
    // Behavior pattern alignment (weight: 0.1)
    const behaviorMatch = this.calculateBehaviorMatch(userProfile.behaviorPatterns, product);
    factors.push({ factor: 'behavior-match', weight: 0.1, contribution: behaviorMatch });
    totalScore += 0.1 * behaviorMatch;
 
    // Generate reasoning
    const reasoning = this.generateReasoningText(factors, product);
    
    // Calculate confidence based on number of matching factors
    const confidence = Math.min(1, factors.length / 6);
 
    return {
      productId: product._id.toString(),
      score: Math.min(1, totalScore),
      reasoning,
      confidence,
      factors,
    };
  }
 
  private calculateStyleMatch(preferredStyles: string[], product: ProductDocument): number {
    Iif (!product.aiFeatures?.occasions?.length) return 0;
    
    const productStyles = product.aiFeatures.occasions;
    const matchCount = preferredStyles.filter(style => 
      productStyles.some(occasion => occasion.toLowerCase().includes(style.toLowerCase()))
    ).length;
    
    return preferredStyles.length > 0 ? matchCount / preferredStyles.length : 0;
  }
 
  private calculatePersonalityMatch(traits: any, product: ProductDocument): number {
    // This is a simplified personality matching algorithm
    // In practice, you'd have more sophisticated product personality scoring
    
    let match = 0.5; // Base score
    
    // Trendy products for trendy users
    Iif (traits.trendy > 0.7 && product.createdAt > new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)) {
      match += 0.2;
    }
    
    // Quality products for quality-focused users
    Iif (traits.qualityFocused > 0.7 && (product.variants[0]?.price?.current || 0) > 200) {
      match += 0.2;
    }
    
    // Budget products for budget-conscious users
    Iif (traits.budgetConscious > 0.7 && (product.variants[0]?.price?.discount || 0) > 0) {
      match += 0.2;
    }
    
    return Math.min(1, match);
  }
 
  private calculateBehaviorMatch(patterns: any, product: ProductDocument): number {
    // Simple behavior matching - can be enhanced
    let match = 0.5;
    
    // Price sensitivity matching
    const hasDiscount = (product.variants[0]?.price?.discount || 0) > 0;
    Iif (patterns.pricesensitivity > 0.7 && hasDiscount) {
      match += 0.3;
    }
    
    return Math.min(1, match);
  }
 
  private generateReasoningText(factors: any[], product: ProductDocument): string {
    const reasons = [];
    
    factors.forEach(factor => {
      Iif (factor.contribution > 0.5) {
        switch (factor.factor) {
          case 'category-match':
            reasons.push('matches your preferred categories');
            break;
          case 'brand-preference':
            reasons.push('from a brand you like');
            break;
          case 'price-range':
            reasons.push('within your budget range');
            break;
          case 'style-match':
            reasons.push('matches your style preferences');
            break;
          case 'personality-match':
            reasons.push('suits your shopping personality');
            break;
          case 'behavior-match':
            reasons.push('aligns with your shopping behavior');
            break;
        }
      }
    });
    
    Iif (reasons.length === 0) {
      return 'Recommended based on general popularity';
    }
    
    return `Recommended because it ${reasons.join(', ')}`;
  }
 
  // Helper methods for behavior analysis
  private calculateShoppingFrequency(interactions: UserInteractionDocument[]): number {
    Iif (interactions.length < 2) return 0;
    
    const sessions = this.groupInteractionsBySessions(interactions);
    Iif (sessions.length < 2) return 0;
    
    const totalDays = (sessions[0].timestamp.getTime() - sessions[sessions.length - 1].timestamp.getTime()) / (24 * 60 * 60 * 1000);
    return totalDays / sessions.length;
  }
 
  private categorizeFrequency(daysBetween: number): string {
    Iif (daysBetween <= 1) return 'daily';
    Iif (daysBetween <= 7) return 'weekly';
    Iif (daysBetween <= 30) return 'monthly';
    return 'occasional';
  }
 
  private calculateSessionDurations(interactions: UserInteractionDocument[]): number[] {
    const sessions = this.groupInteractionsBySessions(interactions);
    return sessions.map(session => session.duration);
  }
 
  private groupInteractionsBySessions(interactions: UserInteractionDocument[]): Array<{
    timestamp: Date;
    duration: number;
  }> {
    // Group interactions into sessions (30-minute gaps)
    const sessions = [];
    let currentSession = null;
    
    interactions.forEach(interaction => {
      if (!currentSession || 
          interaction.timestamp.getTime() - currentSession.lastInteraction.getTime() > 30 * 60 * 1000) {
        // New session
        currentSession = {
          start: interaction.timestamp,
          lastInteraction: interaction.timestamp,
        };
        sessions.push(currentSession);
      } else {
        // Continue current session
        currentSession.lastInteraction = interaction.timestamp;
      }
    });
    
    return sessions.map(session => ({
      timestamp: session.start,
      duration: (session.lastInteraction.getTime() - session.start.getTime()) / 1000, // in seconds
    }));
  }
 
  private calculatePriceSensitivity(interactions: UserInteractionDocument[]): number {
    // Analyze price-related behavior
    const purchaseInteractions = interactions.filter(i => i.actionType === 'purchase');
    Iif (purchaseInteractions.length === 0) return 0.5;
    
    const discountedPurchases = purchaseInteractions.filter(i => 
      (i.metadata as any)?.savingsAmount > 0
    );
    
    return discountedPurchases.length / purchaseInteractions.length;
  }
 
  private calculateCategoryDiversity(interactions: UserInteractionDocument[]): number {
    const categories = new Set();
    interactions.forEach(interaction => {
      Iif ((interaction.context as any)?.category) {
        categories.add((interaction.context as any).category);
      }
    });
    
    // Normalize by maximum expected categories (assume 10 max)
    return Math.min(1, categories.size / 10);
  }
 
  private calculateBrandLoyalty(interactions: UserInteractionDocument[]): number {
    // This would require product data to determine brands
    // For now, return a default value
    return 0.5;
  }
 
  private calculatePriceVariability(interactions: UserInteractionDocument[]): number {
    const purchases = interactions.filter(i => 
      i.actionType === 'purchase' && (i.metadata as any)?.totalAmount
    );
    
    Iif (purchases.length < 2) return 0;
    
    const amounts = purchases.map(p => (p.metadata as any).totalAmount);
    const mean = amounts.reduce((sum, amount) => sum + amount, 0) / amounts.length;
    const variance = amounts.reduce((sum, amount) => sum + Math.pow(amount - mean, 2), 0) / amounts.length;
    const stdDev = Math.sqrt(variance);
    
    // Normalize by mean to get coefficient of variation
    return mean > 0 ? stdDev / mean : 0;
  }
 
  private calculateTrendiness(interactions: UserInteractionDocument[]): number {
    // Calculate based on interaction with recently added products
    const recentInteractions = interactions.filter(i => 
      i.timestamp > new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) // Last 30 days
    );
    
    return interactions.length > 0 ? recentInteractions.length / interactions.length : 0.5;
  }
 
  private calculateBudgetConsciousness(interactions: UserInteractionDocument[]): number {
    // Similar to price sensitivity but includes coupon usage, deal seeking behavior
    return this.calculatePriceSensitivity(interactions);
  }
}