foch 0.0.2

EU4 mod analysis and merge toolkit
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
use crate::model::{GamePath, MaybeScope, ScopeType};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

mod families;
pub(crate) mod load_rules;
mod transform;

#[cfg(test)]
pub(crate) use families::eu4_content_families;
pub use families::{EU4_LOCALISATION_LANGUAGE_HEADERS, eu4, eu4_content_family_for_root_family};

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ContentFamilyId(Arc<str>);

impl ContentFamilyId {
	pub fn new(id: impl Into<Arc<str>>) -> Self {
		Self(id.into())
	}

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

#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ScriptFileKind(Arc<str>);

impl ScriptFileKind {
	pub fn new(name: impl Into<Arc<str>>) -> Self {
		Self(name.into())
	}

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

/// How to resolve scalar conflicts during deep merge.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ScalarMergePolicy {
	/// Sibling mods that change the same scalar to different values must be
	/// reported as a manual conflict rather than silently choosing one. This
	/// is the **baseline** for any family without an explicit numeric policy:
	/// when sibling mods disagree on a scalar leaf there is no signal in the
	/// dependency graph that says which value should win, so the merge engine
	/// must defer the choice to the user (or a `[[resolutions]]` decision)
	/// instead of falling back to an implicit precedence-based pick. The
	/// cross-level dependency-chain "later level overrides earlier" semantics
	/// are handled separately by `patch_deps.rs::compute_dag_patches_*`, which
	/// applies each level's resolved patches into the running base before
	/// diffing the next level — so a downstream mod that *does* explicitly
	/// depend on an upstream mod still wins without invoking this policy.
	#[default]
	Conflict,
	/// Parse both as f64 and sum them.
	Sum,
	/// Parse both as f64 and average them.
	Avg,
	/// Parse both as f64 and take the maximum.
	Max,
	/// Parse both as f64 and take the minimum.
	Min,
	/// Highest-precedence sibling assignment wins. Explicit opt-in for content
	/// families where conflicting leaf assignments, including opaque
	/// block-valued script/effect wrappers, are ordinary load-order overrides
	/// inside an otherwise recursive structural merge.
	LastWriter,
	/// For GUI coordinate leaves only: numeric `x`/`y` scalar conflicts keep
	/// the lowest-precedence contributor. Other scalar leaves still conflict.
	/// This models compatibility patches that preserve the base layout anchor
	/// while recursively unioning sibling GUI edits; it is intentionally much
	/// narrower than `LastWriter`.
	CoordinateFirstWriter,
	/// GUI-specific scalar tie-breaker for same-name widgets: numeric layout
	/// coordinates/bounds keep the lowest-precedence contributor, while sprite
	/// references keep the highest-precedence contributor. Other scalar leaves
	/// still conflict.
	GuiWidget,
}

impl ScalarMergePolicy {
	/// Reduce all changed contributor values in one operation. Callers must
	/// exclude unchanged base copies before invoking this method.
	pub fn reduce_numeric_values<'a>(
		self,
		values: impl IntoIterator<Item = &'a str>,
	) -> Option<String> {
		let values = values.into_iter().collect::<Vec<_>>();
		values.first()?;
		let numbers = values
			.iter()
			.map(|value| parse_finite_number(value))
			.collect::<Option<Vec<_>>>()?;
		let reduced = match self {
			Self::Sum => numbers.iter().sum(),
			Self::Avg => numbers.iter().sum::<f64>() / numbers.len() as f64,
			Self::Max => numbers.into_iter().reduce(f64::max)?,
			Self::Min => numbers.into_iter().reduce(f64::min)?,
			Self::Conflict | Self::LastWriter | Self::CoordinateFirstWriter | Self::GuiWidget => {
				return None;
			}
		};
		format_reduced_number(reduced, &values)
	}

	/// Reduce one pair of already-classified numeric scalar texts. Parsing is
	/// deliberately identical to the existing patch reducer: strict `f64`
	/// parsing, with no coercion of identifiers, dates, or tuple-like values.
	pub fn reduce_numeric_pair(self, left: &str, right: &str) -> Option<String> {
		self.reduce_numeric_values([left, right])
	}
}

fn parse_finite_number(value: &str) -> Option<f64> {
	value.parse::<f64>().ok().filter(|value| value.is_finite())
}

fn format_reduced_number(value: f64, inputs: &[&str]) -> Option<String> {
	if !value.is_finite() {
		return None;
	}
	if value == 0.0 {
		return Some("0".to_string());
	}

	let absolute = value.abs();
	let mut text = if !(1e-15..1e15).contains(&absolute) {
		format!("{value}")
	} else {
		let fixed = format!("{value:.15}");
		fixed
			.trim_end_matches('0')
			.trim_end_matches('.')
			.to_string()
	};
	let omits_leading_zero = inputs.iter().all(|input| {
		input
			.strip_prefix(['+', '-'])
			.unwrap_or(input)
			.starts_with('.')
	});
	if omits_leading_zero {
		if let Some(fraction) = text.strip_prefix("0.") {
			text = format!(".{fraction}");
		} else if let Some(fraction) = text.strip_prefix("-0.") {
			text = format!("-.{fraction}");
		}
	}
	Some(text)
}

/// How to merge bare list items (entries without assignment keys).
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ListMergePolicy {
	/// Append unique items from overlay, dedup by value (default).
	#[default]
	Union,
	/// Append all items; rename duplicates to `{item}_{mod_name}`.
	UnionWithRename,
	/// Preserve base order, append overlay's new items at end.
	OrderedUnion,
	/// Overlay's list replaces base entirely.
	Replace,
}

/// How structured merge treats a base child omitted by one sibling while the
/// other sibling retains it unchanged.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OneSidedRemovalPolicy {
	/// Ordinary three-way semantics: the one-sided removal wins.
	#[default]
	Remove,
	/// Preserve the unchanged child when its semantic parent exists in both
	/// sibling revisions. A removal made by both siblings still wins.
	PreserveIfParentSurvives,
	/// Preserve only additive script structure: optional hook containers,
	/// non-exclusive control-flow branches, and boolean predicates.
	PreserveAdditiveStructure,
	/// Preserve a one-sided removal only when the child is an alternative in an
	/// `OR` block that survives in both sibling revisions.
	PreserveBooleanAlternatives,
}

/// How independently inserted children using the nested merge key correspond
/// across sibling revisions.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NestedInsertionPolicy {
	/// Treat the nested key as sufficient identity even when neither insertion
	/// can be traced to an ancestor child.
	#[default]
	MatchByKey,
	/// Only correlate nested children through a shared ancestor. Unbased
	/// insertions remain source-isolated and are appended in revision order,
	/// preserving each source's order and duplicate cardinality.
	SourceIsolatedAppend,
}

/// How to merge child blocks that share the same key.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BlockMergePolicy {
	/// Deep merge child blocks by key (default).
	#[default]
	Recursive,
	/// Overlay's block replaces base entirely.
	Replace,
}

/// How to merge boolean condition blocks (triggers, potentials, etc.)
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BooleanMergePolicy {
	/// Combine complete revision predicates with AND semantics (both must hold).
	And,
	/// Combine complete revision predicates with OR semantics (either may hold).
	#[default]
	Or,
	/// Overlay replaces base entirely.
	Replace,
}

/// How to resolve named-container body conflicts (e.g. `windowType { name = "x" ... }`)
/// when multiple mods modify the same identity with non-recursively-mergeable content.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NamedContainerPolicy {
	/// Sibling mods that target the same named identity (e.g. two mods both
	/// modify `windowType { name = "left_widget" }`) with non-recursively
	/// mergeable bodies must be reported as a manual conflict. This is the
	/// **baseline** for any family without an explicit silent-strategy
	/// override: like `ScalarMergePolicy::Conflict`, when there is no
	/// dependency-graph signal saying which mod's named child should win the
	/// engine defers the choice to the user instead of fabricating a merge
	/// (e.g. by renaming one side, which produces a *different* game entity
	/// rather than the merged result the user was asking for).
	#[default]
	Conflict,
	/// Lenient: keep both — rename the conflicting candidate's name field (or its
	/// assignment key) with a `_<mod_id>` suffix so both definitions coexist.
	/// Useful for GUI / icon families where multiple mods can ship parallel
	/// widgets without conflict, but explicitly opted into per family.
	SuffixRename,
	/// Strict-with-scalars: highest-precedence overlay wins; conflicting children
	/// from earlier candidates are dropped. Explicit per family.
	OverlayWins,
	/// GUI keep-both: instead of conflicting, synthesize a single widget that
	/// keeps the same `name` (so the engine still finds it) and nests BOTH
	/// contributors' bodies as vertically-offset child `containerWindowType`s
	/// inside a scrollable parent. Lossless — every widget from both sides
	/// survives. Opt-in (the in-game scroll layout is best-effort). EU4-only
	/// limitation: there is no scripted toggle/tab, so "keep both" = scroll.
	ScrollStack,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ScalarReducerRule {
	pub path_suffix: &'static [&'static str],
	pub reducer: ScalarMergePolicy,
}

impl ScalarReducerRule {
	pub const fn new(path_suffix: &'static [&'static str], reducer: ScalarMergePolicy) -> Self {
		Self {
			path_suffix,
			reducer,
		}
	}

	fn matches<T: AsRef<str>>(&self, path: &[T]) -> bool {
		!self.path_suffix.is_empty()
			&& path.len() >= self.path_suffix.len()
			&& path[path.len() - self.path_suffix.len()..]
				.iter()
				.zip(self.path_suffix)
				.all(|(component, expected)| component.as_ref() == *expected)
	}
}

/// Domain policies used by every structural merge implementation.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct MergePolicies {
	pub merge_key_source: MergeKeySource,
	pub nested_merge_key_source: MergeKeySource,
	#[serde(default)]
	pub nested_insertion: NestedInsertionPolicy,
	pub scalar: ScalarMergePolicy,
	#[serde(skip)]
	pub scalar_reducer_rules: &'static [ScalarReducerRule],
	pub list: ListMergePolicy,
	#[serde(default)]
	pub one_sided_removal: OneSidedRemovalPolicy,
	pub block: BlockMergePolicy,
	pub boolean: BooleanMergePolicy,
	pub divergent_block: DivergentBlockPolicy,
	#[serde(skip)]
	pub divergent_block_rules: &'static [(&'static str, DivergentBlockPolicy)],
	pub named_container: NamedContainerPolicy,
	/// When one mod edits a property and a sibling mod removes it, keep the edit
	/// instead of reporting a conflict. This is opt-in for GUI/asset families,
	/// where an omitted field commonly means that a trimmed widget copy did not
	/// re-ship the field. Game-logic families keep edit-vs-remove as a conflict.
	#[serde(default)]
	pub edit_wins_over_remove: bool,
}

impl MergePolicies {
	pub fn scalar_reducer_rule_for_path<T: AsRef<str>>(
		&self,
		path: &[T],
	) -> Option<&'static ScalarReducerRule> {
		let mut best = None;
		for rule in self.scalar_reducer_rules {
			if rule.matches(path)
				&& best.is_none_or(|current: &ScalarReducerRule| {
					rule.path_suffix.len() > current.path_suffix.len()
				}) {
				best = Some(rule);
			}
		}
		best
	}

	pub fn divergent_block_policy_for_key(&self, key: &str) -> DivergentBlockPolicy {
		self.divergent_block_rules
			.iter()
			.find_map(|(policy_key, policy)| (*policy_key == key).then_some(*policy))
			.unwrap_or(self.divergent_block)
	}
}

/// How divergent block-valued nodes are combined.
///
/// This policy belongs to the content family. Merge kernels may implement it
/// with tree synthesis or another structural representation, but the behavior
/// must not depend on that representation.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DivergentBlockPolicy {
	/// Select the highest-precedence complete block.
	LastWriter,
	/// Combine each mod's body inside an `OR = { ... }` wrapper so the
	/// resulting trigger fires if any contributor's predicate holds.
	BooleanOr,
	/// Union the base block's list-like items with every replacement body,
	/// de-duplicating by content fingerprint while preserving first-seen order.
	Union,
	/// Recursively merge the contributors' block bodies. This is the default
	/// for a family/key without an explicit override; unresolved descendants
	/// remain explicit conflicts.
	#[default]
	Recurse,
}

/// How to handle conflicts when two unrelated mods define the same merge key.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConflictPolicy {
	/// Rename conflicting definitions to `{key}_{mod_name}` (default for most families).
	#[default]
	Rename,
	/// Merge leaf values (last-writer per leaf) — for defines-style nested config.
	MergeLeaf,
	/// Last writer wins silently — for families where override is expected.
	LastWriter,
	/// Wrap conflicting bodies in `OR = { <body_a> <body_b> }` (for boolean
	/// trigger-style content where same-named definitions from different mods
	/// should be combined disjunctively rather than suffix-renamed).
	BooleanOr,
}

/// Dedup safety for a content family, replacing the former
/// `cross_file_dedup_safe` / `per_entry_dedup_safe` boolean pair.
///
/// *Cross-file* dedup is safe only for content families where the game builds a global key
/// namespace and file location does not affect the runtime meaning of an identical definition.
/// *Per-entry* dedup is safe only for content families where omitting a same-file entry whose
/// merged value is identical to vanilla leaves the vanilla definition active with the same runtime meaning.
///
/// The four variants are exactly the four reachable boolean combinations.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum DedupPolicy {
	#[default]
	None,
	PerEntryOnly,
	CrossFileOnly,
	CrossFileAndPerEntry,
}

impl DedupPolicy {
	pub const fn cross_file_safe(self) -> bool {
		matches!(
			self,
			DedupPolicy::CrossFileOnly | DedupPolicy::CrossFileAndPerEntry
		)
	}

	pub const fn per_entry_safe(self) -> bool {
		matches!(
			self,
			DedupPolicy::PerEntryOnly | DedupPolicy::CrossFileAndPerEntry
		)
	}

	pub(crate) const fn with_per_entry(self) -> Self {
		match self {
			DedupPolicy::None => DedupPolicy::PerEntryOnly,
			DedupPolicy::CrossFileOnly => DedupPolicy::CrossFileAndPerEntry,
			other => other,
		}
	}
}

#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum ContentLoadPolicy {
	#[default]
	PerPath,
	DefinitionModule(DefinitionModulePolicy),
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct DefinitionModulePolicy {
	pub definition_key: DefinitionKeyPolicy,
	pub file_order: DefinitionFileOrder,
	pub duplicate_definitions: DuplicateDefinitionPolicy,
	pub output_path: &'static GamePath,
	/// The directory the module reads its input files from.
	pub namespace_prefix: &'static GamePath,
	pub output_mode: DefinitionModuleOutput,
	/// Increment when loader semantics change. Callers must include this value
	/// in cache identities for canonical module output.
	pub policy_version: u32,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum DefinitionModuleOutput {
	Overlay,
	ReplaceNamespace,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum DefinitionKeyPolicy {
	AssignmentKey,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum DefinitionFileOrder {
	NormalizedPathAscending,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum DuplicateDefinitionPolicy {
	LaterDefinitionWins,
	PreserveAll,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct ContentFamilyCapabilities {
	pub semantic_complete: bool,
	pub graph_ready: bool,
	pub merge_ready: bool,
	pub dedup_policy: DedupPolicy,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ContentFamilyScopePolicy {
	pub root_scope: MaybeScope,
	pub from_alias: Option<ScopeType>,
	/// True when this content family has no statically determinable implicit
	/// scope at runtime (callables, UI bindings, customizable localization,
	/// on_actions callbacks, etc.). Analyses that warn about Unknown scope
	/// (unknown-scope-type) should suppress findings inside such files because the implicit
	/// scope is supplied by the caller, not the file.
	pub dynamic_scope: bool,
}

impl Default for ContentFamilyScopePolicy {
	fn default() -> Self {
		Self {
			root_scope: MaybeScope::Unknown,
			from_alias: None,
			dynamic_scope: false,
		}
	}
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ModuleNameRule {
	Static(&'static str),
	/// `fallback`, followed by each directory between the family's prefix
	/// and the file: `common/scripted_effects/a/b/c.txt` is
	/// `scripted_effects.a.b`.
	Tail {
		fallback: &'static str,
	},
	FallbackParent,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum MergeKeySource {
	/// Top-level named assignments are the merge units (e.g. `effect_name = { ... }`).
	#[default]
	AssignmentKey,
	/// Merge key is extracted from an inner field value (e.g. `id` inside event blocks).
	FieldValue(&'static str),
	/// Merge units are children of a known container block (e.g. decisions).
	ContainerChildKey,
	/// Merge units are child assignments inside a named container, keyed by an
	/// inner scalar field. `child_types = []` means any child assignment with the
	/// field participates; otherwise unmatched children fall back to assignment-key
	/// semantics inside the container.
	ContainerChildFieldValue {
		containers: &'static [&'static str],
		child_key_field: &'static str,
		child_types: &'static [&'static str],
	},
	/// Merge units are direct child assignments in the current block, keyed by
	/// an inner scalar field. Used for recursive merges inside a
	/// `ContainerChildFieldValue` unit, where the outer container has already
	/// been stripped from the local diff body.
	ChildFieldValue {
		child_key_field: &'static str,
		child_types: &'static [&'static str],
	},
	/// Leaf-level defines paths (e.g. `NGame.START_YEAR`).
	LeafPath,
}

impl MergeKeySource {
	pub const fn nested(self) -> Self {
		match self {
			MergeKeySource::ContainerChildFieldValue {
				child_key_field,
				child_types,
				..
			} => MergeKeySource::ChildFieldValue {
				child_key_field,
				child_types,
			},
			MergeKeySource::ChildFieldValue { .. } => self,
			_ => MergeKeySource::AssignmentKey,
		}
	}
}

#[derive(Serialize)]
struct ContainerChildFieldValueSerde<'a> {
	containers: &'a [&'a str],
	child_key_field: &'a str,
	child_types: &'a [&'a str],
}

#[derive(Deserialize)]
struct ContainerChildFieldValueOwned {
	containers: Vec<String>,
	child_key_field: String,
	#[serde(default)]
	child_types: Vec<String>,
}

#[derive(Serialize)]
struct ChildFieldValueSerde<'a> {
	child_key_field: &'a str,
	child_types: &'a [&'a str],
}

#[derive(Deserialize)]
struct ChildFieldValueOwned {
	child_key_field: String,
	#[serde(default)]
	child_types: Vec<String>,
}

impl Serialize for MergeKeySource {
	fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
		match self {
			MergeKeySource::AssignmentKey => serializer.serialize_str("assignment_key"),
			MergeKeySource::FieldValue(field) => {
				use serde::ser::SerializeMap;
				let mut map = serializer.serialize_map(Some(1))?;
				map.serialize_entry("field_value", field)?;
				map.end()
			}
			MergeKeySource::ContainerChildKey => serializer.serialize_str("container_child_key"),
			MergeKeySource::ContainerChildFieldValue {
				containers,
				child_key_field,
				child_types,
			} => {
				use serde::ser::SerializeMap;
				let spec = ContainerChildFieldValueSerde {
					containers,
					child_key_field,
					child_types,
				};
				let mut map = serializer.serialize_map(Some(1))?;
				map.serialize_entry("container_child_field_value", &spec)?;
				map.end()
			}
			MergeKeySource::ChildFieldValue {
				child_key_field,
				child_types,
			} => {
				use serde::ser::SerializeMap;
				let spec = ChildFieldValueSerde {
					child_key_field,
					child_types,
				};
				let mut map = serializer.serialize_map(Some(1))?;
				map.serialize_entry("child_field_value", &spec)?;
				map.end()
			}
			MergeKeySource::LeafPath => serializer.serialize_str("leaf_path"),
		}
	}
}

impl<'de> Deserialize<'de> for MergeKeySource {
	fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
		use serde::de;

		struct MergeKeySourceVisitor;
		impl<'de> de::Visitor<'de> for MergeKeySourceVisitor {
			type Value = MergeKeySource;
			fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
				write!(f, "a MergeKeySource string or map")
			}
			fn visit_str<E: de::Error>(self, v: &str) -> Result<MergeKeySource, E> {
				match v {
					"assignment_key" => Ok(MergeKeySource::AssignmentKey),
					"container_child_key" => Ok(MergeKeySource::ContainerChildKey),
					"leaf_path" => Ok(MergeKeySource::LeafPath),
					_ => Err(E::unknown_variant(
						v,
						&["assignment_key", "container_child_key", "leaf_path"],
					)),
				}
			}
			fn visit_map<A: de::MapAccess<'de>>(
				self,
				mut map: A,
			) -> Result<MergeKeySource, A::Error> {
				let key: String = map.next_key()?.ok_or_else(|| {
					de::Error::custom("expected field_value or container_child_field_value key")
				})?;
				match key.as_str() {
					"field_value" => {
						let value: String = map.next_value()?;
						let leaked: &'static str = Box::leak(value.into_boxed_str());
						Ok(MergeKeySource::FieldValue(leaked))
					}
					"container_child_field_value" => {
						let spec: ContainerChildFieldValueOwned = map.next_value()?;
						let containers = spec
							.containers
							.into_iter()
							.map(|container| Box::leak(container.into_boxed_str()) as &'static str)
							.collect::<Vec<_>>();
						let containers = Box::leak(containers.into_boxed_slice());
						let child_key_field = Box::leak(spec.child_key_field.into_boxed_str());
						let child_types = spec
							.child_types
							.into_iter()
							.map(|child_type| {
								Box::leak(child_type.into_boxed_str()) as &'static str
							})
							.collect::<Vec<_>>();
						let child_types = Box::leak(child_types.into_boxed_slice());
						Ok(MergeKeySource::ContainerChildFieldValue {
							containers,
							child_key_field,
							child_types,
						})
					}
					"child_field_value" => {
						let spec: ChildFieldValueOwned = map.next_value()?;
						let child_key_field = Box::leak(spec.child_key_field.into_boxed_str());
						let child_types = spec
							.child_types
							.into_iter()
							.map(|child_type| {
								Box::leak(child_type.into_boxed_str()) as &'static str
							})
							.collect::<Vec<_>>();
						let child_types = Box::leak(child_types.into_boxed_slice());
						Ok(MergeKeySource::ChildFieldValue {
							child_key_field,
							child_types,
						})
					}
					_ => Err(de::Error::unknown_field(
						&key,
						&[
							"field_value",
							"container_child_field_value",
							"child_field_value",
						],
					)),
				}
			}
		}
		deserializer.deserialize_any(MergeKeySourceVisitor)
	}
}

/// The game paths a content family owns. Both forms compare whole names as
/// spelled, including their case.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ContentFamilyPathMatcher {
	/// Every file below this directory, at any depth.
	Prefix(&'static GamePath),
	/// This one file.
	Exact(&'static GamePath),
}

impl ContentFamilyPathMatcher {
	pub fn matches(&self, path: &GamePath) -> bool {
		match self {
			Self::Prefix(directory) => path.strip_prefix(directory).is_some(),
			Self::Exact(file) => path == *file,
		}
	}
}

/// A game path spelled by a static rule table, either as a literal or
/// derived from one. The tables are fixed at compile time and their tests
/// build and check every entry, so text that is not a game path is a defect
/// in the table: it panics, naming the text, when the table is first built.
pub(crate) fn table_game_path(text: &str) -> &GamePath {
	match GamePath::new(text) {
		Ok(path) => path,
		Err(error) => panic!("static EU4 rule table: {error}"),
	}
}

#[non_exhaustive]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ContentFamilyDescriptor {
	pub id: ContentFamilyId,
	pub matcher: ContentFamilyPathMatcher,
	pub script_file_kind: ScriptFileKind,
	pub module_name_rule: ModuleNameRule,
	pub load_policy: ContentLoadPolicy,
	pub scope_policy: ContentFamilyScopePolicy,
	pub capabilities: ContentFamilyCapabilities,
	pub merge_key_source: Option<MergeKeySource>,
	pub conflict_policy: ConflictPolicy,
	pub merge_policies: MergePolicies,
}

#[derive(Clone, Debug)]
pub struct ContentFamilyDescriptorBuilder {
	id: ContentFamilyId,
	matcher: ContentFamilyPathMatcher,
	script_file_kind: ScriptFileKind,
	module_name_rule: ModuleNameRule,
	load_policy: ContentLoadPolicy,
	scope_policy: ContentFamilyScopePolicy,
	capabilities: ContentFamilyCapabilities,
	merge_key_source: Option<MergeKeySource>,
	conflict_policy: ConflictPolicy,
	merge_policies: MergePolicies,
}

impl ContentFamilyDescriptorBuilder {
	pub fn kind(mut self, kind: ScriptFileKind) -> Self {
		self.script_file_kind = kind;
		self
	}

	pub fn module_name(mut self, rule: ModuleNameRule) -> Self {
		self.module_name_rule = rule;
		self
	}

	pub fn load_policy(mut self, policy: ContentLoadPolicy) -> Self {
		self.load_policy = policy;
		self
	}

	pub fn scope(mut self, policy: ContentFamilyScopePolicy) -> Self {
		self.scope_policy = policy;
		self
	}

	pub fn capabilities(mut self, caps: ContentFamilyCapabilities) -> Self {
		self.capabilities = caps;
		self
	}

	pub fn per_entry_dedup_safe(mut self) -> Self {
		self.capabilities.dedup_policy = self.capabilities.dedup_policy.with_per_entry();
		self
	}

	pub fn merge_key(mut self, source: MergeKeySource) -> Self {
		self.merge_key_source = Some(source);
		self.merge_policies.merge_key_source = source;
		self.merge_policies.nested_merge_key_source = source.nested();
		self
	}

	pub fn nested_merge_key(mut self, source: MergeKeySource) -> Self {
		self.merge_policies.nested_merge_key_source = source;
		self
	}

	pub fn nested_insertion_policy(mut self, policy: NestedInsertionPolicy) -> Self {
		self.merge_policies.nested_insertion = policy;
		self
	}

	pub fn conflict_policy(mut self, policy: ConflictPolicy) -> Self {
		self.conflict_policy = policy;
		self
	}

	pub fn merge_policies(mut self, policies: MergePolicies) -> Self {
		self.merge_policies = policies;
		self
	}

	pub fn scalar_policy(mut self, policy: ScalarMergePolicy) -> Self {
		self.merge_policies.scalar = policy;
		self
	}

	pub fn scalar_reducer_rules(mut self, rules: &'static [ScalarReducerRule]) -> Self {
		self.merge_policies.scalar_reducer_rules = rules;
		self
	}

	pub fn list_policy(mut self, policy: ListMergePolicy) -> Self {
		self.merge_policies.list = policy;
		self
	}

	pub fn one_sided_removal_policy(mut self, policy: OneSidedRemovalPolicy) -> Self {
		self.merge_policies.one_sided_removal = policy;
		self
	}

	/// Opt this family into edit-wins-over-remove (GUI/asset families): a mod
	/// editing a property beats a sibling mod removing it, instead of conflicting.
	pub fn edit_wins_over_remove(mut self) -> Self {
		self.merge_policies.edit_wins_over_remove = true;
		self
	}

	pub fn block_policy(mut self, policy: BlockMergePolicy) -> Self {
		self.merge_policies.block = policy;
		self
	}

	pub fn boolean_policy(mut self, policy: BooleanMergePolicy) -> Self {
		self.merge_policies.boolean = policy;
		self
	}

	pub fn divergent_block_policy(mut self, policy: DivergentBlockPolicy) -> Self {
		self.merge_policies.divergent_block = policy;
		self
	}

	pub fn divergent_block_rules(
		mut self,
		policies: &'static [(&'static str, DivergentBlockPolicy)],
	) -> Self {
		self.merge_policies.divergent_block_rules = policies;
		self
	}

	pub fn build(self) -> ContentFamilyDescriptor {
		ContentFamilyDescriptor {
			id: self.id,
			matcher: self.matcher,
			script_file_kind: self.script_file_kind,
			module_name_rule: self.module_name_rule,
			load_policy: self.load_policy,
			scope_policy: self.scope_policy,
			capabilities: self.capabilities,
			merge_key_source: self.merge_key_source,
			conflict_policy: self.conflict_policy,
			merge_policies: self.merge_policies,
		}
	}
}

impl ContentFamilyDescriptor {
	/// Whether a file-level semantic merge may use an empty ancestor after the
	/// current game root has authoritatively proved that the exact path does not
	/// exist. This is a property of the merge unit: aggregate definition modules
	/// have namespace-wide ancestors and must not infer them from one path.
	pub fn supports_verified_empty_file_base(&self) -> bool {
		self.load_policy == ContentLoadPolicy::PerPath
			&& self.capabilities.merge_ready
			&& self.merge_key_source.is_some()
	}

	/// A family owning every file below `directory`, a game path literal.
	pub fn prefix(id: &'static str, directory: &'static str) -> ContentFamilyDescriptorBuilder {
		ContentFamilyDescriptorBuilder {
			id: ContentFamilyId::new(id),
			matcher: ContentFamilyPathMatcher::Prefix(table_game_path(directory)),
			script_file_kind: ScriptFileKind::new("other"),
			module_name_rule: ModuleNameRule::FallbackParent,
			load_policy: ContentLoadPolicy::PerPath,
			scope_policy: ContentFamilyScopePolicy {
				root_scope: MaybeScope::Unknown,
				from_alias: None,
				dynamic_scope: false,
			},
			capabilities: ContentFamilyCapabilities {
				semantic_complete: false,
				graph_ready: false,
				merge_ready: false,
				dedup_policy: DedupPolicy::None,
			},
			merge_key_source: None,
			conflict_policy: ConflictPolicy::Rename,
			merge_policies: MergePolicies {
				merge_key_source: MergeKeySource::AssignmentKey,
				nested_merge_key_source: MergeKeySource::AssignmentKey,
				nested_insertion: NestedInsertionPolicy::MatchByKey,
				scalar: ScalarMergePolicy::Conflict,
				scalar_reducer_rules: &[],
				list: ListMergePolicy::Union,
				one_sided_removal: OneSidedRemovalPolicy::Remove,
				block: BlockMergePolicy::Recursive,
				boolean: BooleanMergePolicy::Or,
				divergent_block: DivergentBlockPolicy::Recurse,
				divergent_block_rules: &[],
				named_container: NamedContainerPolicy::Conflict,
				edit_wins_over_remove: false,
			},
		}
	}

	/// A family owning the single file `exact_path`, a game path literal.
	pub fn exact(id: &'static str, exact_path: &'static str) -> ContentFamilyDescriptorBuilder {
		ContentFamilyDescriptorBuilder {
			id: ContentFamilyId::new(id),
			matcher: ContentFamilyPathMatcher::Exact(table_game_path(exact_path)),
			script_file_kind: ScriptFileKind::new("other"),
			module_name_rule: ModuleNameRule::FallbackParent,
			load_policy: ContentLoadPolicy::PerPath,
			scope_policy: ContentFamilyScopePolicy {
				root_scope: MaybeScope::Unknown,
				from_alias: None,
				dynamic_scope: false,
			},
			capabilities: ContentFamilyCapabilities {
				semantic_complete: false,
				graph_ready: false,
				merge_ready: false,
				dedup_policy: DedupPolicy::None,
			},
			merge_key_source: None,
			conflict_policy: ConflictPolicy::Rename,
			merge_policies: MergePolicies {
				merge_key_source: MergeKeySource::AssignmentKey,
				nested_merge_key_source: MergeKeySource::AssignmentKey,
				nested_insertion: NestedInsertionPolicy::MatchByKey,
				scalar: ScalarMergePolicy::Conflict,
				scalar_reducer_rules: &[],
				list: ListMergePolicy::Union,
				one_sided_removal: OneSidedRemovalPolicy::Remove,
				block: BlockMergePolicy::Recursive,
				boolean: BooleanMergePolicy::Or,
				divergent_block: DivergentBlockPolicy::Recurse,
				divergent_block_rules: &[],
				named_container: NamedContainerPolicy::Conflict,
				edit_wins_over_remove: false,
			},
		}
	}
}

pub fn module_name_for_descriptor(
	relative: &GamePath,
	descriptor: &ContentFamilyDescriptor,
) -> String {
	match descriptor.module_name_rule {
		ModuleNameRule::Static(value) => value.to_string(),
		ModuleNameRule::Tail { fallback } => module_with_tail(relative, descriptor, fallback),
		ModuleNameRule::FallbackParent => {
			fallback_module_name(&relative.iter().collect::<Vec<_>>())
		}
	}
}

/// The tail is read below the family's own prefix, so it never depends on a
/// hand-counted prefix length.
fn module_with_tail(
	relative: &GamePath,
	descriptor: &ContentFamilyDescriptor,
	fallback: &str,
) -> String {
	let mut name = fallback.to_string();
	let ContentFamilyPathMatcher::Prefix(directory) = descriptor.matcher else {
		return name;
	};
	let Some(below) = relative.strip_prefix(directory) else {
		return name;
	};
	let parts = below.iter().collect::<Vec<_>>();
	for part in &parts[..parts.len().saturating_sub(1)] {
		name.push('.');
		name.push_str(part);
	}
	name
}

fn fallback_module_name(parts: &[&str]) -> String {
	if parts.len() <= 1 {
		return "other".to_string();
	}
	parts[..parts.len() - 1].join(".")
}

#[cfg(test)]
mod dedup_policy_tests {
	use super::DedupPolicy;

	#[test]
	fn dedup_policy_maps_to_old_boolean_pairs() {
		assert_eq!(
			(
				DedupPolicy::None.cross_file_safe(),
				DedupPolicy::None.per_entry_safe()
			),
			(false, false)
		);
		assert_eq!(
			(
				DedupPolicy::PerEntryOnly.cross_file_safe(),
				DedupPolicy::PerEntryOnly.per_entry_safe()
			),
			(false, true)
		);
		assert_eq!(
			(
				DedupPolicy::CrossFileOnly.cross_file_safe(),
				DedupPolicy::CrossFileOnly.per_entry_safe()
			),
			(true, false)
		);
		assert_eq!(
			(
				DedupPolicy::CrossFileAndPerEntry.cross_file_safe(),
				DedupPolicy::CrossFileAndPerEntry.per_entry_safe()
			),
			(true, true)
		);
		assert_eq!(
			DedupPolicy::None.with_per_entry(),
			DedupPolicy::PerEntryOnly
		);
		assert_eq!(
			DedupPolicy::CrossFileOnly.with_per_entry(),
			DedupPolicy::CrossFileAndPerEntry
		);
		assert_eq!(
			DedupPolicy::PerEntryOnly.with_per_entry(),
			DedupPolicy::PerEntryOnly
		);
		assert_eq!(
			DedupPolicy::CrossFileAndPerEntry.with_per_entry(),
			DedupPolicy::CrossFileAndPerEntry
		);
	}
}

#[cfg(test)]
mod tests {
	use super::{
		BooleanMergePolicy, ContentFamilyDescriptor, ContentFamilyId, MergePolicies, ScriptFileKind,
	};
	use std::collections::hash_map::DefaultHasher;
	use std::hash::{Hash, Hasher};
	use std::sync::Arc;

	#[test]
	fn content_family_id_new_round_trips_str() {
		assert_eq!(ContentFamilyId::new("foo").as_str(), "foo");
	}

	#[test]
	fn cwt_type_equality_is_string_based() {
		assert_eq!(ScriptFileKind::new("events"), ScriptFileKind::new("events"));
	}

	#[test]
	fn content_family_id_hashes_match_for_equal_strings() {
		let left = ContentFamilyId::new(Arc::<str>::from("family"));
		let right = ContentFamilyId::new(Arc::<str>::from("family"));

		let mut left_hasher = DefaultHasher::new();
		left.hash(&mut left_hasher);

		let mut right_hasher = DefaultHasher::new();
		right.hash(&mut right_hasher);

		assert_eq!(left_hasher.finish(), right_hasher.finish());
	}

	#[test]
	fn boolean_merge_defaults_to_or_across_revisions() {
		assert_eq!(MergePolicies::default().boolean, BooleanMergePolicy::Or);
		assert_eq!(
			ContentFamilyDescriptor::prefix("test", "common/test")
				.build()
				.merge_policies
				.boolean,
			BooleanMergePolicy::Or
		);
	}
}

#[cfg(test)]
mod scalar_reducer_tests {
	use super::{MergePolicies, ScalarMergePolicy, ScalarReducerRule};

	const RULES: &[ScalarReducerRule] = &[
		ScalarReducerRule::new(&[], ScalarMergePolicy::Avg),
		ScalarReducerRule::new(&["value"], ScalarMergePolicy::Sum),
		ScalarReducerRule::new(&["special", "value"], ScalarMergePolicy::Max),
	];

	#[test]
	fn numeric_reducers_are_strict_and_deterministic() {
		assert_eq!(
			ScalarMergePolicy::Max.reduce_numeric_pair("50", "35"),
			Some("50".to_string())
		);
		assert_eq!(
			ScalarMergePolicy::Avg.reduce_numeric_pair(".2", ".1"),
			Some(".15".to_string())
		);
		assert_eq!(
			ScalarMergePolicy::Sum.reduce_numeric_pair("2.5", "1.25"),
			Some("3.75".to_string())
		);
		assert_eq!(
			ScalarMergePolicy::Min.reduce_numeric_pair("-2", "3"),
			Some("-2".to_string())
		);
		assert_eq!(
			ScalarMergePolicy::Avg.reduce_numeric_pair("1444.11.11", "1445.1.1"),
			None
		);
		assert_eq!(
			ScalarMergePolicy::Avg.reduce_numeric_pair("identifier", ".1"),
			None
		);
		assert_eq!(
			ScalarMergePolicy::LastWriter.reduce_numeric_pair("1", "2"),
			None
		);
		assert_eq!(
			ScalarMergePolicy::Avg.reduce_numeric_values([".2", ".1", ".3"]),
			Some(".2".to_string())
		);
		assert_eq!(
			ScalarMergePolicy::Sum.reduce_numeric_values(["1", "2", "3"]),
			Some("6".to_string())
		);
		assert_eq!(
			ScalarMergePolicy::Avg.reduce_numeric_values(std::iter::empty::<&str>()),
			None
		);
	}

	#[test]
	fn scalar_reducer_rules_use_the_longest_matching_suffix() {
		let policies = MergePolicies {
			scalar_reducer_rules: RULES,
			..Default::default()
		};
		let generic = policies
			.scalar_reducer_rule_for_path(&["root", "value"])
			.expect("generic suffix");
		let specific = policies
			.scalar_reducer_rule_for_path(&["root", "special", "value"])
			.expect("specific suffix");

		assert_eq!(generic.reducer, ScalarMergePolicy::Sum);
		assert_eq!(specific.reducer, ScalarMergePolicy::Max);
		assert!(
			policies
				.scalar_reducer_rule_for_path(&["root", "technology"])
				.is_none()
		);
	}
}

#[cfg(test)]
mod content_load_policy_tests {
	use super::{
		ContentFamilyDescriptor, ContentLoadPolicy, DefinitionFileOrder, DefinitionKeyPolicy,
		DefinitionModuleOutput, DefinitionModulePolicy, DuplicateDefinitionPolicy,
	};
	use crate::model::GamePath;

	fn module_policy() -> DefinitionModulePolicy {
		DefinitionModulePolicy {
			definition_key: DefinitionKeyPolicy::AssignmentKey,
			file_order: DefinitionFileOrder::NormalizedPathAscending,
			duplicate_definitions: DuplicateDefinitionPolicy::LaterDefinitionWins,
			output_path: GamePath::new("common/governments/00_foch_governments.txt")
				.expect("valid game path"),
			namespace_prefix: GamePath::new("common/governments").expect("valid game path"),
			output_mode: DefinitionModuleOutput::ReplaceNamespace,
			policy_version: 1,
		}
	}

	#[test]
	fn load_policy_defaults_to_per_path() {
		assert_eq!(ContentLoadPolicy::default(), ContentLoadPolicy::PerPath);
		assert_eq!(
			ContentFamilyDescriptor::prefix("test", "common/test")
				.build()
				.load_policy,
			ContentLoadPolicy::PerPath
		);
	}

	#[test]
	fn descriptor_records_the_complete_definition_module_policy() {
		let module_policy = module_policy();
		let descriptor = ContentFamilyDescriptor::prefix("test", "common/test")
			.load_policy(ContentLoadPolicy::DefinitionModule(module_policy))
			.build();

		assert_eq!(
			descriptor.load_policy,
			ContentLoadPolicy::DefinitionModule(module_policy)
		);
		assert_eq!(
			module_policy.definition_key,
			DefinitionKeyPolicy::AssignmentKey
		);
		assert_eq!(
			module_policy.file_order,
			DefinitionFileOrder::NormalizedPathAscending
		);
		assert_eq!(
			module_policy.duplicate_definitions,
			DuplicateDefinitionPolicy::LaterDefinitionWins
		);
		assert_eq!(
			module_policy.output_path.as_str(),
			"common/governments/00_foch_governments.txt"
		);
		assert_eq!(
			module_policy.namespace_prefix.as_str(),
			"common/governments"
		);
		assert_eq!(
			module_policy.output_mode,
			DefinitionModuleOutput::ReplaceNamespace
		);
		assert_eq!(module_policy.policy_version, 1);
	}
}