workshop-rs 0.1.15

Canonical multi-locale Overwatch Workshop semantic core: catalog, parser, WIR, validation, emitter.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
//! Canonical typed facts for Workshop custom-game settings.
//!
//! Definitions are a semantic projection of the reviewed settings table. The
//! table remains the parser/emitter lookup source, while [`Settings`] and
//! [`SettingsNode`] remain the source-preserving authored-value carrier.

use std::fmt;

use crate::gameplay::{AbilityVariant, HeroId, LogicalSlot};
use crate::{gameplay::GameplayDataError, gameplay_data};

use super::reconciliation;
use super::table::{self, KeyKind, PathPart, TableEntry};
use super::{Settings, SettingsNode};

/// A locale-independent Workshop setting concept identity.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SettingId(String);

impl SettingId {
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl From<&str> for SettingId {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

impl fmt::Display for SettingId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Whether a definition has a reviewed canonical concept identity.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SettingIdentity {
    Known(SettingId),
    Unknown,
}

/// The Workshop-native section that owns a setting.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SettingScope {
    Main,
    Lobby,
    GameModes,
    Heroes,
    Extensions,
    Workshop,
    Unknown,
}

/// An open team identity used by hero settings structure.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TeamId(String);

impl TeamId {
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// The semantic entity to which a setting applies.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SettingTarget {
    Global,
    Mode(String),
    Team(TeamId),
    Hero {
        team: Option<TeamId>,
        hero: HeroId,
    },
    TeamAbility {
        team: Option<TeamId>,
        slot: LogicalSlot,
        variant: Option<AbilityVariant>,
    },
    HeroAbility {
        team: Option<TeamId>,
        hero: HeroId,
        slot: LogicalSlot,
        variant: Option<AbilityVariant>,
    },
}

/// The target shape described by a definition. Concrete identities are
/// supplied separately when applicability is queried.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SettingTargetKind {
    Global,
    Mode,
    Team,
    TeamAbility {
        slot: LogicalSlot,
        variant: Option<AbilityVariant>,
    },
    Hero,
    HeroAbility {
        slot: LogicalSlot,
        variant: Option<AbilityVariant>,
    },
    Unknown,
}

/// The result of asking whether a definition applies to a target.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Applicability {
    Applicable,
    NotApplicable,
    Unknown,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumericBoundsError {
    NonFinite,
    Reversed,
}

/// Evidence-backed effective numeric bounds. `None` means the current
/// reviewed evidence does not establish that bound.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct NumericBounds {
    min: Option<f64>,
    max: Option<f64>,
}

impl NumericBounds {
    pub const fn unknown() -> Self {
        Self {
            min: None,
            max: None,
        }
    }

    pub fn new(min: Option<f64>, max: Option<f64>) -> Result<Self, NumericBoundsError> {
        if min.is_some_and(|value| !value.is_finite())
            || max.is_some_and(|value| !value.is_finite())
        {
            return Err(NumericBoundsError::NonFinite);
        }
        if min.zip(max).is_some_and(|(min, max)| min > max) {
            return Err(NumericBoundsError::Reversed);
        }
        Ok(Self { min, max })
    }

    pub fn min(&self) -> Option<f64> {
        self.min
    }

    pub fn max(&self) -> Option<f64> {
        self.max
    }

    pub fn effective(&self, authored: f64) -> Option<EffectiveNumber> {
        if !authored.is_finite() || self.min.is_none() && self.max.is_none() {
            return None;
        }
        match (self.min, self.max) {
            (Some(min), None) if authored >= min => return None,
            (None, Some(max)) if authored <= max => return None,
            _ => {}
        }
        let mut effective = authored;
        if let Some(min) = self.min {
            effective = effective.max(min);
        }
        if let Some(max) = self.max {
            effective = effective.min(max);
        }
        Some(EffectiveNumber {
            authored,
            effective,
        })
    }
}

/// An authored numeric value paired with its Workshop-effective value.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct EffectiveNumber {
    pub authored: f64,
    pub effective: f64,
}

/// The machine-readable value domain of a setting.
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub enum SettingValueDomain {
    Boolean,
    Number(NumericBounds),
    Percent(NumericBounds),
    String,
    Enum { domain: String },
    HeroList,
    MapList,
    PresenceOnly,
}

/// A typed authored value in the settings carrier.
#[derive(Debug, Clone, PartialEq)]
pub enum SettingValue {
    Boolean(bool),
    Number(f64),
    Percent(f64),
    String(String),
    Enum(String),
    HeroList(Vec<String>),
    MapList(Vec<String>),
    PresenceOnly,
}

/// A typed occurrence together with an evidenced effective numeric value.
#[derive(Debug, Clone, PartialEq)]
pub struct SettingOccurrence {
    pub authored: SettingValue,
    pub effective: Option<EffectiveNumber>,
}

/// Failure from a typed settings query or source-preserving edit.
#[derive(Debug, Clone, PartialEq)]
pub enum SettingOperationError {
    NotApplicable {
        setting: SettingId,
        target: SettingTarget,
    },
    NotFound {
        setting: SettingId,
        target: SettingTarget,
    },
    ApplicabilityUnknown {
        setting: SettingId,
        target: Box<SettingTarget>,
    },
    WrongValueKind {
        setting: SettingId,
        expected: &'static str,
        actual: &'static str,
        span: Option<crate::source::Span>,
    },
    InvalidValue {
        setting: SettingId,
        message: String,
        span: Option<crate::source::Span>,
    },
}

impl fmt::Display for SettingOperationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotApplicable { setting, target } => {
                write!(
                    formatter,
                    "setting {setting} does not apply to target {target:?}"
                )
            }
            Self::NotFound { setting, target } => {
                write!(
                    formatter,
                    "setting {setting} was not found for target {target:?}"
                )
            }
            Self::ApplicabilityUnknown { setting, target } => write!(
                formatter,
                "applicability of setting {setting} is unknown for target {target:?}"
            ),
            Self::WrongValueKind {
                setting,
                expected,
                actual,
                ..
            } => write!(
                formatter,
                "setting {setting} expects {expected} value, got {actual}"
            ),
            Self::InvalidValue {
                setting, message, ..
            } => write!(formatter, "invalid value for setting {setting}: {message}"),
        }
    }
}

impl std::error::Error for SettingOperationError {}

impl SettingValueDomain {
    /// Apply evidenced effective clamping without changing the authored
    /// value held by [`super::SettingsNode`].
    pub fn effective_number(&self, authored: f64) -> Option<EffectiveNumber> {
        match self {
            Self::Number(bounds) | Self::Percent(bounds) => bounds.effective(authored),
            _ => None,
        }
    }
}

/// Locale-facing names associated with a canonical setting concept.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SettingPresentation {
    pub english_name: &'static str,
    pub locale_section: &'static str,
}

impl SettingPresentation {
    pub fn localized_name(&self, locale: &str) -> Option<&'static str> {
        if locale.eq_ignore_ascii_case("en-US") {
            Some(self.english_name)
        } else {
            table::localized_name(locale, self.locale_section, self.english_name)
        }
    }
}

/// Provenance shared by the reviewed table projection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SettingProvenance {
    pub kind: SettingEvidenceKind,
    pub source: &'static str,
    pub reviewed: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SettingEvidenceKind {
    RawWorkshopFixture,
    WorkshopDataExport,
}

/// One canonical semantic definition projected from an existing table entry.
#[derive(Debug, Clone, PartialEq)]
pub struct SettingDefinition {
    identity: SettingIdentity,
    scope: SettingScope,
    path: String,
    path_parts: &'static [PathPart<'static>],
    key: &'static str,
    target: TargetPattern,
    domain: SettingValueDomain,
    presentation: SettingPresentation,
    provenance: SettingProvenance,
}

impl SettingDefinition {
    pub fn identity(&self) -> &SettingIdentity {
        &self.identity
    }

    pub fn id(&self) -> Option<&SettingId> {
        match &self.identity {
            SettingIdentity::Known(id) => Some(id),
            SettingIdentity::Unknown => None,
        }
    }

    pub fn scope(&self) -> SettingScope {
        self.scope
    }

    pub fn path(&self) -> &str {
        &self.path
    }

    pub fn domain(&self) -> &SettingValueDomain {
        &self.domain
    }

    pub fn target_kind(&self) -> SettingTargetKind {
        match &self.target {
            TargetPattern::Global => SettingTargetKind::Global,
            TargetPattern::Mode(_) => SettingTargetKind::Mode,
            TargetPattern::Team(_) => SettingTargetKind::Team,
            TargetPattern::TeamAbility { slot, variant, .. } => SettingTargetKind::TeamAbility {
                slot: slot.clone(),
                variant: variant.clone(),
            },
            TargetPattern::Hero { .. } => SettingTargetKind::Hero,
            TargetPattern::HeroAbility { slot, variant, .. } => SettingTargetKind::HeroAbility {
                slot: slot.clone(),
                variant: variant.clone(),
            },
            TargetPattern::Unknown => SettingTargetKind::Unknown,
        }
    }

    pub fn presentation(&self) -> &SettingPresentation {
        &self.presentation
    }

    pub fn localized_name(
        &self,
        locale: &str,
        target: &SettingTarget,
    ) -> Result<Option<&'static str>, GameplayDataError> {
        match target {
            SettingTarget::Hero { hero, .. } | SettingTarget::HeroAbility { hero, .. } => {
                if self.applicability(target)? == Applicability::NotApplicable {
                    Ok(None)
                } else {
                    Ok(table::hero_setting_name(hero.as_str(), self.key, locale)
                        .or_else(|| self.presentation.localized_name(locale)))
                }
            }
            _ => Ok(self.presentation.localized_name(locale)),
        }
    }

    pub fn provenance(&self) -> SettingProvenance {
        self.provenance
    }

    /// Query effective applicability without exposing table deduplication.
    pub fn applicability(
        &self,
        target: &SettingTarget,
    ) -> Result<Applicability, GameplayDataError> {
        Ok(match (&self.target, target) {
            (TargetPattern::Global, SettingTarget::Global) => Applicability::Applicable,
            (TargetPattern::Mode(expected), SettingTarget::Mode(actual)) => {
                if expected
                    .as_deref()
                    .is_none_or(|expected| expected == actual)
                {
                    Applicability::Applicable
                } else {
                    Applicability::NotApplicable
                }
            }
            (TargetPattern::Team(expected), SettingTarget::Team(actual)) => {
                if expected
                    .as_deref()
                    .is_none_or(|expected| expected == actual.as_str())
                {
                    Applicability::Applicable
                } else {
                    Applicability::NotApplicable
                }
            }
            (TargetPattern::Team(expected), SettingTarget::Hero { team, .. }) => {
                if team_matches(expected.as_deref(), team.as_ref()) {
                    Applicability::Unknown
                } else {
                    Applicability::NotApplicable
                }
            }
            (
                TargetPattern::TeamAbility {
                    team,
                    slot,
                    variant: expected_variant,
                },
                SettingTarget::TeamAbility {
                    team: actual_team,
                    slot: actual_slot,
                    variant: actual_variant,
                },
            ) => {
                if !team_matches(team.as_deref(), actual_team.as_ref())
                    || slot != actual_slot
                    || expected_variant
                        .as_ref()
                        .is_some_and(|expected| actual_variant.as_ref() != Some(expected))
                {
                    Applicability::NotApplicable
                } else {
                    Applicability::Applicable
                }
            }
            (
                TargetPattern::TeamAbility {
                    team,
                    slot,
                    variant: expected_variant,
                },
                SettingTarget::HeroAbility {
                    team: actual_team,
                    hero: actual_hero,
                    slot: actual_slot,
                    variant: actual_variant,
                },
            ) => {
                if !team_matches(team.as_deref(), actual_team.as_ref())
                    || slot != actual_slot
                    || expected_variant
                        .as_ref()
                        .is_some_and(|expected| actual_variant.as_ref() != Some(expected))
                {
                    Applicability::NotApplicable
                } else {
                    match hero_ability_exists(actual_hero, actual_slot, actual_variant.as_ref())? {
                        Some(true) => Applicability::Unknown,
                        Some(false) => Applicability::NotApplicable,
                        None => Applicability::Unknown,
                    }
                }
            }
            (
                TargetPattern::Hero { team, hero },
                SettingTarget::Hero {
                    team: actual_team,
                    hero: actual_hero,
                },
            ) => {
                if !team_matches(team.as_deref(), actual_team.as_ref())
                    || hero
                        .as_deref()
                        .is_some_and(|expected| expected != actual_hero.as_str())
                {
                    Applicability::NotApplicable
                } else {
                    Applicability::Unknown
                }
            }
            (
                TargetPattern::HeroAbility {
                    team,
                    hero,
                    slot,
                    variant: expected_variant,
                },
                SettingTarget::HeroAbility {
                    team: actual_team,
                    hero: actual_hero,
                    slot: actual_slot,
                    ..
                },
            ) => {
                if !team_matches(team.as_deref(), actual_team.as_ref())
                    || hero
                        .as_deref()
                        .is_some_and(|expected| expected != actual_hero.as_str())
                    || slot.as_str() != actual_slot.as_str()
                    || expected_variant
                        .as_ref()
                        .is_some_and(|expected| Some(expected) != target_variant(target))
                {
                    return Ok(Applicability::NotApplicable);
                }
                match hero_ability_exists(actual_hero, actual_slot, target_variant(target))? {
                    None => Applicability::Unknown,
                    Some(false) => Applicability::NotApplicable,
                    Some(true) => Applicability::Unknown,
                }
            }
            (TargetPattern::Unknown, _) => Applicability::Unknown,
            _ => Applicability::NotApplicable,
        })
    }

    pub fn effective_number(&self, authored: f64) -> Option<EffectiveNumber> {
        self.domain.effective_number(authored)
    }

    /// Read an existing source-preserving occurrence with its authored value
    /// and, when evidenced, its effective numeric value.
    pub fn read(
        &self,
        settings: &Settings,
        target: &SettingTarget,
    ) -> Result<SettingOccurrence, SettingOperationError> {
        let id = self.operation_id()?;
        self.ensure_read_target(target)?;
        let path = self.concrete_path(target);
        let node = find_node(&settings.children, &path).ok_or_else(|| {
            SettingOperationError::NotFound {
                setting: id.clone(),
                target: target.clone(),
            }
        })?;
        let authored = value_from_node(node, &self.domain, &id)?;
        let effective = match authored {
            SettingValue::Number(value) | SettingValue::Percent(value) => {
                self.effective_number(value)
            }
            _ => None,
        };
        Ok(SettingOccurrence {
            authored,
            effective,
        })
    }

    /// Update one existing occurrence without rebuilding the surrounding
    /// settings tree. Unknown and unrelated source structure is untouched.
    pub fn write(
        &self,
        settings: &mut Settings,
        target: &SettingTarget,
        value: SettingValue,
    ) -> Result<(), SettingOperationError> {
        let id = self.operation_id()?;
        self.ensure_write_target(target)?;
        let path = self.concrete_path(target);
        let node = find_node_mut(&mut settings.children, &path).ok_or_else(|| {
            SettingOperationError::NotFound {
                setting: id.clone(),
                target: target.clone(),
            }
        })?;
        let span = node.span();
        validate_value(&self.domain, &id, &value, span)?;
        apply_value(node, &id, value)
    }

    fn ensure_read_target(&self, target: &SettingTarget) -> Result<(), SettingOperationError> {
        let id = self.operation_id()?;
        match self
            .applicability(target)
            .map_err(|error| SettingOperationError::InvalidValue {
                setting: id.clone(),
                message: error.to_string(),
                span: None,
            })? {
            Applicability::NotApplicable => Err(SettingOperationError::NotApplicable {
                setting: id,
                target: target.clone(),
            }),
            Applicability::Applicable | Applicability::Unknown => Ok(()),
        }
    }

    fn ensure_write_target(&self, target: &SettingTarget) -> Result<(), SettingOperationError> {
        let id = self.operation_id()?;
        match self
            .applicability(target)
            .map_err(|error| SettingOperationError::InvalidValue {
                setting: id.clone(),
                message: error.to_string(),
                span: None,
            })? {
            Applicability::NotApplicable => Err(SettingOperationError::NotApplicable {
                setting: id,
                target: target.clone(),
            }),
            Applicability::Unknown => Err(SettingOperationError::ApplicabilityUnknown {
                setting: id,
                target: Box::new(target.clone()),
            }),
            Applicability::Applicable => Ok(()),
        }
    }

    fn operation_id(&self) -> Result<SettingId, SettingOperationError> {
        self.id()
            .cloned()
            .ok_or_else(|| SettingOperationError::InvalidValue {
                setting: SettingId::new("unknown"),
                message: "setting has no reviewed canonical identity".to_string(),
                span: None,
            })
    }

    fn concrete_path(&self, target: &SettingTarget) -> Vec<String> {
        self.path_parts
            .iter()
            .map(|part| match part {
                PathPart::Part(name) => (*name).to_string(),
                PathPart::Team => target_team(target),
                PathPart::Hero => target_hero(target),
            })
            .collect()
    }
}

fn target_team(target: &SettingTarget) -> String {
    match target {
        SettingTarget::Team(team)
        | SettingTarget::Hero {
            team: Some(team), ..
        }
        | SettingTarget::TeamAbility {
            team: Some(team), ..
        }
        | SettingTarget::HeroAbility {
            team: Some(team), ..
        } => team.as_str().to_string(),
        _ => "allTeams".to_string(),
    }
}

fn target_hero(target: &SettingTarget) -> String {
    match target {
        SettingTarget::Hero { hero, .. } | SettingTarget::HeroAbility { hero, .. } => {
            hero.as_str().to_string()
        }
        _ => String::new(),
    }
}

fn find_node<'a>(children: &'a [SettingsNode], path: &[String]) -> Option<&'a SettingsNode> {
    let (name, rest) = path.split_first()?;
    let node = children.iter().find(|node| node.name() == name)?;
    if rest.is_empty() {
        Some(node)
    } else {
        match node {
            SettingsNode::Workshop { children, .. } | SettingsNode::Group { children, .. } => {
                find_node(children, rest)
            }
            _ => None,
        }
    }
}

fn find_node_mut<'a>(
    children: &'a mut [SettingsNode],
    path: &[String],
) -> Option<&'a mut SettingsNode> {
    let (name, rest) = path.split_first()?;
    let node = children.iter_mut().find(|node| node.name() == name)?;
    if rest.is_empty() {
        Some(node)
    } else {
        match node {
            SettingsNode::Workshop { children, .. } | SettingsNode::Group { children, .. } => {
                find_node_mut(children, rest)
            }
            _ => None,
        }
    }
}

fn value_kind(value: &SettingValue) -> &'static str {
    match value {
        SettingValue::Boolean(_) => "boolean",
        SettingValue::Number(_) => "number",
        SettingValue::Percent(_) => "percent",
        SettingValue::String(_) => "string",
        SettingValue::Enum(_) => "enum",
        SettingValue::HeroList(_) => "hero-list",
        SettingValue::MapList(_) => "map-list",
        SettingValue::PresenceOnly => "presence-only",
    }
}

fn domain_kind(domain: &SettingValueDomain) -> &'static str {
    match domain {
        SettingValueDomain::Boolean => "boolean",
        SettingValueDomain::Number(_) => "number",
        SettingValueDomain::Percent(_) => "percent",
        SettingValueDomain::String => "string",
        SettingValueDomain::Enum { .. } => "enum",
        SettingValueDomain::HeroList => "hero-list",
        SettingValueDomain::MapList => "map-list",
        SettingValueDomain::PresenceOnly => "presence-only",
    }
}

fn validate_value(
    domain: &SettingValueDomain,
    id: &SettingId,
    value: &SettingValue,
    span: Option<crate::source::Span>,
) -> Result<(), SettingOperationError> {
    let expected = domain_kind(domain);
    if value_kind(value) != expected {
        return Err(SettingOperationError::WrongValueKind {
            setting: id.clone(),
            expected,
            actual: value_kind(value),
            span,
        });
    }
    match (domain, value) {
        (
            SettingValueDomain::Number(_) | SettingValueDomain::Percent(_),
            SettingValue::Number(value) | SettingValue::Percent(value),
        ) if !value.is_finite() => Err(SettingOperationError::InvalidValue {
            setting: id.clone(),
            message: "numeric settings values must be finite".to_string(),
            span,
        }),
        (SettingValueDomain::Enum { domain }, SettingValue::Enum(member))
            if table::enum_name(domain, member).is_none() =>
        {
            Err(SettingOperationError::InvalidValue {
                setting: id.clone(),
                message: format!("unknown member '{member}' for enum domain '{domain}'"),
                span,
            })
        }
        (SettingValueDomain::HeroList, SettingValue::HeroList(values))
            if values.iter().any(|value| table::hero_name(value).is_none()) =>
        {
            Err(SettingOperationError::InvalidValue {
                setting: id.clone(),
                message: "hero list contains an unknown hero".to_string(),
                span,
            })
        }
        (SettingValueDomain::MapList, SettingValue::MapList(values))
            if values.iter().any(|value| table::map_name(value).is_none()) =>
        {
            Err(SettingOperationError::InvalidValue {
                setting: id.clone(),
                message: "map list contains an unknown map".to_string(),
                span,
            })
        }
        _ => Ok(()),
    }
}

fn value_from_node(
    node: &SettingsNode,
    domain: &SettingValueDomain,
    id: &SettingId,
) -> Result<SettingValue, SettingOperationError> {
    let value = match node {
        SettingsNode::Bool { value, .. } => SettingValue::Boolean(*value),
        SettingsNode::Number { value, .. } => match domain {
            SettingValueDomain::Percent(_) => SettingValue::Percent(*value),
            _ => SettingValue::Number(*value),
        },
        SettingsNode::String { value, .. } => match domain {
            SettingValueDomain::Enum { .. } => SettingValue::Enum(value.clone()),
            _ => SettingValue::String(value.clone()),
        },
        SettingsNode::Flag { .. } => SettingValue::PresenceOnly,
        SettingsNode::List { elements, .. } => {
            let values = elements
                .iter()
                .map(|element| element.value.clone())
                .collect();
            match domain {
                SettingValueDomain::HeroList => SettingValue::HeroList(values),
                _ => SettingValue::MapList(values),
            }
        }
        _ => {
            return Err(SettingOperationError::InvalidValue {
                setting: id.clone(),
                message: "settings occurrence is not a typed leaf".to_string(),
                span: node.span(),
            });
        }
    };
    validate_value(domain, id, &value, node.span())?;
    Ok(value)
}

fn apply_value(
    node: &mut SettingsNode,
    id: &SettingId,
    value: SettingValue,
) -> Result<(), SettingOperationError> {
    match (node, value) {
        (SettingsNode::Bool { value: current, .. }, SettingValue::Boolean(value)) => {
            *current = value
        }
        (
            SettingsNode::Number { value: current, .. },
            SettingValue::Number(value) | SettingValue::Percent(value),
        ) => *current = value,
        (
            SettingsNode::String { value: current, .. },
            SettingValue::String(value) | SettingValue::Enum(value),
        ) => *current = value,
        (
            SettingsNode::List { elements, span, .. },
            SettingValue::HeroList(values) | SettingValue::MapList(values),
        ) => {
            if elements.len() != values.len() {
                return Err(SettingOperationError::InvalidValue {
                    setting: id.clone(),
                    message: "source-preserving list edits cannot change list length".to_string(),
                    span: *span,
                });
            }
            elements
                .iter_mut()
                .zip(values)
                .for_each(|(element, value)| element.value = value);
        }
        (SettingsNode::Flag { .. }, SettingValue::PresenceOnly) => {}
        (node, value) => {
            return Err(SettingOperationError::WrongValueKind {
                setting: id.clone(),
                expected: "existing typed value",
                actual: value_kind(&value),
                span: node.span(),
            });
        }
    }
    Ok(())
}

#[derive(Debug, Clone, PartialEq)]
enum TargetPattern {
    Global,
    Mode(Option<String>),
    Team(Option<String>),
    TeamAbility {
        team: Option<String>,
        slot: LogicalSlot,
        variant: Option<AbilityVariant>,
    },
    Hero {
        team: Option<String>,
        hero: Option<String>,
    },
    HeroAbility {
        team: Option<String>,
        hero: Option<String>,
        slot: LogicalSlot,
        variant: Option<AbilityVariant>,
    },
    Unknown,
}

fn team_matches(expected: Option<&str>, actual: Option<&TeamId>) -> bool {
    expected.is_none_or(|expected| actual.is_some_and(|actual| actual.as_str() == expected))
}

fn target_variant(target: &SettingTarget) -> Option<&AbilityVariant> {
    match target {
        SettingTarget::HeroAbility { variant, .. } => variant.as_ref(),
        _ => None,
    }
}

fn hero_ability_exists(
    hero: &HeroId,
    slot: &LogicalSlot,
    variant: Option<&AbilityVariant>,
) -> Result<Option<bool>, GameplayDataError> {
    gameplay_data::builtin_ref()
        .map_err(Clone::clone)
        .map(|catalog| {
            catalog.hero(hero).map(|hero| match variant {
                Some(variant) => hero.ability_variant(slot, variant).is_ok(),
                None => !hero.abilities_in_slot(slot).is_empty(),
            })
        })
}

/// Project all currently reviewed table entries into the canonical semantic
/// catalog. The table remains the single parser/emitter source; this
/// projection supplies the stable semantic identity and typed facts consumed
/// by callers.
pub fn definitions() -> impl Iterator<Item = SettingDefinition> {
    table::entries().map(SettingDefinition::from_entry)
}

/// Project one reviewed table entry into the canonical semantic definition.
pub fn definition(path: &[PathPart<'_>]) -> Option<SettingDefinition> {
    table::lookup(path).map(SettingDefinition::from_entry)
}

/// Find all definitions for a canonical concept identity.
///
/// A concept can intentionally have more than one target shape, so the
/// result is an iterator rather than a single definition. This keeps normal
/// consumers independent of the private table paths while retaining the
/// target-specific schema facts.
pub fn definitions_by_id(id: &SettingId) -> impl Iterator<Item = SettingDefinition> {
    definitions().filter(move |definition| definition.id() == Some(id))
}

impl SettingDefinition {
    fn from_entry(entry: &TableEntry) -> Self {
        let scope = scope_for(entry.path);
        let key = entry
            .path
            .last()
            .and_then(|part| match part {
                PathPart::Part(key) => Some(*key),
                _ => None,
            })
            .unwrap_or("");
        let target = target_for(entry.path);
        let path = table::path_string(entry.path);
        let domain = domain_for(entry.kind);
        let identity = canonical_id(scope, key, entry.path)
            .map(SettingIdentity::Known)
            .unwrap_or(SettingIdentity::Unknown);
        Self {
            identity,
            scope,
            path,
            path_parts: entry.path,
            key,
            target,
            domain,
            presentation: SettingPresentation {
                english_name: entry.workshop_name,
                locale_section: "labels",
            },
            provenance: SettingProvenance {
                kind: if table::is_generated_entry(entry) {
                    SettingEvidenceKind::WorkshopDataExport
                } else {
                    SettingEvidenceKind::RawWorkshopFixture
                },
                source: if table::is_generated_entry(entry) {
                    "workshop-data/workshop-data.json"
                } else {
                    "pinned raw Workshop settings fixtures"
                },
                reviewed: true,
            },
        }
    }
}

fn scope_for(path: &[PathPart<'_>]) -> SettingScope {
    match path.first() {
        Some(PathPart::Part("main")) => SettingScope::Main,
        Some(PathPart::Part("lobby")) => SettingScope::Lobby,
        Some(PathPart::Part("gamemodes")) => SettingScope::GameModes,
        Some(PathPart::Part("heroes")) => SettingScope::Heroes,
        Some(PathPart::Part("extensions")) => SettingScope::Extensions,
        Some(PathPart::Part("workshop")) => SettingScope::Workshop,
        _ => SettingScope::Unknown,
    }
}

fn target_for(path: &[PathPart<'_>]) -> TargetPattern {
    match path {
        [PathPart::Part("gamemodes"), PathPart::Part("general"), ..] => TargetPattern::Global,
        [PathPart::Part("gamemodes"), PathPart::Part(mode), ..] => {
            TargetPattern::Mode(Some((*mode).to_string()))
        }
        [PathPart::Part("gamemodes"), ..] => TargetPattern::Mode(None),
        [PathPart::Part("heroes"), PathPart::Team, PathPart::Hero, ..] => {
            target_for_hero(path, None)
        }
        [
            PathPart::Part("heroes"),
            PathPart::Part(team),
            PathPart::Hero,
            ..,
        ] => target_for_hero(path, Some((*team).to_string())),
        [PathPart::Part("heroes"), PathPart::Team, ..] => target_for_team(path, None),
        [PathPart::Part("heroes"), PathPart::Part(team), ..] => {
            target_for_team(path, Some((*team).to_string()))
        }
        [
            PathPart::Part("main" | "lobby" | "extensions" | "workshop"),
            ..,
        ] => TargetPattern::Global,
        _ => TargetPattern::Unknown,
    }
}

fn target_for_team(path: &[PathPart<'_>], team: Option<String>) -> TargetPattern {
    match semantic_ability_slot_for_path(path) {
        Some(slot) => TargetPattern::TeamAbility {
            team,
            slot: LogicalSlot::new(slot),
            variant: None,
        },
        None => TargetPattern::Team(team),
    }
}

fn target_for_hero(path: &[PathPart<'_>], team: Option<String>) -> TargetPattern {
    let slot = semantic_ability_slot_for_path(path).map(str::to_string);
    match slot {
        Some(slot) => TargetPattern::HeroAbility {
            team,
            hero: None,
            slot: LogicalSlot::new(slot),
            variant: None,
        },
        None => TargetPattern::Hero { team, hero: None },
    }
}

fn semantic_ability_slot_for_path(path: &[PathPart<'_>]) -> Option<&'static str> {
    match path.last() {
        Some(PathPart::Part("enablePrimaryFire")) => Some("primaryFire"),
        Some(PathPart::Part("enableGenericSecondaryFire")) => Some("secondaryFire"),
        Some(PathPart::Part("enablePassiveUnlimitedFuel")) => Some("passive"),
        Some(PathPart::Part("enablePrimaryFireFreezeStack")) => Some("primaryFire"),
        Some(PathPart::Part(key)) if key.starts_with("ability1") => Some("ability1"),
        Some(PathPart::Part(key)) if key.starts_with("ability2") => Some("ability2"),
        Some(PathPart::Part(key)) if key.starts_with("ability3") => Some("ability3"),
        Some(PathPart::Part(key)) if key.starts_with("secondaryFire") => Some("secondaryFire"),
        _ => table::ability_slot_for_path(path),
    }
}

fn domain_for(kind: KeyKind) -> SettingValueDomain {
    match kind {
        KeyKind::Flag => SettingValueDomain::PresenceOnly,
        KeyKind::String => SettingValueDomain::String,
        KeyKind::Bool => SettingValueDomain::Boolean,
        KeyKind::Number => SettingValueDomain::Number(NumericBounds::unknown()),
        KeyKind::Percent => SettingValueDomain::Percent(NumericBounds::unknown()),
        KeyKind::Enum(domain) => SettingValueDomain::Enum {
            domain: domain.to_string(),
        },
        KeyKind::ListMap => SettingValueDomain::MapList,
        KeyKind::ListHero => SettingValueDomain::HeroList,
    }
}

fn canonical_id(scope: SettingScope, key: &str, path: &[PathPart<'_>]) -> Option<SettingId> {
    let prefix = match scope {
        SettingScope::Main => "main",
        SettingScope::Lobby => "lobby",
        SettingScope::GameModes => "gameMode",
        SettingScope::Heroes => "hero",
        SettingScope::Extensions => "extension",
        SettingScope::Workshop => "workshop",
        SettingScope::Unknown => "unknown",
    };
    if matches!(scope, SettingScope::Unknown) {
        return None;
    }
    let concept = canonical_concept(key, path)?;
    Some(SettingId::new(format!("setting.{prefix}.{concept}")))
}

/// Map a Workshop leaf to a locale-independent setting concept. These names
/// intentionally describe the setting's meaning, while hero and logical slot
/// topology stays in `SettingTarget`.
fn canonical_concept(key: &str, path: &[PathPart<'_>]) -> Option<String> {
    let key = key.trim_end_matches('%');
    Some(match key {
        "health" => "health".to_string(),
        "damageDealt" | "damageReceived" | "healingDealt" | "healingReceived" => key.to_string(),
        "passiveUltGen" => "ultimateGeneration.passive".to_string(),
        "combatUltGen" => "ultimateGeneration.combat".to_string(),
        "ultGen" => "ultimateGeneration".to_string(),
        "enableUlt" => "ability.enabled".to_string(),
        "enablePrimaryFire"
        | "enableSecondaryFire"
        | "enableGenericSecondaryFire"
        | "enableAbility1"
        | "enableAbility2"
        | "enableAbility3" => "ability.enabled".to_string(),
        "enableAutomaticFire" => "primaryFire.automaticFireEnabled".to_string(),
        "enableScoping" => "primaryFire.scopingEnabled".to_string(),
        "enablePassiveUnlimitedFuel" => "passive.unlimitedFuelEnabled".to_string(),
        "enablePrimaryFireFreezeStack" => "primaryFire.freezeStackEnabled".to_string(),
        "setValidControlPoints" | "firstActiveControlPoint" => path
            .iter()
            .filter_map(|part| match part {
                PathPart::Part(name) if *name != "gamemodes" && *name != key => Some(*name),
                _ => None,
            })
            .next()
            .map(|mode| format!("{key}.{mode}"))?,
        _ => key.to_string(),
    })
}

/// Validate the effective settings catalog and reject stale or conflicting
/// semantic projections before parser/emitter data is shipped.
pub fn validate_catalog() -> Result<(), Vec<String>> {
    use std::collections::{HashMap, HashSet};

    let mut errors = Vec::new();
    errors.extend(reconciliation::validate());
    errors.extend(validate_raw_projection(table::raw_entries()));
    errors.extend(validate_enum_projection(
        table::ENUM_MEMBERS.iter(),
        table::GENERATED_ENUM_MEMBERS.iter(),
        &reconciliation::data().enum_member_mappings,
    ));
    let mut paths = HashSet::new();
    let mut concepts: HashMap<(String, SettingTargetKind, String), SettingValueDomain> =
        HashMap::new();
    let mut concept_keys: HashMap<(String, SettingTargetKind), String> = HashMap::new();

    for definition in definitions() {
        if !paths.insert(definition.path.clone()) {
            errors.push(format!("duplicate settings path: {}", definition.path));
        }
        if definition.scope == SettingScope::Unknown {
            errors.push(format!("unknown settings scope: {}", definition.path));
        }
        let Some(id) = definition.id() else {
            errors.push(format!(
                "missing canonical settings identity: {}",
                definition.path
            ));
            continue;
        };
        if !definition.provenance.reviewed {
            errors.push(format!(
                "unreviewed settings definition: {}",
                definition.path
            ));
        }
        if definition.presentation.english_name.is_empty() {
            errors.push(format!(
                "missing settings presentation: {}",
                definition.path
            ));
        }
        let target_kind = definition.target_kind();
        let semantic_key = semantic_identity_key(definition.key);
        let collision_key = (id.as_str().to_string(), target_kind.clone());
        if let Some(previous_key) = concept_keys.insert(collision_key, semantic_key.clone()) {
            if previous_key != semantic_key {
                errors.push(format!(
                    "conflicting settings concepts for {id}: {previous_key} vs {semantic_key}"
                ));
            }
        }
        let key = (id.as_str().to_string(), target_kind, semantic_key);
        if let Some(previous) = concepts.insert(key, definition.domain.clone()) {
            if previous != definition.domain {
                errors.push(format!("conflicting settings domains for {id}"));
            }
        }
    }
    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

/// Reject raw table overlaps unless their complete parser/emitter contract is
/// identical. Effective lookup may deduplicate exact repeats, but must never
/// make a divergent generated or fixture projection silently win.
fn validate_raw_projection(
    entries: impl IntoIterator<Item = table::ProjectedEntry>,
) -> Vec<String> {
    use std::collections::HashMap;

    let mut errors = Vec::new();
    let mut paths = HashMap::new();
    for projected in entries {
        let entry = projected.entry;
        if let Some(previous) = paths.insert(entry.path, projected) {
            if previous.entry != entry
                && !reconciled_entry_override(
                    table::path_string(entry.path).as_str(),
                    previous,
                    projected,
                )
            {
                errors.push(format!(
                    "conflicting duplicate settings path between {} and {}: {}",
                    previous.source.label(),
                    projected.source.label(),
                    table::path_string(entry.path),
                ));
            }
        }
    }
    errors
}

fn reconciled_entry_override(
    path: &str,
    fixture: table::ProjectedEntry,
    generated: table::ProjectedEntry,
) -> bool {
    use table::ProjectionSource::{FixtureTable, WorkshopDataExport};

    let (fixture, generated) = match (fixture.source, generated.source) {
        (FixtureTable, WorkshopDataExport) => (fixture.entry, generated.entry),
        (WorkshopDataExport, FixtureTable) => (generated.entry, fixture.entry),
        _ => return false,
    };
    reconciliation::data()
        .entry_overrides
        .iter()
        .find(|override_| override_.path == path)
        .is_some_and(|override_| {
            entry_contract_matches(fixture, &override_.fixture)
                && entry_contract_matches(generated, &override_.generated)
        })
}

fn entry_contract_matches(entry: &TableEntry, expected: &reconciliation::EntryContract) -> bool {
    entry.workshop_name == expected.name && key_kind_matches(entry.kind, expected)
}

fn key_kind_matches(kind: KeyKind, expected: &reconciliation::EntryContract) -> bool {
    match (kind, expected.kind.as_str(), expected.domain.as_deref()) {
        (KeyKind::Flag, "flag", None)
        | (KeyKind::String, "string", None)
        | (KeyKind::Bool, "bool", None)
        | (KeyKind::Number, "number", None)
        | (KeyKind::Percent, "percent", None)
        | (KeyKind::ListMap, "mapList", None)
        | (KeyKind::ListHero, "heroList", None) => true,
        (KeyKind::Enum(actual), "enum", Some(expected)) => actual == expected,
        _ => false,
    }
}

/// Validate enum members independently of entry lookup order. This catches
/// both stale enum projections and conflicting duplicate spellings that the
/// lookup helper would otherwise hide.
fn validate_enum_projection(
    fixture_entries: impl IntoIterator<Item = &'static table::EnumMember>,
    generated_entries: impl IntoIterator<Item = &'static table::EnumMember>,
    mappings: &[reconciliation::EnumMemberMapping],
) -> Vec<String> {
    use std::collections::{HashMap, HashSet};

    let domains: HashSet<_> = table::entries()
        .filter_map(|entry| match entry.kind {
            KeyKind::Enum(domain) => Some(domain),
            _ => None,
        })
        .collect();
    let mut errors = Vec::new();
    let mut members = HashMap::new();
    let mut names = HashMap::new();
    for member in fixture_entries {
        if !domains.contains(member.domain) {
            errors.push(format!("orphaned settings enum domain: {}", member.domain));
        }
        let key = (member.domain, member.member);
        if let Some(previous) = members.insert(key, member.name) {
            if previous != member.name {
                errors.push(format!(
                    "conflicting settings enum member {}.{}: {previous:?} vs {:?}",
                    member.domain, member.member, member.name
                ));
            }
        }
        if let Some(previous) = names.insert((member.domain, member.name), member.member) {
            if previous != member.member {
                errors.push(format!(
                    "conflicting settings enum display name {}.{:?}: {previous} vs {}",
                    member.domain, member.name, member.member
                ));
            }
        }
    }
    let fixture_members: HashMap<_, _> = table::ENUM_MEMBERS
        .iter()
        .map(|member| ((member.domain, member.member), member))
        .collect();
    let mut mapped_sources = HashSet::new();
    for member in generated_entries {
        let key = (member.domain, member.member);
        if let Some(previous) = members.insert(key, member.name) {
            if previous != member.name {
                errors.push(format!(
                    "conflicting settings enum member {}.{}: {previous:?} vs {:?}",
                    member.domain, member.member, member.name
                ));
            }
        }
        let mapping = mappings.iter().find(|mapping| {
            mapping.source_domain == member.domain && mapping.source_member == member.member
        });
        if mapping.is_none() && !domains.contains(member.domain) {
            errors.push(format!("orphaned settings enum domain: {}", member.domain));
        }
        let (domain, canonical_member, name) = match mapping {
            Some(mapping) => {
                if !mapped_sources.insert((
                    mapping.source_domain.as_str(),
                    mapping.source_member.as_str(),
                )) {
                    errors.push(format!(
                        "duplicate settings enum reconciliation for {}.{}",
                        mapping.source_domain, mapping.source_member
                    ));
                }
                match fixture_members.get(&(
                    mapping.target_domain.as_str(),
                    mapping.target_member.as_str(),
                )) {
                    Some(target) if target.name == member.name => {
                        (target.domain, target.member, target.name)
                    }
                    Some(target) => {
                        errors.push(format!(
                            "settings enum reconciliation name mismatch {}.{} -> {}.{}: {:?} vs {:?}",
                            mapping.source_domain, mapping.source_member,
                            mapping.target_domain, mapping.target_member, member.name, target.name
                        ));
                        continue;
                    }
                    None => {
                        errors.push(format!(
                            "settings enum reconciliation target is missing: {}.{} -> {}.{}",
                            mapping.source_domain,
                            mapping.source_member,
                            mapping.target_domain,
                            mapping.target_member
                        ));
                        continue;
                    }
                }
            }
            None => (member.domain, member.member, member.name),
        };
        if let Some(previous) = names.insert((domain, name), canonical_member) {
            if previous != canonical_member {
                errors.push(format!(
                    "conflicting settings enum display name {}.{name:?}: {previous} vs {canonical_member}",
                    domain
                ));
            }
        }
    }
    for mapping in mappings {
        if !mapped_sources.contains(&(
            mapping.source_domain.as_str(),
            mapping.source_member.as_str(),
        )) {
            errors.push(format!(
                "orphaned settings enum reconciliation: {}.{}",
                mapping.source_domain, mapping.source_member
            ));
        }
    }
    errors
}

fn semantic_identity_key(key: &str) -> String {
    match key {
        "enableSecondaryFire" | "enableGenericSecondaryFire" => "enableSecondaryFire".to_string(),
        _ => key.to_string(),
    }
}

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

    static DUPLICATE_PATH: [PathPart<'static>; 2] =
        [PathPart::Part("test"), PathPart::Part("value")];
    static FIXTURE_ENTRY: TableEntry = TableEntry {
        path: &DUPLICATE_PATH,
        workshop_name: "Fixture Value",
        kind: KeyKind::Bool,
    };
    static GENERATED_ENTRY: TableEntry = TableEntry {
        path: &DUPLICATE_PATH,
        workshop_name: "Generated Value",
        kind: KeyKind::Bool,
    };
    static FIXTURE_ENUM_MEMBER: table::EnumMember = table::EnumMember {
        domain: "mapRotation",
        member: "afterAGame",
        name: "After A Game",
    };
    static GENERATED_ENUM_MEMBER: table::EnumMember = table::EnumMember {
        domain: "mapRotation",
        member: "afterAGame",
        name: "After Game",
    };
    static DISPLAY_NAME_COLLISION: table::EnumMember = table::EnumMember {
        domain: "mapRotation",
        member: "afterMirrorMatch",
        name: "After A Game",
    };
    static EXPORT_ENUM_MEMBER: table::EnumMember = table::EnumMember {
        domain: "setting_lobby_mapRotation",
        member: "afterGame",
        name: "After A Game",
    };

    fn definition(target: TargetPattern) -> SettingDefinition {
        SettingDefinition {
            identity: SettingIdentity::Known(SettingId::new("setting.test.value")),
            scope: SettingScope::Heroes,
            path: "heroes.test.value".to_string(),
            path_parts: &[],
            key: "value",
            target,
            domain: SettingValueDomain::Boolean,
            presentation: SettingPresentation {
                english_name: "Value",
                locale_section: "labels",
            },
            provenance: SettingProvenance {
                kind: SettingEvidenceKind::RawWorkshopFixture,
                source: "test",
                reviewed: true,
            },
        }
    }

    #[test]
    fn common_target_narrowing_rejects_team_and_slot_mismatches() {
        let team = definition(TargetPattern::Team(Some("team1".to_string())));
        assert_eq!(
            team.applicability(&SettingTarget::Hero {
                team: Some(TeamId::new("team2")),
                hero: HeroId::from(crate::gameplay::hero_ids::ANA),
            })
            .expect("applicability"),
            Applicability::NotApplicable
        );

        let team_ability = definition(TargetPattern::TeamAbility {
            team: Some("team1".to_string()),
            slot: LogicalSlot::from(crate::gameplay::slots::PRIMARY_FIRE),
            variant: None,
        });
        let target = SettingTarget::HeroAbility {
            team: Some(TeamId::new("team2")),
            hero: HeroId::from(crate::gameplay::hero_ids::DVA),
            slot: LogicalSlot::from(crate::gameplay::slots::ABILITY_1),
            variant: Some(AbilityVariant::new("mech")),
        };
        assert_eq!(
            team_ability.applicability(&target).expect("applicability"),
            Applicability::NotApplicable
        );
    }

    #[test]
    fn raw_projection_conflicts_include_presentation_contract() {
        let errors = validate_raw_projection([
            table::ProjectedEntry {
                source: table::ProjectionSource::FixtureTable,
                entry: &FIXTURE_ENTRY,
            },
            table::ProjectedEntry {
                source: table::ProjectionSource::WorkshopDataExport,
                entry: &GENERATED_ENTRY,
            },
        ]);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("fixture table"));
        assert!(errors[0].contains("Workshop-data export"));
    }

    #[test]
    fn enum_projection_conflicts_are_not_hidden_by_lookup_order() {
        let errors =
            validate_enum_projection([&FIXTURE_ENUM_MEMBER], [&GENERATED_ENUM_MEMBER], &[]);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("mapRotation.afterAGame"));
    }

    #[test]
    fn enum_projection_rejects_display_name_to_identity_collisions() {
        let errors =
            validate_enum_projection([&FIXTURE_ENUM_MEMBER, &DISPLAY_NAME_COLLISION], [], &[]);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("conflicting settings enum display name"));
    }

    #[test]
    fn enum_projection_reconciles_export_members_to_canonical_identities() {
        let mappings = [reconciliation::EnumMemberMapping {
            source_domain: "setting_lobby_mapRotation".to_string(),
            source_member: "afterGame".to_string(),
            target_domain: "mapRotation".to_string(),
            target_member: "afterAGame".to_string(),
        }];
        let errors =
            validate_enum_projection([&FIXTURE_ENUM_MEMBER], [&EXPORT_ENUM_MEMBER], &mappings);
        assert!(errors.is_empty(), "{errors:?}");
    }
}