pdf_oxide 0.3.33

The fastest Rust PDF library with text extraction: 0.8ms mean, 100% pass rate on 3,830 PDFs. 5× faster than pdf_extract, 17× faster than oxidize_pdf. Extract, create, and edit PDFs.
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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
//! ISO 32000-1:2008 Section 9.4.4 Word Boundary Detection
//!
//! This module implements specification-compliant word boundary detection for PDF text extraction.
//! Word boundaries are identified through multiple mechanisms defined in the PDF specification:
//!
//! 1. **TJ Array Offsets** (Section 9.4.4): Character-level spacing information from text positioning
//! 2. **Geometric Positioning** (Section 9.4): Layout-based word breaking through character positions
//! 3. **Space Characters** (Section 5.3.2): Explicit word separators (U+0020 and variants)
//! 4. **Font Metrics** (Section 9.3): Character width, font size, and scaling adjustments
//! 5. **Script-Aware Detection**: CJK text, custom encodings, and special characters
//!
//! # Specification References
//!
//! - ISO 32000-1:2008 Section 9.4: Text Objects
//! - ISO 32000-1:2008 Section 9.4.3: Text Positioning Operators
//! - ISO 32000-1:2008 Section 9.4.4: Text Objects and Word Spacing
//! - ISO 32000-1:2008 Section 9.3: Text State Parameters (Tc, Tw, Tz, TL)
//! - ISO 32000-1:2008 Section 9.6-9.8: Font Metrics

use crate::text::cjk_punctuation;
use crate::text::complex_script_detector::{
    detect_complex_script, handle_devanagari_boundary, handle_indic_boundary,
    handle_khmer_boundary, handle_thai_boundary, ComplexScript,
};
use crate::text::rtl_detector::should_split_at_rtl_boundary;
use crate::text::script_detector::{
    detect_cjk_script, handle_japanese_text, handle_korean_text, should_split_on_script_transition,
    DocumentLanguage,
};

/// Information about a character in the text stream for boundary detection.
///
/// This type captures all the information needed to determine word boundaries
/// per PDF specification Section 9.4.4.
#[derive(Clone, Debug)]
pub struct CharacterInfo {
    /// Unicode code point of the character
    pub code: u32,

    /// Glyph ID in the font (if available)
    pub glyph_id: Option<u16>,

    /// Character width in text space units (thousandths of em)
    pub width: f32,

    /// X position (horizontal) in text space
    pub x_position: f32,

    /// TJ array offset value (in thousandths of em) - negative = extra space
    /// Per spec: Negative values in TJ array increase spacing between characters
    pub tj_offset: Option<i32>,

    /// Current font size in points
    pub font_size: f32,

    /// Whether this character is a ligature (U+FB00-U+FB04)
    pub is_ligature: bool,

    /// Original ligature character if this was split from a ligature
    /// Used for debugging and tracking ligature expansion
    pub original_ligature: Option<char>,

    /// Whether this character is protected from word boundary splitting
    ///
    /// When true, word boundary detection will skip creating boundaries
    /// before or after this character. Used to preserve email addresses
    /// (`user@example.com`) and URLs (`http://example.com`) as single tokens.
    pub protected_from_split: bool,
}

/// Context information for word boundary detection.
///
/// Provides the font metrics and text state parameters that influence
/// how word boundaries are determined (per Section 9.3).
#[derive(Clone, Debug)]
pub struct BoundaryContext {
    /// Font size (Tf parameter in text state)
    pub font_size: f32,

    /// Horizontal scaling percentage (Tz parameter, default 100.0)
    pub horizontal_scaling: f32,

    /// Word spacing adjustment (Tw parameter, added after space character)
    pub word_spacing: f32,

    /// Character spacing adjustment (Tc parameter, added after every character)
    pub char_spacing: f32,
}

impl BoundaryContext {
    /// Create a new boundary context with default text state parameters.
    pub fn new(font_size: f32) -> Self {
        Self {
            font_size,
            horizontal_scaling: 100.0,
            word_spacing: 0.0,
            char_spacing: 0.0,
        }
    }

    /// Get the effective font size accounting for horizontal scaling
    fn effective_font_size(&self) -> f32 {
        self.font_size * (self.horizontal_scaling / 100.0)
    }
}

/// Document script profile for optimization.
///
/// OPTIMIZATION (Issue #1 fix): Detect document primary script once,
/// then skip unnecessary script detection functions for faster boundary detection.
///
/// When documents contain only Latin text, we skip RTL and CJK detection entirely.
/// When documents are CJK-dominant, we skip RTL detection.
/// This reduces function call overhead from millions per batch to thousands.
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DocumentScript {
    /// Latin-only document (ASCII + extended Latin)
    /// Fast path: only check space, TJ offset, geometric gap
    Latin,

    /// CJK-dominant document (Chinese, Japanese, Korean)
    /// Skip RTL detection, use optimized CJK path
    CJK,

    /// Right-to-left dominant (Arabic, Hebrew)
    /// Skip CJK detection, use optimized RTL path
    RTL,

    /// Complex scripts (Devanagari, Thai, Khmer, etc.)
    /// Use specialized complex script detection
    Complex,

    /// Mixed scripts or unknown
    /// Check all detection functions (slowest path)
    Mixed,
}

impl DocumentScript {
    /// Detect document script profile by sampling first 1000 characters.
    ///
    /// This optimization reduces boundary detection overhead by skipping
    /// unnecessary script detection for documents with known script profiles.
    ///
    /// PERFORMANCE: O(min(n, 1000)) sampling, executed once per extraction
    pub fn detect_from_characters(characters: &[CharacterInfo]) -> Self {
        if characters.is_empty() {
            return Self::Latin; // Default to Latin for empty documents
        }

        let mut has_rtl = false;
        let mut has_cjk = false;
        let mut has_complex = false;
        let sample_size = characters.len().min(1000);

        // Sample first 1000 characters to classify document
        for ch in &characters[..sample_size] {
            // Check for RTL (fast range check)
            if (0x0590..=0x08FF).contains(&ch.code) || (0xFB1D..=0xFDFF).contains(&ch.code) {
                has_rtl = true;
            }

            // Check for CJK (fast range checks - common ranges first)
            if (0x4E00..=0x9FFF).contains(&ch.code) // Han
                || (0x3040..=0x309F).contains(&ch.code) // Hiragana
                || (0x30A0..=0x30FF).contains(&ch.code) // Katakana
                || (0xAC00..=0xD7AF).contains(&ch.code)
            {
                // Hangul
                has_cjk = true;
            }

            // Check for complex scripts
            if (0x0900..=0x097F).contains(&ch.code) // Devanagari
                || (0x0E00..=0x0E7F).contains(&ch.code) // Thai
                || (0x1780..=0x17FF).contains(&ch.code)
            {
                // Khmer
                has_complex = true;
            }
        }

        // Decision tree: classify based on what we found
        #[allow(clippy::let_and_return)]
        let script = match (has_rtl, has_cjk, has_complex) {
            (false, false, false) => Self::Latin, // Pure Latin (fast path)
            (false, true, _) => Self::CJK,        // CJK-dominant (skip RTL)
            (true, false, _) => Self::RTL,        // RTL-dominant (skip CJK)
            (_, _, true) => Self::Complex,        // Complex scripts present
            _ => Self::Mixed,                     // Mixed scripts
        };

        // Log detected script at TRACE level for debugging
        crate::extract_log_trace!(
            "Detected document script: {:?} (sampled {} characters)",
            script,
            sample_size
        );

        script
    }
}

/// Main word boundary detection engine.
///
/// Implements the specification-compliant word boundary detection algorithm
/// that considers TJ offsets, geometric spacing, and font metrics.
#[derive(Debug)]
pub struct WordBoundaryDetector {
    /// Threshold for TJ offset values that indicate word boundaries
    /// Default: -100 (representing 0.1em in thousand-units of em)
    tj_offset_threshold: i32,

    /// Ratio of font size to use as geometric gap threshold
    /// Default: 0.3 (30% of font size indicates a word boundary)
    geometric_gap_ratio: f32,

    /// Enable CJK-aware boundary detection
    cjk_enabled: bool,

    /// Enable script-aware transition detection
    detect_script_transitions: bool,

    /// Document language context (if known)
    document_language: Option<DocumentLanguage>,

    /// Detected document script profile (Issue #1 optimization)
    /// Cached at detector creation to skip unnecessary detection functions
    primary_script: DocumentScript,

    /// Enable adaptive TJ threshold calculation based on font metrics
    /// When true, uses calculate_tj_threshold() instead of static tj_offset_threshold
    /// Default: true (adaptive mode enabled)
    use_adaptive_threshold: bool,
}

impl Default for WordBoundaryDetector {
    fn default() -> Self {
        Self::new()
    }
}

impl WordBoundaryDetector {
    /// Create a new word boundary detector with default settings.
    pub fn new() -> Self {
        Self {
            tj_offset_threshold: -100,
            // Geometric gap threshold: 80% of font size
            // This is conservative enough to avoid false positives from normal character spacing
            // but sensitive enough to detect actual word breaks
            geometric_gap_ratio: 0.8,
            cjk_enabled: true,
            detect_script_transitions: true,
            document_language: None,
            primary_script: DocumentScript::Mixed, // Default to Mixed, will be set by caller
            use_adaptive_threshold: true,          // Enable adaptive threshold by default
        }
    }

    /// Set the TJ offset threshold for boundary detection.
    ///
    /// Negative values in TJ arrays that are more negative than this threshold
    /// are considered word boundaries. Default: -100
    pub fn with_tj_threshold(mut self, threshold: i32) -> Self {
        self.tj_offset_threshold = threshold;
        self
    }

    /// Set the geometric gap ratio as a fraction of font size.
    ///
    /// Gaps between characters larger than (font_size * ratio) are considered
    /// word boundaries. Default: 0.3
    pub fn with_geometric_gap_ratio(mut self, ratio: f32) -> Self {
        self.geometric_gap_ratio = ratio;
        self
    }

    /// Enable or disable CJK-aware word boundary detection.
    pub fn with_cjk_enabled(mut self, enabled: bool) -> Self {
        self.cjk_enabled = enabled;
        self
    }

    /// Enable or disable script-aware transition detection.
    ///
    /// When enabled, the detector will analyze script transitions (e.g., Hiragana→Katakana)
    /// and apply language-specific rules for word boundaries.
    pub fn with_script_detection(mut self, enabled: bool) -> Self {
        self.detect_script_transitions = enabled;
        self
    }

    /// Set the document language context.
    ///
    /// This helps apply appropriate script transition rules:
    /// - Japanese: Allow Han↔Kana transitions
    /// - Korean: Allow Hangul↔Hanja transitions
    /// - Chinese: Use conservative Han character boundaries
    pub fn with_document_language(mut self, lang: DocumentLanguage) -> Self {
        self.document_language = Some(lang);
        self
    }

    /// Set the document script profile (Issue #1 optimization).
    ///
    /// When set, the detector will skip unnecessary script detection functions
    /// for documents with known script profiles, significantly improving performance.
    pub fn with_document_script(mut self, script: DocumentScript) -> Self {
        self.primary_script = script;
        self
    }

    /// Enable or disable adaptive TJ threshold calculation.
    ///
    /// When enabled (default), TJ offset thresholds are calculated dynamically
    /// based on font metrics (size, scaling, spacing). When disabled, uses the
    /// static threshold set via `with_tj_threshold()`.
    ///
    /// Adaptive mode provides better accuracy across documents with varying
    /// font sizes and text state parameters.
    pub fn with_adaptive_threshold(mut self, enabled: bool) -> Self {
        self.use_adaptive_threshold = enabled;
        self
    }

    /// Calculate adaptive TJ threshold based on font metrics and text state.
    ///
    /// Per PDF Spec Section 9.3, TJ array offsets depend on:
    /// - Font size (Tf): Larger fonts need larger thresholds
    /// - Character spacing (Tc): Manual spacing offsets base threshold
    /// - Word spacing (Tw): Applied after space characters
    /// - Horizontal scaling (Tz): Affects text width calculations
    ///
    /// Formula: base_threshold = -font_size * (h_scale / 100.0) * 0.025
    /// Then adjust by: -(char_spacing.abs() + word_spacing.abs()) * 0.5
    fn calculate_tj_threshold(&self, context: &BoundaryContext) -> f32 {
        let font_size = context.font_size.max(1.0);
        let h_scale = (context.horizontal_scaling / 100.0).max(0.01);

        // Base threshold as percentage of font size (2.5%)
        // 12pt font → -0.3, 24pt font → -0.6
        let base_threshold = -font_size * h_scale * 0.025;

        // Adjust for explicit spacing parameters
        let spacing_adjustment = (context.char_spacing.abs() + context.word_spacing.abs()) * 0.5;

        base_threshold - spacing_adjustment
    }

    /// Detect word boundaries in a character stream.
    ///
    /// Returns a vector of indices where word boundaries occur.
    /// A boundary at index `i` means there is a word break between
    /// characters at indices `i-1` and `i`.
    ///
    /// Per ISO 32000-1:2008 Section 9.4.4, word boundaries are determined by:
    /// 1. Space characters (U+0020, U+200B)
    /// 2. TJ array offset signals (negative values below threshold)
    /// 3. Geometric gaps exceeding font-size relative threshold
    /// 4. CJK character transitions
    ///
    /// # Arguments
    ///
    /// * `characters` - Sequence of characters with positioning information
    /// * `context` - Font metrics and text state parameters
    ///
    /// # Returns
    ///
    /// Vector of indices where word boundaries occur (between characters)
    pub fn detect_word_boundaries(
        &self,
        characters: &[CharacterInfo],
        context: &BoundaryContext,
    ) -> Vec<usize> {
        if characters.is_empty() {
            return Vec::new();
        }

        let mut boundaries = Vec::new();

        for i in 1..characters.len() {
            let prev_char = &characters[i - 1];
            let curr_char = &characters[i];

            if self.is_word_boundary(prev_char, curr_char, context) {
                boundaries.push(i);
            }
        }

        // Log boundary count at TRACE level for debugging word boundary detection
        crate::extract_log_trace!(
            "Word boundary detection: {} boundaries in {} characters",
            boundaries.len(),
            characters.len()
        );

        boundaries
    }

    /// Determine if a word boundary exists between two consecutive characters.
    ///
    /// Implements the specification rules per ISO 32000-1:2008 Section 9.4.4:
    ///
    /// 1. **Space characters** (U+0020, U+200B): Always create boundaries
    /// 2. **TJ array offsets**: Negative values below threshold indicate spacing
    /// 3. **Geometric gaps**: Gaps larger than font-size-relative threshold
    /// 4. **CJK script transitions**: Script-aware word boundaries
    /// 5. **CJK characters**: Each non-punctuation CJK character creates boundary (legacy)
    ///
    /// # Arguments
    ///
    /// * `prev_char` - Previous character in the stream
    /// * `curr_char` - Current character
    /// * `context` - Font metrics and text state
    ///
    /// # Returns
    ///
    /// `true` if a word boundary should be placed between these characters
    fn is_word_boundary(
        &self,
        prev_char: &CharacterInfo,
        curr_char: &CharacterInfo,
        context: &BoundaryContext,
    ) -> bool {
        // Skip boundaries in protected contexts (emails, URLs)
        if prev_char.protected_from_split || curr_char.protected_from_split {
            return false;
        }

        // Rule 1: ASCII space (U+0020) or zero-width space (U+200B)
        if prev_char.code == 0x20 || prev_char.code == 0x200B {
            return true;
        }

        // OPTIMIZATION (Issue #1): Use script-aware dispatch to avoid unnecessary function calls
        // This reduces millions of function calls per batch by skipping detection for known script types
        match self.primary_script {
            // Fast path: Latin-only documents - skip RTL and CJK detection entirely
            DocumentScript::Latin => self.is_word_boundary_basic(prev_char, curr_char, context),

            // CJK path: Skip RTL detection, use only CJK detection
            DocumentScript::CJK => {
                if self.detect_script_transitions {
                    if let Some(decision) = self.should_split_at_cjk_boundary(prev_char, curr_char)
                    {
                        return decision;
                    }
                }
                self.is_word_boundary_basic(prev_char, curr_char, context)
            },

            // RTL path: Skip CJK detection, use only RTL detection
            DocumentScript::RTL => {
                if let Some(decision) =
                    should_split_at_rtl_boundary(prev_char, curr_char, Some(context))
                {
                    return decision;
                }
                self.is_word_boundary_basic(prev_char, curr_char, context)
            },

            // Complex script path: Use complex script detection, skip RTL/CJK
            DocumentScript::Complex => {
                if let Some(decision) =
                    self.should_split_at_complex_script_boundary(prev_char, curr_char)
                {
                    return decision;
                }
                self.is_word_boundary_basic(prev_char, curr_char, context)
            },

            // Mixed path: Check all detection functions (original behavior)
            DocumentScript::Mixed => {
                // RTL (Arabic/Hebrew) boundary detection
                if let Some(decision) =
                    should_split_at_rtl_boundary(prev_char, curr_char, Some(context))
                {
                    return decision;
                }

                // CJK script-aware boundaries
                if self.detect_script_transitions {
                    if let Some(decision) = self.should_split_at_cjk_boundary(prev_char, curr_char)
                    {
                        return decision;
                    }
                }

                // Complex script boundary detection
                if let Some(decision) =
                    self.should_split_at_complex_script_boundary(prev_char, curr_char)
                {
                    return decision;
                }

                self.is_word_boundary_basic(prev_char, curr_char, context)
            },
        }
    }

    /// Basic boundary detection used by all script paths.
    ///
    /// This contains the core TJ offset and geometric gap checks
    /// that apply to all scripts.
    fn is_word_boundary_basic(
        &self,
        prev_char: &CharacterInfo,
        curr_char: &CharacterInfo,
        context: &BoundaryContext,
    ) -> bool {
        // Rule 2: TJ array offset signals explicit spacing (adaptive threshold)
        if let Some(tj_offset) = prev_char.tj_offset {
            let threshold = if self.use_adaptive_threshold {
                self.calculate_tj_threshold(context)
            } else {
                self.tj_offset_threshold as f32
            };
            if (tj_offset as f32) < threshold {
                return true;
            }
        }

        // Rule 3: Geometric spacing detection
        if self.has_significant_geometric_gap(prev_char, curr_char, context) {
            return true;
        }

        // Rule 4: CJK character boundaries (legacy, if enabled but script detection disabled)
        if self.cjk_enabled
            && !self.detect_script_transitions
            && self.is_cjk_character(prev_char.code)
            && !self.is_cjk_punctuation(prev_char.code)
        {
            return true;
        }

        false
    }

    /// Determine if a complex script boundary should be created.
    ///
    /// This implements Complex Script support:
    /// - Devanagari virama and matras
    /// - Thai tone marks and vowel modifiers
    /// - Khmer COENG and vowels
    /// - Indic scripts (Tamil, Telugu, Kannada, Malayalam) diacritics
    ///
    /// # Arguments
    ///
    /// * `prev_char` - Previous character information
    /// * `curr_char` - Current character information
    ///
    /// # Returns
    ///
    /// - `Some(true)` - Must create boundary
    /// - `Some(false)` - Must not create boundary
    /// - `None` - Use other signals (TJ offset, geometry)
    fn should_split_at_complex_script_boundary(
        &self,
        prev_char: &CharacterInfo,
        curr_char: &CharacterInfo,
    ) -> Option<bool> {
        let prev_script = detect_complex_script(prev_char.code);
        let curr_script = detect_complex_script(curr_char.code);

        // If neither is complex script, not our concern
        if prev_script.is_none() && curr_script.is_none() {
            return None;
        }

        // Apply script-specific rules based on which scripts are involved
        match (prev_script, curr_script) {
            // Devanagari boundaries
            (Some(ComplexScript::Devanagari), _) | (_, Some(ComplexScript::Devanagari)) => {
                handle_devanagari_boundary(prev_char, curr_char)
            },
            // Thai boundaries
            (Some(ComplexScript::Thai), _) | (_, Some(ComplexScript::Thai)) => {
                handle_thai_boundary(prev_char, curr_char)
            },
            // Khmer boundaries
            (Some(ComplexScript::Khmer), _) | (_, Some(ComplexScript::Khmer)) => {
                handle_khmer_boundary(prev_char, curr_char)
            },
            // South Asian Indic scripts (Tamil, Telugu, Kannada, Malayalam)
            (Some(ComplexScript::Tamil), _)
            | (_, Some(ComplexScript::Tamil))
            | (Some(ComplexScript::Telugu), _)
            | (_, Some(ComplexScript::Telugu))
            | (Some(ComplexScript::Kannada), _)
            | (_, Some(ComplexScript::Kannada))
            | (Some(ComplexScript::Malayalam), _)
            | (_, Some(ComplexScript::Malayalam))
            | (Some(ComplexScript::Bengali), _)
            | (_, Some(ComplexScript::Bengali)) => handle_indic_boundary(prev_char, curr_char),
            // Other complex scripts - use conservative default (let other signals decide)
            _ => None,
        }
    }

    /// Determine if a CJK boundary should be created based on script analysis.
    ///
    /// This implements CJK script support:
    /// - CJK punctuation detection
    /// - Script type detection
    /// - Language-specific transition rules
    /// - Japanese modifier handling
    ///
    /// # Arguments
    ///
    /// * `prev_char` - Previous character information
    /// * `curr_char` - Current character information
    ///
    /// # Returns
    ///
    /// - `Some(true)` - Must create boundary
    /// - `Some(false)` - Must not create boundary
    /// - `None` - Use other signals (TJ offset, geometry)
    fn should_split_at_cjk_boundary(
        &self,
        prev_char: &CharacterInfo,
        curr_char: &CharacterInfo,
    ) -> Option<bool> {
        // Check CJK punctuation (always creates boundary with high confidence)
        // Note: Using None for density to maintain current behavior
        // Future: Could integrate document-wide density measurement here
        let prev_punctuation_score =
            cjk_punctuation::get_cjk_punctuation_boundary_score(prev_char.code, None);
        if prev_punctuation_score >= 0.9 {
            // Sentence-ending and enumeration punctuation create boundaries
            return Some(true);
        }

        // Detect scripts for both characters
        let prev_script = detect_cjk_script(prev_char.code);
        let curr_script = detect_cjk_script(curr_char.code);

        // If neither character is CJK, not our concern
        if prev_script.is_none() && curr_script.is_none() {
            return None;
        }

        // Apply language-specific rules
        match self.document_language {
            Some(DocumentLanguage::Japanese) => {
                handle_japanese_text(prev_char, curr_char, prev_script, curr_script)
            },
            Some(DocumentLanguage::Korean) => {
                handle_korean_text(prev_char, curr_char, prev_script, curr_script)
            },
            Some(DocumentLanguage::Chinese) | None => {
                // Chinese or unknown: use script transition analysis
                should_split_on_script_transition(prev_script, curr_script, self.document_language)
            },
        }
    }

    /// Check if a gap is internal to a ligature expansion.
    ///
    /// When a ligature like 'fi' (U+FB01) is expanded into 'f' + 'i',
    /// the geometric gap between expanded components should not create a word boundary.
    fn is_ligature_internal_gap(
        &self,
        prev_char: &CharacterInfo,
        curr_char: &CharacterInfo,
    ) -> bool {
        // Ligature Unicode range: U+FB00-U+FB06
        const LIGATURES: [u32; 7] = [0xFB00, 0xFB01, 0xFB02, 0xFB03, 0xFB04, 0xFB05, 0xFB06];

        // Check if either character is a ligature or was expanded from one
        LIGATURES.contains(&prev_char.code)
            || prev_char.is_ligature
            || LIGATURES.contains(&curr_char.code)
            || curr_char.is_ligature
    }

    /// Check if a character code represents punctuation that attaches to words.
    ///
    /// Punctuation like periods, commas, colons should use reduced threshold
    /// to avoid creating unwanted boundaries when appearing after words.
    pub fn is_punctuation(code: u32) -> bool {
        matches!(
            code,
            // ASCII punctuation
            0x21     // ! EXCLAMATION MARK
            | 0x22   // " QUOTATION MARK
            | 0x27   // ' APOSTROPHE
            | 0x2C   // , COMMA
            | 0x2E   // . FULL STOP
            | 0x3A   // : COLON
            | 0x3B   // ; SEMICOLON
            | 0x3F   // ? QUESTION MARK
            // Unicode quotation marks
            | 0x2018..=0x201F  // General Punctuation: quotes, dashes, etc.
            // Unicode dashes and hyphens
            | 0x2010..=0x2015  // Hyphen, dash variants
        )
    }

    /// Check if there is a significant geometric gap between two characters.
    ///
    /// Per Section 9.4, character positions and widths determine visual spacing.
    /// A gap larger than the threshold (font_size * ratio) indicates a word boundary.
    ///
    /// Special cases:
    /// 1. **Ligature internal gaps**: Gaps inside expanded ligatures never create boundaries
    /// 2. **Punctuation attachment**: Punctuation uses 50% threshold to attach to preceding words
    /// 3. **Character spacing**: Tc parameter adjusts baseline gap calculation
    fn has_significant_geometric_gap(
        &self,
        prev_char: &CharacterInfo,
        curr_char: &CharacterInfo,
        context: &BoundaryContext,
    ) -> bool {
        // Special case 1: Ligatures - gaps inside ligature expansions are NOT boundaries
        if self.is_ligature_internal_gap(prev_char, curr_char) {
            return false;
        }

        // Calculate the expected end position of previous character
        let prev_end_x = prev_char.x_position + prev_char.width;

        // Calculate raw gap between characters
        let raw_gap = curr_char.x_position - prev_end_x;

        // Adjust for character spacing (Tc parameter)
        // Tc is added after every character, so subtract it from the gap
        let adjusted_gap = raw_gap - context.char_spacing;

        // Base threshold is relative to font size (accounting for horizontal scaling)
        let base_threshold = context.effective_font_size() * self.geometric_gap_ratio;

        // Special case 2: Punctuation - use reduced threshold (50% of normal)
        // This keeps punctuation attached to the preceding word
        if Self::is_punctuation(curr_char.code) {
            return adjusted_gap > (base_threshold * 0.5);
        }

        // Normal case: full threshold
        adjusted_gap > base_threshold
    }

    /// Check if a character code represents a CJK (Chinese/Japanese/Korean) character.
    ///
    /// CJK Unicode ranges per Unicode Standard:
    /// - CJK Unified Ideographs: U+4E00-U+9FFF
    /// - CJK Unified Ideographs Extension A: U+3400-U+4DBF
    /// - CJK Unified Ideographs Extension B and beyond: higher ranges
    /// - Hiragana: U+3040-U+309F
    /// - Katakana: U+30A0-U+30FF
    fn is_cjk_character(&self, code: u32) -> bool {
        matches!(
            code,
            0x3040..=0x309F   // Hiragana
            | 0x30A0..=0x30FF // Katakana
            | 0x3400..=0x4DBF // CJK Unified Ideographs Extension A
            | 0x4E00..=0x9FFF // CJK Unified Ideographs
            | 0x20000..=0x2A6DF // CJK Unified Ideographs Extension B
            | 0x2A700..=0x2B73F // CJK Unified Ideographs Extension C
            | 0x2B740..=0x2B81F // CJK Unified Ideographs Extension D
            | 0x2B820..=0x2CEAF // CJK Unified Ideographs Extension E
            | 0x2CEB0..=0x2EBEF // CJK Unified Ideographs Extension F
        )
    }

    /// Check if a character is CJK punctuation that attaches to words.
    ///
    /// CJK punctuation like ideographic commas and periods attach to the preceding
    /// word and should not create boundaries.
    fn is_cjk_punctuation(&self, code: u32) -> bool {
        matches!(
            code,
            0x3001 // IDEOGRAPHIC COMMA
            | 0x3002 // IDEOGRAPHIC FULL STOP
            | 0x3008 // LEFT ANGLE BRACKET
            | 0x3009 // RIGHT ANGLE BRACKET
            | 0x300A // LEFT DOUBLE ANGLE BRACKET
            | 0x300B // RIGHT DOUBLE ANGLE BRACKET
            | 0x300C // LEFT CORNER BRACKET
            | 0x300D // RIGHT CORNER BRACKET
            | 0x300E // LEFT WHITE CORNER BRACKET
            | 0x300F // RIGHT WHITE CORNER BRACKET
            | 0x3010 // LEFT BLACK LENTICULAR BRACKET
            | 0x3011 // RIGHT BLACK LENTICULAR BRACKET
            | 0x3014 // LEFT TORTOISE SHELL BRACKET
            | 0x3015 // RIGHT TORTOISE SHELL BRACKET
        )
    }
}

/// Detect word boundaries in a character stream.
///
/// This is a convenience function that creates a detector with default settings
/// and performs boundary detection in one call.
///
/// # Arguments
///
/// * `characters` - Sequence of characters with positioning information
/// * `context` - Font metrics and text state parameters
///
/// # Returns
///
/// Vector of indices where word boundaries occur
pub fn detect_word_boundaries(
    characters: &[CharacterInfo],
    context: &BoundaryContext,
) -> Vec<usize> {
    let detector = WordBoundaryDetector::new();
    detector.detect_word_boundaries(characters, context)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_ascii_space_detection() {
        let characters = vec![
            CharacterInfo {
                code: 0x48,
                glyph_id: Some(1),
                width: 0.5,
                x_position: 0.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'H'
            CharacterInfo {
                code: 0x65,
                glyph_id: Some(2),
                width: 0.4,
                x_position: 6.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'e'
            CharacterInfo {
                code: 0x20,
                glyph_id: Some(5),
                width: 0.25,
                x_position: 10.8,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // SPACE
            CharacterInfo {
                code: 0x57,
                glyph_id: Some(6),
                width: 0.7,
                x_position: 16.2,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'W'
        ];

        let context = BoundaryContext::new(12.0);
        let boundaries = WordBoundaryDetector::new().detect_word_boundaries(&characters, &context);

        // Space character at index 2 creates boundary at index 3
        assert!(boundaries.contains(&3));
    }

    #[test]
    fn test_tj_offset_threshold() {
        let characters = vec![
            CharacterInfo {
                code: 0x54,
                glyph_id: Some(1),
                width: 0.5,
                x_position: 0.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'T'
            CharacterInfo {
                code: 0x2D,
                glyph_id: Some(5),
                width: 0.25,
                x_position: 6.0,
                tj_offset: Some(-200),
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // '-' with large negative offset
            CharacterInfo {
                code: 0x6F,
                glyph_id: Some(6),
                width: 0.4,
                x_position: 18.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'o'
        ];

        let context = BoundaryContext::new(12.0);
        let boundaries = WordBoundaryDetector::new().detect_word_boundaries(&characters, &context);

        // TJ offset at index 1 creates boundary at index 2
        assert!(boundaries.contains(&2));
    }

    #[test]
    fn test_geometric_gap_detection() {
        let characters = vec![
            CharacterInfo {
                code: 0x54,
                glyph_id: Some(1),
                width: 0.5,
                x_position: 0.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'T'
            CharacterInfo {
                code: 0x65,
                glyph_id: Some(2),
                width: 0.4,
                x_position: 6.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'e'
            CharacterInfo {
                code: 0x78,
                glyph_id: Some(3),
                width: 0.4,
                x_position: 10.8,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'x'
            CharacterInfo {
                code: 0x74,
                glyph_id: Some(4),
                width: 0.3,
                x_position: 15.6,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 't'
            // Gap of ~11.1 units (much larger than threshold ~3.6)
            CharacterInfo {
                code: 0x42,
                glyph_id: Some(5),
                width: 0.5,
                x_position: 27.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'B'
        ];

        let context = BoundaryContext::new(12.0);
        let boundaries = WordBoundaryDetector::new().detect_word_boundaries(&characters, &context);

        // Gap between 't' (ends at 15.9) and 'B' (at 27.0) is 11.1 units > threshold (3.6)
        // This creates a boundary at index 4 (the 'B' character)
        assert!(boundaries.contains(&4), "Expected boundary at index 4, got: {:?}", boundaries);
    }

    #[test]
    fn test_cjk_character_boundaries() {
        let characters = vec![
            CharacterInfo {
                code: 0x4E2D,
                glyph_id: Some(1),
                width: 1.0,
                x_position: 0.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // CJK UNIFIED IDEOGRAPH
            CharacterInfo {
                code: 0x6587,
                glyph_id: Some(2),
                width: 1.0,
                x_position: 12.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // CJK UNIFIED IDEOGRAPH
            CharacterInfo {
                code: 0x5B57,
                glyph_id: Some(3),
                width: 1.0,
                x_position: 24.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // CJK UNIFIED IDEOGRAPH
        ];

        let context = BoundaryContext::new(12.0);
        let boundaries = WordBoundaryDetector::new().detect_word_boundaries(&characters, &context);

        // Each CJK character creates a boundary after it
        // Character 0 -> boundary at 1, Character 1 -> boundary at 2
        assert!(boundaries.contains(&1), "Expected boundary at index 1");
        assert!(boundaries.contains(&2), "Expected boundary at index 2");
    }

    #[test]
    fn test_zero_width_space() {
        let characters = vec![
            CharacterInfo {
                code: 0x6E,
                glyph_id: Some(1),
                width: 0.4,
                x_position: 0.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'n'
            CharacterInfo {
                code: 0x200B,
                glyph_id: Some(2),
                width: 0.0,
                x_position: 4.8,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // ZERO WIDTH SPACE
            CharacterInfo {
                code: 0x72,
                glyph_id: Some(3),
                width: 0.3,
                x_position: 4.8,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'r'
        ];

        let context = BoundaryContext::new(12.0);
        let boundaries = WordBoundaryDetector::new().detect_word_boundaries(&characters, &context);

        // Zero-width space creates boundary
        assert!(boundaries.contains(&2));
    }

    #[test]
    fn test_horizontal_scaling_affects_gap_threshold() {
        // Create a gap that's on the threshold boundary
        // Gap = 7.5 units
        // At 100% scaling (font size 12): threshold = 12 * 0.8 = 9.6, gap < threshold = no boundary
        // At 75% scaling (font size 9): threshold = 9 * 0.8 = 7.2, gap > threshold = boundary!
        let characters = vec![
            CharacterInfo {
                code: 0x41,
                glyph_id: Some(1),
                width: 0.5,
                x_position: 0.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'A' ends at 0.5
            CharacterInfo {
                code: 0x42,
                glyph_id: Some(2),
                width: 0.5,
                x_position: 8.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'B' starts at 8.0
        ];

        // With 100% scaling, gap (7.5) doesn't exceed threshold (9.6)
        let mut context = BoundaryContext::new(12.0);
        context.horizontal_scaling = 100.0;
        let boundaries_normal =
            WordBoundaryDetector::new().detect_word_boundaries(&characters, &context);

        // With 75% scaling, gap (7.5) exceeds threshold (7.2)
        context.horizontal_scaling = 75.0;
        let boundaries_scaled =
            WordBoundaryDetector::new().detect_word_boundaries(&characters, &context);

        // Scaling affects the effective threshold, so results should differ
        // Normal: no boundary, Scaled: boundary at index 1
        assert!(boundaries_normal.is_empty(), "Should have no boundaries at 100% scaling");
        assert!(boundaries_scaled.contains(&1), "Should have boundary at 75% scaling");
    }

    #[test]
    fn test_detect_word_boundaries_ascii_space() {
        // Test that ASCII space creates word boundary
        let characters = vec![
            CharacterInfo {
                code: 0x48,
                glyph_id: Some(1),
                width: 0.5,
                x_position: 0.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'H'
            CharacterInfo {
                code: 0x65,
                glyph_id: Some(2),
                width: 0.4,
                x_position: 6.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'e'
            CharacterInfo {
                code: 0x20,
                glyph_id: Some(5),
                width: 0.25,
                x_position: 10.8,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // SPACE
            CharacterInfo {
                code: 0x57,
                glyph_id: Some(6),
                width: 0.7,
                x_position: 16.2,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'W'
        ];

        let context = BoundaryContext::new(12.0);
        let boundaries = WordBoundaryDetector::new().detect_word_boundaries(&characters, &context);

        // Space character at index 2 creates boundary at index 3
        assert!(boundaries.contains(&3), "Should have boundary after space");
    }

    #[test]
    fn test_detect_word_boundaries_tj_offset() {
        // Test that large negative TJ offset creates boundary
        let characters = vec![
            CharacterInfo {
                code: 0x54,
                glyph_id: Some(1),
                width: 0.5,
                x_position: 0.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'T'
            CharacterInfo {
                code: 0x2D,
                glyph_id: Some(5),
                width: 0.25,
                x_position: 6.0,
                tj_offset: Some(-200),
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // '-' with large negative offset
            CharacterInfo {
                code: 0x6F,
                glyph_id: Some(6),
                width: 0.4,
                x_position: 18.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // 'o'
        ];

        let context = BoundaryContext::new(12.0);
        let boundaries = WordBoundaryDetector::new().detect_word_boundaries(&characters, &context);

        // TJ offset at index 1 creates boundary at index 2
        assert!(boundaries.contains(&2), "Should have boundary after large TJ offset");
    }

    #[test]
    fn test_detect_word_boundaries_cjk() {
        // Test that CJK characters create boundaries
        let characters = vec![
            CharacterInfo {
                code: 0x4E2D,
                glyph_id: Some(1),
                width: 1.0,
                x_position: 0.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // CJK character
            CharacterInfo {
                code: 0x6587,
                glyph_id: Some(2),
                width: 1.0,
                x_position: 12.0,
                tj_offset: None,
                font_size: 12.0,
                is_ligature: false,
                original_ligature: None,
                protected_from_split: false,
            }, // CJK character
        ];

        let context = BoundaryContext::new(12.0);
        let boundaries = WordBoundaryDetector::new().detect_word_boundaries(&characters, &context);

        // Each CJK character should create a boundary
        assert!(boundaries.contains(&1), "Should have boundary after first CJK character");
    }

    #[test]
    fn test_calculate_tj_threshold_default_font() {
        let detector = WordBoundaryDetector::new();
        let context = BoundaryContext::new(12.0); // 12pt
        let threshold = detector.calculate_tj_threshold(&context);
        // Expected: -12.0 * 1.0 * 0.025 = -0.3
        assert!(
            (threshold - (-0.3)).abs() < 0.01,
            "12pt font should give -0.3, got {}",
            threshold
        );
    }

    #[test]
    fn test_calculate_tj_threshold_large_font() {
        let detector = WordBoundaryDetector::new();
        let context = BoundaryContext::new(24.0); // 24pt
        let threshold = detector.calculate_tj_threshold(&context);
        // Expected: -24.0 * 1.0 * 0.025 = -0.6
        assert!(
            (threshold - (-0.6)).abs() < 0.01,
            "24pt font should give -0.6, got {}",
            threshold
        );
    }

    #[test]
    fn test_calculate_tj_threshold_with_char_spacing() {
        let detector = WordBoundaryDetector::new();
        let mut context = BoundaryContext::new(12.0);
        context.char_spacing = 2.0;
        let threshold = detector.calculate_tj_threshold(&context);
        // Expected: -0.3 - (2.0 * 0.5) = -1.3
        assert!(
            (threshold - (-1.3)).abs() < 0.01,
            "With char_spacing=2.0, expected -1.3, got {}",
            threshold
        );
    }

    #[test]
    fn test_calculate_tj_threshold_with_word_spacing() {
        let detector = WordBoundaryDetector::new();
        let mut context = BoundaryContext::new(12.0);
        context.word_spacing = 3.0;
        let threshold = detector.calculate_tj_threshold(&context);
        // Expected: -0.3 - (3.0 * 0.5) = -1.8
        assert!(
            (threshold - (-1.8)).abs() < 0.01,
            "With word_spacing=3.0, expected -1.8, got {}",
            threshold
        );
    }

    #[test]
    fn test_calculate_tj_threshold_with_horizontal_scaling() {
        let detector = WordBoundaryDetector::new();
        let mut context = BoundaryContext::new(12.0);
        context.horizontal_scaling = 80.0; // 80%
        let threshold = detector.calculate_tj_threshold(&context);
        // Expected: -12.0 * 0.8 * 0.025 = -0.24
        assert!(
            (threshold - (-0.24)).abs() < 0.01,
            "With 80% scaling, expected -0.24, got {}",
            threshold
        );
    }

    #[test]
    fn test_adaptive_threshold_affects_boundary_detection() {
        let detector = WordBoundaryDetector::new().with_adaptive_threshold(true);
        let context = BoundaryContext::new(12.0);

        let prev = CharacterInfo {
            code: 't' as u32,
            glyph_id: None,
            width: 5.0,
            x_position: 100.0,
            tj_offset: Some(-200), // Significant negative offset
            font_size: 12.0,
            is_ligature: false,
            original_ligature: None,
            protected_from_split: false,
        };

        let curr = CharacterInfo {
            code: 'h' as u32,
            glyph_id: None,
            width: 5.0,
            x_position: 110.0,
            tj_offset: None,
            font_size: 12.0,
            is_ligature: false,
            original_ligature: None,
            protected_from_split: false,
        };

        let boundary = detector.is_word_boundary(&prev, &curr, &context);
        assert!(boundary, "TJ offset -200 should trigger boundary with 12pt font");
    }

    #[test]
    fn test_disable_adaptive_threshold_uses_static() {
        let detector = WordBoundaryDetector::new()
            .with_adaptive_threshold(false)
            .with_tj_threshold(-100);
        let context = BoundaryContext::new(12.0);

        let prev = CharacterInfo {
            code: 'a' as u32,
            glyph_id: None,
            width: 5.0,
            x_position: 100.0,
            tj_offset: Some(-50), // Below -100 threshold
            font_size: 12.0,
            is_ligature: false,
            original_ligature: None,
            protected_from_split: false,
        };

        let curr = CharacterInfo {
            code: 'b' as u32,
            glyph_id: None,
            width: 5.0,
            x_position: 110.0,
            tj_offset: None,
            font_size: 12.0,
            is_ligature: false,
            original_ligature: None,
            protected_from_split: false,
        };

        let boundary = detector.is_word_boundary(&prev, &curr, &context);
        assert!(!boundary, "TJ offset -50 should NOT trigger boundary when static -100 is used");
    }

    #[test]
    fn test_geometric_gap_basic() {
        let detector = WordBoundaryDetector::new();
        let context = BoundaryContext::new(12.0);

        let prev = CharacterInfo {
            code: 't' as u32,
            glyph_id: None,
            width: 5.0,
            x_position: 100.0,
            tj_offset: None,
            font_size: 12.0,
            is_ligature: false,
            original_ligature: None,
            protected_from_split: false,
        };

        // Large gap (10 units > 9.6 = 12*0.8 threshold)
        let curr = CharacterInfo {
            code: 'h' as u32,
            glyph_id: None,
            width: 5.0,
            x_position: 115.0, // 115 - 105 = 10 unit gap
            tj_offset: None,
            font_size: 12.0,
            is_ligature: false,
            original_ligature: None,
            protected_from_split: false,
        };

        assert!(
            detector.has_significant_geometric_gap(&prev, &curr, &context),
            "Gap of 10 units should exceed threshold of 9.6 (12pt * 0.8)"
        );
    }

    #[test]
    fn test_geometric_gap_with_char_spacing() {
        let detector = WordBoundaryDetector::new();
        let mut context = BoundaryContext::new(12.0);
        context.char_spacing = 2.0; // Tc = 2.0

        let prev = CharacterInfo {
            code: 'a' as u32,
            glyph_id: None,
            width: 5.0,
            x_position: 100.0,
            tj_offset: None,
            font_size: 12.0,
            is_ligature: false,
            original_ligature: None,
            protected_from_split: false,
        };

        // Raw gap = 10, but Tc = 2.0 reduces it to 8.0
        // 8.0 < 9.6 (threshold), so NO boundary
        let curr = CharacterInfo {
            code: 'b' as u32,
            glyph_id: None,
            width: 5.0,
            x_position: 115.0, // 115 - 105 = 10 unit gap
            tj_offset: None,
            font_size: 12.0,
            is_ligature: false,
            original_ligature: None,
            protected_from_split: false,
        };

        assert!(
            !detector.has_significant_geometric_gap(&prev, &curr, &context),
            "Gap of 10 - 2.0 (Tc) = 8.0 should NOT exceed threshold of 9.6"
        );
    }

    #[test]
    fn test_ligature_internal_gap_fi() {
        let detector = WordBoundaryDetector::new();
        let context = BoundaryContext::new(12.0);

        // 'f' component from expanded 'fi' ligature
        let prev = CharacterInfo {
            code: 'f' as u32,
            glyph_id: None,
            width: 5.0,
            x_position: 100.0,
            tj_offset: None,
            font_size: 12.0,
            is_ligature: true, // This is from ligature expansion
            original_ligature: Some(''),
            protected_from_split: false,
        };

        // Large gap but prev is from ligature
        let curr = CharacterInfo {
            code: 'i' as u32,
            glyph_id: None,
            width: 3.0,
            x_position: 120.0, // 120 - 105 = 15 unit gap (would normally be boundary)
            tj_offset: None,
            font_size: 12.0,
            is_ligature: true,
            original_ligature: Some(''),
            protected_from_split: false,
        };

        assert!(
            !detector.has_significant_geometric_gap(&prev, &curr, &context),
            "Ligature internal gap should NOT create boundary even with large gap"
        );
    }

    #[test]
    fn test_punctuation_reduced_threshold() {
        let detector = WordBoundaryDetector::new();
        let context = BoundaryContext::new(12.0);
        // Base threshold: 12.0 * 0.8 = 9.6
        // Punctuation threshold: 9.6 * 0.5 = 4.8

        let prev = CharacterInfo {
            code: 'd' as u32,
            glyph_id: None,
            width: 5.0,
            x_position: 100.0,
            tj_offset: None,
            font_size: 12.0,
            is_ligature: false,
            original_ligature: None,
            protected_from_split: false,
        };

        // Gap of 6.0 units
        // Normal threshold would be 9.6 (no boundary)
        // Punctuation threshold is 4.8 (YES boundary)
        let curr_period = CharacterInfo {
            code: '.' as u32, // Period is punctuation
            glyph_id: None,
            width: 2.0,
            x_position: 111.0, // 111 - 105 = 6 unit gap
            tj_offset: None,
            font_size: 12.0,
            is_ligature: false,
            original_ligature: None,
            protected_from_split: false,
        };

        assert!(
            detector.has_significant_geometric_gap(&prev, &curr_period, &context),
            "Gap of 6 units should exceed punctuation threshold of 4.8 (50% of 9.6)"
        );
    }

    #[test]
    fn test_punctuation_does_not_trigger_on_normal_text() {
        let detector = WordBoundaryDetector::new();
        let context = BoundaryContext::new(12.0);

        let prev = CharacterInfo {
            code: 'd' as u32,
            glyph_id: None,
            width: 5.0,
            x_position: 100.0,
            tj_offset: None,
            font_size: 12.0,
            is_ligature: false,
            original_ligature: None,
            protected_from_split: false,
        };

        // Same gap (6.0) but current character is 'e', not punctuation
        let curr = CharacterInfo {
            code: 'e' as u32, // 'e' is NOT punctuation
            glyph_id: None,
            width: 5.0,
            x_position: 111.0,
            tj_offset: None,
            font_size: 12.0,
            is_ligature: false,
            original_ligature: None,
            protected_from_split: false,
        };

        assert!(
            !detector.has_significant_geometric_gap(&prev, &curr, &context),
            "Gap of 6 units should NOT exceed normal threshold of 9.6"
        );
    }

    #[test]
    fn test_is_punctuation_ascii() {
        assert!(WordBoundaryDetector::is_punctuation('.' as u32));
        assert!(WordBoundaryDetector::is_punctuation(',' as u32));
        assert!(WordBoundaryDetector::is_punctuation('!' as u32));
        assert!(WordBoundaryDetector::is_punctuation('?' as u32));
        assert!(WordBoundaryDetector::is_punctuation(':' as u32));
        assert!(WordBoundaryDetector::is_punctuation(';' as u32));
    }

    #[test]
    fn test_is_punctuation_non_punctuation() {
        assert!(!WordBoundaryDetector::is_punctuation('a' as u32));
        assert!(!WordBoundaryDetector::is_punctuation('1' as u32));
        assert!(!WordBoundaryDetector::is_punctuation(' ' as u32));
    }

    #[test]
    fn test_is_ligature_internal_gap_ffi() {
        let detector = WordBoundaryDetector::new();

        // 'f' from 'ffi' ligature
        let prev = CharacterInfo {
            code: 'f' as u32,
            glyph_id: None,
            width: 5.0,
            x_position: 100.0,
            tj_offset: None,
            font_size: 12.0,
            is_ligature: true,
            original_ligature: Some(''), // ffi ligature U+FB04
            protected_from_split: false,
        };

        let curr = CharacterInfo {
            code: 'f' as u32,
            glyph_id: None,
            width: 5.0,
            x_position: 110.0,
            tj_offset: None,
            font_size: 12.0,
            is_ligature: true,
            original_ligature: Some(''),
            protected_from_split: false,
        };

        assert!(
            detector.is_ligature_internal_gap(&prev, &curr),
            "Should detect ligature internal gap when both have is_ligature=true"
        );
    }

    #[test]
    fn test_is_ligature_internal_gap_actual_ligature_code() {
        let detector = WordBoundaryDetector::new();

        // Previous character IS the ligature U+FB00 ('ff')
        let prev = CharacterInfo {
            code: 0xFB00, // 'ff' ligature
            glyph_id: None,
            width: 10.0,
            x_position: 100.0,
            tj_offset: None,
            font_size: 12.0,
            is_ligature: false, // Not expanded, still the ligature
            original_ligature: None,
            protected_from_split: false,
        };

        let curr = CharacterInfo {
            code: 'i' as u32,
            glyph_id: None,
            width: 3.0,
            x_position: 115.0,
            tj_offset: None,
            font_size: 12.0,
            is_ligature: false,
            original_ligature: None,
            protected_from_split: false,
        };

        assert!(
            detector.is_ligature_internal_gap(&prev, &curr),
            "Should detect ligature internal gap when prev code is U+FB00"
        );
    }
}