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
use std::fs;
use std::path::PathBuf;

use crate::game::schema::cache::{CwtLoadStatus, load_cwt_from_dir};
use crate::game::schema::compile::{CwtSchemaGraph, SchemaRootId};
use crate::game::schema::query::{
	CompiledAliasCategory, CompiledRuleCondition, CompiledRuleOrigin, CompiledRulePack,
	CompiledRuleValue, CompiledSeverity, CompiledTypeKeyFilter, CwtQuery, RuleContext,
	SchemaBinding,
};
use crate::game::schema::rule_path::SchemaDirectory;
use crate::game::schema::syntax::ParadoxTree;
use crate::model::GamePath;

fn game_path(text: &str) -> &GamePath {
	GamePath::new(text).expect("valid game path")
}

#[test]
fn compiled_engine_binds_root_and_alias_chain() {
	let graph = load_binding_graph();
	let engine = CwtQuery::from_graph(&graph);

	let root_path = game_path("events/example.txt");
	assert!(matches!(
		engine.root_binding(root_path),
		SchemaBinding::Bound { .. }
	));
	let root = engine.bind_root(root_path).expect("bind event root");
	assert_eq!(
		root.subtypes
			.iter()
			.find(|subtype| subtype.name == "country")
			.and_then(|subtype| subtype.attributes.push_scope.as_deref()),
		Some("country")
	);

	let ast_path = ["country_event", "trigger", "is_year"];
	let SchemaBinding::Bound { type_id, node_id } = engine.bind_chain(root_path, &ast_path) else {
		panic!("expected compiled binding to resolve alias path");
	};
	assert_eq!(type_id.as_str(), "event");
	assert_eq!(
		node_id.0,
		"type:event:subtype:country_event/field:trigger/alias:trigger:is_year"
	);
}

#[test]
fn compiled_engine_projects_field_and_alias_metadata() {
	let graph = load_binding_graph();
	let engine = CwtQuery::from_graph(&graph);
	let event = engine
		.bind_root(game_path("events/example.txt"))
		.expect("bind event root");
	let iterator = engine
		.bind_field(RuleContext::RootType(event), "every_country")
		.expect("bind every_country");
	assert_eq!(
		iterator.attributes.scope,
		vec!["country".to_string(), "province".to_string()]
	);
	assert_eq!(iterator.attributes.push_scope.as_deref(), Some("country"));
	assert_eq!(
		iterator.attributes.description.as_deref(),
		Some("Scopes to all countries.")
	);

	let trigger = engine
		.bind_field(RuleContext::RootType(event), "trigger")
		.expect("bind trigger field");
	let alias_match = engine
		.bind_field_match(RuleContext::RuleField(trigger), "is_year")
		.expect("bind trigger alias");
	assert_eq!(alias_match.field().key, "alias_name[trigger]");
	let alias = alias_match.alias().expect("alias metadata");
	assert_eq!(alias.name, "is_year");
	assert_eq!(alias.value, CompiledRuleValue::Scalar("int".to_string()));
	assert_eq!(alias.attributes.scope, vec!["country".to_string()]);
}

#[test]
fn compiled_engine_tracks_subtype_and_root_instance_contexts() {
	let graph = load_binding_graph();
	let engine = CwtQuery::from_graph(&graph);

	let event_context = engine
		.bind_context(game_path("events/example.txt"), &["country_event"])
		.expect("bind event subtype context");
	let RuleContext::Subtype(event, subtype) = event_context else {
		panic!("expected subtype context, got {event_context:?}");
	};
	assert_eq!(event.name, "event");
	assert_eq!(
		subtype.type_key_filter,
		Some(CompiledTypeKeyFilter::Exact(vec![
			"country_event".to_string()
		]))
	);

	let mission_context = engine
		.bind_context(game_path("missions/example.txt"), &["my_mission"])
		.expect("bind mission root instance context");
	let RuleContext::RootType(mission) = mission_context else {
		panic!("expected root context, got {mission_context:?}");
	};
	assert_eq!(mission.name, "mission");
}

#[test]
fn compiled_engine_returns_all_direct_field_matches() {
	let schema = r#"
	types = {
		type[estate_privilege] = {
			path = "game/common/estate_privileges"
		}
	}

	estate_privilege = {
		can_revoke = bool
		can_revoke = {
			alias_name[trigger] = alias_match_left[trigger]
		}
	}
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let graph = CwtSchemaGraph::from_paradox_tree(&tree);
	let engine = CwtQuery::from_graph(&graph);
	let privilege = engine
		.bind_root(game_path("common/estate_privileges/example.txt"))
		.expect("bind privilege root");
	let matches = engine.bind_fields(RuleContext::RootType(privilege), "can_revoke");

	assert_eq!(matches.len(), 2);
	assert!(matches.iter().any(|field| matches!(
		&field.value,
		CompiledRuleValue::Scalar(value) if value == "bool"
	)));
	assert!(
		matches
			.iter()
			.any(|field| matches!(&field.value, CompiledRuleValue::Block(_)))
	);
}

#[test]
fn compiled_engine_projects_plural_replace_scopes() {
	let schema = r#"
	types = {
		type[incident] = {
			path = "game/common/incidents"
		}
	}

	incident = {
		## replace_scopes = { this = country root = country }
		immediate = {
			alias_name[effect] = alias_match_left[effect]
		}
	}
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let graph = CwtSchemaGraph::from_paradox_tree(&tree);
	let engine = CwtQuery::from_graph(&graph);
	let incident = engine
		.bind_root(game_path("common/incidents/example.txt"))
		.expect("bind incident root");
	let field = engine
		.bind_field(RuleContext::RootType(incident), "immediate")
		.expect("bind immediate field");

	assert_eq!(
		field
			.attributes
			.replace_scope
			.get("this")
			.map(String::as_str),
		Some("country")
	);
	assert_eq!(
		field
			.attributes
			.replace_scope
			.get("root")
			.map(String::as_str),
		Some("country")
	);
}

#[test]
fn compiled_binary_pack_roundtrips_conditional_rule_fields() {
	let schema = r#"
	types = {
		type[event] = {
			path = "game/events"
			subtype[hidden] = {
				hidden = yes
			}
		}
	}

	event = {
		subtype[hidden] = {
			hidden_only = bool
		}
		subtype[!hidden] = {
			visible_only = bool
		}
	}
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let graph = CwtSchemaGraph::from_paradox_tree(&tree);
	let pack = CompiledRulePack::from_graph(&graph);
	let decoded = CompiledRulePack::from_bytes(&pack.to_bytes().expect("encode compiled pack"))
		.expect("decode compiled pack");
	let engine = CwtQuery::new(decoded);
	let event = engine
		.bind_root(game_path("events/example.txt"))
		.expect("bind event root");
	let hidden_only = event
		.rules
		.iter()
		.find(|field| field.key == "hidden_only")
		.expect("hidden-only conditional field");
	assert_eq!(
		hidden_only.conditions,
		vec![CompiledRuleCondition::SubtypeActive("hidden".to_string())]
	);
	let visible_only = event
		.rules
		.iter()
		.find(|field| field.key == "visible_only")
		.expect("visible-only conditional field");
	assert_eq!(
		visible_only.conditions,
		vec![CompiledRuleCondition::SubtypeInactive("hidden".to_string())]
	);
}

/// A subtype group's first field keeps its own `##` attributes, at the top of
/// a rule body and nested in a block.
#[test]
fn subtype_group_first_field_keeps_its_attributes() {
	let schema = r#"
	types = {
		type[event] = {
			path = "game/events"
			subtype[hidden] = {
				hidden = yes
			}
		}
	}

	event = {
		subtype[hidden] = {
			## cardinality = 0..1
			hidden_only = bool
		}
		option = {
			subtype[hidden] = {
				## severity = info
				nested_only = bool
			}
		}
	}
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let graph = CwtSchemaGraph::from_paradox_tree(&tree);
	let engine = CwtQuery::new(CompiledRulePack::from_graph(&graph));
	let event = engine
		.bind_root(game_path("events/example.txt"))
		.expect("bind event root");
	let hidden_only = event
		.rules
		.iter()
		.find(|field| field.key == "hidden_only")
		.expect("hidden-only conditional field");
	assert_eq!(hidden_only.attributes.cardinality, Some((0, Some(1))));

	let option = event
		.rules
		.iter()
		.find(|field| field.key == "option")
		.expect("option block field");
	let CompiledRuleValue::Block(option_rules) = &option.value else {
		panic!("option is a block: {:?}", option.value);
	};
	let nested_only = option_rules
		.iter()
		.find(|field| field.key == "nested_only")
		.expect("nested conditional field");
	assert_eq!(
		nested_only.attributes.severity,
		Some(CompiledSeverity::Info)
	);
}

#[test]
fn compiled_binary_pack_roundtrips_type_localisation_metadata() {
	let schema = r#"
	types = {
		type[event] = {
			path = "game/events"
			localisation = {
				## required
				title = "$_title"
				desc = "$_desc"
			}
		}
	}

	event = {
		title = scalar
	}
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let graph = CwtSchemaGraph::from_paradox_tree(&tree);
	let pack = CompiledRulePack::from_graph(&graph);
	let decoded = CompiledRulePack::from_bytes(&pack.to_bytes().expect("encode compiled pack"))
		.expect("decode compiled pack");
	let engine = CwtQuery::new(decoded);
	let event = engine
		.bind_root(game_path("events/example.txt"))
		.expect("bind event root");
	assert!(
		event.rules.iter().all(|field| field.key != "localisation"),
		"type header localisation metadata must not become a compiled script field"
	);
	assert_eq!(event.localisation.len(), 2);
	assert_eq!(event.localisation[0].key, "title");
	assert_eq!(
		event.localisation[0].attributes.raw,
		vec![("required".to_string(), String::new())]
	);
	assert_eq!(
		event.localisation[0].value,
		CompiledRuleValue::Scalar("$_title".to_string())
	);
	assert_eq!(event.localisation[1].key, "desc");
}

#[test]
fn compiled_engine_uses_enums_and_values_blocks() {
	let schema = r#"
	enums = {
		enum[power_categories] = { ADM DIP MIL }
	}

	values = {
		value[event_target] = { root from prev }
		value_set[cooldown_token] = { parliament_debate }
	}
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let graph = CwtSchemaGraph::from_paradox_tree(&tree);
	let pack = CompiledRulePack::from_graph(&graph);
	let decoded = CompiledRulePack::from_bytes(&pack.to_bytes().expect("encode compiled pack"))
		.expect("decode compiled pack");
	let engine = CwtQuery::new(decoded);
	assert_eq!(
		engine.enum_values("power_categories"),
		Some(&["ADM".to_string(), "DIP".to_string(), "MIL".to_string()][..])
	);
	assert_eq!(
		engine.value_set_values("event_target"),
		Some(&["from".to_string(), "prev".to_string(), "root".to_string()][..])
	);
	assert_eq!(
		engine.value_set_values("cooldown_token"),
		Some(&["parliament_debate".to_string()][..])
	);
}

#[test]
fn compiled_engine_roundtrips_complex_enums() {
	let schema = r#"
	enums = {
		complex_enum[country_tags] = {
			path = "game/common/country_tags"
			name = {
				enum_name = scalar
			}
			start_from_root = yes
		}
		complex_enum[graphical_cultures] = {
			path = "game/common"
			path_file = "graphicalculturetype.txt"
			name = {
				enum_name
			}
			start_from_root = yes
		}
	}
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let graph = CwtSchemaGraph::from_paradox_tree(&tree);
	let pack = CompiledRulePack::from_graph(&graph);
	let decoded = CompiledRulePack::from_bytes(&pack.to_bytes().expect("encode compiled pack"))
		.expect("decode compiled pack");
	let engine = CwtQuery::new(decoded);
	let complex_enum = engine
		.complex_enum("country_tags")
		.expect("country_tags complex enum");
	assert_eq!(
		complex_enum.path,
		Some(SchemaDirectory::Directory(
			game_path("common/country_tags").to_owned()
		))
	);
	assert!(complex_enum.matches(game_path("common/country_tags/00_tags.txt")));
	assert!(complex_enum.start_from_root);
	assert_eq!(complex_enum.name_rules.len(), 1);
	assert_eq!(complex_enum.name_rules[0].key, "enum_name");
	assert_eq!(
		complex_enum.name_rules[0].value,
		CompiledRuleValue::Scalar("scalar".to_string())
	);
	assert_eq!(engine.complex_enums().len(), 2);
	let graphical_cultures = engine
		.complex_enum("graphical_cultures")
		.expect("graphical_cultures complex enum");
	assert_eq!(
		graphical_cultures.path,
		Some(SchemaDirectory::Directory(game_path("common").to_owned()))
	);
	assert_eq!(
		graphical_cultures.path_file.as_deref(),
		Some(game_path("graphicalculturetype.txt"))
	);
	assert!(graphical_cultures.matches(game_path("common/graphicalculturetype.txt")));
	assert!(!graphical_cultures.matches(game_path("common/other.txt")));
	assert!(graphical_cultures.start_from_root);
	assert_eq!(graphical_cultures.name_rules.len(), 1);
	assert_eq!(graphical_cultures.name_rules[0].key, "enum_name");
	assert_eq!(
		graphical_cultures.name_rules[0].value,
		CompiledRuleValue::Marker("enum_name".to_string())
	);
}

#[test]
fn compiled_engine_roundtrips_links() {
	let schema = r#"
	links = {
		owner = {
			input_scopes = { province country province }
			output_scope = country
		}
		controller = {
			input_scopes = { province }
			output_scope = country
		}
	}
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let graph = CwtSchemaGraph::from_paradox_tree(&tree);
	let pack = CompiledRulePack::from_graph(&graph);
	let decoded = CompiledRulePack::from_bytes(&pack.to_bytes().expect("encode compiled pack"))
		.expect("decode compiled pack");
	let engine = CwtQuery::new(decoded);
	let owner = engine.link("owner").expect("owner link");
	assert_eq!(owner.output_scope.as_deref(), Some("country"));
	assert_eq!(
		owner.input_scopes,
		vec!["country".to_string(), "province".to_string()]
	);
	assert_eq!(engine.links().len(), 2);
	assert_eq!(engine.links()[0].name, "controller");
	assert_eq!(engine.links()[1].name, "owner");
}

#[test]
fn compiled_engine_lists_scope_values_from_scope_hierarchy() {
	let schema = r#"
	scopes = {
		country = {
			aliases = { country root }
		}
		province = {
			aliases = { province from }
			is_subscope_of = { country }
		}
		sea = {
			aliases = { sea }
		}
	}
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let graph = CwtSchemaGraph::from_paradox_tree(&tree);
	let engine = CwtQuery::from_graph(&graph);
	assert_eq!(
		engine.scope_values("country"),
		vec![
			"country".to_string(),
			"from".to_string(),
			"province".to_string(),
			"root".to_string()
		]
	);
	assert_eq!(
		engine.scope_values("any"),
		vec![
			"country".to_string(),
			"from".to_string(),
			"province".to_string(),
			"root".to_string(),
			"sea".to_string()
		]
	);
	assert!(engine.scope_values("unknown").is_empty());
}

#[test]
fn compiled_engine_matches_static_dynamic_key_markers() {
	let schema = r#"
	types = {
		type[event] = {
			path = "game/events"
		}
	}

	event = {
		dynamic_fields = {
			enum[dynamic_keys] = int
			value[dynamic_value_key] = bool
			value_set[dynamic_set_key] = float
			scope[country] = yes
		}
	}

	enums = {
		enum[dynamic_keys] = { alpha beta }
	}

	values = {
		value[dynamic_value_key] = { saved_key }
		value_set[dynamic_set_key] = { reusable_key }
	}

	scopes = {
		country = {
			aliases = { country root }
		}
		province = {
			aliases = { province from }
			is_subscope_of = { country }
		}
		sea = {
			aliases = { sea }
		}
	}
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let graph = CwtSchemaGraph::from_paradox_tree(&tree);
	let pack = CompiledRulePack::from_graph(&graph);
	let decoded = CompiledRulePack::from_bytes(&pack.to_bytes().expect("encode compiled pack"))
		.expect("decode compiled pack");
	let engine = CwtQuery::new(decoded);
	let event = engine
		.bind_root(game_path("events/example.txt"))
		.expect("bind event root");
	let dynamic_fields = engine
		.bind_field(RuleContext::RootType(event), "dynamic_fields")
		.expect("bind dynamic_fields");
	let context = RuleContext::RuleField(dynamic_fields);
	assert_eq!(
		engine
			.bind_field(context, "alpha")
			.map(|field| field.key.as_str()),
		Some("enum[dynamic_keys]")
	);
	assert_eq!(
		engine
			.bind_field(context, "saved_key")
			.map(|field| field.key.as_str()),
		Some("value[dynamic_value_key]")
	);
	assert_eq!(
		engine
			.bind_field(context, "reusable_key")
			.map(|field| field.key.as_str()),
		Some("value_set[dynamic_set_key]")
	);
	assert_eq!(
		engine
			.bind_field(context, "province")
			.map(|field| field.key.as_str()),
		Some("scope[country]")
	);
	assert!(engine.bind_field(context, "sea").is_none());
	assert!(engine.bind_field(context, "missing_key").is_none());
}

#[test]
fn compiled_engine_binds_angle_bracket_dynamic_fields() {
	let schema = r#"
	types = {
		type[mission] = {
			path = "game/missions"
		}
	}

	mission = {
		mission_tree = {
			<mission_stage> = {
				trigger = bool
			}
		}
	}
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let graph = CwtSchemaGraph::from_paradox_tree(&tree);
	let engine = CwtQuery::from_graph(&graph);
	let path = game_path("missions/example.txt");
	let ast_path = ["demo_mission", "mission_tree", "conquest", "trigger"];

	let SchemaBinding::Bound { type_id, node_id } = engine.bind_chain(path, &ast_path) else {
		panic!("expected compiled dynamic field binding");
	};
	assert_eq!(type_id.as_str(), "mission");
	assert_eq!(
		node_id.0,
		"type:mission:field:mission_tree/field:<mission_stage>/field:trigger"
	);

	let context = engine
		.bind_context(path, &["demo_mission", "mission_tree"])
		.expect("bind mission tree context");
	let field_match = engine
		.bind_field_match(context, "conquest")
		.expect("bind dynamic mission stage");
	assert_eq!(field_match.field().key, "<mission_stage>");
}

#[test]
fn compiled_engine_honors_root_type_key_filter_exclusions() {
	let schema = r#"
	types = {
		type[idea_group] = {
			path = "game/common/ideas"
			subtype[selectable] = {
				category = scalar
			}
		}
		## type_key_filter <> { start trigger bonus ai_will_do }
		type[idea] = {
			path = "game/common/ideas"
			skip_root_key = any
		}
	}

	idea_group = {
		subtype[selectable] = {
			category = scalar
		}
	}

	idea = {
		idea_only = bool
	}
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let graph = CwtSchemaGraph::from_paradox_tree(&tree);
	let engine = CwtQuery::from_graph(&graph);
	let path = game_path("common/ideas/example.txt");
	let ast_path = ["sample_group", "sample_idea", "idea_only"];

	let SchemaBinding::Bound { type_id, node_id } = engine.bind_chain(path, &ast_path) else {
		panic!("expected compiled idea binding");
	};
	assert_eq!(type_id.as_str(), "idea");
	assert_eq!(node_id.0, "type:idea:field:idea_only");

	let excluded_path = ["sample_group", "start", "idea_only"];
	assert!(
		!matches!(
			engine.bind_chain(path, &excluded_path),
			SchemaBinding::Bound { ref type_id, .. } if type_id.as_str() == "idea"
		),
		"compiled engine must not bind excluded root key to idea type"
	);
}

#[test]
fn compiled_engine_honors_path_file_root_matching() {
	let schema = r#"
	types = {
		type[map_fallback] = {
			path = "game/map"
		}
		type[area] = {
			path = "game/map"
			path_file = "area.txt"
		}
		type[region] = {
			path = "game/map"
			path_file = "region.txt"
		}
	}

	map_fallback = {
		fallback_only = bool
	}

	area = {
		area_only = bool
	}

	region = {
		region_only = bool
	}
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let graph = CwtSchemaGraph::from_paradox_tree(&tree);
	let engine = CwtQuery::from_graph(&graph);
	let area_path = game_path("map/area.txt");
	let area_ast_path = ["sample_area", "area_only"];

	let SchemaBinding::Bound { type_id, node_id } = engine.bind_chain(area_path, &area_ast_path)
	else {
		panic!("expected compiled area binding");
	};
	assert_eq!(type_id.as_str(), "area");
	assert_eq!(node_id.0, "type:area:field:area_only");

	let region_path = game_path("map/region.txt");
	let region_ast_path = ["sample_region", "region_only"];
	let SchemaBinding::Bound { type_id, node_id } =
		engine.bind_chain(region_path, &region_ast_path)
	else {
		panic!("expected compiled region binding");
	};
	assert_eq!(type_id.as_str(), "region");
	assert_eq!(node_id.0, "type:region:field:region_only");

	let fallback_path = game_path("map/other.txt");
	let fallback_ast_path = ["sample_map", "fallback_only"];
	let SchemaBinding::Bound { type_id, node_id } =
		engine.bind_chain(fallback_path, &fallback_ast_path)
	else {
		panic!("expected compiled fallback binding");
	};
	assert_eq!(type_id.as_str(), "map_fallback");
	assert_eq!(node_id.0, "type:map_fallback:field:fallback_only");
}

#[test]
fn compiled_engine_honors_ordered_skip_root_key_chain() {
	let schema = r#"
	types = {
		type[game_age] = {
			path = "game/common/ages"
		}
		type[game_age_ability] = {
			path = "game/common/ages"
			skip_root_key = { any abilities }
		}
	}

	game_age = {
		start = int
	}

	game_age_ability = {
		power = bool
	}
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let graph = CwtSchemaGraph::from_paradox_tree(&tree);
	let engine = CwtQuery::from_graph(&graph);
	let path = game_path("common/ages/example.txt");
	let ast_path = ["age_of_discovery", "abilities", "free_war_taxes", "power"];

	let SchemaBinding::Bound { type_id, node_id } = engine.bind_chain(path, &ast_path) else {
		panic!("expected compiled game_age_ability binding");
	};
	assert_eq!(type_id.as_str(), "game_age_ability");
	assert_eq!(node_id.0, "type:game_age_ability:field:power");

	let missing_fixed_wrapper = ["age_of_discovery", "free_war_taxes", "power"];
	assert!(
		!matches!(
			engine.bind_chain(path, &missing_fixed_wrapper),
			SchemaBinding::Bound { ref type_id, .. } if type_id.as_str() == "game_age_ability"
		),
		"ability type must require the ordered skip_root_key chain"
	);
}

#[test]
fn compiled_engine_matches_scope_hierarchy_metadata() {
	let graph = CwtSchemaGraph::from_directory(&schema_pack_fixture_dir())
		.expect("load schema-pack fixture graph");
	let engine = CwtQuery::from_graph(&graph);
	assert_eq!(engine.pack().scope_definitions.len(), 2);

	assert!(engine.scope_matches("country", "country"));
	assert!(engine.scope_matches("province", "province"));
	assert!(engine.scope_matches("country", "province"));
	assert!(!engine.scope_matches("province", "country"));
	assert!(engine.scope_matches("unknown", "unknown"));
	assert!(!engine.scope_matches("country", "unknown"));
	assert!(!engine.scope_matches("unknown", "country"));
	assert!(engine.scope_matches("any", "country"));
	assert!(engine.scope_matches("province", "any"));
	assert!(engine.is_unlisted_scope("unknown"));
	assert!(!engine.is_unlisted_scope("country"));
	assert!(!engine.is_unlisted_scope("any"));
}

#[test]
fn compiled_binary_pack_roundtrips_and_keeps_binding_semantics() {
	let graph = load_binding_graph();
	let pack = CompiledRulePack::from_graph(&graph);
	let bytes = pack.to_bytes().expect("encode compiled pack");
	let decoded = CompiledRulePack::from_bytes(&bytes).expect("decode compiled pack");
	assert_eq!(decoded, pack);

	let engine = CwtQuery::new(decoded);
	let mission = engine
		.bind_root(game_path("missions/example.txt"))
		.expect("bind mission root after roundtrip");
	let field = engine
		.bind_field(RuleContext::RootType(mission), "provinces_to_highlight")
		.expect("bind mission field after roundtrip");
	assert_eq!(field.attributes.cardinality, Some((0, Some(1))));
	assert!(matches!(field.value, CompiledRuleValue::Block(_)));
}

#[test]
fn compiled_binary_pack_roundtrips_severity_attributes() {
	let schema = r#"
	types = {
		type[event] = {
			path = "game/events"
		}
	}

	event = {
		## severity = warning
		gentle_bool = bool
		trigger = {
			alias_name[trigger] = alias_match_left[trigger]
		}
	}

	## scope = country
	## severity = info
	alias[trigger:gentle_trigger] = bool
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let graph = CwtSchemaGraph::from_paradox_tree(&tree);
	let pack = CompiledRulePack::from_graph(&graph);
	let decoded = CompiledRulePack::from_bytes(&pack.to_bytes().expect("encode compiled pack"))
		.expect("decode compiled pack");
	let engine = CwtQuery::new(decoded);
	let event = engine
		.bind_root(game_path("events/example.txt"))
		.expect("bind event root");
	let field = engine
		.bind_field(RuleContext::RootType(event), "gentle_bool")
		.expect("bind severity field");
	assert_eq!(field.attributes.severity, Some(CompiledSeverity::Warning));

	let trigger = engine
		.bind_field(RuleContext::RootType(event), "trigger")
		.expect("bind trigger field");
	let alias_match = engine
		.bind_field_match(RuleContext::RuleField(trigger), "gentle_trigger")
		.expect("bind severity alias");
	assert_eq!(
		alias_match.alias().map(|alias| alias.attributes.severity),
		Some(Some(CompiledSeverity::Info))
	);
}

#[test]
fn compiled_rule_cache_reuses_binary_pack_when_source_unchanged() {
	let root = binding_fixture_dir();
	let cache = tempfile::tempdir().expect("create compiled rule cache tempdir");
	let obsolete_generation = cache.path().join("v0.10.0");
	fs::create_dir_all(&obsolete_generation).expect("create obsolete generation");
	fs::write(obsolete_generation.join("rules.bin"), b"obsolete")
		.expect("write obsolete generation entry");
	let legacy_flat_entry = cache.path().join("rules-fmt-0_10_0-src-old.bin");
	fs::write(&legacy_flat_entry, b"obsolete").expect("write legacy flat entry");

	let first =
		load_cwt_from_dir(&root, Some(cache.path())).expect("compile fixture schema into cache");
	assert_eq!(first.status, CwtLoadStatus::CompiledFromSource);
	assert!(first.cache_path.as_ref().is_some_and(|path| path.is_file()));
	assert!(first.cache_path.as_ref().is_some_and(|path| {
		path.starts_with(cache.path().join(format!("v{}", crate::DATA_VERSION)))
	}));
	assert!(obsolete_generation.exists());
	assert!(legacy_flat_entry.exists());
	assert!(first.timings.cache_read.is_some());
	assert!(first.timings.source_compile.is_some());
	assert!(first.facts.alias_count() > 0);

	let second = load_cwt_from_dir(&root, Some(cache.path()))
		.expect("load fixture schema from compiled cache");
	assert_eq!(second.status, CwtLoadStatus::CacheHit);
	assert!(second.timings.cache_read.is_some());
	assert!(second.timings.source_compile.is_none());
	assert_eq!(second.source_id, first.source_id);
	assert_eq!(second.facts.alias_count(), first.facts.alias_count());
	assert_eq!(
		second.facts.root_binding(game_path("events/example.txt")),
		first.facts.root_binding(game_path("events/example.txt"))
	);
}

#[test]
fn compiled_vendor_pack_preserves_cwtools_alias_binding() {
	let root = vendor_schema_dir();
	let graph = CwtSchemaGraph::from_directory(&root).expect("load CWTools schema graph");
	let engine = CwtQuery::from_graph(&graph);
	assert_eq!(
		engine.alias_count(),
		graph.aliases.values().map(Vec::len).sum::<usize>()
	);
	assert!(engine.alias_count() > 2_000);

	let context = engine
		.bind_context(
			game_path("events/example.txt"),
			&["country_event", "trigger"],
		)
		.expect("bind event trigger context");
	let field_match = engine
		.bind_field_match(context, "is_year")
		.expect("bind real CWTools trigger alias");
	assert_eq!(field_match.field().key, "alias_name[trigger]");
	assert_eq!(
		field_match.alias().map(|alias| alias.name.as_str()),
		Some("is_year")
	);

	let bytes = engine
		.pack()
		.to_bytes()
		.expect("encode vendor compiled pack");
	let decoded = CompiledRulePack::from_bytes(&bytes).expect("decode vendor compiled pack");
	let roundtripped = CwtQuery::new(decoded);
	assert_eq!(roundtripped.alias_count(), engine.alias_count());
}

/// An alias the schema defines several times keeps every definition, in
/// schema order; binding still resolves to the last one.
#[test]
fn compiled_vendor_pack_keeps_every_alias_overload() {
	let graph = CwtSchemaGraph::from_directory(&vendor_schema_dir()).expect("load CWTools schema");
	let engine = CwtQuery::from_graph(&graph);
	let values = engine
		.alias_overloads(CompiledAliasCategory::Trigger, "stability")
		.map(|alias| alias.value.clone())
		.collect::<Vec<_>>();
	assert_eq!(
		values,
		["int[-3..3]", "scope[country]", "enum[country_tags]"]
			.map(|value| CompiledRuleValue::Marker(value.to_string()))
	);
	assert_eq!(
		engine
			.alias(CompiledAliasCategory::Trigger, "stability")
			.map(|alias| &alias.value),
		values.last()
	);

	let context = engine
		.bind_context(
			game_path("events/example.txt"),
			&["country_event", "trigger"],
		)
		.expect("bind event trigger context");
	assert_eq!(engine.bind_field_matches(context, "stability").len(), 1);
	let overloads = engine.bind_field_overloads(context, "stability", |_| true);
	assert_eq!(overloads.len(), 3);
	assert_eq!(
		overloads.first().map(|field_match| field_match.value()),
		values.last()
	);
}

/// The schema's `modifiers` section declares most modifiers only by name and
/// scope. Each becomes a `float` modifier the editor accepts, unless an
/// explicit `alias[modifier:...]` already defines it; binding never sees them.
#[test]
fn compiled_vendor_pack_declares_section_modifiers() {
	let graph = CwtSchemaGraph::from_directory(&vendor_schema_dir()).expect("load CWTools schema");
	assert!(!graph.types.contains_key(&SchemaRootId::new("modifiers")));
	let engine = CwtQuery::from_graph(&graph);

	let global_unrest = engine
		.declared_modifier("global_unrest")
		.expect("declared modifier");
	assert_eq!(global_unrest.category, CompiledAliasCategory::Modifier);
	assert_eq!(
		global_unrest.value,
		CompiledRuleValue::Marker("float".to_string())
	);
	assert_eq!(global_unrest.attributes.scope, ["country"]);
	assert_eq!(
		engine
			.declared_modifier("local_unrest")
			.map(|modifier| modifier.attributes.scope.as_slice()),
		Some(["province".to_string()].as_slice())
	);
	assert!(
		engine
			.alias(CompiledAliasCategory::Modifier, "global_unrest")
			.is_none()
	);
	assert!(engine.declared_modifier("has_banners").is_none());
	assert!(
		engine
			.alias(CompiledAliasCategory::Modifier, "has_banners")
			.is_some()
	);
}

#[test]
fn root_binding_matches_file_paths_ignoring_ascii_case() {
	let engine = CwtQuery::from_graph(&load_binding_graph());
	for file in [
		"events/example.txt",
		"EVENTS/Example.TXT",
		"Events/nested/x.txt",
	] {
		assert_eq!(
			engine
				.bind_root(game_path(file))
				.map(|root| root.name.as_str()),
			Some("event"),
			"{file}"
		);
	}
	// The reason spells the file folded as rule paths compare it.
	assert_eq!(
		engine.root_binding(game_path("Common/Example.txt")),
		SchemaBinding::Unbound {
			reason: "no root type matches `common/example.txt`".to_string(),
		}
	);
	assert!(engine.bind_root(game_path("eventsx/example.txt")).is_none());
}

#[test]
fn a_root_type_declared_on_the_game_root_binds_no_file() {
	let schema = r#"
		types = {
			type[everything] = { path = "game" }
			type[everything_file] = { path = "game" path_file = "descriptor.mod" }
		}
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let engine = CwtQuery::from_graph(&CwtSchemaGraph::from_paradox_tree(&tree));
	assert_eq!(
		engine.root("everything").and_then(|root| root.path.clone()),
		Some(SchemaDirectory::GameRoot)
	);
	for file in ["events/example.txt", "descriptor.mod", "game/x.txt"] {
		assert!(
			matches!(
				engine.root_binding(game_path(file)),
				SchemaBinding::Unbound { .. }
			),
			"{file}"
		);
	}
}

#[test]
fn a_path_file_root_binds_only_its_direct_child() {
	let schema = r#"
		types = {
			type[achievement] = { path = "game/common" path_file = "achievements.txt" }
		}
	"#;
	let tree = ParadoxTree::parse(schema.as_bytes()).expect("parse inline schema");
	let engine = CwtQuery::from_graph(&CwtSchemaGraph::from_paradox_tree(&tree));
	assert!(
		engine
			.bind_root(game_path("common/achievements.txt"))
			.is_some()
	);
	assert!(
		engine
			.bind_root(game_path("Common/ACHIEVEMENTS.txt"))
			.is_some()
	);
	for file in [
		"common/sub/achievements.txt",
		"common/other.txt",
		"achievements.txt",
	] {
		assert!(engine.bind_root(game_path(file)).is_none(), "{file}");
	}
}

#[test]
fn a_rule_path_that_is_not_a_game_path_fails_to_compile_naming_the_type_and_file() {
	for (declaration, reason) in [
		(r#"path = "game/common\ideas""#, "contains '\\\\'"),
		(r#"path = "game/common/../events""#, "`..` component"),
		(
			r#"path = "game/common" path_file = "../x.txt""#,
			"`..` component",
		),
	] {
		let root = tempfile::tempdir().expect("create schema dir");
		let file = root.path().join("rules.cwt");
		fs::write(
			&file,
			format!("types = {{\n\ttype[bad_type] = {{ {declaration} }}\n}}\n"),
		)
		.expect("write schema");
		let error = CwtSchemaGraph::from_directory(root.path())
			.expect_err("an invalid rule path must not compile");
		let message = error.to_string();
		assert!(message.contains(&file.display().to_string()), "{message}");
		assert!(message.contains("`bad_type`"), "{message}");
		assert!(message.contains(reason), "{reason}: {message}");
	}
}

#[test]
fn a_complex_enum_rule_path_that_is_not_a_game_path_fails_to_compile_naming_the_enum_and_file() {
	for (declaration, field, reason) in [
		(
			r#"path = "game/common\ideas""#,
			"invalid path:",
			"contains '\\\\'",
		),
		(
			r#"path = "game/common" path_file = "../x.txt""#,
			"invalid path_file:",
			"`..` component",
		),
	] {
		let root = tempfile::tempdir().expect("create schema dir");
		let file = root.path().join("enums.cwt");
		fs::write(
			&file,
			format!(
				"enums = {{\n\tcomplex_enum[bad_enum] = {{ {declaration} name = {{ enum_name }} }}\n}}\n"
			),
		)
		.expect("write schema");
		let error = CwtSchemaGraph::from_directory(root.path())
			.expect_err("an invalid rule path must not compile");
		let message = error.to_string();
		for expected in [
			file.display().to_string(),
			"`bad_enum`".to_string(),
			field.to_string(),
			reason.to_string(),
		] {
			assert!(message.contains(&expected), "{expected}: {message}");
		}
	}
}

/// A top-level block only gives rules to the type a `type[...]` header
/// declares: on its own it reads no file, wherever its schema file sits. The
/// vendored config's undeclared `power_projection` block in `common/` must
/// not claim every file there no declared type reads.
#[test]
fn a_rule_block_without_a_type_declaration_reads_no_file() {
	let root = tempfile::tempdir().expect("create schema dir");
	let common = root.path().join("common");
	fs::create_dir(&common).expect("create schema subdir");
	fs::write(common.join("foo.cwt"), "foo = { x = bool }\n").expect("write schema");
	fs::write(root.path().join("bar.cwt"), "bar = { x = bool }\n").expect("write schema");

	let graph = CwtSchemaGraph::from_directory(root.path()).expect("compile schema");
	for name in ["foo", "bar"] {
		assert_eq!(graph.types[&SchemaRootId::new(name)].path, None, "{name}");
	}
	let engine = CwtQuery::from_graph(&graph);
	for file in [
		"common/alerts.txt",
		"common/units/a.txt",
		"bar.txt",
		"events/a.txt",
	] {
		assert!(engine.bind_root(game_path(file)).is_none(), "{file}");
	}
}

/// The first directory a schema compiles from writes CWTools' rules; every
/// rule a later directory adds — to an existing type, nested in a block, as a
/// new type or as an alias — is that extension's.
#[test]
fn compiled_rules_record_which_rule_files_wrote_them() {
	let base = tempfile::tempdir().expect("create base schema dir");
	fs::write(
		base.path().join("base.cwt"),
		"types = {\n\ttype[sample] = { path = \"game/common/samples\" }\n}\nsample = {\n\trank = int\n}\nalias[effect:base_effect] = int\n",
	)
	.expect("write base schema");
	let extension = tempfile::tempdir().expect("create extension schema dir");
	fs::write(
		extension.path().join("extension.cwt"),
		"types = {\n\ttype[extra] = { path = \"game/common/extras\" }\n}\nsample = {\n\tbonus = { factor = float }\n}\nextra = {\n\tsize = int\n}\nalias[effect:extension_effect] = int\n",
	)
	.expect("write extension schema");

	let graph =
		CwtSchemaGraph::from_directories(&[base.path(), extension.path()]).expect("compile schema");
	let engine = CwtQuery::from_graph(&graph);
	let sample = engine
		.bind_root(game_path("common/samples/a.txt"))
		.expect("bind sample root");
	assert_eq!(sample.origin, CompiledRuleOrigin::Base);
	let rank = engine
		.bind_field(RuleContext::RootType(sample), "rank")
		.expect("bind rank");
	assert_eq!(rank.origin, CompiledRuleOrigin::Base);
	let bonus = engine
		.bind_field(RuleContext::RootType(sample), "bonus")
		.expect("bind bonus");
	assert_eq!(bonus.origin, CompiledRuleOrigin::Extension);
	let factor = engine
		.bind_field(RuleContext::RuleField(bonus), "factor")
		.expect("bind factor");
	assert_eq!(factor.origin, CompiledRuleOrigin::Extension);

	let extra = engine
		.bind_root(game_path("common/extras/a.txt"))
		.expect("bind extra root");
	assert_eq!(extra.origin, CompiledRuleOrigin::Extension);
	let size = engine
		.bind_field(RuleContext::RootType(extra), "size")
		.expect("bind size");
	assert_eq!(size.origin, CompiledRuleOrigin::Extension);

	for (name, origin) in [
		("base_effect", CompiledRuleOrigin::Base),
		("extension_effect", CompiledRuleOrigin::Extension),
	] {
		let alias = engine
			.alias(CompiledAliasCategory::Effect, name)
			.unwrap_or_else(|| panic!("alias {name}"));
		assert_eq!(alias.origin, origin, "{name}");
	}
}

fn load_binding_graph() -> CwtSchemaGraph {
	CwtSchemaGraph::from_directory(&binding_fixture_dir()).expect("load binding fixture graph")
}

fn binding_fixture_dir() -> PathBuf {
	PathBuf::from(env!("CARGO_MANIFEST_DIR"))
		.join("src/game/schema/tests/fixtures")
		.join("binding")
}

fn schema_pack_fixture_dir() -> PathBuf {
	PathBuf::from(env!("CARGO_MANIFEST_DIR"))
		.join("src/game/schema/tests/fixtures")
		.join("schema-pack")
}

/// The build embeds this directory, so it is present whenever the crate compiles.
fn vendor_schema_dir() -> PathBuf {
	PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("vendor/cwtools-eu4-config")
}