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
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
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
mod cultures;
mod fingerprint;
mod gui;
mod repairs;
mod transform;

pub use cultures::{CultureConfig, CultureRenameEntry, CultureRepairEntry};
pub use fingerprint::compute_playset_fingerprint;
pub use gui::{GuiConfig, GuiMode, GuiTextOverride, GuiVisibilityOverride};
pub(crate) use repairs::repairs_identity;
pub use repairs::{SourceRepairEntry, proposed_repair_entry, render_repairs_toml};
pub use transform::SourceEdit;

use crate::game::eu4::Eu4;
use crate::model::{GamePath, GamePathBuf};
use crate::playset::steam::WorkshopInstallIdentity;
use globset::{Candidate, GlobBuilder, GlobMatcher};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashSet};
use std::error::Error;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};

pub const DEFAULT_EMIT_INDENT: &str = "\t";

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
pub struct Project {
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub project: Option<ProjectConfig>,
	#[serde(default)]
	pub overrides: Vec<DepOverride>,
	#[serde(default)]
	pub resolutions: Vec<ResolutionEntry>,
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub emit: Option<EmitConfig>,
	#[serde(default, skip_serializing_if = "CultureConfig::is_empty")]
	pub cultures: CultureConfig,
	#[serde(default, skip_serializing_if = "GuiConfig::is_empty")]
	pub gui: GuiConfig,
	/// Reviewed syntax repairs of mod script files.
	#[serde(default, skip_serializing_if = "Vec::is_empty")]
	pub repairs: Vec<SourceRepairEntry>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EmitConfig {
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub indent: Option<String>,
	/// `false` keeps every fraction digit the merge produced, including the
	/// ones the game was seen to ignore.
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub drop_unread_decimals: Option<bool>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawProject {
	#[serde(default)]
	project: Option<ProjectConfig>,
	#[serde(default)]
	overrides: Vec<DepOverride>,
	#[serde(default)]
	resolutions: Vec<ResolutionEntry>,
	#[serde(default)]
	emit: Option<EmitConfig>,
	#[serde(default)]
	cultures: CultureConfig,
	#[serde(default)]
	gui: GuiConfig,
	#[serde(default)]
	repairs: Vec<SourceRepairEntry>,
}

impl<'de> Deserialize<'de> for Project {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: serde::Deserializer<'de>,
	{
		let raw = RawProject::deserialize(deserializer)?;
		ResolutionMap::from_entries(&raw.resolutions).map_err(serde::de::Error::custom)?;
		raw.cultures.validate().map_err(serde::de::Error::custom)?;
		raw.gui.validate().map_err(serde::de::Error::custom)?;
		repairs::validate_repairs(&raw.repairs).map_err(serde::de::Error::custom)?;
		Ok(Self {
			project: raw.project,
			overrides: raw.overrides,
			resolutions: raw.resolutions,
			emit: raw.emit,
			cultures: raw.cultures,
			gui: raw.gui,
			repairs: raw.repairs,
		})
	}
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProjectConfig {
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub game: Option<Eu4>,
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub game_path: Option<PathBuf>,
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub paradox_data_path: Option<PathBuf>,
	#[serde(default, skip_serializing_if = "Vec::is_empty")]
	pub imports: Vec<ProjectImport>,
	#[serde(default, skip_serializing_if = "Vec::is_empty")]
	pub mods: Vec<ProjectMod>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProjectImport {
	pub kind: ProjectImportKind,
	pub path: PathBuf,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProjectImportKind {
	DlcLoad,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProjectMod {
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub id: Option<String>,
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub path: Option<PathBuf>,
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub steam_id: Option<String>,
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub workshop_identity: Option<WorkshopInstallIdentity>,
	#[serde(default = "default_project_mod_enabled")]
	pub enabled: bool,
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub position: Option<usize>,
}

fn default_project_mod_enabled() -> bool {
	true
}

#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct DepOverride {
	#[serde(rename = "mod", alias = "mod_id")]
	pub mod_id: String,
	#[serde(rename = "dep", alias = "dep_id")]
	pub dep_id: String,
	#[serde(default)]
	pub note: Option<String>,
}

impl DepOverride {
	pub fn new(mod_id: impl Into<String>, dep_id: impl Into<String>) -> Self {
		Self {
			mod_id: mod_id.into(),
			dep_id: dep_id.into(),
			note: None,
		}
	}

	pub fn matches(&self, mod_id: &str, dep_id: &str) -> bool {
		self.mod_id == mod_id && self.dep_id == dep_id
	}
}

#[derive(Debug, Clone, Deserialize, Serialize, Eq, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct ResolutionEntry {
	/// The output file a whole-file resolution applies to, as a game path.
	/// Reading a config validates it.
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub file: Option<GamePathBuf>,
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub conflict_id: Option<String>,
	#[serde(rename = "mod", default, skip_serializing_if = "Option::is_none")]
	pub mod_id: Option<String>,
	/// Pattern selector DSL: `<file_side>::<addr_side>?`. Each side defaults
	/// to a glob; prefix `re:` switches that side to a regex. The address
	/// side is optional — if absent (or empty after `::`), the rule matches
	/// on file path alone, applying to every leaf in matching files.
	///
	/// Examples:
	/// - `common/ideas/**` — every leaf inside any file under common/ideas/
	/// - `common/ideas/**::xx_idea_*` — only leaves whose address matches
	/// - `re:^events/.*\.txt$::re:^test\..*` — both sides regex
	#[serde(rename = "match", default, skip_serializing_if = "Option::is_none")]
	pub r#match: Option<String>,
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub prefer_mod: Option<String>,
	/// One-based exact candidate index. Valid only with an exact `conflict_id`
	/// selector, whose identity binds the complete candidate sequence.
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub prefer_candidate: Option<usize>,
	/// A file on this host whose bytes replace the output, in host syntax.
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub use_file: Option<PathBuf>,
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub keep_existing: Option<bool>,
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub priority_boost: Option<i32>,
	/// Named handler from the merge handler registry (e.g. `last_writer`,
	/// `defer`, `keep_existing`). Only valid alongside the `match` selector.
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub handler: Option<String>,
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub policy: Option<ResolutionPolicy>,
}

#[derive(Debug, Clone, Default)]
pub struct ResolutionMap {
	/// Indexed by game path. BTreeMap (not HashMap) for deterministic iteration
	/// order across runs — important for foch.toml dumps and diagnostic output.
	pub by_file: BTreeMap<GamePathBuf, ResolutionDecision>,
	/// Indexed by conflict ID. BTreeMap (not HashMap) for deterministic iteration
	/// order across runs — important for foch.toml dumps and diagnostic output.
	pub by_conflict_id: BTreeMap<String, ResolutionDecision>,
	/// Indexed by mod ID. BTreeMap (not HashMap) for deterministic iteration
	/// order across runs — important for foch.toml dumps and diagnostic output.
	pub mod_priority_boost: BTreeMap<String, i32>,
	pub pattern_rules: Vec<PatternRule>,
}

impl PartialEq for ResolutionMap {
	fn eq(&self, other: &Self) -> bool {
		self.by_file == other.by_file
			&& self.by_conflict_id == other.by_conflict_id
			&& self.mod_priority_boost == other.mod_priority_boost
			&& self.pattern_rules.len() == other.pattern_rules.len()
			&& self
				.pattern_rules
				.iter()
				.zip(other.pattern_rules.iter())
				.all(|(a, b)| a.dsl == b.dsl && a.decision == b.decision)
	}
}

impl Eq for ResolutionMap {}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ResolutionDecision {
	PreferMod(String),
	/// Zero-based exact candidate index used internally after config parsing.
	PreferCandidate(usize),
	/// Configured external file whose payload is frozen during merge analysis.
	UseFile(PathBuf),
	/// Runtime-only external file selected interactively after export starts.
	UseLiveFile(PathBuf),
	KeepExisting,
	/// Dispatch to a named handler in the merge handler registry.
	Handler(String),
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResolutionPolicy {
	CwtSuggested,
}

/// Compiled pattern rule from a `[[resolutions]]` entry that uses the
/// `match` selector. Holds the original DSL string for diagnostics plus the
/// pre-compiled file/leaf matchers ready for lookup-time use.
#[derive(Clone, Debug)]
pub struct PatternRule {
	pub dsl: String,
	pub file_matcher: Matcher,
	pub leaf_matcher: Option<Matcher>,
	pub decision: ResolutionDecision,
}

impl PatternRule {
	/// Returns true when this rule covers the given (file, leaf_address).
	/// The file side matches the game path's canonical text. `leaf_address`
	/// may be empty when the caller has no per-leaf identity (e.g. file-only
	/// resolutions); rules with a leaf matcher then never match.
	pub fn matches(&self, file: &GamePath, leaf_address: &str) -> bool {
		if !self.file_matcher.is_match(file.as_str()) {
			return false;
		}
		match &self.leaf_matcher {
			None => true,
			Some(matcher) => !leaf_address.is_empty() && matcher.is_match(leaf_address),
		}
	}
}

/// Matches a single side of a pattern rule. Globs are compiled via
/// [`globset`]; the `re:` prefix switches to a [`regex::Regex`].
#[derive(Clone, Debug)]
pub enum Matcher {
	Glob(GlobMatcher),
	Regex(Regex),
}

impl Matcher {
	pub fn is_match(&self, value: &str) -> bool {
		match self {
			Self::Glob(matcher) => matcher.is_match_candidate(&Candidate::from_bytes(value)),
			Self::Regex(regex) => regex.is_match(value),
		}
	}
}

/// Splits a DSL `<file_side>::<addr_side>?` into a file matcher plus an
/// optional leaf matcher. Each side independently honors the `re:` prefix.
/// An empty address side (`"events/**::"` or trailing `::`) is treated as
/// "no address constraint" — same as omitting `::` entirely.
pub fn parse_match_dsl(input: &str) -> Result<(Matcher, Option<Matcher>), ConfigError> {
	let trimmed = input.trim();
	if trimmed.is_empty() {
		return Err(ConfigError::new("match pattern cannot be empty"));
	}
	let (file_side, addr_side) = match trimmed.split_once("::") {
		Some((file, addr)) => {
			let addr = addr.trim();
			(file.trim(), if addr.is_empty() { None } else { Some(addr) })
		}
		None => (trimmed, None),
	};
	if file_side.is_empty() {
		return Err(ConfigError::new(
			"match pattern file side cannot be empty (use `**` to match everything)",
		));
	}
	let file_matcher = parse_pattern_side(file_side)?;
	let leaf_matcher = match addr_side {
		Some(side) => Some(parse_pattern_side(side)?),
		None => None,
	};
	Ok((file_matcher, leaf_matcher))
}

fn parse_pattern_side(side: &str) -> Result<Matcher, ConfigError> {
	if let Some(re) = side.strip_prefix("re:") {
		let re = re.trim();
		if re.is_empty() {
			return Err(ConfigError::new(
				"regex pattern side cannot be empty after `re:` prefix",
			));
		}
		Regex::new(re)
			.map(Matcher::Regex)
			.map_err(|err| ConfigError::new(format!("invalid regex `{re}`: {err}")))
	} else {
		GlobBuilder::new(side)
			.backslash_escape(true)
			.build()
			.map(|glob| Matcher::Glob(glob.compile_matcher()))
			.map_err(|err| ConfigError::new(format!("invalid glob `{side}`: {err}")))
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ConfigError {
	message: String,
}

impl ConfigError {
	pub fn new(message: impl Into<String>) -> Self {
		Self {
			message: message.into(),
		}
	}

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

	fn resolution_entry(index: usize, message: impl Into<String>) -> Self {
		Self::new(format!(
			"invalid [[resolutions]] entry {}: {}",
			index + 1,
			message.into()
		))
	}
}

impl fmt::Display for ConfigError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.write_str(&self.message)
	}
}

impl Error for ConfigError {}

impl ResolutionMap {
	pub fn from_entries(entries: &[ResolutionEntry]) -> Result<Self, ConfigError> {
		let mut map = Self::default();
		for (index, entry) in entries.iter().enumerate() {
			entry.validate(index)?;
			if let Some(mod_id) = &entry.mod_id {
				let priority_boost = entry
					.priority_boost
					.expect("validated mod resolution has priority_boost");
				map.mod_priority_boost
					.insert(mod_id.clone(), priority_boost);
				continue;
			}

			// A policy entry is validated and then takes no part in the merge:
			// nothing applies a policy yet, so none is stored.
			if entry.policy.is_some() {
				if let Some(dsl) = &entry.r#match {
					let (_, leaf_matcher) = parse_match_dsl(dsl)
						.map_err(|err| ConfigError::resolution_entry(index, err.message()))?;
					if leaf_matcher.is_some() {
						return Err(ConfigError::resolution_entry(
							index,
							"policy action does not support address-constrained match selectors",
						));
					}
				}
				continue;
			}

			let decision = entry
				.decision_action()
				.expect("validated non-policy resolution has a decision");
			if let Some(file) = &entry.file {
				map.by_file.insert(file.clone(), decision);
			} else if let Some(conflict_id) = &entry.conflict_id {
				map.by_conflict_id.insert(conflict_id.clone(), decision);
			} else if let Some(dsl) = &entry.r#match {
				let (file_matcher, leaf_matcher) = parse_match_dsl(dsl)
					.map_err(|err| ConfigError::resolution_entry(index, err.message()))?;
				map.pattern_rules.push(PatternRule {
					dsl: dsl.clone(),
					file_matcher,
					leaf_matcher,
					decision,
				});
			}
		}
		Ok(map)
	}

	/// Look up a resolution for the given (file, conflict_id, leaf_address).
	///
	/// Precedence (first match wins):
	/// 1. exact `conflict_id` match (per-leaf hash from foch.toml)
	/// 2. exact `file` match (whole-file resolutions from foch.toml)
	/// 3. pattern rules in declaration order
	///
	/// `leaf_address` should follow the canonical `path/key` shape (e.g.
	/// `flavor_fra.3135/option/define_advisor/name`); pass an empty string
	/// when the caller has no leaf identity (file-only lookups still work
	/// against the first two layers and against pattern rules with no
	/// address side).
	pub fn lookup(
		&self,
		file: &GamePath,
		conflict_id: &str,
		leaf_address: &str,
	) -> Option<&ResolutionDecision> {
		if let Some(decision) = self.by_conflict_id.get(conflict_id) {
			return Some(decision);
		}
		if let Some(decision) = self.by_file.get(file) {
			return Some(decision);
		}
		self.pattern_rules
			.iter()
			.find(|rule| rule.matches(file, leaf_address))
			.map(|rule| &rule.decision)
	}
}

impl ResolutionEntry {
	fn validate(&self, index: usize) -> Result<(), ConfigError> {
		if self.selector_count() != 1 {
			return Err(ConfigError::resolution_entry(
				index,
				"exactly one selector (file, conflict_id, mod, match) must be set",
			));
		}
		if matches!(self.keep_existing, Some(false)) {
			return Err(ConfigError::resolution_entry(
				index,
				"keep_existing must be true when set",
			));
		}
		if self.mod_id.is_some() {
			if self.priority_boost.is_none() {
				return Err(ConfigError::resolution_entry(
					index,
					"mod selector requires priority_boost action",
				));
			}
			if self.all_action_count() != 1 {
				return Err(ConfigError::resolution_entry(
					index,
					"priority_boost cannot be combined with prefer_mod, prefer_candidate, use_file, keep_existing, handler, or policy",
				));
			}
			return Ok(());
		}
		if self.priority_boost.is_some() {
			return Err(ConfigError::resolution_entry(
				index,
				"priority_boost requires mod selector",
			));
		}
		if self.handler.is_some() && self.r#match.is_none() {
			return Err(ConfigError::resolution_entry(
				index,
				"handler action requires match selector",
			));
		}
		if self.policy.is_some() && !(self.file.is_some() || self.r#match.is_some()) {
			return Err(ConfigError::resolution_entry(
				index,
				"policy action requires file selector or match selector",
			));
		}
		if let Some(candidate) = self.prefer_candidate {
			if self.conflict_id.is_none() {
				return Err(ConfigError::resolution_entry(
					index,
					"prefer_candidate requires an exact conflict_id selector",
				));
			}
			if candidate == 0 {
				return Err(ConfigError::resolution_entry(
					index,
					"prefer_candidate is one-based and must be at least 1",
				));
			}
		}
		if self.all_action_count() != 1 {
			return Err(ConfigError::resolution_entry(
				index,
				"exactly one action (prefer_mod, prefer_candidate, use_file, keep_existing, handler, policy) must be set",
			));
		}
		if self.keep_existing.is_some() && self.file.is_none() {
			return Err(ConfigError::resolution_entry(
				index,
				"keep_existing action requires file selector",
			));
		}
		Ok(())
	}

	fn selector_count(&self) -> usize {
		option_count(&self.file)
			+ option_count(&self.conflict_id)
			+ option_count(&self.mod_id)
			+ option_count(&self.r#match)
	}

	fn standard_action_count(&self) -> usize {
		option_count(&self.prefer_mod)
			+ option_count(&self.prefer_candidate)
			+ option_count(&self.use_file)
			+ option_count(&self.keep_existing)
			+ option_count(&self.handler)
			+ option_count(&self.policy)
	}

	fn all_action_count(&self) -> usize {
		self.standard_action_count() + option_count(&self.priority_boost)
	}

	fn decision_action(&self) -> Option<ResolutionDecision> {
		if let Some(prefer_candidate) = self.prefer_candidate {
			Some(ResolutionDecision::PreferCandidate(prefer_candidate - 1))
		} else if let Some(prefer_mod) = &self.prefer_mod {
			Some(ResolutionDecision::PreferMod(prefer_mod.clone()))
		} else if let Some(use_file) = &self.use_file {
			Some(ResolutionDecision::UseFile(use_file.clone()))
		} else if self.keep_existing.is_some() {
			Some(ResolutionDecision::KeepExisting)
		} else {
			self.handler
				.as_ref()
				.map(|handler| ResolutionDecision::Handler(handler.clone()))
		}
	}
}

/// The persisted identity of an address-patch conflict. `foch.toml` stores it,
/// so the hashed text is the game path's canonical text, exactly what the
/// slash-normalized path text was for every valid path.
pub fn compute_conflict_id(file_path: &GamePath, addr_path: &str, addr_key: &str) -> String {
	let mut hasher = blake3::Hasher::new();
	hasher.update(file_path.as_str().as_bytes());
	hasher.update(b"\0");
	hasher.update(addr_path.as_bytes());
	hasher.update(b"\0");
	hasher.update(addr_key.as_bytes());
	let hash = hasher.finalize();
	let hex = hash.to_hex();
	hex.as_str()[..8].to_owned()
}

fn option_count<T>(option: &Option<T>) -> usize {
	if option.is_some() { 1 } else { 0 }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DepOverrideSource {
	Config,
	Cli,
}

impl fmt::Display for DepOverrideSource {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::Config => f.write_str("config"),
			Self::Cli => f.write_str("cli"),
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct AppliedDepOverride {
	pub mod_id: String,
	pub dep_id: String,
	pub source: DepOverrideSource,
}

impl AppliedDepOverride {
	pub fn config(dep_override: &DepOverride) -> Self {
		Self {
			mod_id: dep_override.mod_id.clone(),
			dep_id: dep_override.dep_id.clone(),
			source: DepOverrideSource::Config,
		}
	}

	pub fn cli(mod_id: impl Into<String>, dep_id: impl Into<String>) -> Self {
		Self {
			mod_id: mod_id.into(),
			dep_id: dep_id.into(),
			source: DepOverrideSource::Cli,
		}
	}
}

impl From<&AppliedDepOverride> for DepOverride {
	fn from(value: &AppliedDepOverride) -> Self {
		Self::new(value.mod_id.clone(), value.dep_id.clone())
	}
}

#[derive(Debug)]
pub enum FochConfigLoadError {
	Io {
		path: PathBuf,
		source: std::io::Error,
	},
	Parse {
		path: PathBuf,
		source: toml::de::Error,
	},
}

impl fmt::Display for FochConfigLoadError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::Io { path, source } => {
				write!(f, "failed to read foch config {}: {source}", path.display())
			}
			Self::Parse { path, source } => {
				write!(
					f,
					"failed to parse foch config {}: {source}",
					path.display()
				)
			}
		}
	}
}

impl Error for FochConfigLoadError {
	fn source(&self) -> Option<&(dyn Error + 'static)> {
		match self {
			Self::Io { source, .. } => Some(source),
			Self::Parse { source, .. } => Some(source),
		}
	}
}

impl Project {
	pub fn from_toml_str(content: &str) -> Result<Self, toml::de::Error> {
		toml::from_str(content)
	}

	pub fn emit_indent(&self) -> &str {
		self.emit
			.as_ref()
			.and_then(|emit| emit.indent.as_deref())
			.unwrap_or(DEFAULT_EMIT_INDENT)
	}

	/// Whether merged files drop the fraction digits the game was seen to
	/// ignore. On unless `[emit] drop_unread_decimals = false`.
	pub fn emit_drops_unread_decimals(&self) -> bool {
		self.emit
			.as_ref()
			.and_then(|emit| emit.drop_unread_decimals)
			.unwrap_or(true)
	}

	pub fn load(playset_root: &Path) -> Self {
		Self::try_load(playset_root).unwrap_or_default()
	}

	pub fn try_load(playset_root: &Path) -> Result<Self, FochConfigLoadError> {
		Self::try_load_from_paths(Self::search_paths(playset_root))
	}

	pub fn load_from_path(path: &Path) -> Result<Self, FochConfigLoadError> {
		Self::load_file(path)
	}

	fn try_load_from_paths(paths: Vec<PathBuf>) -> Result<Self, FochConfigLoadError> {
		let mut merged = Self::default();
		for path in paths {
			if path.is_file() {
				let config = Self::load_file(&path)?;
				merged.overrides.extend(config.overrides);
				merged.resolutions.extend(config.resolutions);
				merged.cultures.renames.extend(config.cultures.renames);
				merged.cultures.repairs.extend(config.cultures.repairs);
				if config.gui.mode.is_some() {
					merged.gui.mode = config.gui.mode;
				}
				merged.gui.text.extend(config.gui.text);
				merged.gui.visibility.extend(config.gui.visibility);
				merged
					.gui
					.validate()
					.map_err(|error| FochConfigLoadError::Parse {
						path: path.clone(),
						source: serde::de::Error::custom(error),
					})?;
				merged
					.cultures
					.validate()
					.map_err(|error| FochConfigLoadError::Parse {
						path: path.clone(),
						source: serde::de::Error::custom(error),
					})?;
				merged.repairs.extend(config.repairs);
				repairs::validate_repairs(&merged.repairs).map_err(|error| {
					FochConfigLoadError::Parse {
						path: path.clone(),
						source: serde::de::Error::custom(error),
					}
				})?;
				if config.project.is_some() {
					merged.project = config.project;
				}
				if config.emit.is_some() {
					merged.emit = config.emit;
				}
			}
		}
		Ok(merged)
	}

	fn load_file(path: &Path) -> Result<Self, FochConfigLoadError> {
		let content = fs::read_to_string(path).map_err(|source| FochConfigLoadError::Io {
			path: path.to_path_buf(),
			source,
		})?;
		if content.trim().is_empty() {
			return Ok(Self::default());
		}
		let mut config =
			Self::from_toml_str(&content).map_err(|source| FochConfigLoadError::Parse {
				path: path.to_path_buf(),
				source,
			})?;
		config.anchor_relative_use_files(path)?;
		Ok(config)
	}

	/// A relative `use_file` names a file next to the `foch.toml` that
	/// declares it, wherever the process runs. Anchoring it at load keeps that
	/// meaning when several configs merge and when the merge freezes or
	/// fingerprints the source.
	fn anchor_relative_use_files(&mut self, config_path: &Path) -> Result<(), FochConfigLoadError> {
		if !self
			.resolutions
			.iter()
			.any(|entry| entry.use_file.as_deref().is_some_and(Path::is_relative))
		{
			return Ok(());
		}
		let config_path =
			std::path::absolute(config_path).map_err(|source| FochConfigLoadError::Io {
				path: config_path.to_path_buf(),
				source,
			})?;
		let config_dir = config_path.parent().unwrap_or(Path::new(""));
		for entry in &mut self.resolutions {
			if let Some(use_file) = entry.use_file.as_mut()
				&& use_file.is_relative()
			{
				*use_file = config_dir.join(&*use_file);
			}
		}
		Ok(())
	}

	fn search_paths(playset_root: &Path) -> Vec<PathBuf> {
		let mut paths = Vec::new();
		let mut seen = HashSet::new();
		if let Ok(cwd) = std::env::current_dir() {
			push_unique_path(&mut paths, &mut seen, cwd.join("foch.toml"));
		}
		push_unique_path(&mut paths, &mut seen, playset_root.join("foch.toml"));
		// 注意:不要扫 ~/.config/foch/config.toml — 那个文件归
		// input::Config (steam_root_path / game_path / extra_ignore_patterns),
		// 跟此处的本地 foch.toml(overrides / resolutions)是两个不同 schema。
		// 用户级 foch.toml 用 ~/.config/foch/foch.toml 隔离开。
		if let Some(home) = dirs::home_dir() {
			push_unique_path(
				&mut paths,
				&mut seen,
				home.join(".config").join("foch").join("foch.toml"),
			);
		}
		paths
	}
}

fn push_unique_path(paths: &mut Vec<PathBuf>, seen: &mut HashSet<PathBuf>, path: PathBuf) {
	if seen.insert(path.clone()) {
		paths.push(path);
	}
}

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

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

	fn game_path_buf(text: &str) -> GamePathBuf {
		GamePathBuf::parse(text).expect("valid game path")
	}

	#[test]
	fn parses_valid_toml_with_multiple_overrides() {
		let config = Project::from_toml_str(
			r#"
[[overrides]]
mod = "3378403419"
dep = "1999055990"
note = "not a git parent"

[[overrides]]
mod = "abc"
dep = "def"
"#,
		)
		.expect("parse config");

		assert_eq!(config.overrides.len(), 2);
		assert_eq!(config.overrides[0].mod_id, "3378403419");
		assert_eq!(config.overrides[0].dep_id, "1999055990");
		assert_eq!(
			config.overrides[0].note.as_deref(),
			Some("not a git parent")
		);
		assert_eq!(config.overrides[1], DepOverride::new("abc", "def"));
	}

	#[test]
	fn parses_emit_indent_config() {
		let config = Project::from_toml_str(
			r#"
[emit]
indent = "  "
"#,
		)
		.expect("parse config");

		assert_eq!(
			config.emit,
			Some(EmitConfig {
				indent: Some("  ".to_string()),
				drop_unread_decimals: None,
			})
		);
		assert_eq!(config.emit_indent(), "  ");
		assert!(config.emit_drops_unread_decimals());
	}

	#[test]
	fn unread_decimals_are_dropped_unless_the_project_keeps_them() {
		assert!(Project::default().emit_drops_unread_decimals());
		let config = Project::from_toml_str(
			r#"
[emit]
drop_unread_decimals = false
"#,
		)
		.expect("parse config");

		assert!(!config.emit_drops_unread_decimals());
		assert_eq!(config.emit_indent(), DEFAULT_EMIT_INDENT);
	}

	#[test]
	fn culture_config_accepts_source_bound_renames_and_repairs() {
		let source = format!(
			r#"
[[cultures.renames]]
from = "old_culture"
to = "new_culture"
mod = "culture_mod"
file = "common/cultures/test.txt"
sha256 = "{digest}"
[[cultures.repairs]]
mod = "culture_mod"
file = "common/cultures/test.txt"
sha256 = "{digest}"
edits = [{{ start = 1, end = 3, expected = "é", replacement = "e" }}]
"#,
			digest = "a".repeat(64),
		);
		let parsed = Project::from_toml_str(&source).expect("reviewed culture inputs");
		let encoded = toml::to_string(&parsed).expect("serialize reviewed inputs");
		assert!(encoded.contains("old_culture"));
		assert!(encoded.contains("expected = \"é\""));
		assert_eq!(Project::from_toml_str(&encoded).unwrap(), parsed);
	}

	#[test]
	fn culture_config_is_retained_and_validated_across_project_sources() {
		let temp = tempfile::tempdir().unwrap();
		let first = temp.path().join("first.toml");
		let second = temp.path().join("second.toml");
		let source = format!(
			"[[cultures.renames]]\nfrom='old_culture'\nto='new_culture'\nmod='mod-a'\nfile='common/cultures/test.txt'\nsha256='{}'\n",
			"a".repeat(64)
		);
		std::fs::write(&first, &source).unwrap();
		std::fs::write(
			&second,
			source
				.replace("new_culture", "other_culture")
				.replace("mod-a", "mod-b"),
		)
		.unwrap();
		let merged = Project::try_load_from_paths(vec![first.clone()]).unwrap();
		assert_eq!(merged.cultures.renames.len(), 1);
		assert!(Project::try_load_from_paths(vec![first, second]).is_err());
	}

	#[test]
	fn culture_config_rejects_invalid_bindings_and_mapping_conflicts() {
		let valid = format!(
			"[[cultures.renames]]\nfrom = 'old_culture'\nto = 'new_culture'\nmod = 'culture_mod'\nfile = 'common/cultures/test.txt'\nsha256 = '{}'\n",
			"a".repeat(64),
		);
		for invalid in [
			valid.replace("old_culture", "new_culture"),
			valid.replace("test.txt", "../test.txt"),
			valid.replace("common/cultures", "events"),
			valid.replace("test.txt", "nested/test.txt"),
			valid.replace("test.txt", "*.txt"),
			valid.replace(&"a".repeat(64), &"A".repeat(64)),
			valid.replace("mod = 'culture_mod'", "mod = ''"),
			format!("{valid}unknown = true\n"),
			format!("{valid}{valid}"),
			format!("{valid}{}", valid.replace("new_culture", "other_culture")),
			format!("{valid}{}", valid.replace("old_culture", "other_culture")),
		] {
			assert!(
				Project::from_toml_str(&invalid).is_err(),
				"accepted {invalid}"
			);
		}
	}

	#[test]
	fn culture_config_identity_binds_decisions_but_not_entry_order() {
		let entry = |id: &str| CultureRenameEntry {
			from: format!("old_{id}"),
			to: format!("new_{id}"),
			mod_id: id.into(),
			file: "common/cultures/test.txt".into(),
			sha256: "a".repeat(64),
		};
		let mut config = CultureConfig {
			renames: vec![entry("one"), entry("two")],
			repairs: vec![CultureRepairEntry {
				mod_id: "one".into(),
				file: "common/cultures/test.txt".into(),
				sha256: "a".repeat(64),
				edits: vec![SourceEdit {
					start: 1,
					end: 1,
					expected: String::new(),
					replacement: "}".into(),
				}],
			}],
		};
		config.validate().unwrap();
		let identity = config.identity();
		config.renames.reverse();
		assert_eq!(config.identity(), identity);
		config.repairs[0].edits[0].replacement = "{".into();
		assert_ne!(config.identity(), identity);
		config.repairs[0].edits[0].replacement = "}".into();
		config.renames[0].to = "different_culture".into();
		assert_ne!(config.identity(), identity);
	}

	#[test]
	fn culture_config_rejects_overlapping_or_inconsistent_repairs() {
		let source = |edits: &str| {
			format!(
				"[[cultures.repairs]]\nmod = 'culture_mod'\nfile = 'common/cultures/test.txt'\nsha256 = '{}'\nedits = [{edits}]\n",
				"a".repeat(64),
			)
		};
		for edits in [
			"",
			"{ start = 3, end = 1, expected = '', replacement = '}' }",
			"{ start = 1, end = 2, expected = 'é', replacement = 'e' }",
			"{ start = 1, end = 3, expected = 'ab', replacement = '' }, { start = 2, end = 4, expected = 'bc', replacement = '' }",
			"{ start = 1, end = 1, expected = '', replacement = '}' }, { start = 1, end = 1, expected = '', replacement = '}' }",
		] {
			assert!(
				Project::from_toml_str(&source(edits)).is_err(),
				"accepted {edits}"
			);
		}
	}

	#[test]
	fn parses_project_manifest_config() {
		let config = Project::from_toml_str(
			r#"
[project]
game = "eu4"
game_path = "/games/eu4"
paradox_data_path = "/paradox/eu4"

[[project.imports]]
kind = "dlc_load"
path = "/paradox/eu4/dlc_load.json"

[[project.mods]]
id = "local_patch"
path = "../mods/local_patch"

[[project.mods]]
steam_id = "2164202838"
workshop_identity = { app_id = 236850, workshop_id = "2164202838", manifest_id = "9007199254740993" }
enabled = false
position = 4
"#,
		)
		.expect("parse project manifest");

		let project = config.project.expect("project config");
		assert_eq!(project.game, Some(Eu4));
		assert_eq!(project.imports.len(), 1);
		assert_eq!(project.imports[0].kind, ProjectImportKind::DlcLoad);
		assert_eq!(project.mods.len(), 2);
		assert_eq!(project.mods[0].id.as_deref(), Some("local_patch"));
		assert!(project.mods[0].enabled);
		assert_eq!(project.mods[1].steam_id.as_deref(), Some("2164202838"));
		assert_eq!(
			project.mods[1]
				.workshop_identity
				.as_ref()
				.expect("Workshop identity")
				.manifest_id
				.as_str(),
			"9007199254740993"
		);
		assert!(!project.mods[1].enabled);
		assert_eq!(project.mods[1].position, Some(4));
	}

	#[test]
	fn missing_emit_config_uses_default_indent() {
		let config = Project::from_toml_str(
			r#"
[[overrides]]
mod = "abc"
dep = "def"
"#,
		)
		.expect("parse config");

		assert_eq!(config.emit, None);
		assert_eq!(config.emit_indent(), DEFAULT_EMIT_INDENT);
	}

	#[test]
	fn rejects_override_missing_dep_field() {
		let err = Project::from_toml_str(
			r#"
[[overrides]]
mod = "3378403419"
"#,
		)
		.expect_err("missing dep must be invalid");

		assert!(err.to_string().contains("dep"), "error was: {err}");
	}

	#[test]
	fn parses_valid_toml_with_resolution_variants() {
		let config = Project::from_toml_str(
			r#"
[[overrides]]
mod = "abc"
dep = "def"

[[resolutions]]
file = "events/PirateEvents.txt"
prefer_mod = "1234567890"

[[resolutions]]
file = "events/ManualEvents.txt"
use_file = "manual/PirateEvents.txt"

[[resolutions]]
file = "events/ExistingEvents.txt"
keep_existing = true

[[resolutions]]
conflict_id = "ab12cd34"
prefer_mod = "9876543210"

[[resolutions]]
conflict_id = "exact-node"
prefer_candidate = 2

[[resolutions]]
mod = "1234567890"
priority_boost = 100

[[resolutions]]
file = "common/estates_preload/test.txt"
policy = "cwt_suggested"
"#,
		)
		.expect("parse config");

		assert_eq!(config.overrides, vec![DepOverride::new("abc", "def")]);
		assert_eq!(config.resolutions.len(), 7);

		let map = ResolutionMap::from_entries(&config.resolutions).expect("build resolution map");
		assert_eq!(
			map.by_file.get(game_path("events/PirateEvents.txt")),
			Some(&ResolutionDecision::PreferMod("1234567890".to_owned()))
		);
		assert_eq!(
			map.by_file.get(game_path("events/ManualEvents.txt")),
			Some(&ResolutionDecision::UseFile(PathBuf::from(
				"manual/PirateEvents.txt"
			)))
		);
		assert_eq!(
			map.by_file.get(game_path("events/ExistingEvents.txt")),
			Some(&ResolutionDecision::KeepExisting)
		);
		assert_eq!(
			map.by_conflict_id.get("ab12cd34"),
			Some(&ResolutionDecision::PreferMod("9876543210".to_owned()))
		);
		assert_eq!(
			map.by_conflict_id.get("exact-node"),
			Some(&ResolutionDecision::PreferCandidate(1))
		);
		assert_eq!(map.mod_priority_boost.get("1234567890"), Some(&100));
		assert_eq!(
			config.resolutions[6].policy,
			Some(ResolutionPolicy::CwtSuggested)
		);
		// A policy entry is validated but not applied, so it adds no decision.
		assert_eq!(map.by_file.len(), 3);
		assert!(
			!map.by_file
				.contains_key(game_path("common/estates_preload/test.txt"))
		);
	}

	#[test]
	fn lookup_iteration_is_deterministic_across_processes() {
		let entries = Project::from_toml_str(
			r#"
[[resolutions]]
file = "events/zulu.txt"
prefer_mod = "zulu-mod"

[[resolutions]]
conflict_id = "ff00aa11"
prefer_mod = "late-conflict-mod"

[[resolutions]]
mod = "7777777777"
priority_boost = 70

[[resolutions]]
file = "events/alpha.txt"
use_file = "manual/alpha.txt"

[[resolutions]]
conflict_id = "0011aaff"
use_file = "manual/conflict.txt"

[[resolutions]]
mod = "1111111111"
priority_boost = 10
"#,
		)
		.expect("parse config")
		.resolutions;
		let first = ResolutionMap::from_entries(&entries).expect("build first map");
		let second = ResolutionMap::from_entries(&entries).expect("build second map");

		let collect_by_file = |map: &ResolutionMap| {
			map.by_file
				.iter()
				.map(|(path, decision)| (path.clone(), decision.clone()))
				.collect::<Vec<_>>()
		};
		let by_file = collect_by_file(&first);
		assert_eq!(by_file, collect_by_file(&second));
		assert_eq!(
			by_file,
			vec![
				(
					game_path_buf("events/alpha.txt"),
					ResolutionDecision::UseFile(PathBuf::from("manual/alpha.txt")),
				),
				(
					game_path_buf("events/zulu.txt"),
					ResolutionDecision::PreferMod("zulu-mod".to_string()),
				),
			]
		);

		let collect_by_conflict_id = |map: &ResolutionMap| {
			map.by_conflict_id
				.iter()
				.map(|(conflict_id, decision)| (conflict_id.clone(), decision.clone()))
				.collect::<Vec<_>>()
		};
		let by_conflict_id = collect_by_conflict_id(&first);
		assert_eq!(by_conflict_id, collect_by_conflict_id(&second));
		assert_eq!(
			by_conflict_id,
			vec![
				(
					"0011aaff".to_string(),
					ResolutionDecision::UseFile(PathBuf::from("manual/conflict.txt")),
				),
				(
					"ff00aa11".to_string(),
					ResolutionDecision::PreferMod("late-conflict-mod".to_string()),
				),
			]
		);

		let collect_mod_priority_boost = |map: &ResolutionMap| {
			map.mod_priority_boost
				.iter()
				.map(|(mod_id, boost)| (mod_id.clone(), *boost))
				.collect::<Vec<_>>()
		};
		let mod_priority_boost = collect_mod_priority_boost(&first);
		assert_eq!(mod_priority_boost, collect_mod_priority_boost(&second));
		assert_eq!(
			mod_priority_boost,
			vec![
				("1111111111".to_string(), 10),
				("7777777777".to_string(), 70),
			]
		);
	}

	#[test]
	fn rejects_invalid_resolution_entries() {
		let cases = [
			(
				"missing selector",
				r#"
[[resolutions]]
prefer_mod = "123"
"#,
				"exactly one selector",
			),
			(
				"missing action",
				r#"
[[resolutions]]
file = "events/PirateEvents.txt"
"#,
				"exactly one action",
			),
			(
				"multiple selectors",
				r#"
[[resolutions]]
file = "events/PirateEvents.txt"
conflict_id = "ab12cd34"
prefer_mod = "123"
"#,
				"exactly one selector",
			),
			(
				"multiple actions",
				r#"
[[resolutions]]
file = "events/PirateEvents.txt"
prefer_mod = "123"
use_file = "manual/PirateEvents.txt"
"#,
				"exactly one action",
			),
			(
				"candidate selection without exact conflict",
				r#"
[[resolutions]]
file = "events/PirateEvents.txt"
prefer_candidate = 1
"#,
				"prefer_candidate requires an exact conflict_id",
			),
			(
				"zero candidate selection",
				r#"
[[resolutions]]
conflict_id = "ab12cd34"
prefer_candidate = 0
"#,
				"prefer_candidate is one-based",
			),
			(
				"mod without priority boost",
				r#"
[[resolutions]]
mod = "123"
prefer_mod = "123"
"#,
				"mod selector requires priority_boost",
			),
			(
				"keep existing without file",
				r#"
[[resolutions]]
conflict_id = "ab12cd34"
keep_existing = true
"#,
				"keep_existing action requires file selector",
			),
			(
				"policy without file or match selector",
				r#"
[[resolutions]]
conflict_id = "ab12cd34"
policy = "cwt_suggested"
"#,
				"policy action requires file selector or match selector",
			),
			(
				"policy with address-constrained match",
				r#"
[[resolutions]]
match = "common/estates_preload/**::modifier"
policy = "cwt_suggested"
"#,
				"does not support address-constrained match selectors",
			),
		];

		for (name, content, expected) in cases {
			let err = Project::from_toml_str(content).expect_err(name);
			let message = err.to_string();
			assert!(
				message.contains(expected),
				"{name} error should contain {expected:?}, error was: {message}"
			);
		}
	}

	#[test]
	fn compute_conflict_id_is_stable_and_input_sensitive() {
		let base = compute_conflict_id(game_path("events/PirateEvents.txt"), "root/event", "id");

		assert_eq!(base.len(), 8);
		assert!(base.chars().all(|c| c.is_ascii_hexdigit()));
		assert_eq!(
			base,
			compute_conflict_id(game_path("events/PirateEvents.txt"), "root/event", "id")
		);
		assert_ne!(
			base,
			compute_conflict_id(game_path("events/OtherEvents.txt"), "root/event", "id")
		);
		assert_ne!(
			base,
			compute_conflict_id(game_path("events/PirateEvents.txt"), "root/other", "id")
		);
		assert_ne!(
			base,
			compute_conflict_id(game_path("events/PirateEvents.txt"), "root/event", "other")
		);
	}

	/// `foch.toml` stores these ids, so typing the path must not move them:
	/// the value is the one the slash-normalized path text produced.
	#[test]
	fn compute_conflict_id_keeps_the_ids_persisted_before_paths_were_typed() {
		assert_eq!(
			compute_conflict_id(game_path("events/PirateEvents.txt"), "root/event", "id"),
			"2d6e0b85"
		);
	}

	/// A whole-file resolution names a game path; text that is not one is a
	/// config error naming it, not a key that silently never matches.
	#[test]
	fn a_resolution_file_that_is_not_a_game_path_is_a_config_error() {
		for (file, rejected) in [
			(r#""events\\PirateEvents.txt""#, r"events\PirateEvents.txt"),
			(
				r#""../events/PirateEvents.txt""#,
				"../events/PirateEvents.txt",
			),
			(r#""/events/PirateEvents.txt""#, "/events/PirateEvents.txt"),
		] {
			let error = Project::from_toml_str(&format!(
				"[[resolutions]]\nfile = {file}\nprefer_mod = \"x\"\n"
			))
			.expect_err(file)
			.to_string();
			assert!(
				error.contains(&format!("invalid game path `{rejected}`")),
				"{file}: {error}"
			);
		}
	}

	/// `use_file` names a host file: its text is kept exactly, including a
	/// `\`, which is an ordinary name character off Windows.
	#[test]
	fn a_use_file_keeps_its_host_text() {
		let config = Project::from_toml_str(
			r#"
[[resolutions]]
file = "events/PirateEvents.txt"
use_file = "manual\\Pirate Events.txt"
"#,
		)
		.expect("parse config");
		assert_eq!(
			config.resolutions[0].use_file.as_deref(),
			Some(Path::new(r"manual\Pirate Events.txt"))
		);
	}

	#[test]
	fn resolution_map_lookup_prefers_conflict_id_over_file() {
		let config = Project::from_toml_str(
			r#"
[[resolutions]]
file = "events/PirateEvents.txt"
prefer_mod = "file-mod"

[[resolutions]]
conflict_id = "ab12cd34"
prefer_mod = "conflict-mod"
"#,
		)
		.expect("parse config");
		let map = ResolutionMap::from_entries(&config.resolutions).expect("build resolution map");

		let conflict_decision = ResolutionDecision::PreferMod("conflict-mod".to_owned());
		let file_decision = ResolutionDecision::PreferMod("file-mod".to_owned());
		assert_eq!(
			map.lookup(game_path("events/PirateEvents.txt"), "ab12cd34", ""),
			Some(&conflict_decision)
		);
		assert_eq!(
			map.lookup(game_path("events/PirateEvents.txt"), "unknown", ""),
			Some(&file_decision)
		);
		assert_eq!(
			map.lookup(game_path("events/OtherEvents.txt"), "unknown", ""),
			None
		);
	}

	#[test]
	fn load_merges_multiple_existing_sources() {
		let temp = TempDir::new().expect("temp dir");
		let first = temp.path().join("first.toml");
		let second = temp.path().join("second.toml");
		fs::write(&first, "[[overrides]]\nmod = \"a\"\ndep = \"b\"\n").expect("write first");
		fs::write(&second, "[[overrides]]\nmod = \"c\"\ndep = \"d\"\n").expect("write second");

		let config = Project::try_load_from_paths(vec![first, second]).expect("load configs");

		assert_eq!(
			config.overrides,
			vec![DepOverride::new("a", "b"), DepOverride::new("c", "d")]
		);
	}

	/// Each config's relative `use_file` is read from that config's own
	/// directory, not the process working directory; an absolute one is kept.
	#[test]
	fn a_relative_use_file_is_anchored_at_its_declaring_config() {
		let temp = TempDir::new().expect("temp dir");
		let project_dir = temp.path().join("project");
		let user_dir = temp.path().join("user");
		fs::create_dir_all(&project_dir).expect("create project dir");
		fs::create_dir_all(&user_dir).expect("create user dir");
		let absolute = temp.path().join("shared").join("Absolute.txt");
		let first = project_dir.join("foch.toml");
		let second = user_dir.join("foch.toml");
		fs::write(
			&first,
			"[[resolutions]]\nfile = \"events/PirateEvents.txt\"\nuse_file = \"resolutions/PirateEvents.txt\"\n",
		)
		.expect("write project config");
		let absolute_text = toml_edit::value(absolute.to_str().expect("UTF-8 temp path"));
		fs::write(
			&second,
			format!(
				"[[resolutions]]\nfile = \"events/A.txt\"\nuse_file = \"A.txt\"\n\n[[resolutions]]\nfile = \"events/B.txt\"\nuse_file = {absolute_text}\n"
			),
		)
		.expect("write user config");

		let config = Project::try_load_from_paths(vec![first, second]).expect("load configs");

		let use_files = config
			.resolutions
			.iter()
			.map(|entry| entry.use_file.clone().expect("use_file entry"))
			.collect::<Vec<_>>();
		assert_eq!(
			use_files,
			vec![
				std::path::absolute(&project_dir)
					.unwrap()
					.join("resolutions/PirateEvents.txt"),
				std::path::absolute(&user_dir).unwrap().join("A.txt"),
				absolute,
			]
		);
	}

	#[test]
	fn search_paths_excludes_engine_config_toml() {
		let temp = TempDir::new().expect("temp dir");
		let paths = Project::search_paths(temp.path());
		// Project (overrides/resolutions) 不能撞到 input::Config
		// 占用的 ~/.config/foch/config.toml 文件,否则两个 schema 互相 deny_unknown_fields。
		for path in &paths {
			assert!(
				!path.ends_with("config.toml"),
				"Project 不应扫描 config.toml 文件名(归 input::Config 所有);命中:{:?}",
				path
			);
		}
	}

	// ---------------------------------------------------------------
	// Pattern DSL + Handler decision tests (p-pattern + p-decision)
	// ---------------------------------------------------------------

	#[test]
	fn pattern_dsl_pure_glob_matches_file_only() {
		let (file_matcher, leaf_matcher) = parse_match_dsl("common/ideas/**").expect("parse glob");
		assert!(file_matcher.is_match("common/ideas/foo.txt"));
		assert!(file_matcher.is_match("common/ideas/sub/bar.txt"));
		assert!(!file_matcher.is_match("events/foo.txt"));
		assert!(leaf_matcher.is_none());
	}

	#[test]
	fn pattern_dsl_uses_portable_glob_escapes_on_every_host() {
		let (file_matcher, leaf_matcher): (Matcher, Option<Matcher>) =
			parse_match_dsl(r"common/ideas/literal\*.txt").expect("parse glob");
		assert!(file_matcher.is_match("common/ideas/literal*.txt"));
		assert!(!file_matcher.is_match("common/ideas/literal_other.txt"));
		assert!(leaf_matcher.is_none());
	}

	#[test]
	fn pattern_dsl_glob_address_side() {
		let (file_matcher, leaf_matcher) =
			parse_match_dsl("common/ideas/**::xx_idea_*").expect("parse mixed");
		assert!(file_matcher.is_match("common/ideas/national.txt"));
		let leaf = leaf_matcher.expect("address side present");
		assert!(leaf.is_match("xx_idea_pirates"));
		assert!(!leaf.is_match("yy_idea_pirates"));
	}

	#[test]
	fn pattern_dsl_pure_regex() {
		let (file_matcher, leaf_matcher) =
			parse_match_dsl("re:^events/.*\\.txt$").expect("parse regex");
		assert!(file_matcher.is_match("events/PirateEvents.txt"));
		assert!(!file_matcher.is_match("events/PirateEvents.json"));
		assert!(leaf_matcher.is_none());
	}

	#[test]
	fn pattern_dsl_mixed_glob_file_regex_address() {
		let (file_matcher, leaf_matcher) =
			parse_match_dsl("common/**::re:^test\\..*").expect("parse mixed");
		assert!(file_matcher.is_match("common/ideas/anything.txt"));
		let leaf = leaf_matcher.expect("address side present");
		assert!(leaf.is_match("test.123"));
		assert!(!leaf.is_match("other.123"));
	}

	#[test]
	fn pattern_dsl_empty_address_side_treated_as_no_constraint() {
		let (file_matcher, leaf_matcher) =
			parse_match_dsl("events/**::").expect("parse trailing colons");
		assert!(file_matcher.is_match("events/foo.txt"));
		assert!(leaf_matcher.is_none());
	}

	#[test]
	fn pattern_dsl_rejects_empty_input() {
		assert!(parse_match_dsl("").is_err());
		assert!(parse_match_dsl("   ").is_err());
	}

	#[test]
	fn pattern_dsl_rejects_empty_file_side() {
		let err = parse_match_dsl("::xx_idea_*").expect_err("empty file side rejected");
		assert!(err.to_string().contains("file side"));
	}

	#[test]
	fn pattern_dsl_rejects_empty_regex() {
		let err = parse_match_dsl("re:").expect_err("empty regex rejected");
		assert!(err.to_string().contains("regex"));
	}

	#[test]
	fn pattern_dsl_rejects_invalid_regex() {
		let err = parse_match_dsl("re:[unterminated").expect_err("bad regex rejected");
		assert!(err.to_string().contains("invalid regex"));
	}

	#[test]
	fn match_selector_with_handler_action_round_trips() {
		let config = Project::from_toml_str(
			r#"
[[resolutions]]
match = "common/ideas/**::xx_idea_*"
handler = "last_writer"
"#,
		)
		.expect("parse match+handler");
		let map = ResolutionMap::from_entries(&config.resolutions).expect("build map");
		assert_eq!(map.pattern_rules.len(), 1);
		let rule = &map.pattern_rules[0];
		assert_eq!(rule.dsl, "common/ideas/**::xx_idea_*");
		assert_eq!(
			rule.decision,
			ResolutionDecision::Handler("last_writer".to_string())
		);
		assert!(rule.matches(game_path("common/ideas/national.txt"), "xx_idea_pirates"));
		assert!(!rule.matches(game_path("common/ideas/national.txt"), "yy_idea_pirates"));
		assert!(!rule.matches(game_path("events/foo.txt"), "xx_idea_pirates"));
	}

	#[test]
	fn match_selector_supports_prefer_mod_action_too() {
		let config = Project::from_toml_str(
			r#"
[[resolutions]]
match = "common/ideas/**"
prefer_mod = "ideas-mod"
"#,
		)
		.expect("parse match+prefer_mod");
		let map = ResolutionMap::from_entries(&config.resolutions).expect("build map");
		assert_eq!(map.pattern_rules.len(), 1);
		assert_eq!(
			map.pattern_rules[0].decision,
			ResolutionDecision::PreferMod("ideas-mod".to_string())
		);
	}

	#[test]
	fn match_selector_supports_cwt_suggested_policy() {
		let config = Project::from_toml_str(
			r#"
[[resolutions]]
match = "common/estates_preload/**"
policy = "cwt_suggested"
"#,
		)
		.expect("parse match+policy");
		assert_eq!(
			config.resolutions[0].policy,
			Some(ResolutionPolicy::CwtSuggested)
		);
		let map = ResolutionMap::from_entries(&config.resolutions).expect("build map");
		// Validated but not applied: the policy adds no pattern decision.
		assert!(map.pattern_rules.is_empty());
		assert_eq!(
			map.lookup(game_path("common/estates_preload/test.txt"), "no-id", ""),
			None
		);
	}

	#[test]
	fn a_policy_with_an_address_constrained_match_is_a_config_error() {
		let error = Project::from_toml_str(
			r#"
[[resolutions]]
match = "common/estates_preload/**::estate_*"
policy = "cwt_suggested"
"#,
		)
		.expect_err("a policy match cannot name an address");
		assert!(
			error
				.to_string()
				.contains("policy action does not support address-constrained match selectors"),
			"{error}"
		);
	}

	#[test]
	fn a_policy_with_an_invalid_match_is_a_config_error() {
		let error = Project::from_toml_str(
			r#"
[[resolutions]]
match = "re:("
policy = "cwt_suggested"
"#,
		)
		.expect_err("the match pattern is still compiled");
		assert!(error.to_string().contains("invalid regex"), "{error}");
	}

	#[test]
	fn rejects_match_combined_with_other_selectors() {
		let cases = [
			r#"
[[resolutions]]
match = "common/**"
file = "common/foo.txt"
prefer_mod = "x"
"#,
			r#"
[[resolutions]]
match = "common/**"
conflict_id = "ab12cd34"
prefer_mod = "x"
"#,
		];
		for content in cases {
			let err =
				Project::from_toml_str(content).expect_err("multi-selector should be rejected");
			assert!(
				err.to_string().contains("exactly one selector"),
				"expected multi-selector error, got {err}"
			);
		}
	}

	#[test]
	fn rejects_handler_without_match_selector() {
		let err = Project::from_toml_str(
			r#"
[[resolutions]]
file = "common/foo.txt"
handler = "last_writer"
"#,
		)
		.expect_err("handler+file should be rejected");
		assert!(
			err.to_string().contains("handler action requires match"),
			"got: {err}"
		);
	}

	#[test]
	fn rejects_handler_combined_with_other_actions() {
		let err = Project::from_toml_str(
			r#"
[[resolutions]]
match = "common/**"
handler = "last_writer"
prefer_mod = "x"
"#,
		)
		.expect_err("handler+prefer_mod should be rejected");
		assert!(err.to_string().contains("exactly one action"), "got: {err}");
	}

	#[test]
	fn rejects_invalid_match_dsl() {
		let err = Project::from_toml_str(
			r#"
[[resolutions]]
match = "re:[unterminated"
handler = "last_writer"
"#,
		)
		.expect_err("invalid regex must surface");
		assert!(err.to_string().contains("invalid regex"), "got: {err}");
	}

	#[test]
	fn lookup_precedence_conflict_id_beats_pattern() {
		let config = Project::from_toml_str(
			r#"
[[resolutions]]
match = "**"
handler = "last_writer"

[[resolutions]]
conflict_id = "abc12345"
prefer_mod = "specific-mod"
"#,
		)
		.expect("parse");
		let map = ResolutionMap::from_entries(&config.resolutions).expect("build map");
		assert_eq!(
			map.lookup(game_path("anything.txt"), "abc12345", "any/leaf"),
			Some(&ResolutionDecision::PreferMod("specific-mod".to_string()))
		);
	}

	#[test]
	fn lookup_precedence_file_beats_pattern() {
		let config = Project::from_toml_str(
			r#"
[[resolutions]]
match = "**"
handler = "last_writer"

[[resolutions]]
file = "events/foo.txt"
prefer_mod = "file-mod"
"#,
		)
		.expect("parse");
		let map = ResolutionMap::from_entries(&config.resolutions).expect("build map");
		assert_eq!(
			map.lookup(game_path("events/foo.txt"), "no-id", "any/leaf"),
			Some(&ResolutionDecision::PreferMod("file-mod".to_string()))
		);
		// pattern still applies to non-matching file
		assert_eq!(
			map.lookup(game_path("events/bar.txt"), "no-id", "any/leaf"),
			Some(&ResolutionDecision::Handler("last_writer".to_string()))
		);
	}

	#[test]
	fn file_and_match_policy_entries_validate_and_add_no_decisions() {
		let config = Project::from_toml_str(
			r#"
[[resolutions]]
match = "common/estates_preload/**"
policy = "cwt_suggested"

[[resolutions]]
file = "common/estates_preload/exact.txt"
policy = "cwt_suggested"
"#,
		)
		.expect("parse");
		let map = ResolutionMap::from_entries(&config.resolutions).expect("build map");
		assert_eq!(map, ResolutionMap::default());
	}

	#[test]
	fn lookup_pattern_rules_evaluated_in_declaration_order() {
		let config = Project::from_toml_str(
			r#"
[[resolutions]]
match = "common/ideas/**::xx_idea_*"
handler = "last_writer"

[[resolutions]]
match = "common/ideas/**"
handler = "defer"
"#,
		)
		.expect("parse");
		let map = ResolutionMap::from_entries(&config.resolutions).expect("build map");
		// xx_idea_* should win; first rule covers it
		assert_eq!(
			map.lookup(
				game_path("common/ideas/national.txt"),
				"no-id",
				"xx_idea_pirates"
			),
			Some(&ResolutionDecision::Handler("last_writer".to_string()))
		);
		// non-xx_ leaf falls through to second rule
		assert_eq!(
			map.lookup(
				game_path("common/ideas/national.txt"),
				"no-id",
				"yy_idea_pirates"
			),
			Some(&ResolutionDecision::Handler("defer".to_string()))
		);
	}

	#[test]
	fn lookup_pattern_with_leaf_matcher_skipped_when_address_empty() {
		let config = Project::from_toml_str(
			r#"
[[resolutions]]
match = "common/**::xx_*"
handler = "last_writer"
"#,
		)
		.expect("parse");
		let map = ResolutionMap::from_entries(&config.resolutions).expect("build map");
		// empty leaf address — leaf matcher can't match
		assert_eq!(map.lookup(game_path("common/foo.txt"), "no-id", ""), None);
	}
}