anno 0.8.0

NER, coreference resolution, relation extraction, PII detection, and zero-shot entity types
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
//! Schema harmonization for multi-dataset NER training.
//!
//! # The Schema Misalignment Problem
//!
//! Different NER datasets use incompatible label schemas:
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────────┐
//! │ Dataset        │ "Marie Curie"  │ "Paris"      │ "Americans"        │
//! ├─────────────────────────────────────────────────────────────────────┤
//! │ CoNLL-2003     │ PER            │ LOC          │ MISC               │
//! │ OntoNotes 5.0  │ PERSON         │ GPE          │ NORP               │
//! │ Science Corpus │ SCIENTIST      │ LOCATION     │ —                  │
//! │ MultiNERD      │ PER            │ LOC          │ —                  │
//! └─────────────────────────────────────────────────────────────────────┘
//! ```
//!
//! **Naive concatenation causes ~30% F1 degradation** (CyberNER 2025, ESNERA 2025).
//!
//! # Solution: Canonical Ontology
//!
//! This module defines a single source of truth for entity types, with explicit
//! mappings from each dataset schema. Information loss is documented and intentional.
//!
//! # Usage
//!
//! ```rust
//! use anno::schema::{CanonicalType, DatasetSchema, SchemaMapper};
//!
//! // Create mapper for OntoNotes
//! let mapper = SchemaMapper::for_dataset(DatasetSchema::OntoNotes);
//!
//! // Map dataset-specific label to canonical type
//! let canonical = mapper.to_canonical("NORP");
//! assert_eq!(canonical.name(), "GROUP");  // Not "ORG"!
//!
//! // Check information loss
//! let loss = mapper.information_loss("FAC");
//! assert!(loss.is_some());  // FAC → LOCATION loses "man-made" semantics
//! ```
//!
//! # Research References
//!
//! - CyberNER (2025): Schema harmonization for cyber threat NER
//! - ESNERA (2025): Entity schema normalization for evaluation
//! - OntoNotes 5.0 Guidelines: <https://catalog.ldc.upenn.edu/docs/LDC2013T19/OntoNotes-Release-5.0.pdf>

use crate::{EntityCategory, EntityType};
use std::collections::HashMap;

// =============================================================================
// Canonical Entity Types
// =============================================================================

/// Canonical entity type in the unified schema.
///
/// This is the single source of truth. All dataset-specific labels map here.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CanonicalType {
    // === Agent Types (people and groups) ===
    /// Individual person (maps from: PER, PERSON, ACTOR, DIRECTOR, etc.)
    Person,
    /// Group of people by nationality/religion/politics (maps from: NORP)
    /// NOT the same as Organization!
    Group,

    // === Organization Types ===
    /// Formal organization (maps from: ORG, ORGANIZATION, CORPORATION)
    Organization,

    // === Location Types (with semantic preservation) ===
    /// Geopolitical entity - has government (maps from: GPE, COUNTRY, CITY)
    GeopoliticalEntity,
    /// Natural location (maps from: LOC, LOCATION - mountains, rivers)
    NaturalLocation,
    /// Man-made facility (maps from: FAC, FACILITY - buildings, airports)
    Facility,
    /// Generic location (fallback when distinction unknown)
    Location,

    // === Temporal Types ===
    /// Date expression
    Date,
    /// Time expression
    Time,

    // === Numeric Types ===
    /// Monetary value
    Money,
    /// Percentage
    Percent,
    /// Quantity with unit
    Quantity,
    /// Cardinal number
    Cardinal,
    /// Ordinal number
    Ordinal,

    // === Creative/Legal ===
    /// Creative work (maps from: WORK_OF_ART, TITLE, creative-work)
    CreativeWork,
    /// Product (maps from: PRODUCT, PROD)
    Product,
    /// Event (maps from: EVENT, EVE)
    Event,
    /// Law or legal document
    Law,
    /// Language
    Language,

    // === Domain-Specific (Biomedical) ===
    /// Disease or medical condition
    Disease,
    /// Chemical compound
    Chemical,
    /// Gene
    Gene,
    /// Drug
    Drug,

    // === Domain-Specific (Other) ===
    /// Animal
    Animal,
    /// Plant
    Plant,
    /// Food item
    Food,

    // === Fallback ===
    /// Miscellaneous (maps from: MISC, unknown types)
    Misc,
}

impl CanonicalType {
    /// Get the canonical name.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Person => "PERSON",
            Self::Group => "GROUP",
            Self::Organization => "ORG",
            Self::GeopoliticalEntity => "GPE",
            Self::NaturalLocation => "LOC",
            Self::Facility => "FAC",
            Self::Location => "LOCATION",
            Self::Date => "DATE",
            Self::Time => "TIME",
            Self::Money => "MONEY",
            Self::Percent => "PERCENT",
            Self::Quantity => "QUANTITY",
            Self::Cardinal => "CARDINAL",
            Self::Ordinal => "ORDINAL",
            Self::CreativeWork => "WORK_OF_ART",
            Self::Product => "PRODUCT",
            Self::Event => "EVENT",
            Self::Law => "LAW",
            Self::Language => "LANGUAGE",
            Self::Disease => "DISEASE",
            Self::Chemical => "CHEMICAL",
            Self::Gene => "GENE",
            Self::Drug => "DRUG",
            Self::Animal => "ANIMAL",
            Self::Plant => "PLANT",
            Self::Food => "FOOD",
            Self::Misc => "MISC",
        }
    }

    /// Get the category for this canonical type.
    #[must_use]
    pub fn category(&self) -> EntityCategory {
        match self {
            Self::Person | Self::Group => EntityCategory::Agent,
            Self::Organization => EntityCategory::Organization,
            Self::GeopoliticalEntity | Self::NaturalLocation | Self::Facility | Self::Location => {
                EntityCategory::Place
            }
            Self::Date | Self::Time => EntityCategory::Temporal,
            Self::Money | Self::Percent | Self::Quantity | Self::Cardinal | Self::Ordinal => {
                EntityCategory::Numeric
            }
            Self::CreativeWork | Self::Product | Self::Event | Self::Law | Self::Language => {
                EntityCategory::Creative
            }
            Self::Disease | Self::Chemical | Self::Gene | Self::Drug => EntityCategory::Agent,
            Self::Animal | Self::Plant | Self::Food => EntityCategory::Misc,
            Self::Misc => EntityCategory::Misc,
        }
    }

    /// Convert to the legacy EntityType for compatibility.
    #[must_use]
    pub fn to_entity_type(&self) -> EntityType {
        match self {
            Self::Person => EntityType::Person,
            Self::Group => EntityType::custom("GROUP", EntityCategory::Agent),
            Self::Organization => EntityType::Organization,
            Self::GeopoliticalEntity => EntityType::custom("GPE", EntityCategory::Place),
            Self::NaturalLocation => EntityType::Location,
            Self::Facility => EntityType::custom("FAC", EntityCategory::Place),
            Self::Location => EntityType::Location,
            Self::Date => EntityType::Date,
            Self::Time => EntityType::Time,
            Self::Money => EntityType::Money,
            Self::Percent => EntityType::Percent,
            Self::Quantity => EntityType::Quantity,
            Self::Cardinal => EntityType::Cardinal,
            Self::Ordinal => EntityType::Ordinal,
            Self::CreativeWork => EntityType::custom("WORK_OF_ART", EntityCategory::Creative),
            Self::Product => EntityType::custom("PRODUCT", EntityCategory::Misc),
            Self::Event => EntityType::custom("EVENT", EntityCategory::Misc),
            Self::Law => EntityType::custom("LAW", EntityCategory::Misc),
            Self::Language => EntityType::custom("LANGUAGE", EntityCategory::Misc),
            Self::Disease => EntityType::custom("DISEASE", EntityCategory::Agent),
            Self::Chemical => EntityType::custom("CHEMICAL", EntityCategory::Misc),
            Self::Gene => EntityType::custom("GENE", EntityCategory::Misc),
            Self::Drug => EntityType::custom("DRUG", EntityCategory::Misc),
            Self::Animal => EntityType::custom("ANIMAL", EntityCategory::Misc),
            Self::Plant => EntityType::custom("PLANT", EntityCategory::Misc),
            Self::Food => EntityType::custom("FOOD", EntityCategory::Misc),
            Self::Misc => EntityType::custom("MISC", EntityCategory::Misc),
        }
    }
}

// =============================================================================
// Dataset Schemas
// =============================================================================

/// Known dataset schemas for automatic mapping.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DatasetSchema {
    /// CoNLL-2003: PER, LOC, ORG, MISC
    CoNLL2003,
    /// OntoNotes 5.0: 18 types including GPE, NORP, FAC
    OntoNotes,
    /// MultiNERD: 15 types
    MultiNERD,
    /// FewNERD: 8 coarse + 66 fine types
    FewNERD,
    /// CrossNER: Domain-specific types
    CrossNER,
    /// BC5CDR: Chemical, Disease
    BC5CDR,
    /// NCBI Disease: Disease only
    NCBIDisease,
    /// MIT Movie: Actor, Director, Title, etc.
    MITMovie,
    /// MIT Restaurant: Restaurant_Name, Cuisine, etc.
    MITRestaurant,
    /// WNUT-17: person, location, corporation, product, creative-work, group
    WNUT17,
}

impl DatasetSchema {
    /// Get the entity labels used by this dataset.
    #[must_use]
    pub fn labels(&self) -> &'static [&'static str] {
        match self {
            Self::CoNLL2003 => &["PER", "LOC", "ORG", "MISC"],
            Self::OntoNotes => &[
                "PERSON",
                "NORP",
                "FAC",
                "ORG",
                "GPE",
                "LOC",
                "PRODUCT",
                "EVENT",
                "WORK_OF_ART",
                "LAW",
                "LANGUAGE",
                "DATE",
                "TIME",
                "PERCENT",
                "MONEY",
                "QUANTITY",
                "ORDINAL",
                "CARDINAL",
            ],
            Self::MultiNERD => &[
                "PER", "LOC", "ORG", "ANIM", "BIO", "CEL", "DIS", "EVE", "FOOD", "INST", "MEDIA",
                "MYTH", "PLANT", "TIME", "VEHI",
            ],
            Self::FewNERD => &[
                "person",
                "organization",
                "location",
                "building",
                "art",
                "product",
                "event",
                "other",
            ],
            Self::CrossNER => &[
                "politician",
                "election",
                "political_party",
                "country",
                "location",
                "organization",
                "person",
                "misc",
            ],
            Self::BC5CDR => &["Chemical", "Disease"],
            Self::NCBIDisease => &["Disease"],
            Self::MITMovie => &[
                "Actor",
                "Director",
                "Genre",
                "Title",
                "Year",
                "Song",
                "Character",
                "Plot",
                "Rating",
            ],
            Self::MITRestaurant => &[
                "Amenity",
                "Cuisine",
                "Dish",
                "Hours",
                "Location",
                "Price",
                "Rating",
                "Restaurant_Name",
            ],
            Self::WNUT17 => &[
                "person",
                "location",
                "corporation",
                "product",
                "creative-work",
                "group",
            ],
        }
    }
}

// =============================================================================
// Information Loss Tracking
// =============================================================================

/// Documents information lost during schema mapping.
#[derive(Debug, Clone)]
pub struct InformationLoss {
    /// The original fine-grained label
    pub original: String,
    /// The coarse canonical type it maps to
    pub canonical: CanonicalType,
    /// What semantic information is lost
    pub lost_semantics: &'static str,
}

// =============================================================================
// Schema Mapper
// =============================================================================

/// Maps dataset-specific labels to canonical types.
#[derive(Debug, Clone)]
pub struct SchemaMapper {
    /// The source dataset schema
    pub source_schema: DatasetSchema,
    /// Label → CanonicalType mapping
    mappings: HashMap<String, CanonicalType>,
    /// Label → InformationLoss (if any)
    losses: HashMap<String, InformationLoss>,
}

impl SchemaMapper {
    /// Create a mapper for a specific dataset.
    #[must_use]
    pub fn for_dataset(schema: DatasetSchema) -> Self {
        let mut mapper = Self {
            source_schema: schema,
            mappings: HashMap::new(),
            losses: HashMap::new(),
        };

        match schema {
            DatasetSchema::CoNLL2003 => {
                mapper.add("PER", CanonicalType::Person);
                mapper.add("LOC", CanonicalType::Location);
                mapper.add("ORG", CanonicalType::Organization);
                mapper.add("MISC", CanonicalType::Misc);
            }
            DatasetSchema::OntoNotes => {
                // Person types
                mapper.add("PERSON", CanonicalType::Person);

                // CRITICAL: NORP is NOT Organization!
                mapper.add_with_loss(
                    "NORP",
                    CanonicalType::Group,
                    "Nationalities/religions/politics - distinct from formal organizations",
                );

                // Location types - preserve distinctions
                mapper.add("GPE", CanonicalType::GeopoliticalEntity);
                mapper.add_with_loss(
                    "LOC",
                    CanonicalType::NaturalLocation,
                    "Natural locations (mountains, rivers)",
                );
                mapper.add_with_loss(
                    "FAC",
                    CanonicalType::Facility,
                    "Man-made structures (buildings, bridges)",
                );

                // Organization
                mapper.add("ORG", CanonicalType::Organization);

                // Temporal
                mapper.add("DATE", CanonicalType::Date);
                mapper.add("TIME", CanonicalType::Time);

                // Numeric
                mapper.add("MONEY", CanonicalType::Money);
                mapper.add("PERCENT", CanonicalType::Percent);
                mapper.add("QUANTITY", CanonicalType::Quantity);
                mapper.add("CARDINAL", CanonicalType::Cardinal);
                mapper.add("ORDINAL", CanonicalType::Ordinal);

                // Creative/Legal
                mapper.add("PRODUCT", CanonicalType::Product);
                mapper.add("EVENT", CanonicalType::Event);
                mapper.add("WORK_OF_ART", CanonicalType::CreativeWork);
                mapper.add("LAW", CanonicalType::Law);
                mapper.add("LANGUAGE", CanonicalType::Language);
            }
            DatasetSchema::MultiNERD => {
                mapper.add("PER", CanonicalType::Person);
                mapper.add("LOC", CanonicalType::Location);
                mapper.add("ORG", CanonicalType::Organization);
                mapper.add("ANIM", CanonicalType::Animal);
                mapper.add_with_loss("BIO", CanonicalType::Misc, "Biological entities");
                mapper.add_with_loss("CEL", CanonicalType::Misc, "Celestial bodies");
                mapper.add("DIS", CanonicalType::Disease);
                mapper.add("EVE", CanonicalType::Event);
                mapper.add("FOOD", CanonicalType::Food);
                mapper.add_with_loss("INST", CanonicalType::Misc, "Instruments");
                mapper.add_with_loss("MEDIA", CanonicalType::CreativeWork, "Media works");
                mapper.add_with_loss("MYTH", CanonicalType::Misc, "Mythological entities");
                mapper.add("PLANT", CanonicalType::Plant);
                mapper.add("TIME", CanonicalType::Time);
                mapper.add_with_loss("VEHI", CanonicalType::Product, "Vehicles");
            }
            DatasetSchema::FewNERD => {
                mapper.add("person", CanonicalType::Person);
                mapper.add("organization", CanonicalType::Organization);
                mapper.add("location", CanonicalType::Location);
                mapper.add_with_loss("building", CanonicalType::Facility, "Buildings/structures");
                mapper.add("art", CanonicalType::CreativeWork);
                mapper.add("product", CanonicalType::Product);
                mapper.add("event", CanonicalType::Event);
                mapper.add("other", CanonicalType::Misc);
            }
            DatasetSchema::CrossNER => {
                mapper.add_with_loss("politician", CanonicalType::Person, "Political role lost");
                mapper.add_with_loss(
                    "election",
                    CanonicalType::Event,
                    "Election specificity lost",
                );
                mapper.add_with_loss(
                    "political_party",
                    CanonicalType::Organization,
                    "Political nature lost",
                );
                mapper.add("country", CanonicalType::GeopoliticalEntity);
                mapper.add("location", CanonicalType::Location);
                mapper.add("organization", CanonicalType::Organization);
                mapper.add("person", CanonicalType::Person);
                mapper.add("misc", CanonicalType::Misc);
            }
            DatasetSchema::BC5CDR => {
                mapper.add("Chemical", CanonicalType::Chemical);
                mapper.add("Disease", CanonicalType::Disease);
            }
            DatasetSchema::NCBIDisease => {
                mapper.add("Disease", CanonicalType::Disease);
            }
            DatasetSchema::MITMovie => {
                mapper.add_with_loss("Actor", CanonicalType::Person, "Acting role lost");
                mapper.add_with_loss("Director", CanonicalType::Person, "Directing role lost");
                mapper.add_with_loss("Character", CanonicalType::Person, "Fictional status lost");
                mapper.add("Title", CanonicalType::CreativeWork);
                mapper.add("Year", CanonicalType::Date);
                mapper.add_with_loss("Song", CanonicalType::CreativeWork, "Song vs film lost");
                mapper.add_with_loss("Genre", CanonicalType::Misc, "Genre semantics lost");
                mapper.add_with_loss("Plot", CanonicalType::Misc, "Plot description lost");
                mapper.add_with_loss("Rating", CanonicalType::Misc, "Rating semantics lost");
            }
            DatasetSchema::MITRestaurant => {
                mapper.add("Restaurant_Name", CanonicalType::Organization);
                mapper.add("Location", CanonicalType::Location);
                mapper.add_with_loss("Cuisine", CanonicalType::Misc, "Cuisine type lost");
                mapper.add_with_loss("Dish", CanonicalType::Food, "Dish specifics lost");
                mapper.add("Price", CanonicalType::Money);
                mapper.add_with_loss("Amenity", CanonicalType::Misc, "Amenity type lost");
                mapper.add("Hours", CanonicalType::Time);
                mapper.add_with_loss("Rating", CanonicalType::Misc, "Rating semantics lost");
            }
            DatasetSchema::WNUT17 => {
                mapper.add("person", CanonicalType::Person);
                mapper.add("location", CanonicalType::Location);
                mapper.add("corporation", CanonicalType::Organization);
                mapper.add("product", CanonicalType::Product);
                mapper.add("creative-work", CanonicalType::CreativeWork);
                mapper.add("group", CanonicalType::Group);
            }
        }

        mapper
    }

    /// Add a simple mapping (no information loss).
    fn add(&mut self, label: &str, canonical: CanonicalType) {
        self.mappings.insert(label.to_uppercase(), canonical);
    }

    /// Add a mapping with documented information loss.
    fn add_with_loss(
        &mut self,
        label: &str,
        canonical: CanonicalType,
        lost_semantics: &'static str,
    ) {
        let upper = label.to_uppercase();
        self.mappings.insert(upper.clone(), canonical);
        self.losses.insert(
            upper.clone(),
            InformationLoss {
                original: label.to_string(),
                canonical,
                lost_semantics,
            },
        );
    }

    /// Map a dataset label to canonical type.
    #[must_use]
    pub fn to_canonical(&self, label: &str) -> CanonicalType {
        self.mappings
            .get(&label.to_uppercase())
            .copied()
            .unwrap_or(CanonicalType::Misc)
    }

    /// Get information loss for a label (if any).
    #[must_use]
    pub fn information_loss(&self, label: &str) -> Option<&InformationLoss> {
        self.losses.get(&label.to_uppercase())
    }

    /// Map to EntityType for compatibility with existing code.
    #[must_use]
    pub fn to_entity_type(&self, label: &str) -> EntityType {
        self.to_canonical(label).to_entity_type()
    }

    /// Get all mappings that have information loss.
    pub fn all_losses(&self) -> impl Iterator<Item = &InformationLoss> {
        self.losses.values()
    }

    /// Calculate label overlap with another schema.
    ///
    /// Used to detect if "zero-shot" evaluation is actually fair.
    /// High overlap (>80%) means evaluation inflates scores.
    #[must_use]
    pub fn label_overlap(&self, other: &SchemaMapper) -> f64 {
        let self_canonicals: std::collections::HashSet<_> =
            self.mappings.values().copied().collect();
        let other_canonicals: std::collections::HashSet<_> =
            other.mappings.values().copied().collect();

        let intersection = self_canonicals.intersection(&other_canonicals).count();
        let union = self_canonicals.union(&other_canonicals).count();

        if union == 0 {
            0.0
        } else {
            intersection as f64 / union as f64
        }
    }
}

// =============================================================================
// Unified Mapping Function (replaces all the ad-hoc ones)
// =============================================================================

/// Unified label mapping - THE SINGLE SOURCE OF TRUTH.
///
/// Replaces:
/// - `EntityType::from_label()` (partial)
/// - `map_entity_type()` in loader.rs
/// - `map_label_to_entity_type()` in datasets.rs
/// - `string_to_entity_type()` in bio_adapter.rs
///
/// # Arguments
/// * `label` - The entity type label from any dataset
/// * `schema` - Optional source schema for precise mapping
///
/// # Returns
/// The canonical EntityType
#[must_use]
pub fn map_to_canonical(label: &str, schema: Option<DatasetSchema>) -> EntityType {
    let label = label
        .strip_prefix("B-")
        .or_else(|| label.strip_prefix("I-"))
        .or_else(|| label.strip_prefix("E-"))
        .or_else(|| label.strip_prefix("S-"))
        .or_else(|| label.strip_prefix("L-"))
        .or_else(|| label.strip_prefix("U-"))
        .unwrap_or(label);

    if let Some(schema) = schema {
        SchemaMapper::for_dataset(schema).to_entity_type(label)
    } else {
        // Fallback: use heuristic mapping
        map_label_heuristic(label)
    }
}

/// Heuristic mapping when schema is unknown.
fn map_label_heuristic(label: &str) -> EntityType {
    match label.to_uppercase().as_str() {
        // Person types
        "PER" | "PERSON" | "ACTOR" | "DIRECTOR" | "CHARACTER" | "POLITICIAN" => EntityType::Person,

        // NORP - distinct from ORG!
        "NORP" | "GROUP" | "NATIONALITY" | "RELIGION" => {
            EntityType::custom("GROUP", EntityCategory::Agent)
        }

        // Organization types
        "ORG" | "ORGANIZATION" | "ORGANISATION" | "CORPORATION" | "COMPANY" | "POLITICAL_PARTY"
        | "RESTAURANT_NAME" => EntityType::Organization,

        // Location types - preserve GPE/FAC when possible
        "GPE" | "COUNTRY" | "CITY" | "STATE" => EntityType::custom("GPE", EntityCategory::Place),
        "FAC" | "FACILITY" | "BUILDING" => EntityType::custom("FAC", EntityCategory::Place),
        "LOC" | "LOCATION" | "GEO" => EntityType::Location,

        // Temporal
        "DATE" | "YEAR" => EntityType::Date,
        "TIME" | "HOURS" => EntityType::Time,

        // Numeric
        "MONEY" | "PRICE" | "CURRENCY" => EntityType::Money,
        "PERCENT" | "PERCENTAGE" => EntityType::Percent,
        "QUANTITY" => EntityType::Quantity,
        "CARDINAL" => EntityType::Cardinal,
        "ORDINAL" => EntityType::Ordinal,

        // Creative/Legal
        "PRODUCT" | "PROD" => EntityType::custom("PRODUCT", EntityCategory::Misc),
        "EVENT" | "EVE" | "ELECTION" => EntityType::custom("EVENT", EntityCategory::Misc),
        "WORK_OF_ART" | "CREATIVE-WORK" | "TITLE" | "SONG" | "ART" | "MEDIA" | "BOOK" => {
            EntityType::custom("WORK_OF_ART", EntityCategory::Creative)
        }
        "LAW" => EntityType::custom("LAW", EntityCategory::Misc),
        "LANGUAGE" => EntityType::custom("LANGUAGE", EntityCategory::Misc),

        // Historical/Official types (CHisIEC - Ancient Chinese)
        "OFI" | "OFFICIAL" | "POSITION" | "TITLE_OFFICE" => {
            EntityType::custom("OFFICIAL", EntityCategory::Misc)
        }

        // Biomedical
        "DISEASE" | "DIS" => EntityType::custom("DISEASE", EntityCategory::Agent),
        "CHEMICAL" => EntityType::custom("CHEMICAL", EntityCategory::Misc),
        "GENE" => EntityType::custom("GENE", EntityCategory::Misc),
        "DRUG" => EntityType::custom("DRUG", EntityCategory::Misc),

        // Other domain types
        "ANIM" | "ANIMAL" => EntityType::custom("ANIMAL", EntityCategory::Misc),
        "PLANT" => EntityType::custom("PLANT", EntityCategory::Misc),
        "FOOD" | "DISH" | "CUISINE" => EntityType::custom("FOOD", EntityCategory::Misc),
        "VEHI" | "VEHICLE" => EntityType::custom("VEHICLE", EntityCategory::Misc),

        // Contact
        "EMAIL" => EntityType::Email,
        "URL" | "URI" => EntityType::Url,
        "PHONE" | "TELEPHONE" => EntityType::Phone,

        // Misc fallback
        "MISC" | "MISCELLANEOUS" | "O" | "OTHER" => {
            EntityType::custom("MISC", EntityCategory::Misc)
        }

        // Unknown - preserve original
        other => EntityType::custom(other, EntityCategory::Misc),
    }
}

// =============================================================================
// Coarse Schema for Training
// =============================================================================

/// Coarse-grained schema for multi-dataset training.
///
/// Use this when training on concatenated datasets to avoid label conflicts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CoarseType {
    /// Any person entity
    Person,
    /// Any organization entity
    Organization,
    /// Any location entity
    Location,
    /// Any temporal entity
    DateTime,
    /// Any numeric entity
    Numeric,
    /// Everything else
    Other,
}

impl CoarseType {
    /// Map from canonical type.
    #[must_use]
    pub fn from_canonical(ct: CanonicalType) -> Self {
        match ct {
            CanonicalType::Person | CanonicalType::Group => Self::Person,
            CanonicalType::Organization => Self::Organization,
            CanonicalType::GeopoliticalEntity
            | CanonicalType::NaturalLocation
            | CanonicalType::Facility
            | CanonicalType::Location => Self::Location,
            CanonicalType::Date | CanonicalType::Time => Self::DateTime,
            CanonicalType::Money
            | CanonicalType::Percent
            | CanonicalType::Quantity
            | CanonicalType::Cardinal
            | CanonicalType::Ordinal => Self::Numeric,
            _ => Self::Other,
        }
    }

    /// Map from any label.
    #[must_use]
    pub fn from_label(label: &str) -> Self {
        let canonical = SchemaMapper::for_dataset(DatasetSchema::OntoNotes).to_canonical(label);
        Self::from_canonical(canonical)
    }
}

// =============================================================================
// Tests
// =============================================================================

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

    #[test]
    fn test_norp_is_not_organization() {
        let mapper = SchemaMapper::for_dataset(DatasetSchema::OntoNotes);
        let norp = mapper.to_canonical("NORP");
        let org = mapper.to_canonical("ORG");

        assert_eq!(norp, CanonicalType::Group);
        assert_eq!(org, CanonicalType::Organization);
        assert_ne!(norp, org, "NORP should NOT map to Organization!");
    }

    #[test]
    fn test_location_distinctions_preserved() {
        let mapper = SchemaMapper::for_dataset(DatasetSchema::OntoNotes);

        assert_eq!(
            mapper.to_canonical("GPE"),
            CanonicalType::GeopoliticalEntity
        );
        assert_eq!(mapper.to_canonical("LOC"), CanonicalType::NaturalLocation);
        assert_eq!(mapper.to_canonical("FAC"), CanonicalType::Facility);
    }

    #[test]
    fn test_information_loss_documented() {
        let mapper = SchemaMapper::for_dataset(DatasetSchema::OntoNotes);

        let fac_loss = mapper.information_loss("FAC");
        assert!(fac_loss.is_some());
        let loss_text = fac_loss.unwrap().lost_semantics.to_lowercase();
        // Check that loss contains info about structures/buildings
        assert!(loss_text.contains("structure") || loss_text.contains("building"));
    }

    #[test]
    fn test_conll_to_ontonotes_overlap() {
        let conll = SchemaMapper::for_dataset(DatasetSchema::CoNLL2003);
        let ontonotes = SchemaMapper::for_dataset(DatasetSchema::OntoNotes);

        let overlap = conll.label_overlap(&ontonotes);
        // CoNLL has 4 types, OntoNotes has 18 - expect low overlap
        assert!(overlap < 0.5);
    }

    #[test]
    fn test_unified_mapping_strips_bio() {
        let et = map_to_canonical("B-PER", None);
        assert_eq!(et, EntityType::Person);

        let et = map_to_canonical("I-ORG", None);
        assert_eq!(et, EntityType::Organization);
    }

    #[test]
    fn test_coarse_schema() {
        assert_eq!(
            CoarseType::from_canonical(CanonicalType::Person),
            CoarseType::Person
        );
        assert_eq!(
            CoarseType::from_canonical(CanonicalType::Group),
            CoarseType::Person
        );
        assert_eq!(
            CoarseType::from_canonical(CanonicalType::GeopoliticalEntity),
            CoarseType::Location
        );
    }
}