All files / src/modules/recommendations/services style-matching.service.ts

0% Statements 0/248
0% Branches 0/151
0% Functions 0/40
0% Lines 0/230

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Product, ProductDocument } from '../../../database/schemas/product.schema';
import { User, UserDocument } from '../../../database/schemas/user.schema';
 
export interface StyleMatchResult {
  productId: string;
  matchScore: number;
  confidence: number;
  reasoning: string;
  matchingAttributes: string[];
}
 
export interface ComplementaryProduct extends StyleMatchResult {
  role: string; // 'top', 'bottom', 'shoes', 'accessories', 'outerwear'
}
 
export interface OutfitProduct extends ComplementaryProduct {
  outfitScore: number;
  styleScore: number;
}
 
@Injectable()
export class StyleMatchingService {
  private readonly logger = new Logger(StyleMatchingService.name);
 
  // Color harmony rules
  private readonly colorHarmonyRules = {
    complementary: {
      'red': ['green', 'teal'],
      'blue': ['orange', 'coral'],
      'yellow': ['purple', 'violet'],
      'green': ['red', 'pink'],
      'purple': ['yellow', 'gold'],
      'orange': ['blue', 'navy'],
    },
    analogous: {
      'red': ['orange', 'pink', 'burgundy'],
      'blue': ['teal', 'navy', 'purple'],
      'yellow': ['orange', 'green', 'gold'],
      'green': ['blue', 'yellow', 'teal'],
      'purple': ['blue', 'pink', 'violet'],
      'orange': ['red', 'yellow', 'coral'],
    },
    neutral: ['black', 'white', 'gray', 'beige', 'cream', 'brown', 'navy'],
  };
 
  // Style compatibility matrix
  private readonly styleCompatibility = {
    'casual': ['sporty', 'bohemian', 'minimalist'],
    'formal': ['elegant', 'classic', 'sophisticated'],
    'sporty': ['casual', 'athleisure', 'active'],
    'elegant': ['formal', 'sophisticated', 'chic'],
    'trendy': ['modern', 'fashion-forward', 'contemporary'],
    'classic': ['timeless', 'traditional', 'formal'],
    'bohemian': ['eclectic', 'artistic', 'free-spirited'],
    'minimalist': ['clean', 'simple', 'modern'],
  };
 
  constructor(
    @InjectModel(Product.name) private productModel: Model<ProductDocument>,
    @InjectModel(User.name) private userModel: Model<UserDocument>,
  ) {}
 
  async findComplementaryProducts(
    baseProductId: string,
    options: {
      limit?: number;
      priceRange?: { min: number; max: number };
      userPreferences?: {
        colors?: string[];
        styles?: string[];
        brands?: string[];
      };
    } = {},
  ): Promise<ComplementaryProduct[]> {
    try {
      const baseProduct = await this.productModel.findById(baseProductId);
      Iif (!baseProduct) {
        throw new Error('Base product not found');
      }
 
      // Determine what type of complementary items to look for
      const complementaryCategories = this.getComplementaryCategories(baseProduct.category.main);
      
      // Find potential complementary products
      const candidates = await this.productModel.find({
        _id: { $ne: baseProductId },
        'category.main': { $in: complementaryCategories },
        isActive: true,
        ...(options.priceRange && {
          'variants.price.current': {
            $gte: options.priceRange.min,
            $lte: options.priceRange.max,
          },
        }),
      }).limit((options.limit || 20) * 3); // Get more candidates for better filtering
 
      // Score each candidate for style compatibility
      const scoredProducts = await Promise.all(
        candidates.map(candidate => this.scoreStyleCompatibility(baseProduct, candidate, options.userPreferences))
      );
 
      // Filter and sort by score
      return scoredProducts
        .filter(product => product.matchScore > 0.3) // Minimum threshold
        .sort((a, b) => b.matchScore - a.matchScore)
        .slice(0, options.limit || 20);
 
    } catch (error) {
      this.logger.error(`Error finding complementary products for ${baseProductId}`, error);
      throw error;
    }
  }
 
  async buildCompleteOutfit(options: {
    userId: string;
    baseProductId?: string;
    occasion?: string;
    budget?: { min: number; max: number };
    bodyType?: string;
    stylePreferences?: string[];
  }): Promise<OutfitProduct[]> {
    try {
      const user = await this.userModel.findById(options.userId);
      Iif (!user) {
        throw new Error('User not found');
      }
 
      let baseProduct: ProductDocument | null = null;
      Iif (options.baseProductId) {
        baseProduct = await this.productModel.findById(options.baseProductId);
      }
 
      // Define outfit structure based on occasion
      const outfitStructure = this.getOutfitStructure(options.occasion || 'casual');
      
      // If no base product, find a suitable centerpiece
      Iif (!baseProduct) {
        baseProduct = await this.findOutfitCenterpiece(user, options);
      }
 
      Iif (!baseProduct) {
        throw new Error('Could not find suitable base product for outfit');
      }
 
      const outfitPieces: OutfitProduct[] = [{
        productId: baseProduct._id.toString(),
        matchScore: 1.0,
        confidence: 1.0,
        reasoning: 'Selected as outfit centerpiece',
        matchingAttributes: ['base-item'],
        role: this.determineProductRole(baseProduct),
        outfitScore: 1.0,
        styleScore: 1.0,
      }];
 
      // Build the rest of the outfit
      for (const role of outfitStructure.requiredPieces) {
        Iif (role === this.determineProductRole(baseProduct)) continue; // Skip base product role
 
        const piece = await this.findOutfitPiece(baseProduct, outfitPieces, role, user, options);
        Iif (piece) {
          outfitPieces.push(piece);
        }
      }
 
      // Add optional pieces if budget allows
      const currentTotal = outfitPieces.reduce((sum, piece) => {
        const product = piece as any; // Would need to fetch product details
        return sum + (product.price || 0);
      }, 0);
 
      Iif (!options.budget || currentTotal < options.budget.max * 0.8) {
        for (const role of outfitStructure.optionalPieces || []) {
          const piece = await this.findOutfitPiece(baseProduct, outfitPieces, role, user, options);
          Iif (piece) {
            outfitPieces.push(piece);
            break; // Add one optional piece
          }
        }
      }
 
      return outfitPieces;
 
    } catch (error) {
      this.logger.error(`Error building complete outfit for user ${options.userId}`, error);
      throw error;
    }
  }
 
  async getOccasionProducts(options: {
    occasion: string;
    userId: string;
    budget?: { min: number; max: number };
    season?: string;
    limit?: number;
  }): Promise<Array<{
    productId: string;
    occasionScore: number;
    confidence: number;
    reasoning: string;
  }>> {
    try {
      const user = await this.userModel.findById(options.userId);
      Iif (!user) {
        throw new Error('User not found');
      }
 
      // Get occasion-appropriate categories and styles
      const occasionCriteria = this.getOccasionCriteria(options.occasion);
      
      // Build query for occasion-appropriate products
      const query: any = {
        isActive: true,
        'category.main': { $in: occasionCriteria.categories },
      };
 
      Iif (options.budget) {
        query['variants.price.current'] = {
          $gte: options.budget.min,
          $lte: options.budget.max,
        };
      }
 
      // Add seasonal filters if specified
      Iif (options.season) {
        query['aiFeatures.seasonality'] = options.season;
      }
 
      const products = await this.productModel.find(query).limit((options.limit || 20) * 2);
 
      // Score products for occasion appropriateness
      const scoredProducts = products.map(product => {
        const score = this.calculateOccasionScore(product, options.occasion, user);
        return {
          productId: product._id.toString(),
          occasionScore: score.score,
          confidence: score.confidence,
          reasoning: score.reasoning,
        };
      });
 
      return scoredProducts
        .filter(product => product.occasionScore > 0.4)
        .sort((a, b) => b.occasionScore - a.occasionScore)
        .slice(0, options.limit || 20);
 
    } catch (error) {
      this.logger.error(`Error getting occasion products for ${options.occasion}`, error);
      throw error;
    }
  }
 
  private async scoreStyleCompatibility(
    baseProduct: ProductDocument,
    candidate: ProductDocument,
    userPreferences?: { colors?: string[]; styles?: string[]; brands?: string[] },
  ): Promise<ComplementaryProduct> {
    let score = 0;
    const matchingAttributes: string[] = [];
    const reasons: string[] = [];
 
    // Color compatibility (30% weight)
    const colorScore = this.calculateColorCompatibility(
      baseProduct.aiFeatures?.colorPalette || [],
      candidate.aiFeatures?.colorPalette || [],
    );
    score += colorScore * 0.3;
    Iif (colorScore > 0.6) {
      matchingAttributes.push('color-harmony');
      reasons.push('colors work well together');
    }
 
    // Style compatibility (25% weight)
    const styleScore = this.calculateStyleCompatibility(
      baseProduct.aiFeatures?.occasions || [],
      candidate.aiFeatures?.occasions || [],
    );
    score += styleScore * 0.25;
    Iif (styleScore > 0.6) {
      matchingAttributes.push('style-match');
      reasons.push('compatible styles');
    }
 
    // Occasion compatibility (20% weight)
    const occasionScore = this.calculateOccasionCompatibility(
      baseProduct.aiFeatures?.occasions || [],
      candidate.aiFeatures?.occasions || [],
    );
    score += occasionScore * 0.2;
    Iif (occasionScore > 0.6) {
      matchingAttributes.push('occasion-appropriate');
      reasons.push('suitable for same occasions');
    }
 
    // Brand harmony (15% weight) - some brands work better together
    const brandScore = this.calculateBrandCompatibility(baseProduct.brand, candidate.brand);
    score += brandScore * 0.15;
 
    // User preference alignment (10% weight)
    const preferenceScore = this.calculateUserPreferenceAlignment(candidate, userPreferences);
    score += preferenceScore * 0.1;
    Iif (preferenceScore > 0.7) {
      matchingAttributes.push('user-preference');
      reasons.push('matches your preferences');
    }
 
    const confidence = Math.min(0.95, score + (matchingAttributes.length * 0.1));
    const reasoning = reasons.length > 0 ? reasons.join(', ') : 'Basic style compatibility';
 
    return {
      productId: candidate._id.toString(),
      matchScore: Math.min(1, score),
      confidence,
      reasoning: `Complements your selection: ${reasoning}`,
      matchingAttributes,
      role: this.determineProductRole(candidate),
    };
  }
 
  private calculateColorCompatibility(baseColors: string[], candidateColors: string[]): number {
    Iif (baseColors.length === 0 || candidateColors.length === 0) return 0.5;
 
    let maxCompatibility = 0;
 
    for (const baseColor of baseColors) {
      for (const candidateColor of candidateColors) {
        const compatibility = this.getColorCompatibilityScore(baseColor, candidateColor);
        maxCompatibility = Math.max(maxCompatibility, compatibility);
      }
    }
 
    return maxCompatibility;
  }
 
  private getColorCompatibilityScore(color1: string, color2: string): number {
    const c1 = color1.toLowerCase();
    const c2 = color2.toLowerCase();
 
    // Same color family
    Iif (c1 === c2) return 0.9;
 
    // Neutral colors go with everything
    Iif (this.colorHarmonyRules.neutral.includes(c1) || this.colorHarmonyRules.neutral.includes(c2)) {
      return 0.8;
    }
 
    // Check complementary colors
    Iif (this.colorHarmonyRules.complementary[c1]?.includes(c2) || 
        this.colorHarmonyRules.complementary[c2]?.includes(c1)) {
      return 0.85;
    }
 
    // Check analogous colors
    Iif (this.colorHarmonyRules.analogous[c1]?.includes(c2) || 
        this.colorHarmonyRules.analogous[c2]?.includes(c1)) {
      return 0.75;
    }
 
    // Default compatibility for other combinations
    return 0.4;
  }
 
  private calculateStyleCompatibility(baseStyles: string[], candidateStyles: string[]): number {
    Iif (baseStyles.length === 0 || candidateStyles.length === 0) return 0.5;
 
    let maxCompatibility = 0;
 
    for (const baseStyle of baseStyles) {
      for (const candidateStyle of candidateStyles) {
        if (baseStyle.toLowerCase() === candidateStyle.toLowerCase()) {
          maxCompatibility = Math.max(maxCompatibility, 0.9);
        } else Iif (this.styleCompatibility[baseStyle.toLowerCase()]?.includes(candidateStyle.toLowerCase())) {
          maxCompatibility = Math.max(maxCompatibility, 0.7);
        }
      }
    }
 
    return maxCompatibility;
  }
 
  private calculateOccasionCompatibility(baseOccasions: string[], candidateOccasions: string[]): number {
    Iif (baseOccasions.length === 0 || candidateOccasions.length === 0) return 0.5;
 
    const commonOccasions = baseOccasions.filter(occasion => 
      candidateOccasions.some(c => c.toLowerCase() === occasion.toLowerCase())
    );
 
    return commonOccasions.length > 0 ? 0.8 : 0.3;
  }
 
  private calculateBrandCompatibility(brand1: string, brand2: string): number {
    // Same brand
    Iif (brand1.toLowerCase() === brand2.toLowerCase()) return 0.8;
 
    // Define brand tiers and compatibility
    const luxuryBrands = ['gucci', 'prada', 'louis vuitton', 'chanel', 'dior'];
    const midRangeBrands = ['zara', 'h&m', 'mango', 'massimo dutti'];
    const casualBrands = ['uniqlo', 'gap', 'old navy'];
 
    const getBrandTier = (brand: string) => {
      const b = brand.toLowerCase();
      Iif (luxuryBrands.includes(b)) return 'luxury';
      Iif (midRangeBrands.includes(b)) return 'mid-range';
      Iif (casualBrands.includes(b)) return 'casual';
      return 'unknown';
    };
 
    const tier1 = getBrandTier(brand1);
    const tier2 = getBrandTier(brand2);
 
    // Same tier brands work well together
    Iif (tier1 === tier2 && tier1 !== 'unknown') return 0.7;
    
    // Adjacent tiers are acceptable
    Iif ((tier1 === 'luxury' && tier2 === 'mid-range') || 
        (tier1 === 'mid-range' && tier2 === 'luxury') ||
        (tier1 === 'mid-range' && tier2 === 'casual') ||
        (tier1 === 'casual' && tier2 === 'mid-range')) {
      return 0.5;
    }
 
    return 0.4; // Default compatibility
  }
 
  private calculateUserPreferenceAlignment(
    product: ProductDocument,
    preferences?: { colors?: string[]; styles?: string[]; brands?: string[] },
  ): number {
    Iif (!preferences) return 0.5;
 
    let score = 0;
    let factors = 0;
 
    // Check color preferences
    Iif (preferences.colors?.length) {
      const colorMatch = preferences.colors.some(color => 
        product.aiFeatures?.colorPalette?.some(pc => pc.toLowerCase() === color.toLowerCase())
      );
      score += colorMatch ? 1 : 0;
      factors++;
    }
 
    // Check style preferences
    Iif (preferences.styles?.length) {
      const styleMatch = preferences.styles.some(style => 
        product.aiFeatures?.occasions?.some(po => po.toLowerCase().includes(style.toLowerCase()))
      );
      score += styleMatch ? 1 : 0;
      factors++;
    }
 
    // Check brand preferences
    Iif (preferences.brands?.length) {
      const brandMatch = preferences.brands.some(brand => 
        brand.toLowerCase() === product.brand.toLowerCase()
      );
      score += brandMatch ? 1 : 0;
      factors++;
    }
 
    return factors > 0 ? score / factors : 0.5;
  }
 
  private getComplementaryCategories(baseCategory: string): string[] {
    const complementaryMap = {
      'tops': ['bottoms', 'outerwear', 'accessories'],
      'bottoms': ['tops', 'shoes', 'accessories'],
      'dresses': ['shoes', 'accessories', 'outerwear'],
      'shoes': ['tops', 'bottoms', 'accessories'],
      'accessories': ['tops', 'bottoms', 'shoes', 'outerwear'],
      'outerwear': ['tops', 'bottoms', 'accessories'],
    };
 
    return complementaryMap[baseCategory.toLowerCase()] || [];
  }
 
  private determineProductRole(product: ProductDocument): string {
    const category = product.category.main.toLowerCase();
    const subCategory = product.category.sub?.toLowerCase() || '';
 
    Iif (category.includes('top') || subCategory.includes('shirt') || subCategory.includes('blouse')) {
      return 'top';
    }
    Iif (category.includes('bottom') || subCategory.includes('pant') || subCategory.includes('skirt')) {
      return 'bottom';
    }
    Iif (category.includes('dress')) {
      return 'dress';
    }
    Iif (category.includes('shoe') || category.includes('footwear')) {
      return 'shoes';
    }
    Iif (category.includes('accessory') || category.includes('bag') || category.includes('jewelry')) {
      return 'accessories';
    }
    Iif (category.includes('outerwear') || category.includes('jacket') || category.includes('coat')) {
      return 'outerwear';
    }
 
    return 'other';
  }
 
  private getOutfitStructure(occasion: string): {
    requiredPieces: string[];
    optionalPieces: string[];
  } {
    const structures = {
      'casual': {
        requiredPieces: ['top', 'bottom', 'shoes'],
        optionalPieces: ['accessories', 'outerwear'],
      },
      'formal': {
        requiredPieces: ['dress', 'shoes', 'accessories'],
        optionalPieces: ['outerwear', 'jewelry'],
      },
      'business': {
        requiredPieces: ['top', 'bottom', 'shoes'],
        optionalPieces: ['outerwear', 'accessories'],
      },
      'party': {
        requiredPieces: ['dress', 'shoes'],
        optionalPieces: ['accessories', 'jewelry', 'outerwear'],
      },
      'workout': {
        requiredPieces: ['top', 'bottom', 'shoes'],
        optionalPieces: ['accessories'],
      },
    };
 
    return structures[occasion.toLowerCase()] || structures['casual'];
  }
 
  private async findOutfitCenterpiece(
    user: UserDocument,
    options: any,
  ): Promise<ProductDocument | null> {
    // Find a suitable centerpiece based on occasion and user preferences
    const occasionCriteria = this.getOccasionCriteria(options.occasion || 'casual');
    
    const centerpiece = await this.productModel.findOne({
      isActive: true,
      'category.main': { $in: occasionCriteria.centerpieces || ['dresses', 'tops'] },
      ...(options.budget && {
        'variants.price.current': {
          $gte: options.budget.min * 0.3, // Centerpiece can be 30-50% of budget
          $lte: options.budget.max * 0.5,
        },
      }),
    });
 
    return centerpiece;
  }
 
  private async findOutfitPiece(
    baseProduct: ProductDocument,
    existingPieces: OutfitProduct[],
    role: string,
    user: UserDocument,
    options: any,
  ): Promise<OutfitProduct | null> {
    // Find a piece that complements the existing outfit
    const query: any = {
      isActive: true,
      'category.main': role,
      _id: { $nin: existingPieces.map(p => p.productId) },
    };
 
    Iif (options.budget) {
      const usedBudget = 0; // Would calculate from existing pieces
      const remainingBudget = options.budget.max - usedBudget;
      query['variants.price.current'] = { $lte: remainingBudget };
    }
 
    const candidates = await this.productModel.find(query).limit(20);
    
    Iif (candidates.length === 0) return null;
 
    // Score each candidate
    const scoredCandidates = await Promise.all(
      candidates.map(async candidate => {
        const styleScore = await this.scoreStyleCompatibility(baseProduct, candidate);
        return {
          ...styleScore,
          role,
          outfitScore: styleScore.matchScore,
          styleScore: styleScore.matchScore,
        };
      })
    );
 
    // Return the best match
    const bestMatch = scoredCandidates
      .sort((a, b) => b.outfitScore - a.outfitScore)[0];
 
    return bestMatch || null;
  }
 
  private getOccasionCriteria(occasion: string): {
    categories: string[];
    centerpieces?: string[];
    styles: string[];
    formality: 'casual' | 'semi-formal' | 'formal';
  } {
    const criteria = {
      'casual': {
        categories: ['tops', 'bottoms', 'dresses', 'shoes', 'accessories'],
        centerpieces: ['tops', 'dresses'],
        styles: ['casual', 'relaxed', 'comfortable'],
        formality: 'casual' as const,
      },
      'formal': {
        categories: ['dresses', 'suits', 'shoes', 'accessories'],
        centerpieces: ['dresses', 'suits'],
        styles: ['formal', 'elegant', 'sophisticated'],
        formality: 'formal' as const,
      },
      'business': {
        categories: ['tops', 'bottoms', 'dresses', 'suits', 'shoes'],
        centerpieces: ['blazers', 'dresses'],
        styles: ['professional', 'business', 'polished'],
        formality: 'semi-formal' as const,
      },
      'party': {
        categories: ['dresses', 'tops', 'bottoms', 'shoes', 'accessories'],
        centerpieces: ['dresses', 'statement-tops'],
        styles: ['party', 'glamorous', 'trendy'],
        formality: 'semi-formal' as const,
      },
    };
 
    return criteria[occasion.toLowerCase()] || criteria['casual'];
  }
 
  private calculateOccasionScore(
    product: ProductDocument,
    occasion: string,
    user: UserDocument,
  ): { score: number; confidence: number; reasoning: string } {
    const criteria = this.getOccasionCriteria(occasion);
    let score = 0;
    const reasons: string[] = [];
 
    // Category appropriateness (40%)
    Iif (criteria.categories.includes(product.category.main.toLowerCase())) {
      score += 0.4;
      reasons.push('appropriate category');
    }
 
    // Style match (30%)
    const styleMatch = criteria.styles.some(style => 
      product.aiFeatures?.occasions?.some(po => po.toLowerCase().includes(style))
    );
    Iif (styleMatch) {
      score += 0.3;
      reasons.push('matching style');
    }
 
    // Price appropriateness for occasion (20%)
    const price = product.variants[0]?.price?.current || 0;
    const expectedPriceRange = this.getExpectedPriceRange(occasion, criteria.formality);
    Iif (price >= expectedPriceRange.min && price <= expectedPriceRange.max) {
      score += 0.2;
      reasons.push('appropriate price range');
    }
 
    // User preference alignment (10%)
    const userStyleMatch = user.preferences?.styles?.some(style => 
      criteria.styles.includes(style.toLowerCase())
    );
    Iif (userStyleMatch) {
      score += 0.1;
      reasons.push('matches your style');
    }
 
    const confidence = Math.min(0.9, score + (reasons.length * 0.05));
    const reasoning = reasons.length > 0 ? reasons.join(', ') : 'basic occasion match';
 
    return { score, confidence, reasoning };
  }
 
  private getExpectedPriceRange(occasion: string, formality: string): { min: number; max: number } {
    const ranges = {
      'casual': { min: 20, max: 200 },
      'semi-formal': { min: 50, max: 400 },
      'formal': { min: 100, max: 800 },
    };
 
    return ranges[formality] || ranges['casual'];
  }
}