// Match one cart line to the same product seen on other stores. Scores are heuristic; only a // score at or above CONFIRM_SCORE, or an explicit user confirmation, lets a match affect a split. import type { CartLine, SeenPrice, Unit } from './model'; export const CONFIRM_SCORE = 0.9; const BRAND_WEIGHT = 0.4; interface Product { name: string; brand: string | null; sizeValue: number; sizeUnit: Unit } const tokens = (text: string) => new Set(text.toLowerCase().normalize('NFKD').replace(/[^a-z0-9 ]+/g, ' ').split(/\s+/).filter(Boolean)); function jaccard(a: Set, b: Set): number { const union = new Set([...a, ...b]).size; return union ? [...a].filter((t) => b.has(t)).length / union : 0; } export function matchScore(a: Product, b: Product): number { if (a.sizeUnit !== b.sizeUnit || a.sizeValue !== b.sizeValue) return 0; const brand = a.brand && b.brand ? (a.brand.trim().toLowerCase() === b.brand.trim().toLowerCase() ? 1 : 0) : 0.5; return BRAND_WEIGHT * brand + (1 - BRAND_WEIGHT) * jaccard(tokens(a.name), tokens(b.name)); } /** Stable identity of a (cart line, seen product) pair, for storing user confirmations. */ export const pairKey = (line: Product & { store: string }, seen: SeenPrice) => JSON.stringify([line.store, line.name, line.sizeValue, line.sizeUnit, seen.store, seen.name, seen.sizeValue, seen.sizeUnit]); export interface Match { seen: SeenPrice; score: number; confirmed: boolean } /** Best match per other store, highest score first. */ export function findMatches(line: CartLine, seen: SeenPrice[], confirmations: ReadonlySet = new Set()): Match[] { const best = new Map(); for (const s of seen) { if (s.store === line.store) continue; const score = matchScore(line, s); if (score === 0 || (best.get(s.store)?.score ?? -1) >= score) continue; best.set(s.store, { seen: s, score, confirmed: score >= CONFIRM_SCORE || confirmations.has(pairKey(line, s)) }); } return [...best.values()].sort((a, b) => b.score - a.score); }