anno-eval 0.8.0

Evaluation harnesses, datasets, and muxer-backed sampling for anno
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
//! Evaluation types: MetricValue, GoalCheckResult, etc.
//!
//! These are shared primitives for evaluation that can be reused
//! across NER evaluation and other evaluation tasks.

use anno::{Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// A type-safe metric value bounded to [0.0, 1.0].
///
/// Ensures metrics like precision, recall, and F1 are always valid.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, PartialOrd)]
#[serde(transparent)]
pub struct MetricValue(f64);

/// A metric with variance and confidence interval.
///
/// Tracks the mean, standard deviation, and 95% confidence interval
/// for a metric computed across multiple samples/runs/datasets.
///
/// # Example
///
/// ```rust
/// use anno::eval::MetricWithVariance;
///
/// let metric = MetricWithVariance::from_samples(&[0.85, 0.87, 0.82, 0.88, 0.84]);
/// println!("F1: {:.1}% ± {:.1}% (95% CI)", metric.mean * 100.0, metric.ci_95 * 100.0);
/// // F1: 85.2% ± 2.1% (95% CI)
/// ```
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
pub struct MetricWithVariance {
    /// Mean value of the metric
    pub mean: f64,
    /// Standard deviation
    pub std_dev: f64,
    /// 95% confidence interval (±)
    pub ci_95: f64,
    /// Minimum observed value
    pub min: f64,
    /// Maximum observed value
    pub max: f64,
    /// Number of samples
    pub n: usize,
}

impl MetricWithVariance {
    /// Create from a slice of sample values.
    ///
    /// Uses sample standard deviation (Bessel's correction) and
    /// t-distribution approximation for 95% CI.
    pub fn from_samples(samples: &[f64]) -> Self {
        if samples.is_empty() {
            return Self {
                mean: 0.0,
                std_dev: 0.0,
                ci_95: 0.0,
                min: 0.0,
                max: 0.0,
                n: 0,
            };
        }

        let n = samples.len();
        let mean = samples.iter().sum::<f64>() / n as f64;
        let min = samples.iter().cloned().fold(f64::INFINITY, f64::min);
        let max = samples.iter().cloned().fold(f64::NEG_INFINITY, f64::max);

        let std_dev = if n > 1 {
            let variance = samples.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64;
            variance.sqrt()
        } else {
            0.0
        };

        // 95% CI using t-distribution approximation
        // For n >= 30, use z = 1.96; otherwise approximate with t
        let t_value = if n >= 30 {
            1.96
        } else {
            // Conservative t-value approximation for smaller samples
            2.0 + 0.1 / (n as f64).sqrt()
        };
        let ci_95 = if n > 1 {
            t_value * std_dev / (n as f64).sqrt()
        } else {
            0.0
        };

        Self {
            mean,
            std_dev,
            ci_95,
            min,
            max,
            n,
        }
    }

    /// Format as "mean ± ci95" string.
    pub fn format_with_ci(&self) -> String {
        if self.n == 0 {
            return "N/A".to_string();
        }
        format!("{:.1}% ± {:.1}%", self.mean * 100.0, self.ci_95 * 100.0)
    }

    /// Format as "mean (min-max)" string.
    pub fn format_with_range(&self) -> String {
        if self.n == 0 {
            return "N/A".to_string();
        }
        format!(
            "{:.1}% ({:.1}%-{:.1}%)",
            self.mean * 100.0,
            self.min * 100.0,
            self.max * 100.0
        )
    }

    /// Get coefficient of variation (CV = std_dev / mean).
    pub fn coefficient_of_variation(&self) -> f64 {
        if self.mean.abs() < 1e-10 {
            0.0
        } else {
            self.std_dev / self.mean
        }
    }
}

impl Default for MetricWithVariance {
    fn default() -> Self {
        Self {
            mean: 0.0,
            std_dev: 0.0,
            ci_95: 0.0,
            min: 0.0,
            max: 0.0,
            n: 0,
        }
    }
}

impl std::fmt::Display for MetricWithVariance {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.format_with_ci())
    }
}

impl MetricValue {
    /// Create a new MetricValue, clamping to [0.0, 1.0].
    ///
    /// # Example
    /// ```
    /// use anno::eval::MetricValue;
    /// let v = MetricValue::new(0.95);
    /// assert!((v.get() - 0.95).abs() < 1e-6);
    /// ```
    pub fn new(value: f64) -> Self {
        MetricValue(value.clamp(0.0, 1.0))
    }

    /// Try to create a MetricValue, returning error if out of bounds.
    pub fn try_new(value: f64) -> Result<Self> {
        if !(0.0..=1.0).contains(&value) {
            return Err(Error::InvalidInput(format!(
                "MetricValue must be in [0.0, 1.0], got {}",
                value
            )));
        }
        Ok(MetricValue(value))
    }

    /// Get the underlying value.
    #[inline]
    pub fn get(&self) -> f64 {
        self.0
    }
}

impl Default for MetricValue {
    fn default() -> Self {
        MetricValue(0.0)
    }
}

impl std::fmt::Display for MetricValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:.4}", self.0)
    }
}

impl From<f64> for MetricValue {
    fn from(value: f64) -> Self {
        MetricValue::new(value)
    }
}

/// Result of checking evaluation goals.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct GoalCheckResult {
    /// Whether all goals were met.
    pub passed: bool,
    /// Individual goal check results.
    pub checks: HashMap<String, GoalCheck>,
    /// Summary message.
    pub summary: Option<String>,
}

impl GoalCheckResult {
    /// Create a new GoalCheckResult (defaults to passed = true).
    #[must_use]
    pub fn new() -> Self {
        Self {
            passed: true,
            checks: HashMap::new(),
            summary: None,
        }
    }

    /// Add a goal check result.
    pub fn add_check(&mut self, name: impl Into<String>, check: GoalCheck) {
        if !check.passed {
            self.passed = false;
        }
        self.checks.insert(name.into(), check);
    }

    /// Add a failure (convenience method for add_check with fail).
    pub fn add_failure(&mut self, name: impl Into<String>, actual: f64, threshold: f64) {
        self.add_check(name, GoalCheck::fail(threshold, actual));
    }

    /// Add a success (convenience method for add_check with pass).
    pub fn add_success(&mut self, name: impl Into<String>, actual: f64, threshold: f64) {
        self.add_check(name, GoalCheck::pass(threshold, actual));
    }

    /// Get number of passed checks.
    pub fn passed_count(&self) -> usize {
        self.checks.values().filter(|c| c.passed).count()
    }

    /// Get number of failed checks.
    pub fn failed_count(&self) -> usize {
        self.checks.values().filter(|c| !c.passed).count()
    }
}

/// Individual goal check.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GoalCheck {
    /// Whether this goal was met.
    pub passed: bool,
    /// Expected threshold.
    pub threshold: f64,
    /// Actual value achieved.
    pub actual: f64,
    /// Optional message.
    pub message: Option<String>,
}

impl GoalCheck {
    /// Create a new goal check.
    pub fn new(passed: bool, threshold: f64, actual: f64) -> Self {
        Self {
            passed,
            threshold,
            actual,
            message: None,
        }
    }

    /// Create a passing check.
    pub fn pass(threshold: f64, actual: f64) -> Self {
        Self::new(true, threshold, actual)
    }

    /// Create a failing check.
    pub fn fail(threshold: f64, actual: f64) -> Self {
        Self::new(false, threshold, actual)
    }

    /// Add a message to the check.
    #[must_use]
    pub fn with_message(mut self, msg: impl Into<String>) -> Self {
        self.message = Some(msg.into());
        self
    }
}

// =============================================================================
// Label Shift Quantification (Familiarity-inspired)
// =============================================================================

/// Label shift between training and evaluation entity types.
///
/// # Why This Matters
///
/// Imagine you trained a model on `{PER, ORG, LOC}` and then evaluate on
/// `{PERSON, COMPANY, CITY}`. Is that zero-shot? Technically yes (new labels).
/// Practically no (same concepts).
///
/// ```text
/// ┌─────────────────────────────────────────────────────────────────────────┐
/// │                    THE LABEL SHIFT PROBLEM                              │
/// ├─────────────────────────────────────────────────────────────────────────┤
/// │                                                                         │
/// │  TRAINING LABELS           EVAL LABELS         ARE THEY THE SAME?       │
/// │  ───────────────           ───────────         ──────────────────       │
/// │                                                                         │
/// │  PER ───────────────────── PERSON             ✓ Obviously (renamed)     │
/// │  ORG ───────────────────── COMPANY            ✓ Subset relationship     │
/// │  LOC ───────────────────── CITY               ✓ Subset relationship     │
/// │                                                                         │
/// │  ??? ←─────────────────── DISEASE            ✗ TRUE ZERO-SHOT!         │
/// │  ??? ←─────────────────── DRUG               ✗ TRUE ZERO-SHOT!         │
/// │                                                                         │
/// │  If 80% of eval types have training equivalents, your F1 is inflated.   │
/// └─────────────────────────────────────────────────────────────────────────┘
/// ```
///
/// # Embedding Space View
///
/// Labels that seem different can be close in embedding space:
///
/// ```text
///                    EMBEDDING SPACE (2D projection)
///                    ───────────────────────────────
///
///            PER ●───────────────● PERSON
//////                 very close in
///                embedding space
///
///            ORG ●─────● COMPANY
///
///            LOC ●─────────● CITY
///
///
///                                        ● DISEASE    ← Far from all
///                                                       training types!
///                                        ● DRUG       ← This is TRUE
///                                                       zero-shot.
///
/// F1 on {PERSON, COMPANY, CITY}:  85%  (but model "knew" these)
/// F1 on {DISEASE, DRUG}:          45%  (honest zero-shot)
/// ```
///
/// # Research Context (arXiv:2412.10121 "Familiarity")
///
/// Key findings from Golde et al. (2024):
/// - 80%+ label overlap in NuNER/PileNER → inflated F1 scores
/// - True zero-shot: evaluate only on types NOT in training
/// - Familiarity = semantic similarity × frequency weighting
///
/// # Example
///
/// ```rust
/// use anno::eval::LabelShift;
///
/// let shift = LabelShift {
///     overlap_ratio: 0.85,    // 85% of eval types in train
///     familiarity: 0.72,      // Semantic similarity score
///     true_zero_shot_types: vec!["DISEASE".into(), "DRUG".into()],
///     transfer_difficulty: "low".into(),
/// };
///
/// // High overlap = easy transfer, but NOT true zero-shot
/// assert!(shift.is_inflated());
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LabelShift {
    /// Fraction of eval types found in training data (exact string match).
    pub overlap_ratio: f64,

    /// Familiarity score: semantic similarity weighted by frequency.
    /// Range: [0, 1]. Higher = more similar training/eval types.
    pub familiarity: f64,

    /// Entity types in eval NOT present in training (true zero-shot).
    pub true_zero_shot_types: Vec<String>,

    /// Qualitative difficulty: "low", "medium", "high".
    pub transfer_difficulty: String,
}

impl LabelShift {
    /// Check if F1 scores are likely inflated due to high label overlap.
    ///
    /// Threshold from Familiarity paper: >0.8 overlap is concernoing.
    #[must_use]
    pub fn is_inflated(&self) -> bool {
        self.overlap_ratio > 0.8 || self.familiarity > 0.85
    }

    /// Get count of true zero-shot types.
    #[must_use]
    pub fn true_zero_shot_count(&self) -> usize {
        self.true_zero_shot_types.len()
    }

    /// Compute label shift from training and eval type sets.
    ///
    /// # Arguments
    /// * `train_types` - Entity types seen during training
    /// * `eval_types` - Entity types in evaluation benchmark
    ///
    /// # Note
    ///
    /// This computes both string-match overlap and semantic similarity-based familiarity.
    /// For true semantic similarity, use `from_type_sets_with_embeddings()` if embeddings are available.
    /// See arXiv:2412.10121 for details.
    #[must_use]
    pub fn from_type_sets(train_types: &[String], eval_types: &[String]) -> Self {
        let train_set: std::collections::HashSet<_> = train_types.iter().collect();
        let eval_set: std::collections::HashSet<_> = eval_types.iter().collect();

        // Exact match overlap
        let overlap_count = eval_set.intersection(&train_set).count();
        let overlap_ratio = if eval_types.is_empty() {
            0.0
        } else {
            overlap_count as f64 / eval_types.len() as f64
        };

        // True zero-shot = eval types NOT in training
        let true_zero_shot_types: Vec<String> = eval_set
            .difference(&train_set)
            .map(|s| (*s).clone())
            .collect();

        // Compute familiarity using string similarity (improved heuristic)
        // This is better than just overlap_ratio but still not true semantic similarity
        let familiarity = compute_string_based_familiarity(train_types, eval_types);

        let transfer_difficulty = if overlap_ratio > 0.8 || familiarity > 0.85 {
            "low"
        } else if overlap_ratio > 0.4 || familiarity > 0.5 {
            "medium"
        } else {
            "high"
        }
        .to_string();

        Self {
            overlap_ratio,
            familiarity,
            true_zero_shot_types,
            transfer_difficulty,
        }
    }

    /// Compute label shift with embedding-based familiarity.
    ///
    /// # Arguments
    /// * `train_types` - Entity types seen during training
    /// * `eval_types` - Entity types in evaluation benchmark
    /// * `embedding_fn` - Function that computes embedding for a label name
    ///
    /// # Note
    ///
    /// This computes true semantic similarity using embeddings, as recommended
    /// in the Familiarity paper (arXiv:2412.10121). Familiarity = semantic similarity × frequency weighting.
    ///
    /// The embedding function should return a normalized vector (unit length) for cosine similarity.
    #[must_use]
    pub fn from_type_sets_with_embeddings<F>(
        train_types: &[String],
        eval_types: &[String],
        embedding_fn: F,
    ) -> Self
    where
        F: Fn(&str) -> Option<Vec<f32>>,
    {
        let mut result = Self::from_type_sets(train_types, eval_types);

        // Compute embedding-based familiarity
        if let Some(familiarity) =
            compute_embedding_based_familiarity(train_types, eval_types, &embedding_fn)
        {
            result.familiarity = familiarity;
        }

        result
    }
}

impl std::fmt::Display for LabelShift {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "LabelShift(overlap={:.0}%, familiarity={:.2}, zero-shot={}, difficulty={})",
            self.overlap_ratio * 100.0,
            self.familiarity,
            self.true_zero_shot_types.len(),
            self.transfer_difficulty
        )
    }
}

// =============================================================================
// Coreference Chain Statistics (arXiv:2401.00238 inspired)
// =============================================================================

/// Statistics for stratified coreference evaluation.
///
/// # Why Chain Length Matters: A Narrative
///
/// Imagine analyzing "Pride and Prejudice":
///
/// ```text
/// ┌─────────────────────────────────────────────────────────────────────────┐
/// │                    COREFERENCE IN A NOVEL                               │
/// ├─────────────────────────────────────────────────────────────────────────┤
/// │                                                                         │
/// │  LONG CHAINS (>10 mentions) - THE PROTAGONISTS                          │
/// │  ─────────────────────────────────────────────                          │
/// │                                                                         │
/// │  "Elizabeth" ─── "she" ─── "Lizzy" ─── "her" ─── "Miss Bennet" ───...  │
/// │       │            │          │          │            │                 │
/// │       └────────────┴──────────┴──────────┴────────────┘                 │
/// │                         800+ mentions                                   │
/// │                                                                         │
/// │  Getting these right = understanding the PLOT.                          │
/// │  Who did what to whom? What's Elizabeth's arc?                          │
/// │                                                                         │
/// │  SHORT CHAINS (2-10 mentions) - SECONDARY CHARACTERS                    │
/// │  ───────────────────────────────────────────────────                    │
/// │                                                                         │
/// │  "Mr. Collins" ─── "he" ─── "the clergyman"                             │
/// │       │              │             │                                    │
/// │       └──────────────┴─────────────┘                                    │
/// │                  15 mentions                                            │
/// │                                                                         │
/// │  Important for context, but errors here are less catastrophic.          │
/// │                                                                         │
/// │  SINGLETONS (1 mention) - BACKGROUND                                    │
/// │  ───────────────────────────────────────                                │
/// │                                                                         │
/// │  "a tall man" ─── (no other mentions)                                   │
/// │  "the servant" ─── (no other mentions)                                  │
/// │                                                                         │
/// │  These are closer to entity detection than coreference.                  │
/// │  Including them in CoNLL F1 can change the interpretation of the score.  │
/// └─────────────────────────────────────────────────────────────────────────┘
/// ```
///
/// # The Problem with Averaged Metrics
///
/// ```text
/// Model Performance:
///
/// A single averaged metric can hide systematic differences across chain sizes.
/// Prefer reporting stratified metrics by chain length (and be explicit about
/// whether singletons are included).
/// ```
///
/// # Research Context (arXiv:2401.00238)
///
/// "How to Evaluate Coreference in Literary Texts?"
/// - A single CoNLL F1 score is "uninformative, or even misleading."
/// - Stratify by chain length for interpretable results.
///
/// # Example
///
/// ```rust
/// use anno::eval::CorefChainStats;
///
/// let stats = CorefChainStats {
///     long_chain_count: 3,      // Main characters
///     short_chain_count: 15,    // Secondary
///     singleton_count: 42,      // Isolated
///     long_chain_f1: 0.92,      // Good on main characters
///     short_chain_f1: 0.71,     // Weaker on secondary
///     singleton_f1: 0.45,       // Poor on singletons
/// };
///
/// // Report metrics separately, not averaged
/// println!("Main characters: {:.1}% F1", stats.long_chain_f1 * 100.0);
/// ```
pub use anno_metrics::types::CorefChainStats;

// =============================================================================
// Document Scale Classification (Bourgois & Poibeau 2025)
// =============================================================================

/// Document scale classification based on token count.
///
/// # Research Context (Bourgois & Poibeau 2025, arXiv:2510.15594)
///
/// The paper shows that coreference performance degrades significantly with
/// document length. These thresholds are informed by their analysis:
///
/// ```text
/// Scale           Token Range     Performance Impact
/// ─────────────────────────────────────────────────────
/// Short           <2k             Baseline (OntoNotes-like)
/// Medium          2k-10k          -5% CoNLL F1
/// Long            10k-50k         -10% CoNLL F1
/// BookScale       >50k            -15% CoNLL F1, metrics unreliable
/// ```
///
/// # Example
///
/// ```rust
/// use anno::eval::DocumentScale;
///
/// let scale = DocumentScale::from_tokens(95_000);
/// assert!(scale.is_book_scale());
/// assert!(scale.metrics_may_be_unreliable());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum DocumentScale {
    /// Short document (<2k tokens). OntoNotes-like scale.
    #[default]
    Short,
    /// Medium document (2k-10k tokens). Slight performance drop.
    Medium,
    /// Long document (10k-50k tokens). Noticeable degradation.
    Long,
    /// Book-scale document (>50k tokens). Metrics may be unreliable.
    BookScale,
}

impl DocumentScale {
    /// Classify document scale from token count.
    #[must_use]
    pub fn from_tokens(token_count: usize) -> Self {
        match token_count {
            0..=2000 => Self::Short,
            2001..=10000 => Self::Medium,
            10001..=50000 => Self::Long,
            _ => Self::BookScale,
        }
    }

    /// Check if this is book-scale (>50k tokens).
    #[must_use]
    pub fn is_book_scale(&self) -> bool {
        matches!(self, Self::BookScale)
    }

    /// Check if coreference metrics may be unreliable at this scale.
    ///
    /// At book scale, MUC tends to inflate while CEAF-e tends to collapse.
    #[must_use]
    pub fn metrics_may_be_unreliable(&self) -> bool {
        matches!(self, Self::Long | Self::BookScale)
    }

    /// Get expected CoNLL F1 degradation relative to short documents.
    #[must_use]
    pub fn expected_degradation(&self) -> f64 {
        match self {
            Self::Short => 0.0,
            Self::Medium => 0.05,
            Self::Long => 0.10,
            Self::BookScale => 0.15,
        }
    }
}

impl std::fmt::Display for DocumentScale {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Short => write!(f, "Short (<2k tokens)"),
            Self::Medium => write!(f, "Medium (2k-10k tokens)"),
            Self::Long => write!(f, "Long (10k-50k tokens)"),
            Self::BookScale => write!(f, "Book-scale (>50k tokens)"),
        }
    }
}

// =============================================================================
// Metric Divergence (Book-scale Coreference Analysis)
// =============================================================================

/// Divergence between coreference metrics.
///
/// # Research Context
///
/// At book scale, different metrics diverge significantly:
/// - MUC tends to be inflated (favors link-based evaluation)
/// - CEAF-e tends to collapse (entity alignment struggles)
/// - B³ falls between but is more stable
///
/// Large divergence (>0.20) indicates potential metric unreliability.
///
/// # Example
///
/// ```rust
/// use anno::eval::MetricDivergence;
///
/// let divergence = MetricDivergence::from_scores(0.90, 0.65, 0.45);
/// assert!(divergence.has_high_divergence());
/// println!("MUC-CEAF divergence: {:.0}%", divergence.muc_ceaf_divergence * 100.0);
/// ```
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
pub struct MetricDivergence {
    /// MUC F1 score.
    pub muc_f1: f64,
    /// B³ F1 score.
    pub b3_f1: f64,
    /// CEAF-e F1 score.
    pub ceaf_e_f1: f64,
    /// Divergence between MUC and CEAF-e (absolute difference).
    pub muc_ceaf_divergence: f64,
    /// Divergence between MUC and B³.
    pub muc_b3_divergence: f64,
    /// Divergence between B³ and CEAF-e.
    pub b3_ceaf_divergence: f64,
}

impl MetricDivergence {
    /// Compute divergence from raw scores.
    #[must_use]
    pub fn from_scores(muc_f1: f64, b3_f1: f64, ceaf_e_f1: f64) -> Self {
        Self {
            muc_f1,
            b3_f1,
            ceaf_e_f1,
            muc_ceaf_divergence: (muc_f1 - ceaf_e_f1).abs(),
            muc_b3_divergence: (muc_f1 - b3_f1).abs(),
            b3_ceaf_divergence: (b3_f1 - ceaf_e_f1).abs(),
        }
    }

    /// Check if divergence is high (>0.20), indicating unreliable metrics.
    #[must_use]
    pub fn has_high_divergence(&self) -> bool {
        self.muc_ceaf_divergence > 0.20
    }

    /// Check if MUC is likely inflated (MUC >> CEAF-e).
    #[must_use]
    pub fn muc_likely_inflated(&self) -> bool {
        self.muc_f1 > self.ceaf_e_f1 + 0.15
    }

    /// Check if CEAF-e is likely collapsed (CEAF-e << others).
    #[must_use]
    pub fn ceaf_likely_collapsed(&self) -> bool {
        self.ceaf_e_f1 < self.b3_f1 - 0.15 && self.ceaf_e_f1 < self.muc_f1 - 0.20
    }

    /// Get most reliable metric recommendation.
    #[must_use]
    pub fn most_reliable_metric(&self) -> &'static str {
        if self.muc_likely_inflated() && self.ceaf_likely_collapsed() {
            "B³ (MUC inflated, CEAF-e collapsed)"
        } else if self.muc_likely_inflated() {
            "B³ or CEAF-e (MUC inflated)"
        } else if self.ceaf_likely_collapsed() {
            "MUC or B³ (CEAF-e collapsed)"
        } else {
            "CoNLL F1 (metrics agree)"
        }
    }
}

// =============================================================================
// Document Statistics for Coreference (Entity Spread)
// =============================================================================

/// Document-level statistics for coreference evaluation.
///
/// # Research Context (Bourgois & Poibeau 2025)
///
/// The paper introduces "entity spread" as a key metric:
/// > "The entity spread refers to the distance between the first and the last
/// > mention of an entity."
///
/// Their Long-LitBank-fr corpus shows:
/// - Average entity spread: 17,529 tokens
/// - Maximum entity spread: 115,369 tokens (spanning entire novels)
///
/// This metric characterizes the difficulty of coreference:
/// high spread = mentions far apart = harder to resolve.
///
/// # Example
///
/// ```rust
/// use anno::eval::{CorefDocStats, coref::CorefChain};
///
/// // Create from chains (would use actual chains in practice)
/// let stats = CorefDocStats {
///     chain_count: 159,
///     mention_count: 13178,
///     avg_chain_length: 82.9,
///     avg_entity_spread: 17529,
///     max_entity_spread: 115369,
///     ..Default::default()
/// };
///
/// println!("Avg entity spread: {} tokens", stats.avg_entity_spread);
/// ```
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
pub struct CorefDocStats {
    /// Document length in tokens (approximate).
    pub doc_length: usize,
    /// Total number of coreference chains.
    pub chain_count: usize,
    /// Total number of mentions.
    pub mention_count: usize,
    /// Average mentions per chain.
    pub avg_chain_length: f64,
    /// Maximum chain length.
    pub max_chain_length: usize,

    // =========================================================================
    // Entity Spread (Bourgois & Poibeau 2025)
    // =========================================================================
    /// Average entity spread in tokens.
    /// Entity spread = distance between first and last mention of an entity.
    pub avg_entity_spread: usize,

    /// Maximum entity spread in tokens.
    /// For protagonists in novels, this can exceed 100k tokens.
    pub max_entity_spread: usize,

    /// Median entity spread in tokens.
    pub median_entity_spread: usize,

    // =========================================================================
    // Mention Type Distribution
    // =========================================================================
    /// Proportion of pronominal mentions.
    pub pronoun_ratio: f64,
    /// Proportion of proper noun mentions.
    pub proper_ratio: f64,
    /// Proportion of nominal mentions.
    pub nominal_ratio: f64,
    /// Proportion of singleton chains.
    pub singleton_ratio: f64,
}

impl CorefDocStats {
    /// Compute statistics from coreference chains.
    ///
    /// Chains should have mentions with character offsets.
    /// Use `doc_length` to set the token count separately.
    #[must_use]
    pub fn from_chains(chains: &[crate::eval::coref::CorefChain]) -> Self {
        if chains.is_empty() {
            return Self::default();
        }

        let chain_count = chains.len();
        let mention_count: usize = chains.iter().map(|c| c.mentions.len()).sum();
        let avg_chain_length = mention_count as f64 / chain_count as f64;
        let max_chain_length = chains.iter().map(|c| c.mentions.len()).max().unwrap_or(0);

        // Count singletons
        let singleton_count = chains.iter().filter(|c| c.mentions.len() == 1).count();
        let singleton_ratio = singleton_count as f64 / chain_count as f64;

        // Compute entity spread for each chain
        let mut spreads: Vec<usize> = Vec::with_capacity(chain_count);
        for chain in chains {
            if chain.mentions.len() <= 1 {
                spreads.push(0);
                continue;
            }

            let first_start = chain.mentions.iter().map(|m| m.start).min().unwrap_or(0);
            let last_end = chain.mentions.iter().map(|m| m.end).max().unwrap_or(0);
            let spread = last_end.saturating_sub(first_start);
            spreads.push(spread);
        }

        let avg_entity_spread = if !spreads.is_empty() {
            spreads.iter().sum::<usize>() / spreads.len()
        } else {
            0
        };

        let max_entity_spread = spreads.iter().copied().max().unwrap_or(0);

        // Compute median spread
        spreads.sort_unstable();
        let median_entity_spread = if spreads.is_empty() {
            0
        } else {
            spreads[spreads.len() / 2]
        };

        // Compute mention type ratios (approximate from text patterns)
        // This is a heuristic; proper classification requires POS tagging
        let mut pronoun_count = 0usize;
        let mut proper_count = 0usize;
        let mut nominal_count = 0usize;

        for chain in chains {
            for mention in &chain.mentions {
                let text_lower = mention.text.to_lowercase();
                let is_pronoun = matches!(
                    text_lower.as_str(),
                    "he" | "she"
                        | "it"
                        | "they"
                        | "him"
                        | "her"
                        | "them"
                        | "his"
                        | "hers"
                        | "its"
                        | "their"
                        | "i"
                        | "me"
                        | "we"
                        | "us"
                        | "you"
                );

                if is_pronoun {
                    pronoun_count += 1;
                } else if mention
                    .text
                    .chars()
                    .next()
                    .is_some_and(|c| c.is_uppercase())
                {
                    proper_count += 1;
                } else {
                    nominal_count += 1;
                }
            }
        }

        let total_mentions = mention_count.max(1) as f64;
        let pronoun_ratio = pronoun_count as f64 / total_mentions;
        let proper_ratio = proper_count as f64 / total_mentions;
        let nominal_ratio = nominal_count as f64 / total_mentions;

        Self {
            doc_length: 0, // Must be set separately
            chain_count,
            mention_count,
            avg_chain_length,
            max_chain_length,
            avg_entity_spread,
            max_entity_spread,
            median_entity_spread,
            pronoun_ratio,
            proper_ratio,
            nominal_ratio,
            singleton_ratio,
        }
    }

    /// Get document scale classification.
    #[must_use]
    pub fn scale_classification(&self) -> DocumentScale {
        DocumentScale::from_tokens(self.doc_length)
    }

    /// Check if entity spread suggests book-scale complexity.
    ///
    /// Book-scale documents typically have entities spanning >10k tokens.
    #[must_use]
    pub fn has_book_scale_spread(&self) -> bool {
        self.avg_entity_spread > 5000 || self.max_entity_spread > 20000
    }

    /// Format as summary string.
    #[must_use]
    pub fn format_summary(&self) -> String {
        format!(
            "Chains: {}, Mentions: {}, Avg length: {:.1}, Spread: avg={} max={}",
            self.chain_count,
            self.mention_count,
            self.avg_chain_length,
            self.avg_entity_spread,
            self.max_entity_spread,
        )
    }
}

/// Compute string-based familiarity using normalized edit distance and substring matching.
///
/// This is an improved heuristic over simple overlap ratio, but still not true semantic similarity.
fn compute_string_based_familiarity(train_types: &[String], eval_types: &[String]) -> f64 {
    if eval_types.is_empty() {
        return 0.0;
    }

    let mut total_similarity = 0.0;
    let mut counts = std::collections::HashMap::<String, usize>::new();

    // Count frequency of each eval type (for weighting)
    for eval_type in eval_types {
        *counts.entry(eval_type.clone()).or_insert(0) += 1;
    }

    let total_eval_count = eval_types.len() as f64;

    for (eval_type, freq) in counts {
        let max_sim = train_types
            .iter()
            .map(|train_type| string_similarity(&eval_type, train_type))
            .fold(0.0, f64::max);

        // Weight by frequency (as in Familiarity paper)
        let weight = freq as f64 / total_eval_count;
        total_similarity += max_sim * weight;
    }

    total_similarity
}

/// Compute embedding-based familiarity (semantic similarity × frequency weighting).
///
/// Returns None if embeddings cannot be computed for any type.
fn compute_embedding_based_familiarity<F>(
    train_types: &[String],
    eval_types: &[String],
    embedding_fn: &F,
) -> Option<f64>
where
    F: Fn(&str) -> Option<Vec<f32>>,
{
    if eval_types.is_empty() {
        return Some(0.0);
    }

    // Compute embeddings for all types
    let train_embeddings: Vec<(String, Vec<f32>)> = train_types
        .iter()
        .filter_map(|t| embedding_fn(t).map(|e| (t.clone(), e)))
        .collect();

    if train_embeddings.is_empty() {
        return None; // Can't compute without train embeddings
    }

    let mut counts = std::collections::HashMap::<String, usize>::new();
    for eval_type in eval_types {
        *counts.entry(eval_type.clone()).or_insert(0) += 1;
    }

    let total_eval_count = eval_types.len() as f64;
    let mut total_similarity = 0.0;

    for (eval_type, freq) in counts {
        if let Some(eval_emb) = embedding_fn(&eval_type) {
            // Find maximum cosine similarity with any training type
            let max_sim = train_embeddings
                .iter()
                .map(|(_, train_emb)| cosine_similarity(&eval_emb, train_emb))
                .fold(0.0, f64::max);

            // Weight by frequency
            let weight = freq as f64 / total_eval_count;
            total_similarity += max_sim * weight;
        } else {
            // If we can't embed this type, fall back to string similarity
            let max_sim = train_types
                .iter()
                .map(|train_type| string_similarity(&eval_type, train_type))
                .fold(0.0, f64::max);
            let weight = freq as f64 / total_eval_count;
            total_similarity += max_sim * weight;
        }
    }

    Some(total_similarity)
}

/// Compute cosine similarity between two normalized vectors.
fn cosine_similarity(a: &[f32], b: &[f32]) -> f64 {
    if a.len() != b.len() {
        return 0.0;
    }
    let dot_product: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
    dot_product as f64
}

/// Compute string similarity using normalized edit distance and substring matching.
///
/// Returns a value in [0, 1] where 1.0 = identical strings.
fn string_similarity(a: &str, b: &str) -> f64 {
    let a_lower = a.to_lowercase();
    let b_lower = b.to_lowercase();

    // Exact match
    if a_lower == b_lower {
        return 1.0;
    }

    // Substring match (e.g., "PERSON" contains "PER")
    if a_lower.contains(&b_lower) || b_lower.contains(&a_lower) {
        return 0.8;
    }

    // Normalized edit distance (Levenshtein)
    let max_len = a_lower.len().max(b_lower.len());
    if max_len == 0 {
        return 1.0;
    }

    let distance = levenshtein_distance(&a_lower, &b_lower);
    1.0 - (distance as f64 / max_len as f64)
}

/// Compute Levenshtein distance between two strings.
///
/// Delegates to `anno::edit_distance::levenshtein` (single-row optimized,
/// Unicode-correct implementation).
fn levenshtein_distance(a: &str, b: &str) -> usize {
    anno::edit_distance::levenshtein(a, b)
}

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

    #[test]
    fn test_familiarity_computation() {
        let train_types = vec![
            "person".to_string(),
            "organization".to_string(),
            "location".to_string(),
        ];

        let eval_types = vec![
            "PERSON".to_string(),  // Should match "person" via similarity (not zero-shot)
            "ORG".to_string(),     // Should match "organization" via similarity (not zero-shot)
            "DISEASE".to_string(), // True zero-shot (no similarity)
        ];

        let shift = LabelShift::from_type_sets(&train_types, &eval_types);

        // Should detect similarity even without exact match
        assert!(shift.familiarity > 0.0, "Should have non-zero familiarity");
        // Note: String similarity may match PERSON->person and ORG->organization,
        // so true_zero_shot_types may only contain DISEASE, or all three if similarity
        // threshold is low. The important thing is familiarity > 0.
        assert!(
            !shift.true_zero_shot_types.is_empty(),
            "Should have at least 1 true zero-shot type"
        );
        assert!(shift.true_zero_shot_types.contains(&"DISEASE".to_string()));
    }

    #[test]
    fn test_familiarity_inflation_detection() {
        let train_types = vec![
            "person".to_string(),
            "organization".to_string(),
            "location".to_string(),
        ];

        let eval_types = vec![
            "PERSON".to_string(),
            "ORGANIZATION".to_string(),
            "LOCATION".to_string(),
        ];

        let shift = LabelShift::from_type_sets(&train_types, &eval_types);

        // High similarity should trigger high familiarity
        assert!(shift.familiarity > 0.5, "Should have high familiarity");
    }

    #[test]
    fn test_label_shift_zero_shot_types() {
        let train_types = vec!["person".to_string()];
        let eval_types = vec![
            "person".to_string(),
            "disease".to_string(),
            "drug".to_string(),
        ];

        let shift = LabelShift::from_type_sets(&train_types, &eval_types);

        assert_eq!(shift.true_zero_shot_types.len(), 2);
        assert!(shift.true_zero_shot_types.contains(&"disease".to_string()));
        assert!(shift.true_zero_shot_types.contains(&"drug".to_string()));
    }

    #[test]
    fn test_metric_value_clamping() {
        assert_eq!(MetricValue::new(0.5).get(), 0.5);
        assert_eq!(MetricValue::new(-0.5).get(), 0.0);
        assert_eq!(MetricValue::new(1.5).get(), 1.0);
    }

    #[test]
    fn test_metric_value_try_new() {
        assert!(MetricValue::try_new(0.5).is_ok());
        assert!(MetricValue::try_new(-0.1).is_err());
        assert!(MetricValue::try_new(1.1).is_err());
    }

    #[test]
    fn test_goal_check_result() {
        let mut result = GoalCheckResult::new();
        assert!(result.passed);

        result.add_check("precision", GoalCheck::pass(0.8, 0.85));
        assert!(result.passed);

        result.add_check("recall", GoalCheck::fail(0.9, 0.75));
        assert!(!result.passed);

        assert_eq!(result.passed_count(), 1);
        assert_eq!(result.failed_count(), 1);
    }

    #[test]
    fn test_metric_with_variance_from_samples() {
        let samples = vec![0.85, 0.87, 0.82, 0.88, 0.84];
        let m = MetricWithVariance::from_samples(&samples);

        // Mean should be 0.852
        assert!((m.mean - 0.852).abs() < 0.001);
        assert_eq!(m.n, 5);
        assert!((m.min - 0.82).abs() < 0.001);
        assert!((m.max - 0.88).abs() < 0.001);
        assert!(m.std_dev > 0.0);
        assert!(m.ci_95 > 0.0);
    }

    #[test]
    fn test_metric_with_variance_empty() {
        let m = MetricWithVariance::from_samples(&[]);
        assert_eq!(m.n, 0);
        assert_eq!(m.mean, 0.0);
        assert_eq!(m.format_with_ci(), "N/A");
    }

    #[test]
    fn test_metric_with_variance_single() {
        let m = MetricWithVariance::from_samples(&[0.9]);
        assert!((m.mean - 0.9).abs() < 0.001);
        assert_eq!(m.std_dev, 0.0);
        assert_eq!(m.ci_95, 0.0);
        assert_eq!(m.n, 1);
    }

    #[test]
    fn test_metric_with_variance_format() {
        let samples = vec![0.85, 0.87, 0.82, 0.88, 0.84];
        let m = MetricWithVariance::from_samples(&samples);

        // Should format nicely
        let formatted = m.format_with_ci();
        assert!(formatted.contains("%"));
        assert!(formatted.contains("±"));

        let range = m.format_with_range();
        assert!(range.contains("82.0%"));
        assert!(range.contains("88.0%"));
    }

    // =========================================================================
    // Tests for DocumentScale (Bourgois & Poibeau 2025)
    // =========================================================================

    #[test]
    fn test_document_scale_classification() {
        // Short documents (<2k tokens)
        assert_eq!(DocumentScale::from_tokens(500), DocumentScale::Short);
        assert_eq!(DocumentScale::from_tokens(2000), DocumentScale::Short);

        // Medium documents (2k-10k tokens)
        assert_eq!(DocumentScale::from_tokens(2001), DocumentScale::Medium);
        assert_eq!(DocumentScale::from_tokens(5000), DocumentScale::Medium);
        assert_eq!(DocumentScale::from_tokens(10000), DocumentScale::Medium);

        // Long documents (10k-50k tokens)
        assert_eq!(DocumentScale::from_tokens(10001), DocumentScale::Long);
        assert_eq!(DocumentScale::from_tokens(30000), DocumentScale::Long);
        assert_eq!(DocumentScale::from_tokens(50000), DocumentScale::Long);

        // Book-scale documents (>50k tokens)
        assert_eq!(DocumentScale::from_tokens(50001), DocumentScale::BookScale);
        assert_eq!(DocumentScale::from_tokens(100000), DocumentScale::BookScale);
    }

    #[test]
    fn test_document_scale_is_book_scale() {
        assert!(!DocumentScale::Short.is_book_scale());
        assert!(!DocumentScale::Medium.is_book_scale());
        assert!(!DocumentScale::Long.is_book_scale());
        assert!(DocumentScale::BookScale.is_book_scale());
    }

    #[test]
    fn test_document_scale_metrics_reliability() {
        assert!(!DocumentScale::Short.metrics_may_be_unreliable());
        assert!(!DocumentScale::Medium.metrics_may_be_unreliable());
        assert!(DocumentScale::Long.metrics_may_be_unreliable());
        assert!(DocumentScale::BookScale.metrics_may_be_unreliable());
    }

    #[test]
    fn test_document_scale_expected_degradation() {
        assert!((DocumentScale::Short.expected_degradation() - 0.0).abs() < 0.001);
        assert!((DocumentScale::Medium.expected_degradation() - 0.05).abs() < 0.001);
        assert!((DocumentScale::Long.expected_degradation() - 0.10).abs() < 0.001);
        assert!((DocumentScale::BookScale.expected_degradation() - 0.15).abs() < 0.001);
    }

    #[test]
    fn test_document_scale_display() {
        assert!(DocumentScale::Short.to_string().contains("Short"));
        assert!(DocumentScale::BookScale.to_string().contains("Book-scale"));
    }

    // =========================================================================
    // Tests for MetricDivergence
    // =========================================================================

    #[test]
    fn test_metric_divergence_computation() {
        // Typical book-scale pattern: high MUC, lower B³, collapsed CEAF-e
        let divergence = MetricDivergence::from_scores(0.90, 0.65, 0.45);

        assert!((divergence.muc_f1 - 0.90).abs() < 0.001);
        assert!((divergence.b3_f1 - 0.65).abs() < 0.001);
        assert!((divergence.ceaf_e_f1 - 0.45).abs() < 0.001);

        // MUC-CEAF divergence should be 0.45
        assert!((divergence.muc_ceaf_divergence - 0.45).abs() < 0.001);
    }

    #[test]
    fn test_metric_divergence_high_divergence_detection() {
        // High divergence (>0.20)
        let high = MetricDivergence::from_scores(0.90, 0.70, 0.50);
        assert!(high.has_high_divergence());

        // Low divergence (<0.20)
        let low = MetricDivergence::from_scores(0.80, 0.75, 0.70);
        assert!(!low.has_high_divergence());
    }

    #[test]
    fn test_metric_divergence_muc_inflation() {
        // MUC inflated (MUC >> CEAF-e by >0.15)
        let inflated = MetricDivergence::from_scores(0.90, 0.70, 0.50);
        assert!(inflated.muc_likely_inflated());

        // MUC not inflated
        let not_inflated = MetricDivergence::from_scores(0.80, 0.75, 0.70);
        assert!(!not_inflated.muc_likely_inflated());
    }

    #[test]
    fn test_metric_divergence_ceaf_collapse() {
        // CEAF-e collapsed (much lower than others)
        let collapsed = MetricDivergence::from_scores(0.90, 0.70, 0.40);
        assert!(collapsed.ceaf_likely_collapsed());

        // CEAF-e not collapsed
        let not_collapsed = MetricDivergence::from_scores(0.80, 0.75, 0.70);
        assert!(!not_collapsed.ceaf_likely_collapsed());
    }

    #[test]
    fn test_metric_divergence_recommendation() {
        // When both MUC inflated and CEAF-e collapsed -> recommend B³
        let both_bad = MetricDivergence::from_scores(0.90, 0.65, 0.40);
        assert!(both_bad.most_reliable_metric().contains(""));

        // When metrics agree -> recommend CoNLL F1
        let agree = MetricDivergence::from_scores(0.75, 0.73, 0.71);
        assert!(agree.most_reliable_metric().contains("CoNLL"));
    }

    // =========================================================================
    // Tests for CorefDocStats (Entity Spread)
    // =========================================================================

    #[test]
    fn test_coref_doc_stats_default() {
        let stats = CorefDocStats::default();
        assert_eq!(stats.chain_count, 0);
        assert_eq!(stats.mention_count, 0);
        assert_eq!(stats.avg_entity_spread, 0);
        assert_eq!(stats.max_entity_spread, 0);
    }

    #[test]
    fn test_coref_doc_stats_scale_classification() {
        let mut stats = CorefDocStats {
            doc_length: 1000,
            ..Default::default()
        };
        assert_eq!(stats.scale_classification(), DocumentScale::Short);

        stats.doc_length = 5000;
        assert_eq!(stats.scale_classification(), DocumentScale::Medium);

        stats.doc_length = 30000;
        assert_eq!(stats.scale_classification(), DocumentScale::Long);

        stats.doc_length = 100000;
        assert_eq!(stats.scale_classification(), DocumentScale::BookScale);
    }

    #[test]
    fn test_coref_doc_stats_book_scale_spread() {
        let mut stats = CorefDocStats {
            avg_entity_spread: 1000,
            max_entity_spread: 5000,
            ..Default::default()
        };

        // Low spread - not book-scale
        assert!(!stats.has_book_scale_spread());

        // High avg spread - book-scale
        stats.avg_entity_spread = 6000;
        stats.max_entity_spread = 10000;
        assert!(stats.has_book_scale_spread());

        // High max spread - book-scale
        stats.avg_entity_spread = 2000;
        stats.max_entity_spread = 25000;
        assert!(stats.has_book_scale_spread());
    }

    #[test]
    fn test_coref_doc_stats_format_summary() {
        let stats = CorefDocStats {
            chain_count: 159,
            mention_count: 13178,
            avg_chain_length: 82.9,
            avg_entity_spread: 17529,
            max_entity_spread: 115369,
            ..Default::default()
        };

        let summary = stats.format_summary();
        assert!(summary.contains("159"));
        assert!(summary.contains("13178"));
        assert!(summary.contains("17529"));
        assert!(summary.contains("115369"));
    }

    #[test]
    fn test_coref_doc_stats_from_chains() {
        use crate::eval::coref::{CorefChain, Mention};

        // Create test chains
        let chains = vec![
            CorefChain::new(vec![
                Mention::new("John", 0, 4),
                Mention::new("he", 20, 22),
                Mention::new("him", 50, 53),
            ]),
            CorefChain::new(vec![
                Mention::new("Mary", 5, 9),
                Mention::new("she", 30, 33),
            ]),
            // Singleton
            CorefChain::new(vec![Mention::new("London", 60, 66)]),
        ];

        let stats = CorefDocStats::from_chains(&chains);

        assert_eq!(stats.chain_count, 3);
        assert_eq!(stats.mention_count, 6);
        assert!((stats.avg_chain_length - 2.0).abs() < 0.01);
        assert_eq!(stats.max_chain_length, 3);

        // Entity spread: John chain spans 0-53 = 53, Mary chain spans 5-33 = 28
        assert!(stats.avg_entity_spread > 0);
        assert!(stats.max_entity_spread >= 53);

        // Singleton ratio: 1/3 = 0.333
        assert!((stats.singleton_ratio - 0.333).abs() < 0.01);
    }

    #[test]
    fn test_coref_doc_stats_mention_type_ratios() {
        use crate::eval::coref::{CorefChain, Mention};

        // Create chains with mixed mention types
        let chains = vec![
            CorefChain::new(vec![
                Mention::new("John", 0, 4),  // Proper (capitalized)
                Mention::new("he", 10, 12),  // Pronoun
                Mention::new("him", 20, 23), // Pronoun
            ]),
            CorefChain::new(vec![
                Mention::new("Mary", 30, 34), // Proper
                Mention::new("she", 40, 43),  // Pronoun
            ]),
        ];

        let stats = CorefDocStats::from_chains(&chains);

        // 3 pronouns (he, him, she), 2 proper (John, Mary)
        // pronoun_ratio = 3/5 = 0.6, proper_ratio = 2/5 = 0.4
        assert!(stats.pronoun_ratio > 0.5, "Should have majority pronouns");
        assert!(stats.proper_ratio > 0.3, "Should have some proper nouns");
        assert_eq!(stats.mention_count, 5);
    }
}