patient-matching 0.2.0

Patient matching algorithms for healthcare information exchange
Documentation
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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
//! Patient matching engine: deterministic and probabilistic algorithms.
//!
//! This is the orchestration layer of the crate. It pulls together the data
//! types from [`crate::models`], the text transformations from
//! [`crate::normalizer`], and the similarity primitives from
//! [`crate::scorer`] to produce a single answer about whether two patient
//! records refer to the same individual.
//!
//! ## Two strategies, one engine
//!
//! - [`MatchingEngine::deterministic_match`] — fast, binary, defensible.
//!   Returns `true` iff either both NHS numbers parse to the same value or
//!   the normalised name + DOB + gender all match exactly.
//! - [`MatchingEngine::match_patients`] — weighted probabilistic scoring,
//!   returning a [`MatchResult`] with per-field [`MatchBreakdown`].
//!
//! ## Example
//!
//! ```
//! use patient_matching::{MatchingEngine, Patient};
//! use chrono::NaiveDate;
//!
//! let a = Patient::builder()
//!     .given_name("John")
//!     .family_name("Smith")
//!     .date_of_birth(NaiveDate::from_ymd_opt(1980, 5, 15).unwrap())
//!     .build();
//!
//! let b = Patient::builder()
//!     .given_name("Jon")          // typo
//!     .family_name("Smith")
//!     .date_of_birth(NaiveDate::from_ymd_opt(1980, 5, 15).unwrap())
//!     .build();
//!
//! let engine = MatchingEngine::default_config();
//! let result = engine.match_patients(&a, &b);
//! assert!(result.is_match);
//! ```

use crate::models::{Address, Patient};
use crate::normalizer::Normalizer;
use crate::scorer::{Scorer, SimilarityAlgorithm};
use nhs_number::NHSNumber;
use serde::{Deserialize, Serialize};
use std::str::FromStr;

/// Tunable configuration for the matching engine.
///
/// All weights are dimensionless and contribute to a renormalised weighted
/// sum — they do not need to add to `1.0`. The matching pipeline divides the
/// weighted sum by the sum of *participating* weights so that missing fields
/// neither contribute nor penalise. The score is then compared against
/// [`MatchConfig::match_threshold`] to produce the `is_match` boolean.
///
/// Two presets cover most needs:
///
/// - [`MatchConfig::strict`]  — `match_threshold = 0.95`, `strict_mode = true`.
/// - [`MatchConfig::lenient`] — `match_threshold = 0.75`, phonetic on.
///
/// # Example
///
/// ```
/// use patient_matching::{MatchConfig, SimilarityAlgorithm};
///
/// let custom = MatchConfig {
///     match_threshold: 0.80,
///     nhs_number_weight: 0.40,
///     given_name_weight: 0.15,
///     family_name_weight: 0.20,
///     date_of_birth_weight: 0.15,
///     gender_weight: 0.05,
///     address_weight: 0.025,
///     phone_weight: 0.025,
///     use_phonetic_matching: true,
///     name_algorithm: SimilarityAlgorithm::JaroWinkler,
///     strict_mode: false,
/// };
/// assert_eq!(custom.match_threshold, 0.80);
/// ```
#[derive(Debug, Clone)]
pub struct MatchConfig {
    /// Threshold score for considering two patients a match (`0.0..=1.0`).
    pub match_threshold: f64,

    /// Weight for NHS-number match (only contributes if both parse).
    pub nhs_number_weight: f64,

    /// Weight for given-name similarity.
    pub given_name_weight: f64,

    /// Weight for family-name similarity.
    pub family_name_weight: f64,

    /// Weight for date-of-birth exact match.
    pub date_of_birth_weight: f64,

    /// Weight for gender exact match.
    pub gender_weight: f64,

    /// Weight for address similarity.
    pub address_weight: f64,

    /// Weight for phone-number exact match (after normalisation).
    pub phone_weight: f64,

    /// Whether to add a phonetic-name bonus when both names sound alike.
    pub use_phonetic_matching: bool,

    /// Similarity algorithm to use when comparing given and family names.
    pub name_algorithm: SimilarityAlgorithm,

    /// Reserved flag for stricter deterministic enforcement. See spec OQ-5.
    pub strict_mode: bool,
}

impl Default for MatchConfig {
    /// Production-ready defaults tuned per spec §13.1.
    ///
    /// ```
    /// use patient_matching::{MatchConfig, SimilarityAlgorithm};
    /// let c = MatchConfig::default();
    /// assert!((c.match_threshold - 0.85).abs() < 1e-9);
    /// assert!(c.use_phonetic_matching);
    /// assert!(matches!(c.name_algorithm, SimilarityAlgorithm::Combined));
    /// ```
    fn default() -> Self {
        Self {
            match_threshold: 0.85,
            nhs_number_weight: 0.30,
            given_name_weight: 0.15,
            family_name_weight: 0.20,
            date_of_birth_weight: 0.20,
            gender_weight: 0.05,
            address_weight: 0.05,
            phone_weight: 0.05,
            use_phonetic_matching: true,
            name_algorithm: SimilarityAlgorithm::Combined,
            strict_mode: false,
        }
    }
}

impl MatchConfig {
    /// A stricter preset: `match_threshold = 0.95`, `strict_mode = true`.
    ///
    /// Use when a clinician must rely on the answer and false positives are
    /// more dangerous than false negatives.
    ///
    /// ```
    /// use patient_matching::MatchConfig;
    /// let c = MatchConfig::strict();
    /// assert!((c.match_threshold - 0.95).abs() < 1e-9);
    /// assert!(c.strict_mode);
    /// ```
    pub fn strict() -> Self {
        Self {
            match_threshold: 0.95,
            strict_mode: true,
            ..Default::default()
        }
    }

    /// A more forgiving preset: `match_threshold = 0.75`, phonetic matching on.
    ///
    /// Use when triaging large candidate sets where false negatives are
    /// worse than false positives.
    ///
    /// ```
    /// use patient_matching::MatchConfig;
    /// let c = MatchConfig::lenient();
    /// assert!((c.match_threshold - 0.75).abs() < 1e-9);
    /// assert!(c.use_phonetic_matching);
    /// ```
    pub fn lenient() -> Self {
        Self {
            match_threshold: 0.75,
            use_phonetic_matching: true,
            ..Default::default()
        }
    }
}

/// Outcome of a probabilistic patient match.
///
/// Contains the overall renormalised `score`, the threshold-derived
/// `is_match` boolean, and a per-field [`MatchBreakdown`] for audit.
///
/// `MatchResult` implements `Serialize + Deserialize` so it can be persisted
/// or returned over an API.
///
/// ```
/// use patient_matching::{MatchingEngine, Patient};
///
/// let p = Patient::builder().given_name("Ada").family_name("Lovelace").build();
/// let q = p.clone();
/// let result = MatchingEngine::default_config().match_patients(&p, &q);
///
/// // Round-trip through JSON.
/// let json = serde_json::to_string(&result).unwrap();
/// let back: patient_matching::MatchResult = serde_json::from_str(&json).unwrap();
/// assert!((result.score - back.score).abs() < 1e-12);
/// assert_eq!(result.is_match, back.is_match);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MatchResult {
    /// Overall match score in `[0.0, 1.0]`.
    pub score: f64,

    /// `true` if `score >= MatchConfig::match_threshold`.
    pub is_match: bool,

    /// Per-field score contributions for explainability.
    pub breakdown: MatchBreakdown,
}

/// Per-field score breakdown returned with every [`MatchResult`].
///
/// Each field is `Option<f64>`:
///
/// - `Some(score)` — the field was scored; the value is in `[0.0, 1.0]`.
/// - `None` — the field was missing on at least one side and so did not
///   participate in the weighted sum.
///
/// The breakdown exists so a clinician or auditor can see *why* a match was
/// flagged. Do not throw it away in downstream services.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MatchBreakdown {
    /// Score for NHS-number equality (`1.0` or `0.0`), or `None` if either side did not parse.
    pub nhs_number_score: Option<f64>,
    /// Score for given-name similarity using the configured algorithm.
    pub given_name_score: Option<f64>,
    /// Score for family-name similarity using the configured algorithm.
    pub family_name_score: Option<f64>,
    /// Score for date-of-birth equality (`1.0` or `0.0`).
    pub date_of_birth_score: Option<f64>,
    /// Score for gender equality (`1.0` or `0.0`).
    pub gender_score: Option<f64>,
    /// Score for address similarity (weighted blend of postcode, city, line 1).
    pub address_score: Option<f64>,
    /// Score for normalised phone-number equality (`1.0` or `0.0`).
    pub phone_score: Option<f64>,
    /// Mean Soundex match across given and family names (`0.0`, `0.5`, or `1.0`).
    pub phonetic_name_score: Option<f64>,
}

/// Patient matching engine.
///
/// The engine is **immutable after construction** and cheap to clone (it
/// owns only a [`MatchConfig`]). Construct one and call its methods from any
/// thread.
///
/// ```
/// use patient_matching::{MatchConfig, MatchingEngine};
///
/// let engine_a = MatchingEngine::default_config();
/// let engine_b = MatchingEngine::new(MatchConfig::strict());
/// # let _ = (engine_a, engine_b);
/// ```
pub struct MatchingEngine {
    config: MatchConfig,
}

impl MatchingEngine {
    /// Construct an engine with the given configuration.
    ///
    /// ```
    /// use patient_matching::{MatchConfig, MatchingEngine};
    /// let engine = MatchingEngine::new(MatchConfig::lenient());
    /// # let _ = engine;
    /// ```
    pub fn new(config: MatchConfig) -> Self {
        Self { config }
    }

    /// Construct an engine with [`MatchConfig::default`].
    ///
    /// ```
    /// use patient_matching::MatchingEngine;
    /// let engine = MatchingEngine::default_config();
    /// # let _ = engine;
    /// ```
    pub fn default_config() -> Self {
        Self::new(MatchConfig::default())
    }

    /// Compare two patients probabilistically and return a [`MatchResult`].
    ///
    /// The score is the weight-renormalised sum of every component that
    /// scored on both records. Missing fields are skipped, not penalised.
    ///
    /// ```
    /// use patient_matching::{MatchingEngine, Patient};
    /// use chrono::NaiveDate;
    ///
    /// let p = Patient::builder()
    ///     .given_name("Carys")
    ///     .family_name("Pritchard")
    ///     .date_of_birth(NaiveDate::from_ymd_opt(1985, 1, 1).unwrap())
    ///     .build();
    ///
    /// let result = MatchingEngine::default_config().match_patients(&p, &p);
    /// assert!(result.is_match);
    /// assert!(result.score > 0.99);
    /// ```
    pub fn match_patients(&self, patient1: &Patient, patient2: &Patient) -> MatchResult {
        let breakdown = self.calculate_breakdown(patient1, patient2);
        let score = self.calculate_weighted_score(&breakdown);
        let is_match = score >= self.config.match_threshold;

        MatchResult {
            score,
            is_match,
            breakdown,
        }
    }

    /// Compare two patients deterministically and return a single boolean.
    ///
    /// Returns `true` iff:
    ///
    /// - Both NHS numbers parse via `nhs-number` and are equal, **or**
    /// - Normalised given name matches, **and** normalised family name
    ///   matches, **and** date of birth matches, **and** gender matches (or
    ///   is missing on at least one side).
    ///
    /// ```
    /// use patient_matching::{MatchingEngine, Patient};
    ///
    /// // Same NHS number, different formatting → match.
    /// let a = Patient::builder().nhs_number("943 476 5919").build();
    /// let b = Patient::builder().nhs_number("9434765919").build();
    /// assert!(MatchingEngine::default_config().deterministic_match(&a, &b));
    /// ```
    pub fn deterministic_match(&self, patient1: &Patient, patient2: &Patient) -> bool {
        if let (Some(a), Some(b)) = (&patient1.nhs_number, &patient2.nhs_number)
            && let (Ok(a), Ok(b)) = (NHSNumber::from_str(a), NHSNumber::from_str(b))
            && a == b
        {
            return true;
        }

        let name_match = match (&patient1.given_name, &patient2.given_name) {
            (Some(f1), Some(f2)) => {
                Normalizer::normalize_name(f1) == Normalizer::normalize_name(f2)
            }
            _ => false,
        } && match (&patient1.family_name, &patient2.family_name) {
            (Some(l1), Some(l2)) => {
                Normalizer::normalize_name(l1) == Normalizer::normalize_name(l2)
            }
            _ => false,
        };

        let dob_match = match (patient1.date_of_birth, patient2.date_of_birth) {
            (Some(d1), Some(d2)) => d1 == d2,
            _ => false,
        };

        let gender_match = match (patient1.gender, patient2.gender) {
            (Some(g1), Some(g2)) => g1 == g2,
            _ => true,
        };

        name_match && dob_match && gender_match
    }

    fn calculate_breakdown(&self, patient1: &Patient, patient2: &Patient) -> MatchBreakdown {
        MatchBreakdown {
            nhs_number_score: self.score_nhs_number(patient1, patient2),
            given_name_score: self.score_given_name(patient1, patient2),
            family_name_score: self.score_family_name(patient1, patient2),
            date_of_birth_score: self.score_date_of_birth(patient1, patient2),
            gender_score: self.score_gender(patient1, patient2),
            address_score: self.score_address(patient1, patient2),
            phone_score: self.score_phone(patient1, patient2),
            phonetic_name_score: if self.config.use_phonetic_matching {
                self.score_phonetic_names(patient1, patient2)
            } else {
                None
            },
        }
    }

    fn calculate_weighted_score(&self, breakdown: &MatchBreakdown) -> f64 {
        let mut total_weight = 0.0;
        let mut weighted_sum = 0.0;

        if let Some(score) = breakdown.nhs_number_score {
            weighted_sum += score * self.config.nhs_number_weight;
            total_weight += self.config.nhs_number_weight;
        }
        if let Some(score) = breakdown.given_name_score {
            weighted_sum += score * self.config.given_name_weight;
            total_weight += self.config.given_name_weight;
        }
        if let Some(score) = breakdown.family_name_score {
            weighted_sum += score * self.config.family_name_weight;
            total_weight += self.config.family_name_weight;
        }
        if let Some(score) = breakdown.date_of_birth_score {
            weighted_sum += score * self.config.date_of_birth_weight;
            total_weight += self.config.date_of_birth_weight;
        }
        if let Some(score) = breakdown.gender_score {
            weighted_sum += score * self.config.gender_weight;
            total_weight += self.config.gender_weight;
        }
        if let Some(score) = breakdown.address_score {
            weighted_sum += score * self.config.address_weight;
            total_weight += self.config.address_weight;
        }
        if let Some(score) = breakdown.phone_score {
            weighted_sum += score * self.config.phone_weight;
            total_weight += self.config.phone_weight;
        }

        // Phonetic match is a bonus only — never lowers the score.
        if let Some(score) = breakdown.phonetic_name_score
            && score > 0.9
        {
            weighted_sum += score * 0.05;
            total_weight += 0.05;
        }

        if total_weight > 0.0 {
            weighted_sum / total_weight
        } else {
            0.0
        }
    }

    fn score_nhs_number(&self, patient1: &Patient, patient2: &Patient) -> Option<f64> {
        if let (Some(a), Some(b)) = (&patient1.nhs_number, &patient2.nhs_number)
            && let (Ok(a), Ok(b)) = (NHSNumber::from_str(a), NHSNumber::from_str(b))
        {
            return Some(f64::from(a == b));
        }
        None
    }

    fn score_given_name(&self, patient1: &Patient, patient2: &Patient) -> Option<f64> {
        match (&patient1.given_name, &patient2.given_name) {
            (Some(name1), Some(name2)) => Some(self.score_name(name1, name2)),
            _ => None,
        }
    }

    fn score_family_name(&self, patient1: &Patient, patient2: &Patient) -> Option<f64> {
        match (&patient1.family_name, &patient2.family_name) {
            (Some(name1), Some(name2)) => Some(self.score_name(name1, name2)),
            _ => None,
        }
    }

    fn score_name(&self, name1: &str, name2: &str) -> f64 {
        let norm1 = Normalizer::normalize_name(name1);
        let norm2 = Normalizer::normalize_name(name2);
        match self.config.name_algorithm {
            SimilarityAlgorithm::JaroWinkler => Scorer::jaro_winkler_similarity(&norm1, &norm2),
            SimilarityAlgorithm::Levenshtein => Scorer::levenshtein_similarity(&norm1, &norm2),
            SimilarityAlgorithm::Exact => Scorer::exact_match(&norm1, &norm2),
            SimilarityAlgorithm::Combined => Scorer::combined_similarity(&norm1, &norm2),
        }
    }

    fn score_date_of_birth(&self, patient1: &Patient, patient2: &Patient) -> Option<f64> {
        match (patient1.date_of_birth, patient2.date_of_birth) {
            (Some(dob1), Some(dob2)) => Some(f64::from(dob1 == dob2)),
            _ => None,
        }
    }

    fn score_gender(&self, patient1: &Patient, patient2: &Patient) -> Option<f64> {
        match (patient1.gender, patient2.gender) {
            (Some(g1), Some(g2)) => Some(if g1 == g2 { 1.0 } else { 0.0 }),
            _ => None,
        }
    }

    fn score_address(&self, patient1: &Patient, patient2: &Patient) -> Option<f64> {
        match (&patient1.address, &patient2.address) {
            (Some(addr1), Some(addr2)) => Some(self.compare_addresses(addr1, addr2)),
            _ => None,
        }
    }

    fn compare_addresses(&self, addr1: &Address, addr2: &Address) -> f64 {
        let mut scores = Vec::new();

        if let (Some(pc1), Some(pc2)) = (&addr1.postcode, &addr2.postcode) {
            let norm1 = Normalizer::normalize_postcode(pc1);
            let norm2 = Normalizer::normalize_postcode(pc2);
            scores.push(if norm1 == norm2 { 1.0 } else { 0.0 } * 0.5);
        }

        if let (Some(city1), Some(city2)) = (&addr1.city, &addr2.city) {
            let norm1 = Normalizer::normalize_name(city1);
            let norm2 = Normalizer::normalize_name(city2);
            scores.push(Scorer::jaro_winkler_similarity(&norm1, &norm2) * 0.3);
        }

        if let (Some(line1), Some(line2)) = (&addr1.line1, &addr2.line1) {
            let norm1 = Normalizer::normalize_name(line1);
            let norm2 = Normalizer::normalize_name(line2);
            scores.push(Scorer::jaro_winkler_similarity(&norm1, &norm2) * 0.2);
        }

        if scores.is_empty() {
            0.5
        } else {
            scores.iter().sum::<f64>() / scores.len() as f64
        }
    }

    fn score_phone(&self, patient1: &Patient, patient2: &Patient) -> Option<f64> {
        let phone1 = patient1
            .phone
            .as_ref()
            .or(patient1.mobile.as_ref())?
            .clone();
        let phone2 = patient2
            .phone
            .as_ref()
            .or(patient2.mobile.as_ref())?
            .clone();

        let norm1 = Normalizer::normalize_phone(&phone1);
        let norm2 = Normalizer::normalize_phone(&phone2);

        Some(f64::from(norm1 == norm2))
    }

    fn score_phonetic_names(&self, patient1: &Patient, patient2: &Patient) -> Option<f64> {
        let p1_given_name = patient1.given_name.as_ref()?;
        let p1_given_name_phonetic = Normalizer::phonetic_code(p1_given_name);
        let p1_family_name = patient1.family_name.as_ref()?;
        let p1_family_name_phonetic = Normalizer::phonetic_code(p1_family_name);

        let p2_given_name = patient2.given_name.as_ref()?;
        let p2_given_name_phonetic = Normalizer::phonetic_code(p2_given_name);
        let p2_family_name = patient2.family_name.as_ref()?;
        let p2_family_name_phonetic = Normalizer::phonetic_code(p2_family_name);

        let given_name_match = f64::from(p1_given_name_phonetic == p2_given_name_phonetic);
        let family_name_match = f64::from(p1_family_name_phonetic == p2_family_name_phonetic);
        Some((given_name_match + family_name_match) / 2.0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::Gender;
    use chrono::NaiveDate;

    fn dob(y: i32, m: u32, d: u32) -> NaiveDate {
        NaiveDate::from_ymd_opt(y, m, d).expect("valid date")
    }

    // ---------- MatchConfig presets ----------

    #[test]
    fn config_default_values() {
        let c = MatchConfig::default();
        assert!((c.match_threshold - 0.85).abs() < 1e-9);
        assert!((c.nhs_number_weight - 0.30).abs() < 1e-9);
        assert!(c.use_phonetic_matching);
        assert!(!c.strict_mode);
    }

    #[test]
    fn config_strict_raises_threshold_and_sets_flag() {
        let c = MatchConfig::strict();
        assert!((c.match_threshold - 0.95).abs() < 1e-9);
        assert!(c.strict_mode);
    }

    #[test]
    fn config_lenient_lowers_threshold() {
        let c = MatchConfig::lenient();
        assert!((c.match_threshold - 0.75).abs() < 1e-9);
        assert!(c.use_phonetic_matching);
    }

    // ---------- probabilistic match ----------

    #[test]
    fn exact_clone_is_a_match() {
        let p = Patient::builder()
            .given_name("John")
            .family_name("Smith")
            .date_of_birth(dob(1980, 5, 15))
            .gender(Gender::Male)
            .nhs_number("9434765919")
            .build();
        let result = MatchingEngine::default_config().match_patients(&p, &p.clone());
        assert!(result.is_match);
        assert!(result.score > 0.95);
    }

    #[test]
    fn fuzzy_given_name_still_matches() {
        let a = Patient::builder()
            .given_name("John")
            .family_name("Smith")
            .date_of_birth(dob(1980, 5, 15))
            .gender(Gender::Male)
            .build();
        let b = Patient::builder()
            .given_name("Jon")
            .family_name("Smith")
            .date_of_birth(dob(1980, 5, 15))
            .gender(Gender::Male)
            .build();
        let r = MatchingEngine::default_config().match_patients(&a, &b);
        assert!(r.is_match);
        assert!(r.score > 0.85);
    }

    #[test]
    fn completely_different_patients_do_not_match() {
        let a = Patient::builder()
            .given_name("John")
            .family_name("Smith")
            .date_of_birth(dob(1980, 5, 15))
            .gender(Gender::Male)
            .build();
        let b = Patient::builder()
            .given_name("Jane")
            .family_name("Doe")
            .date_of_birth(dob(1990, 3, 20))
            .gender(Gender::Female)
            .build();
        let r = MatchingEngine::default_config().match_patients(&a, &b);
        assert!(!r.is_match);
        assert!(r.score < 0.5);
    }

    #[test]
    fn no_overlapping_fields_returns_zero_score() {
        // Neither side has any scoreable field on both records.
        let a = Patient::builder().given_name("Solo").build();
        let b = Patient::builder().family_name("Only").build();
        let r = MatchingEngine::default_config().match_patients(&a, &b);
        assert_eq!(r.score, 0.0);
        assert!(!r.is_match);
    }

    #[test]
    fn unparseable_nhs_number_is_none_not_zero() {
        let a = Patient::builder()
            .nhs_number("not-a-number")
            .given_name("John")
            .family_name("Smith")
            .date_of_birth(dob(1980, 5, 15))
            .build();
        let b = Patient::builder()
            .nhs_number("also-not-a-number")
            .given_name("John")
            .family_name("Smith")
            .date_of_birth(dob(1980, 5, 15))
            .build();
        let r = MatchingEngine::default_config().match_patients(&a, &b);
        assert_eq!(
            r.breakdown.nhs_number_score, None,
            "unparseable NHS numbers should not produce a 0.0 penalty"
        );
        assert!(r.is_match, "should still match on demographics");
    }

    #[test]
    fn missing_field_yields_none_in_breakdown() {
        let a = Patient::builder().given_name("Ada").build();
        let b = Patient::builder()
            .given_name("Ada")
            .family_name("Lovelace")
            .build();
        let r = MatchingEngine::default_config().match_patients(&a, &b);
        assert!(r.breakdown.given_name_score.is_some());
        assert!(r.breakdown.family_name_score.is_none());
    }

    #[test]
    fn phonetic_match_is_a_bonus_not_a_penalty() {
        // Identical names should not be hurt when phonetic matching is on.
        let p = Patient::builder()
            .given_name("Stephen")
            .family_name("Jones")
            .build();
        let with_phon = MatchingEngine::new(MatchConfig {
            use_phonetic_matching: true,
            ..MatchConfig::default()
        })
        .match_patients(&p, &p.clone());
        let without_phon = MatchingEngine::new(MatchConfig {
            use_phonetic_matching: false,
            ..MatchConfig::default()
        })
        .match_patients(&p, &p.clone());
        assert!(with_phon.score >= without_phon.score);
    }

    #[test]
    fn phonetic_score_disabled_when_config_off() {
        let p = Patient::builder()
            .given_name("Steven")
            .family_name("Smith")
            .build();
        let q = Patient::builder()
            .given_name("Stephen")
            .family_name("Smyth")
            .build();
        let r = MatchingEngine::new(MatchConfig {
            use_phonetic_matching: false,
            ..MatchConfig::default()
        })
        .match_patients(&p, &q);
        assert_eq!(r.breakdown.phonetic_name_score, None);
    }

    #[test]
    fn address_with_no_subfields_is_neutral_half() {
        let a = Address::new();
        let b = Address::new();
        let engine = MatchingEngine::default_config();
        let score = engine.compare_addresses(&a, &b);
        assert!(
            (score - 0.5).abs() < 1e-9,
            "empty addresses must be neutral (0.5), got {score}"
        );
    }

    #[test]
    fn address_postcode_dominates() {
        let mut a = Address::new();
        a.postcode = Some("CF10 1AA".into());
        let mut b = Address::new();
        b.postcode = Some("CF10 1AA".into());
        let s = MatchingEngine::default_config().compare_addresses(&a, &b);
        assert!(s > 0.0);
    }

    // ---------- deterministic match ----------

    #[test]
    fn deterministic_nhs_match_overrides_demographics() {
        let a = Patient::builder()
            .nhs_number("943 476 5919")
            .given_name("Bob")
            .build();
        let b = Patient::builder()
            .nhs_number("9434765919")
            .given_name("Alice") // intentionally different
            .build();
        assert!(MatchingEngine::default_config().deterministic_match(&a, &b));
    }

    #[test]
    fn deterministic_demographics_match_when_all_align() {
        let p = Patient::builder()
            .given_name("John")
            .family_name("Smith")
            .date_of_birth(dob(1980, 5, 15))
            .gender(Gender::Male)
            .build();
        assert!(MatchingEngine::default_config().deterministic_match(&p, &p.clone()));
    }

    #[test]
    fn deterministic_demographics_tolerates_missing_gender() {
        let a = Patient::builder()
            .given_name("John")
            .family_name("Smith")
            .date_of_birth(dob(1980, 5, 15))
            .build();
        let b = Patient::builder()
            .given_name("John")
            .family_name("Smith")
            .date_of_birth(dob(1980, 5, 15))
            .gender(Gender::Male)
            .build();
        assert!(MatchingEngine::default_config().deterministic_match(&a, &b));
    }

    #[test]
    fn deterministic_rejects_when_dob_differs() {
        let a = Patient::builder()
            .given_name("John")
            .family_name("Smith")
            .date_of_birth(dob(1980, 5, 15))
            .gender(Gender::Male)
            .build();
        let b = Patient::builder()
            .given_name("John")
            .family_name("Smith")
            .date_of_birth(dob(1980, 5, 16)) // off by one day
            .gender(Gender::Male)
            .build();
        assert!(!MatchingEngine::default_config().deterministic_match(&a, &b));
    }

    #[test]
    fn deterministic_rejects_when_gender_differs() {
        let a = Patient::builder()
            .given_name("John")
            .family_name("Smith")
            .date_of_birth(dob(1980, 5, 15))
            .gender(Gender::Male)
            .build();
        let b = Patient::builder()
            .given_name("John")
            .family_name("Smith")
            .date_of_birth(dob(1980, 5, 15))
            .gender(Gender::Female)
            .build();
        assert!(!MatchingEngine::default_config().deterministic_match(&a, &b));
    }

    #[test]
    fn deterministic_rejects_when_names_missing() {
        let a = Patient::builder()
            .date_of_birth(dob(1980, 5, 15))
            .gender(Gender::Male)
            .build();
        let b = a.clone();
        assert!(!MatchingEngine::default_config().deterministic_match(&a, &b));
    }
}