inkhaven 3.3.0

Inkhaven — TUI literary work editor for Typst books
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
//! 1.2.19+ C.2 — continuity lexicon + numeric / temporal
//! / spatial contradiction detection.
//!
//! The Tier-3 multilingual feature: extraction is
//! lexicon-bound, so this is where the genuine
//! per-language work lives.  Digits are language-agnostic
//! (`3 days`), but number-WORDS (`three` / `trois` /
//! `tres`), units (`day` / `jour` / `día`), and
//! directions (`north` / `nord` / `norte`) need a
//! per-language lexicon.
//!
//! ## Language coverage
//!
//! Built-in lexicons for all five project languages —
//! **English, French, Spanish** (C.2), and **German +
//! Russian** (3.3.0 M1, the multilingual-parity pass).
//! Russian carries the case-inflected unit forms the
//! counting construction demands (`день`/`дня`/`дней`);
//! German carries dative-plural forms (`Tagen`) but does
//! not decompose single-word compounds (`einundzwanzig`)
//! — digits cover those.  Both use a per-language
//! `direction_preps` set so a prepositional direction
//! (`nach Norden` / `на север`) is caught.  Any language
//! without a bundled lexicon still skips the scan with a
//! clear message — graceful degradation, never silent
//! garbage.
//!
//! ## How contradiction detection stays conservative
//!
//! The whole `numeric-contradiction` doctor class is
//! Info / author-judgment / no-autofix, like the 1.2.16
//! narrative-audit classes — false positives are
//! expected, the author decides.  Two checks, both
//! deliberately narrow:
//!
//!   1. **Spatial direction reversal** — two *directed*
//!      spatial magnitudes (`200 leagues north` …
//!      `200 leagues south`) with opposite cardinal
//!      directions + equal magnitude within a window of
//!      sentences.  High-confidence error signal.
//!   2. **Proximate temporal mismatch** — two durations
//!      with different normalised values in the same (or
//!      adjacent) sentence (`the three-day journey, after
//!      a week of travel`).  Framed as "do these refer to
//!      the same span?"  Narrow window keeps the noise
//!      down.
//!
//! Directions are only extracted as part of a directed
//! magnitude — never bare — which sidesteps the
//! cross-language bare-direction ambiguity (Spanish
//! `este` = "east" AND "this") and the "a character
//! legitimately walked north then south" false positive.

use std::collections::{HashMap, HashSet};

/// Cardinal direction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Direction {
    North,
    South,
    East,
    West,
}

impl Direction {
    pub fn opposite(self) -> Direction {
        match self {
            Direction::North => Direction::South,
            Direction::South => Direction::North,
            Direction::East => Direction::West,
            Direction::West => Direction::East,
        }
    }
}

/// The physical dimension a quantity measures.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Dim {
    /// Value normalised to seconds.
    Temporal,
    /// Value normalised to metres.
    Spatial,
}

/// One extracted quantity, normalised to its dimension's
/// base unit.
#[derive(Debug, Clone, PartialEq)]
pub struct Quantity {
    /// Normalised magnitude (seconds for Temporal, metres
    /// for Spatial).
    pub base_value: f64,
    pub dim: Dim,
    /// Cardinal direction, when the quantity was a
    /// directed spatial magnitude.
    pub direction: Option<Direction>,
    /// The raw text span, for the finding quote.
    pub raw: String,
    /// 0-based index of the sentence it appeared in.
    pub sentence: usize,
}

/// Per-language quantity lexicon.  Keys are lowercased.
#[derive(Debug, Clone, Default)]
pub struct ContinuityLexicon {
    /// Number-words + articles → value (`a`/`one` = 1.0).
    numbers: HashMap<String, f64>,
    /// Scale multipliers (`hundred` = 100, `thousand` =
    /// 1000).
    scales: HashMap<String, f64>,
    /// Temporal unit (singular + plural) → seconds.
    temporal: HashMap<String, f64>,
    /// Spatial unit (singular + plural) → metres.
    spatial: HashMap<String, f64>,
    /// Direction word → cardinal.
    directions: HashMap<String, Direction>,
    /// One-token prepositions a direction may hide behind, so
    /// `200 Meilen nach Norden` / `200 вёрст на север` are caught
    /// as directed magnitudes. Empty for languages whose directions
    /// follow the unit bare (EN `north`, FR `nord`, ES `norte`).
    direction_preps: HashSet<String>,
}

// Base-unit constants.
const MINUTE: f64 = 60.0;
const HOUR: f64 = 3600.0;
const DAY: f64 = 86_400.0;
const WEEK: f64 = 604_800.0;
const MONTH: f64 = 2_592_000.0; // 30 days
const YEAR: f64 = 31_536_000.0; // 365 days

const FOOT: f64 = 0.3048;
const YARD: f64 = 0.9144;
const MILE: f64 = 1609.34;
const KM: f64 = 1000.0;
const LEAGUE: f64 = 5556.0;
const PACE: f64 = 0.762;
const VERST: f64 = 1066.8; // верста — Russian historical unit

fn map(pairs: &[(&str, f64)]) -> HashMap<String, f64> {
    pairs.iter().map(|(k, v)| (k.to_string(), *v)).collect()
}

fn set(words: &[&str]) -> HashSet<String> {
    words.iter().map(|w| w.to_string()).collect()
}

/// Built-in lexicon for a supported language, or `None`
/// when no lexicon ships for it (caller skips the scan
/// with a clear message).
pub fn built_in_lexicon(language: &str) -> Option<ContinuityLexicon> {
    match language.trim().to_ascii_lowercase().as_str() {
        "english" | "en" => Some(english()),
        "french" | "fr" => Some(french()),
        "spanish" | "es" => Some(spanish()),
        "german" | "de" => Some(german()),
        "russian" | "ru" => Some(russian()),
        _ => None,
    }
}

fn english() -> ContinuityLexicon {
    ContinuityLexicon {
        numbers: map(&[
            ("a", 1.0), ("an", 1.0), ("one", 1.0),
            ("zero", 0.0), ("two", 2.0), ("three", 3.0),
            ("four", 4.0), ("five", 5.0), ("six", 6.0),
            ("seven", 7.0), ("eight", 8.0), ("nine", 9.0),
            ("ten", 10.0), ("eleven", 11.0), ("twelve", 12.0),
            ("thirteen", 13.0), ("fourteen", 14.0),
            ("fifteen", 15.0), ("sixteen", 16.0),
            ("seventeen", 17.0), ("eighteen", 18.0),
            ("nineteen", 19.0), ("twenty", 20.0),
            ("thirty", 30.0), ("forty", 40.0), ("fifty", 50.0),
            ("sixty", 60.0), ("seventy", 70.0), ("eighty", 80.0),
            ("ninety", 90.0),
        ]),
        scales: map(&[("hundred", 100.0), ("thousand", 1000.0)]),
        temporal: map(&[
            ("second", 1.0), ("seconds", 1.0),
            ("minute", MINUTE), ("minutes", MINUTE),
            ("hour", HOUR), ("hours", HOUR),
            ("day", DAY), ("days", DAY),
            ("week", WEEK), ("weeks", WEEK),
            ("month", MONTH), ("months", MONTH),
            ("year", YEAR), ("years", YEAR),
        ]),
        spatial: map(&[
            ("foot", FOOT), ("feet", FOOT),
            ("yard", YARD), ("yards", YARD),
            ("mile", MILE), ("miles", MILE),
            ("kilometer", KM), ("kilometers", KM),
            ("kilometre", KM), ("kilometres", KM),
            ("meter", 1.0), ("meters", 1.0),
            ("metre", 1.0), ("metres", 1.0),
            ("league", LEAGUE), ("leagues", LEAGUE),
            ("pace", PACE), ("paces", PACE),
        ]),
        directions: directions_en(),
        direction_preps: set(&[]),
    }
}

fn directions_en() -> HashMap<String, Direction> {
    [
        ("north", Direction::North), ("south", Direction::South),
        ("east", Direction::East), ("west", Direction::West),
    ]
    .iter()
    .map(|(k, v)| (k.to_string(), *v))
    .collect()
}

fn french() -> ContinuityLexicon {
    ContinuityLexicon {
        numbers: map(&[
            ("un", 1.0), ("une", 1.0),
            ("zéro", 0.0), ("deux", 2.0), ("trois", 3.0),
            ("quatre", 4.0), ("cinq", 5.0), ("six", 6.0),
            ("sept", 7.0), ("huit", 8.0), ("neuf", 9.0),
            ("dix", 10.0), ("onze", 11.0), ("douze", 12.0),
            ("treize", 13.0), ("quatorze", 14.0),
            ("quinze", 15.0), ("seize", 16.0),
            ("vingt", 20.0), ("trente", 30.0),
            ("quarante", 40.0), ("cinquante", 50.0),
            ("soixante", 60.0),
        ]),
        scales: map(&[("cent", 100.0), ("cents", 100.0), ("mille", 1000.0)]),
        temporal: map(&[
            ("seconde", 1.0), ("secondes", 1.0),
            ("minute", MINUTE), ("minutes", MINUTE),
            ("heure", HOUR), ("heures", HOUR),
            ("jour", DAY), ("jours", DAY),
            ("journée", DAY), ("journées", DAY),
            ("semaine", WEEK), ("semaines", WEEK),
            ("mois", MONTH),
            ("an", YEAR), ("ans", YEAR),
            ("année", YEAR), ("années", YEAR),
        ]),
        spatial: map(&[
            ("mètre", 1.0), ("mètres", 1.0),
            ("kilomètre", KM), ("kilomètres", KM),
            ("lieue", 4000.0), ("lieues", 4000.0),
            ("pas", PACE),
        ]),
        directions: [
            ("nord", Direction::North), ("sud", Direction::South),
            ("est", Direction::East), ("ouest", Direction::West),
        ]
        .iter()
        .map(|(k, v)| (k.to_string(), *v))
        .collect(),
        direction_preps: set(&[]),
    }
}

fn spanish() -> ContinuityLexicon {
    ContinuityLexicon {
        numbers: map(&[
            ("un", 1.0), ("uno", 1.0), ("una", 1.0),
            ("cero", 0.0), ("dos", 2.0), ("tres", 3.0),
            ("cuatro", 4.0), ("cinco", 5.0), ("seis", 6.0),
            ("siete", 7.0), ("ocho", 8.0), ("nueve", 9.0),
            ("diez", 10.0), ("once", 11.0), ("doce", 12.0),
            ("trece", 13.0), ("catorce", 14.0),
            ("quince", 15.0), ("veinte", 20.0),
            ("treinta", 30.0), ("cuarenta", 40.0),
            ("cincuenta", 50.0), ("sesenta", 60.0),
        ]),
        scales: map(&[
            ("cien", 100.0), ("ciento", 100.0),
            ("mil", 1000.0),
        ]),
        temporal: map(&[
            ("segundo", 1.0), ("segundos", 1.0),
            ("minuto", MINUTE), ("minutos", MINUTE),
            ("hora", HOUR), ("horas", HOUR),
            ("día", DAY), ("días", DAY),
            ("semana", WEEK), ("semanas", WEEK),
            ("mes", MONTH), ("meses", MONTH),
            ("año", YEAR), ("años", YEAR),
        ]),
        spatial: map(&[
            ("metro", 1.0), ("metros", 1.0),
            ("kilómetro", KM), ("kilómetros", KM),
            ("milla", MILE), ("millas", MILE),
            ("legua", LEAGUE), ("leguas", LEAGUE),
            ("paso", PACE), ("pasos", PACE),
        ]),
        // Spanish `este` = "east" AND "this" — only ever
        // extracted attached to a spatial magnitude, so
        // the demonstrative never triggers a finding.
        directions: [
            ("norte", Direction::North), ("sur", Direction::South),
            ("este", Direction::East), ("oeste", Direction::West),
        ]
        .iter()
        .map(|(k, v)| (k.to_string(), *v))
        .collect(),
        direction_preps: set(&[]),
    }
}

/// German — number-words 0–90 + tens, plus dative-plural unit forms
/// (`Tagen` / `Jahren`). Single-word compounds (`einundzwanzig` = 21)
/// are not decomposed — digits (`21 Tage`) cover those; a documented
/// limit of the lexicon approach for German. Directions attach via a
/// preposition (`nach Norden`).
fn german() -> ContinuityLexicon {
    ContinuityLexicon {
        numbers: map(&[
            ("ein", 1.0), ("eine", 1.0), ("eins", 1.0),
            ("null", 0.0), ("zwei", 2.0), ("drei", 3.0),
            ("vier", 4.0), ("fünf", 5.0), ("sechs", 6.0),
            ("sieben", 7.0), ("acht", 8.0), ("neun", 9.0),
            ("zehn", 10.0), ("elf", 11.0), ("zwölf", 12.0),
            ("dreizehn", 13.0), ("vierzehn", 14.0),
            ("fünfzehn", 15.0), ("sechzehn", 16.0),
            ("siebzehn", 17.0), ("achtzehn", 18.0),
            ("neunzehn", 19.0), ("zwanzig", 20.0),
            ("dreißig", 30.0), ("dreissig", 30.0),
            ("vierzig", 40.0), ("fünfzig", 50.0),
            ("sechzig", 60.0), ("siebzig", 70.0),
            ("achtzig", 80.0), ("neunzig", 90.0),
        ]),
        scales: map(&[("hundert", 100.0), ("tausend", 1000.0)]),
        temporal: map(&[
            ("sekunde", 1.0), ("sekunden", 1.0),
            ("minute", MINUTE), ("minuten", MINUTE),
            ("stunde", HOUR), ("stunden", HOUR),
            ("tag", DAY), ("tage", DAY), ("tagen", DAY),
            ("woche", WEEK), ("wochen", WEEK),
            ("monat", MONTH), ("monate", MONTH), ("monaten", MONTH),
            ("jahr", YEAR), ("jahre", YEAR), ("jahren", YEAR),
        ]),
        spatial: map(&[
            ("meter", 1.0), ("metern", 1.0),
            ("kilometer", KM), ("kilometern", KM),
            ("meile", MILE), ("meilen", MILE),
            ("fuß", FOOT), ("fuss", FOOT),
            ("schritt", PACE), ("schritte", PACE), ("schritten", PACE),
        ]),
        directions: [
            ("norden", Direction::North), ("nord", Direction::North),
            ("süden", Direction::South), ("süd", Direction::South),
            ("osten", Direction::East), ("ost", Direction::East),
            ("westen", Direction::West), ("west", Direction::West),
        ]
        .iter()
        .map(|(k, v)| (k.to_string(), *v))
        .collect(),
        direction_preps: set(&["nach", "gen", "im", "in"]),
    }
}

/// Russian — Cyrillic, with the case-inflected unit forms that the
/// counting construction demands (`день` / `дня` / `дней` all = day;
/// `год` / `года` / `лет` = year) and the oblique forms of the small
/// numbers (`два` / `двух`, `три` / `трёх`). ё is folded to е in the
/// tokenizer's `to_lowercase`, so both spellings are listed. Single-
/// word hundreds (`двести` = 200) are not decomposed — digits cover
/// those. Directions attach via a preposition (`на север` / `к северу`).
fn russian() -> ContinuityLexicon {
    ContinuityLexicon {
        numbers: map(&[
            ("один", 1.0), ("одна", 1.0), ("одно", 1.0),
            ("ноль", 0.0),
            ("два", 2.0), ("две", 2.0), ("двух", 2.0),
            ("три", 3.0), ("трёх", 3.0), ("трех", 3.0),
            ("четыре", 4.0), ("четырёх", 4.0), ("четырех", 4.0),
            ("пять", 5.0), ("шесть", 6.0), ("семь", 7.0),
            ("восемь", 8.0), ("девять", 9.0), ("десять", 10.0),
            ("одиннадцать", 11.0), ("двенадцать", 12.0),
            ("тринадцать", 13.0), ("четырнадцать", 14.0),
            ("пятнадцать", 15.0), ("шестнадцать", 16.0),
            ("семнадцать", 17.0), ("восемнадцать", 18.0),
            ("девятнадцать", 19.0), ("двадцать", 20.0),
            ("тридцать", 30.0), ("сорок", 40.0),
            ("пятьдесят", 50.0), ("шестьдесят", 60.0),
            ("семьдесят", 70.0), ("восемьдесят", 80.0),
            ("девяносто", 90.0),
        ]),
        scales: map(&[
            ("сто", 100.0),
            ("тысяча", 1000.0), ("тысячи", 1000.0), ("тысяч", 1000.0),
        ]),
        temporal: map(&[
            ("секунда", 1.0), ("секунды", 1.0), ("секунд", 1.0), ("секунду", 1.0),
            ("минута", MINUTE), ("минуты", MINUTE), ("минут", MINUTE), ("минуту", MINUTE),
            ("час", HOUR), ("часа", HOUR), ("часов", HOUR),
            ("день", DAY), ("дня", DAY), ("дней", DAY), ("дню", DAY),
            ("неделя", WEEK), ("недели", WEEK), ("недель", WEEK), ("неделю", WEEK),
            ("месяц", MONTH), ("месяца", MONTH), ("месяцев", MONTH),
            ("год", YEAR), ("года", YEAR), ("лет", YEAR),
        ]),
        spatial: map(&[
            ("метр", 1.0), ("метра", 1.0), ("метров", 1.0),
            ("километр", KM), ("километра", KM), ("километров", KM),
            ("миля", MILE), ("мили", MILE), ("миль", MILE),
            ("верста", VERST), ("версты", VERST), ("вёрст", VERST), ("верст", VERST),
            ("лига", LEAGUE), ("лиги", LEAGUE), ("лиг", LEAGUE),
            ("шаг", PACE), ("шага", PACE), ("шагов", PACE),
        ]),
        directions: [
            ("север", Direction::North), ("северу", Direction::North),
            ("юг", Direction::South), ("югу", Direction::South),
            ("восток", Direction::East), ("востоку", Direction::East),
            ("запад", Direction::West), ("западу", Direction::West),
        ]
        .iter()
        .map(|(k, v)| (k.to_string(), *v))
        .collect(),
        direction_preps: set(&["на", "к", "в"]),
    }
}

/// Split prose into sentences on `.!?` boundaries.
/// Coarse but adequate — the detector only needs sentence
/// *grouping* for the proximity windows, not linguistic
/// precision.
///
/// 1.2.22 D.7b — intentionally NOT shared with
/// `tui::sentence_rhythm::split_sentences`: that one is
/// abbreviation-aware (suppresses `Mr.`/`Dr.`/`e.g.`/…) and
/// returns position-carrying `RawSentence`s for the rhythm
/// bar chart.  This naive split is all the proximity-window
/// detector needs; adopting the abbreviation-aware boundary
/// would change *this* function's behaviour for no gain.
pub fn split_sentences(text: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut cur = String::new();
    for ch in text.chars() {
        cur.push(ch);
        if matches!(ch, '.' | '!' | '?') {
            let trimmed = cur.trim();
            if !trimmed.is_empty() {
                out.push(trimmed.to_string());
            }
            cur.clear();
        }
    }
    let tail = cur.trim();
    if !tail.is_empty() {
        out.push(tail.to_string());
    }
    out
}

/// Tokenise a sentence: split on whitespace, trim
/// leading/trailing punctuation, keep internal hyphens +
/// digits.  Lowercased.
fn tokenize(sentence: &str) -> Vec<String> {
    sentence
        .split_whitespace()
        .map(|t| {
            t.trim_matches(|c: char| !c.is_alphanumeric())
                .to_lowercase()
        })
        .filter(|t| !t.is_empty())
        .collect()
}

/// Parse a number expression starting at `tokens[i]`.
/// Returns `(value, tokens_consumed)`.  Handles: a digit
/// run (`200`, `1,000`), an article/number-word, a
/// hyphenated compound (`twenty-five`), and a
/// `<number> <scale>` pair (`two hundred`, `a thousand`).
fn parse_number(
    tokens: &[String],
    i: usize,
    lex: &ContinuityLexicon,
) -> Option<(f64, usize)> {
    let tok = tokens.get(i)?;

    // Digit run (allow thousands separators + decimals).
    let cleaned: String = tok.chars().filter(|c| *c != ',').collect();
    let base = if cleaned.chars().all(|c| c.is_ascii_digit() || c == '.')
        && cleaned.chars().any(|c| c.is_ascii_digit())
    {
        cleaned.parse::<f64>().ok()?
    } else if let Some((a, b)) = tok.split_once('-') {
        // Hyphenated compound: tens-ones (twenty-five).
        match (lex.numbers.get(a), lex.numbers.get(b)) {
            (Some(t), Some(o)) => t + o,
            _ => *lex.numbers.get(tok)?,
        }
    } else {
        *lex.numbers.get(tok)?
    };

    // Optional trailing scale word: "two hundred".
    if let Some(next) = tokens.get(i + 1) {
        if let Some(scale) = lex.scales.get(next) {
            return Some((base * scale, 2));
        }
    }
    Some((base, 1))
}

/// Extract every quantity from `sentences`.  Pure +
/// multilingual (parametrised entirely by `lex`).
pub fn extract_quantities(
    sentences: &[String],
    lex: &ContinuityLexicon,
) -> Vec<Quantity> {
    let mut out = Vec::new();
    for (s_idx, sentence) in sentences.iter().enumerate() {
        let tokens = tokenize(sentence);
        let mut i = 0;
        while i < tokens.len() {
            let Some((value, consumed)) = parse_number(&tokens, i, lex) else {
                i += 1;
                continue;
            };
            let unit_idx = i + consumed;
            let Some(unit_tok) = tokens.get(unit_idx) else {
                i += consumed;
                continue;
            };
            if let Some(secs) = lex.temporal.get(unit_tok) {
                out.push(Quantity {
                    base_value: value * secs,
                    dim: Dim::Temporal,
                    direction: None,
                    raw: format!("{} {}", tokens[i..unit_idx].join(" "), unit_tok),
                    sentence: s_idx,
                });
                i = unit_idx + 1;
            } else if let Some(metres) = lex.spatial.get(unit_tok) {
                // Optional trailing direction word, possibly behind a
                // one-token preposition (DE `nach Norden`, RU `на север`);
                // `direction_preps` is empty for the bare-direction languages,
                // so this collapses to the plain `unit_idx + 1` lookup there.
                let mut probe = unit_idx + 1;
                if tokens.get(probe).is_some_and(|t| lex.direction_preps.contains(t)) {
                    probe += 1;
                }
                let (direction, raw_end) = match tokens
                    .get(probe)
                    .and_then(|d| lex.directions.get(d).copied())
                {
                    Some(dir) => (Some(dir), probe + 1),
                    None => (None, unit_idx + 1),
                };
                out.push(Quantity {
                    base_value: value * metres,
                    dim: Dim::Spatial,
                    direction,
                    raw: tokens[i..raw_end].join(" "),
                    sentence: s_idx,
                });
                i = raw_end;
            } else {
                i += consumed;
            }
        }
    }
    out
}

/// Tunables for contradiction detection.
#[derive(Debug, Clone)]
pub struct ContradictionConfig {
    /// Window (sentences) for the spatial direction-
    /// reversal check.
    pub spatial_window: usize,
    /// Window (sentences) for the proximate temporal-
    /// mismatch check.  `0` disables temporal checking.
    pub temporal_window: usize,
    /// Relative tolerance for "equal magnitude" in the
    /// spatial check (0.0 = exact).
    pub magnitude_tolerance: f64,
}

impl Default for ContradictionConfig {
    fn default() -> Self {
        Self {
            spatial_window: 3,
            temporal_window: 1,
            magnitude_tolerance: 0.0,
        }
    }
}

/// One flagged contradiction.
#[derive(Debug, Clone, PartialEq)]
pub struct Contradiction {
    pub kind: ContradictionKind,
    pub a_raw: String,
    pub b_raw: String,
    pub a_sentence: usize,
    pub b_sentence: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContradictionKind {
    /// Opposite cardinal directions, equal magnitude,
    /// within the spatial window.
    DirectionReversal,
    /// Two durations of different normalised value within
    /// the temporal window.
    TemporalMismatch,
}

/// Detect contradictions among extracted quantities.
/// Conservative by design — see the module note.
pub fn detect_contradictions(
    quantities: &[Quantity],
    cfg: &ContradictionConfig,
) -> Vec<Contradiction> {
    let mut out = Vec::new();

    // ── Rule 1: spatial direction reversal ────────────
    let directed: Vec<&Quantity> = quantities
        .iter()
        .filter(|q| q.dim == Dim::Spatial && q.direction.is_some())
        .collect();
    for a_i in 0..directed.len() {
        for b_i in (a_i + 1)..directed.len() {
            let a = directed[a_i];
            let b = directed[b_i];
            if b.sentence.saturating_sub(a.sentence) > cfg.spatial_window {
                // M7 (3.0.0 P2) — quantities are sentence-ascending (see
                // `extract_quantities`), so once `b` is past the window every
                // later `b` is too: break, don't scan the rest (was O(n^2)).
                break;
            }
            let (Some(da), Some(db)) = (a.direction, b.direction) else {
                continue;
            };
            if db != da.opposite() {
                continue;
            }
            if !magnitudes_equal(a.base_value, b.base_value, cfg.magnitude_tolerance)
            {
                continue;
            }
            out.push(Contradiction {
                kind: ContradictionKind::DirectionReversal,
                a_raw: a.raw.clone(),
                b_raw: b.raw.clone(),
                a_sentence: a.sentence,
                b_sentence: b.sentence,
            });
        }
    }

    // ── Rule 2: proximate temporal mismatch ───────────
    if cfg.temporal_window > 0 {
        let temporal: Vec<&Quantity> =
            quantities.iter().filter(|q| q.dim == Dim::Temporal).collect();
        for a_i in 0..temporal.len() {
            for b_i in (a_i + 1)..temporal.len() {
                let a = temporal[a_i];
                let b = temporal[b_i];
                if b.sentence.saturating_sub(a.sentence) > cfg.temporal_window {
                    // M7 — sentence-ascending, so break rather than scan the
                    // rest of the window-exceeding pairs (was O(n^2)).
                    break;
                }
                // Different normalised duration → possible
                // mismatch.  Equal durations (3 days vs 72
                // hours) are consistent — skip.
                if (a.base_value - b.base_value).abs() < f64::EPSILON {
                    continue;
                }
                out.push(Contradiction {
                    kind: ContradictionKind::TemporalMismatch,
                    a_raw: a.raw.clone(),
                    b_raw: b.raw.clone(),
                    a_sentence: a.sentence,
                    b_sentence: b.sentence,
                });
            }
        }
    }

    out
}

fn magnitudes_equal(a: f64, b: f64, tol: f64) -> bool {
    if tol <= 0.0 {
        (a - b).abs() < f64::EPSILON
    } else {
        let denom = a.abs().max(b.abs()).max(f64::EPSILON);
        (a - b).abs() / denom <= tol
    }
}

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

    fn sents(v: &[&str]) -> Vec<String> {
        v.iter().map(|s| s.to_string()).collect()
    }

    // ── number parsing ────────────────────────────────

    #[test]
    fn parses_digit_word_compound_and_scale() {
        let lex = english();
        let q = extract_quantities(
            &sents(&[
                "It took 200 days.",
                "It took three days.",
                "It took twenty-five days.",
                "It took two hundred days.",
                "It took a day.",
            ]),
            &lex,
        );
        let vals: Vec<f64> = q.iter().map(|x| x.base_value / DAY).collect();
        assert_eq!(vals, vec![200.0, 3.0, 25.0, 200.0, 1.0]);
    }

    // ── temporal extraction + normalisation ───────────

    #[test]
    fn temporal_normalises_to_seconds() {
        let lex = english();
        let q = extract_quantities(&sents(&["He waited a week."]), &lex);
        assert_eq!(q.len(), 1);
        assert_eq!(q[0].dim, Dim::Temporal);
        assert_eq!(q[0].base_value, WEEK);
    }

    // ── spatial + direction extraction ────────────────

    #[test]
    fn spatial_with_direction() {
        let lex = english();
        let q = extract_quantities(&sents(&["They rode 200 leagues north."]), &lex);
        assert_eq!(q.len(), 1);
        assert_eq!(q[0].dim, Dim::Spatial);
        assert_eq!(q[0].direction, Some(Direction::North));
        assert_eq!(q[0].base_value, 200.0 * LEAGUE);
    }

    // ── Rule 1: direction reversal ────────────────────

    #[test]
    fn flags_direction_reversal() {
        let lex = english();
        let q = extract_quantities(
            &sents(&[
                "They rode 200 leagues north.",
                "By dusk they had gone 200 leagues south.",
            ]),
            &lex,
        );
        let c = detect_contradictions(&q, &ContradictionConfig::default());
        assert_eq!(c.len(), 1);
        assert_eq!(c[0].kind, ContradictionKind::DirectionReversal);
    }

    #[test]
    fn no_reversal_when_magnitudes_differ() {
        let lex = english();
        let q = extract_quantities(
            &sents(&[
                "They rode 200 leagues north.",
                "Then 50 leagues south.",
            ]),
            &lex,
        );
        // Different magnitudes → legitimate movement, not
        // flagged.
        let c = detect_contradictions(&q, &ContradictionConfig::default());
        assert!(!c.iter().any(|x| x.kind == ContradictionKind::DirectionReversal));
    }

    #[test]
    fn no_reversal_beyond_window() {
        let lex = english();
        let mut v = vec!["They rode 200 leagues north.".to_string()];
        for i in 0..5 {
            v.push(format!("Filler sentence number {i}."));
        }
        v.push("They rode 200 leagues south.".to_string());
        let q = extract_quantities(&v, &lex);
        let c = detect_contradictions(&q, &ContradictionConfig::default());
        assert!(c.is_empty(), "reversal beyond window should not flag");
    }

    // ── Rule 2: temporal mismatch ─────────────────────

    #[test]
    fn flags_proximate_temporal_mismatch() {
        let lex = english();
        let q = extract_quantities(
            &sents(&["The three day journey ended after a week."]),
            &lex,
        );
        let c = detect_contradictions(&q, &ContradictionConfig::default());
        assert!(c.iter().any(|x| x.kind == ContradictionKind::TemporalMismatch));
    }

    #[test]
    fn equal_durations_not_flagged() {
        let lex = english();
        // "twenty-four hours" == "a day" → consistent.
        let q = extract_quantities(
            &sents(&["The twenty-four hours felt like a day."]),
            &lex,
        );
        let c = detect_contradictions(&q, &ContradictionConfig::default());
        assert!(!c.iter().any(|x| x.kind == ContradictionKind::TemporalMismatch));
    }

    #[test]
    fn temporal_window_zero_disables() {
        let lex = english();
        let q = extract_quantities(
            &sents(&["The three day journey ended after a week."]),
            &lex,
        );
        let mut cfg = ContradictionConfig::default();
        cfg.temporal_window = 0;
        let c = detect_contradictions(&q, &cfg);
        assert!(c.is_empty());
    }

    // ── multilingual ──────────────────────────────────

    #[test]
    fn french_temporal_extraction() {
        let lex = french();
        let q = extract_quantities(&sents(&["Il a attendu une semaine."]), &lex);
        assert_eq!(q.len(), 1);
        assert_eq!(q[0].base_value, WEEK);
    }

    #[test]
    fn french_direction_reversal() {
        let lex = french();
        let q = extract_quantities(
            &sents(&[
                "Ils ont parcouru 200 lieues nord.",
                "Puis 200 lieues sud.",
            ]),
            &lex,
        );
        let c = detect_contradictions(&q, &ContradictionConfig::default());
        assert_eq!(c.len(), 1);
        assert_eq!(c[0].kind, ContradictionKind::DirectionReversal);
    }

    #[test]
    fn spanish_temporal_extraction() {
        let lex = spanish();
        let q = extract_quantities(&sents(&["Esperó tres días."]), &lex);
        assert_eq!(q.len(), 1);
        assert_eq!(q[0].base_value, 3.0 * DAY);
    }

    #[test]
    fn spanish_este_demonstrative_not_a_finding() {
        let lex = spanish();
        // "este" appears as a demonstrative ("this man"),
        // not attached to a magnitude → no spatial
        // quantity, so it can't produce a reversal.
        let q = extract_quantities(
            &sents(&["Este hombre caminó 10 metros norte.", "Luego 10 metros sur."]),
            &lex,
        );
        // Only the two directed magnitudes extracted; the
        // bare "este" demonstrative is ignored.
        assert!(q.iter().all(|x| x.dim == Dim::Spatial));
        let c = detect_contradictions(&q, &ContradictionConfig::default());
        assert_eq!(c.len(), 1, "norte/sur reversal flagged; 'este' ignored");
    }

    #[test]
    fn german_temporal_and_dative_plural() {
        let lex = german();
        // "drei Tage" (nom pl) and "an drei Tagen" (dat pl) both = 3 days.
        let q = extract_quantities(
            &sents(&["Die Reise dauerte drei Tage.", "Nach drei Tagen kehrte er zurück."]),
            &lex,
        );
        assert_eq!(q.len(), 2);
        assert!(q.iter().all(|x| (x.base_value - 3.0 * DAY).abs() < 1.0));
    }

    #[test]
    fn german_direction_reversal_through_preposition() {
        let lex = german();
        // Direction hides behind "nach": `200 Meilen nach Norden` … `nach Süden`.
        let q = extract_quantities(
            &sents(&[
                "Sie ritten 200 Meilen nach Norden.",
                "Dann 200 Meilen nach Süden.",
            ]),
            &lex,
        );
        assert_eq!(q.iter().filter(|x| x.direction.is_some()).count(), 2);
        let c = detect_contradictions(&q, &ContradictionConfig::default());
        assert_eq!(c.len(), 1);
        assert_eq!(c[0].kind, ContradictionKind::DirectionReversal);
    }

    #[test]
    fn russian_temporal_declension_normalises() {
        let lex = russian();
        // "три дня" (gen sg) and "пять дней" (gen pl) — different forms of
        // "day"; a genuine 3-vs-5 mismatch, both resolving to DAY units.
        let q = extract_quantities(
            &sents(&["Три дня пути закончились через пять дней."]),
            &lex,
        );
        let days: Vec<f64> = q.iter().map(|x| x.base_value / DAY).collect();
        assert_eq!(days, vec![3.0, 5.0]);
        let c = detect_contradictions(&q, &ContradictionConfig::default());
        assert!(c.iter().any(|x| x.kind == ContradictionKind::TemporalMismatch));
    }

    #[test]
    fn russian_direction_reversal_through_preposition() {
        let lex = russian();
        // `200 вёрст на север` … `на юг` — direction behind the preposition "на".
        let q = extract_quantities(
            &sents(&[
                "Они проехали 200 вёрст на север.",
                "Потом 200 вёрст на юг.",
            ]),
            &lex,
        );
        assert_eq!(q.iter().filter(|x| x.direction.is_some()).count(), 2);
        let c = detect_contradictions(&q, &ContradictionConfig::default());
        assert_eq!(c.len(), 1);
        assert_eq!(c[0].kind, ContradictionKind::DirectionReversal);
        assert_eq!((q[0].base_value / VERST).round(), 200.0);
    }

    // ── lexicon availability ──────────────────────────

    #[test]
    fn unsupported_language_has_no_lexicon() {
        assert!(built_in_lexicon("japanese").is_none());
        assert!(built_in_lexicon("italian").is_none());
    }

    #[test]
    fn supported_languages_have_lexicons() {
        for l in [
            "english", "en", "french", "fr", "spanish", "es",
            "german", "de", "russian", "ru",
        ] {
            assert!(built_in_lexicon(l).is_some(), "missing lexicon: {l}");
        }
    }

    // ── direction opposite ────────────────────────────

    #[test]
    fn direction_opposites() {
        assert_eq!(Direction::North.opposite(), Direction::South);
        assert_eq!(Direction::East.opposite(), Direction::West);
        assert_eq!(Direction::South.opposite(), Direction::North);
        assert_eq!(Direction::West.opposite(), Direction::East);
    }

    // ── sentence split ────────────────────────────────

    #[test]
    fn sentence_split_basic() {
        let s = split_sentences("First. Second! Third? Trailing");
        assert_eq!(s.len(), 4);
        assert_eq!(s[3], "Trailing");
    }

    #[test]
    fn no_quantities_in_plain_prose() {
        let lex = english();
        let q = extract_quantities(
            &sents(&["Helena paused at the threshold, listening."]),
            &lex,
        );
        assert!(q.is_empty());
    }
}