1import { distinctiveTokens, normalizeName, uniqueSortedKey, uniqueTokens } from "./normalize.js";
2import { matchStatusFor, scoreNames } from "./score.js";
3import type { EntityType, EntityTypeFilter, ListId, MatchHit, SanctionRecord, ScreeningResult, UnavailableSource } from "./types.js";
4
5export interface NameIndex {
6 records: SanctionRecord[];
7 exact: Map<string, number[]>;
8 tokens: Map<string, Set<number>>;
9}
10
11export function matchesEntityFilter(type: EntityType, filter: EntityTypeFilter): boolean {
12 if (filter === "all") return true;
13 if (filter === "organization") return type === "organization";
14 return type === "individual";
15}
16
17export function buildNameIndex(records: SanctionRecord[], entityType: EntityTypeFilter): NameIndex {
18 const filtered = records.filter((record) => matchesEntityFilter(record.entityType, entityType));
19 const exact = new Map<string, number[]>();
20 const tokens = new Map<string, Set<number>>();
21
22 const addExact = (key: string, index: number) => {
23 if (!key) return;
24 const list = exact.get(key);
25 if (list) list.push(index);
26 else exact.set(key, [index]);
27 };
28
29 filtered.forEach((record, index) => {
30 const names = [record.primaryName, ...record.aliases];
31 for (const name of names) {
32 const normalized = normalizeName(name);
33 if (!normalized) continue;
34 addExact(normalized, index);
35 addExact(uniqueSortedKey(normalized), index);
36 for (const token of uniqueTokens(normalized)) {
37 if (token.length < 3) continue;
38 const bucket = tokens.get(token) ?? new Set<number>();
39 bucket.add(index);
40 tokens.set(token, bucket);
41 }
42 }
43 });
44
45 return { records: filtered, exact, tokens };
46}
47
48function candidateIndexes(index: NameIndex, queryNormalized: string): Set<number> {
49 const exactHits = index.exact.get(queryNormalized) ?? [];
50 const sortedHits = index.exact.get(uniqueSortedKey(queryNormalized)) ?? [];
51 const out = new Set<number>([...exactHits, ...sortedHits]);
52 const distinctive = distinctiveTokens(queryNormalized);
53 const queryTokens = distinctive.length ? distinctive : uniqueTokens(queryNormalized).filter((token) => token.length >= 4);
54 for (const token of queryTokens) {
55 const bucket = index.tokens.get(token);
56 if (bucket) for (const id of bucket) out.add(id);
57 }
58 return out;
59}
60
61function bestHitFor(query: string, record: SanctionRecord): { score: number; method: string; matchedName: string } {
62 let best = { score: 0, method: "none", matchedName: record.primaryName };
63 const names = [record.primaryName, ...record.aliases];
64 for (const name of names) {
65 const result = scoreNames(query, name);
66 if (result.score > best.score) best = { score: result.score, method: result.method, matchedName: name };
67 if (best.score === 100) break;
68 }
69 return best;
70}
71
72function attributionSummary(listsChecked: ListId[], records: SanctionRecord[]): string {
73 const lines = new Map<ListId, string>();
74 for (const record of records) {
75 if (listsChecked.includes(record.list) && !lines.has(record.list)) lines.set(record.list, record.sourceAttribution);
76 }
77 return [...lines.values()].join(" ");
78}
79
80export function screenName(
81 queryName: string,
82 index: NameIndex,
83 options: {
84 matchThreshold: number;
85 maxMatchesPerName: number;
86 listsChecked: ListId[];
87 listsUnavailable: ListId[];
88 checkedAt: string;
89 },
90): ScreeningResult {
91 const threshold = options.matchThreshold;
92 const potentialFloor = Math.max(50, threshold - 20);
93 const normalized = normalizeName(queryName);
94 const hits: MatchHit[] = [];
95
96 if (normalized) {
97 const candidates = candidateIndexes(index, normalized);
98 for (const id of candidates) {
99 const record = index.records[id];
100 const best = bestHitFor(queryName, record);
101 if (best.score < potentialFloor) continue;
102 hits.push({
103 list: record.list,
104 listDataset: record.listDataset,
105 referenceId: record.referenceId,
106 matchedName: best.matchedName,
107 primaryName: record.primaryName,
108 aliases: record.aliases,
109 entityType: record.entityType,
110 programs: record.programs,
111 countries: record.countries,
112 score: best.score,
113 matchMethod: best.method,
114 sourceUrl: record.sourceUrl,
115 listUpdatedAt: record.listUpdatedAt,
116 sourceAttribution: record.sourceAttribution,
117 });
118 }
119 }
120
121 hits.sort((a, b) => b.score - a.score || a.primaryName.localeCompare(b.primaryName) || a.list.localeCompare(b.list));
122 const unique: MatchHit[] = [];
123 const seen = new Set<string>();
124 for (const hit of hits) {
125 const key = `${hit.list}:${hit.referenceId}`;
126 if (seen.has(key)) continue;
127 seen.add(key);
128 unique.push(hit);
129 }
130 const top = unique.slice(0, Math.max(1, options.maxMatchesPerName));
131 const best = top[0];
132 const topScore = best?.score ?? 0;
133 const status = matchStatusFor(topScore, threshold);
134
135 return {
136 queryName,
137 matchStatus: status,
138 topMatchScore: topScore,
139 matchCount: unique.filter((hit) => hit.score >= threshold).length,
140 bestMatchName: status === "NO_MATCH" ? null : best?.primaryName ?? null,
141 bestMatchList: status === "NO_MATCH" ? null : best?.list ?? null,
142 bestMatchEntityType: status === "NO_MATCH" ? null : best?.entityType ?? null,
143 bestMatchPrograms: status === "NO_MATCH" ? [] : best?.programs ?? [],
144 bestMatchCountries: status === "NO_MATCH" ? [] : best?.countries ?? [],
145 bestMatchReferenceId: status === "NO_MATCH" ? null : best?.referenceId ?? null,
146 matches: status === "NO_MATCH" ? [] : top,
147 listsChecked: options.listsChecked,
148 listsUnavailable: options.listsUnavailable,
149 sourceAttribution: attributionSummary(options.listsChecked, index.records),
150 checkedAt: options.checkedAt,
151 };
152}
153
154export function filterExportRecords(
155 records: SanctionRecord[],
156 options: { entityType: EntityTypeFilter; programs?: string[]; countries?: string[]; searchText?: string },
157): SanctionRecord[] {
158 const programs = (options.programs ?? []).map((value) => value.trim().toLowerCase()).filter(Boolean);
159 const countries = (options.countries ?? []).map((value) => value.trim().toLowerCase()).filter(Boolean);
160 const search = (options.searchText ?? "").trim().toLowerCase();
161
162 return records.filter((record) => {
163 if (!matchesEntityFilter(record.entityType, options.entityType)) return false;
164 if (programs.length && !programs.some((program) => record.programs.some((value) => value.toLowerCase().includes(program)))) {
165 return false;
166 }
167 if (countries.length && !countries.some((country) => record.countries.some((value) => value.toLowerCase().includes(country)))) {
168 return false;
169 }
170 if (search) {
171 const haystack = [
172 record.primaryName,
173 ...record.aliases,
174 record.referenceId,
175 record.remarks ?? "",
176 ...record.programs,
177 ...record.countries,
178 ]
179 .join(" ")
180 .toLowerCase();
181 if (!haystack.includes(search)) return false;
182 }
183 return true;
184 });
185}
186
187export function unavailableLists(unavailable: UnavailableSource[]): ListId[] {
188 return [...new Set(unavailable.map((item) => item.list))];
189}