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
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
use super::file_filter::FileFilter;
use super::{
	InputScriptCache, LoadedModSnapshot,
	mod_snapshot::{build_transient_mod_snapshot, load_or_build_mod_snapshot},
};
use crate::game::eu4::Eu4;
use crate::game::eu4::base::snapshot::{
	BaseSnapshotCurrentValidation, InstalledBaseSnapshot, InstalledBaseSnapshotIdentity,
	base_game_mod_id, detect_game_version, installed_base_snapshot_identity,
	load_installed_base_snapshot_from_identity, resolve_game_root, resolve_game_root_and_version,
};
use crate::game::eu4::content::load_rules::load_rules_for_version;
use crate::game::eu4::content::{
	ContentFamilyDescriptor, ContentLoadPolicy, module_name_for_descriptor,
};
use crate::game::eu4::script::documents::classify_document_family;
use crate::input::config::Config;
use crate::input::request::{InputRequest, InputSource};
use crate::model::{
	DocumentFamily, GamePath, GamePathBuf, GamePathError, MergePlanContributor, MergeUnitId,
	ModCandidate, ProductInputManifest, ProductInputMod,
};
use crate::playset::ParseErrorKind;
use crate::playset::descriptor::{load_descriptor, load_launcher_descriptor};
use crate::playset::single_path_component;
use crate::playset::steam::{
	SteamWorkshopCatalog, WorkshopInstallIdentity, steam_workshop_mod_path,
};
use crate::playset::{Playset, PlaysetEntry};
use crate::project::{Project, ProjectConfig, ProjectImportKind, ProjectMod};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::error::Error;
use std::ffi::OsStr;
use std::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum InputResolveErrorKind {
	PlaylistFormat,
	Io,
}

#[derive(Clone, Debug)]
pub struct InputResolveError {
	pub kind: InputResolveErrorKind,
	pub path: PathBuf,
	pub message: String,
}

impl fmt::Display for InputResolveError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}: {}", self.path.display(), self.message)
	}
}

impl Error for InputResolveError {}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum InputTargetRole {
	Game,
	Mod,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InputTarget {
	pub path: PathBuf,
	pub role: InputTargetRole,
	pub mod_id: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ResolvedInputMod {
	pub mod_id: String,
	pub display_name: Option<String>,
	pub steam_id: Option<String>,
	pub root_path: Option<PathBuf>,
	pub descriptor_error: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InputResolveSummary {
	pub source_path: PathBuf,
	pub game: Eu4,
	pub game_root: Option<PathBuf>,
	pub mods: Vec<ResolvedInputMod>,
}

/// One source of one inventory file: which mod ships it, under which root.
#[derive(Clone, Debug)]
pub(crate) struct ResolvedInputContributor {
	pub mod_id: String,
	pub root_path: PathBuf,
	/// The file's game path under `root_path`, the same path that keys it in
	/// the inventory.
	pub relative_path: GamePathBuf,
	pub precedence: usize,
	pub is_base_game: bool,
	pub is_synthetic_base: bool,
	pub parse_ok_hint: Option<bool>,
	pub mod_hash: Option<String>,
}

impl ResolvedInputContributor {
	/// The physical file this contributor reads, resolved under its own root.
	pub(crate) fn absolute_path(&self) -> PathBuf {
		self.relative_path.to_path(&self.root_path)
	}

	/// Whether `planned` names this contributor. A plan contributor carries
	/// its mod, precedence and base-game flag; within one inventory entry
	/// those identify a contributor, except that a synthetic base shares
	/// all three with its seed when both sit at precedence 0 (no base game).
	/// The two read one physical file, so either answers the lookup.
	pub(crate) fn is_planned_as(&self, planned: &MergePlanContributor) -> bool {
		self.mod_id == planned.mod_id
			&& self.precedence == planned.precedence
			&& self.is_base_game == planned.is_base_game
	}
}

#[derive(Clone, Debug)]
pub(crate) struct ResolvedInput {
	pub playlist_path: PathBuf,
	pub playlist: Playset,
	pub game_version: Option<String>,
	pub mods: Vec<ModCandidate>,
	pub installed_base_snapshot: Option<InstalledBaseSnapshot>,
	pub cache_game_version: Option<String>,
	pub mod_snapshots: Vec<Option<LoadedModSnapshot>>,
	pub script_cache: InputScriptCache,
	pub file_inventory: BTreeMap<GamePathBuf, Vec<ResolvedInputContributor>>,
	/// Exact per-path absence observations made against the current game root
	/// for semantic families that explicitly support an empty ancestor. A
	/// missing entry in the installed snapshot is not, by itself, proof of
	/// absence because snapshots can be built with filters.
	pub verified_absent_base_paths: BTreeSet<GamePathBuf>,
	pub requested_retained_paths: Option<BTreeSet<GamePathBuf>>,
	pub effective_retained_paths: Option<BTreeSet<GamePathBuf>>,
}

impl ResolvedInput {
	/// The parse issues the analyzed snapshot of `mod_id` recorded for its
	/// file at `path`; empty when that mod has no snapshot.
	pub(crate) fn snapshot_parse_issues(
		&self,
		mod_id: &str,
		path: &GamePath,
	) -> Vec<&crate::model::ParseIssue> {
		self.mods
			.iter()
			.zip(&self.mod_snapshots)
			.filter(|(candidate, _)| candidate.mod_id == mod_id)
			.filter_map(|(_, snapshot)| snapshot.as_ref())
			.flat_map(|snapshot| &snapshot.semantic_index.parse_issues)
			.filter(|issue| issue.path.as_game_path() == path)
			.collect()
	}
}

#[derive(Clone, Debug)]
pub(crate) struct InputInventory {
	pub playlist_path: PathBuf,
	pub playlist: Playset,
	pub mods: Vec<ModCandidate>,
	pub base_game_root: Option<PathBuf>,
	pub mod_cache_game_version: Option<String>,
	pub base_snapshot_identity: Option<InstalledBaseSnapshotIdentity>,
	base_snapshot_current_validation: BaseSnapshotCurrentValidation,
	pub cache_game_version: Option<String>,
	pub snapshot_filter: FileFilter,
	pub mod_hashes: Vec<Option<String>>,
	pub product_input_manifest: Option<ProductInputManifest>,
	pub requested_retained_paths: Option<BTreeSet<GamePathBuf>>,
}

impl InputInventory {
	pub(crate) fn defer_base_snapshot_current_validation(&mut self) {
		self.base_snapshot_current_validation = BaseSnapshotCurrentValidation::Deferred;
	}
}

#[derive(Clone, Debug)]
struct LoadedInputSource {
	source_path: PathBuf,
	source_root: PathBuf,
	playlist: Playset,
	config: Config,
}

fn load_input_source(request: &InputRequest) -> Result<LoadedInputSource, InputResolveError> {
	match &request.source {
		InputSource::DlcLoad(path) => {
			load_dlc_load_source(path, &request.config, request.preloaded_playset.as_ref())
		}
		InputSource::Manifest(path) => load_manifest_source(path, &request.config),
	}
}

fn load_dlc_load_source(
	path: &Path,
	config: &Config,
	preloaded_playset: Option<&Playset>,
) -> Result<LoadedInputSource, InputResolveError> {
	let playlist = match preloaded_playset {
		Some(playset) => playset.clone(),
		None => Playset::from_dlc_load(path).map_err(input_error_from_playset_parse)?,
	};
	Ok(LoadedInputSource {
		source_path: path.to_path_buf(),
		source_root: source_root_for(path),
		playlist,
		config: config.clone(),
	})
}

fn load_manifest_source(
	path: &Path,
	config: &Config,
) -> Result<LoadedInputSource, InputResolveError> {
	let manifest = Project::load_from_path(path).map_err(|err| InputResolveError {
		kind: InputResolveErrorKind::PlaylistFormat,
		path: path.to_path_buf(),
		message: err.to_string(),
	})?;
	let project = manifest.project.as_ref().ok_or_else(|| InputResolveError {
		kind: InputResolveErrorKind::PlaylistFormat,
		path: path.to_path_buf(),
		message: "foch.toml does not contain a [project] table".to_string(),
	})?;
	let source_root = source_root_for(path);
	let mut effective_config = config.clone();
	apply_project_config_overrides(&mut effective_config, project, &source_root, path)?;
	let playlist = playset_from_project_config(project, &source_root, path)?;
	Ok(LoadedInputSource {
		source_path: path.to_path_buf(),
		source_root,
		playlist,
		config: effective_config,
	})
}

fn input_error_from_playset_parse(err: crate::playset::ParseError) -> InputResolveError {
	InputResolveError {
		kind: if matches!(err.kind, ParseErrorKind::Format) {
			InputResolveErrorKind::PlaylistFormat
		} else {
			InputResolveErrorKind::Io
		},
		path: err.path.clone(),
		// A launcher playset reads its descriptors with
		// `load_launcher_descriptor`, which never interprets `replace_path`.
		message: match err.kind {
			ParseErrorKind::Format => err.message,
			ParseErrorKind::Io | ParseErrorKind::InvalidReplacePath => {
				format!("failed to read Playset: {err}")
			}
		},
	}
}

fn apply_project_config_overrides(
	config: &mut Config,
	project: &ProjectConfig,
	source_root: &Path,
	manifest_path: &Path,
) -> Result<(), InputResolveError> {
	if let Some(path) = project.paradox_data_path.as_ref() {
		config.paradox_data_path = Some(resolve_manifest_path(source_root, path));
	}
	if let Some(path) = project.game_path.as_ref() {
		let game = project.game.as_ref().ok_or_else(|| InputResolveError {
			kind: InputResolveErrorKind::PlaylistFormat,
			path: manifest_path.to_path_buf(),
			message: "[project].game_path requires [project].game".to_string(),
		})?;
		config.game_path.insert(
			game.key().to_string(),
			resolve_manifest_path(source_root, path),
		);
	}
	Ok(())
}

fn playset_from_project_config(
	project: &ProjectConfig,
	source_root: &Path,
	manifest_path: &Path,
) -> Result<Playset, InputResolveError> {
	let mut game = project.game;
	let mut mods = Vec::new();
	let mut next_position = 0usize;
	for import in &project.imports {
		match import.kind {
			ProjectImportKind::DlcLoad => {
				let import_path = resolve_manifest_path(source_root, &import.path);
				let imported =
					Playset::from_dlc_load(&import_path).map_err(input_error_from_playset_parse)?;
				let import_root = source_root_for(&import_path);
				if game.is_none() {
					game = Some(imported.game);
				}
				for mut entry in imported.mods {
					if entry.root_path.is_none()
						&& let Some(steam_id) =
							entry.steam_id.as_deref().and_then(single_path_component)
					{
						entry.root_path = resolve_mod_from_ugc_descriptor(&import_root, steam_id)?;
					}
					entry.position = Some(next_position);
					next_position += 1;
					mods.push(entry);
				}
			}
		}
	}
	for manifest_mod in &project.mods {
		if !manifest_mod.enabled {
			continue;
		}
		let entry = playset_entry_from_project_mod(
			manifest_mod,
			source_root,
			next_position,
			manifest_path,
		)?;
		next_position += 1;
		remove_duplicate_entries(&mut mods, &entry);
		mods.push(entry);
	}
	let game = game.unwrap_or(Eu4);
	Ok(Playset {
		game,
		name: manifest_path
			.file_stem()
			.and_then(|stem| stem.to_str())
			.filter(|stem| !stem.is_empty())
			.unwrap_or("input")
			.to_string(),
		mods,
	})
}

fn playset_entry_from_project_mod(
	manifest_mod: &ProjectMod,
	source_root: &Path,
	next_position: usize,
	manifest_path: &Path,
) -> Result<PlaysetEntry, InputResolveError> {
	let root_path = manifest_mod
		.path
		.as_ref()
		.map(|path| resolve_manifest_path(source_root, path));
	let steam_id = manifest_mod
		.steam_id
		.as_ref()
		.map(|steam_id| steam_id.trim().to_string())
		.filter(|steam_id| !steam_id.is_empty());
	let id = manifest_mod
		.id
		.as_ref()
		.map(|id| id.trim().to_string())
		.filter(|id| !id.is_empty());
	if let Some(steam_id) = steam_id.as_deref()
		&& single_path_component(steam_id).is_none()
	{
		return Err(InputResolveError {
			kind: InputResolveErrorKind::PlaylistFormat,
			path: manifest_path.to_path_buf(),
			message: format!(
				"[[project.mods]] steam_id `{steam_id}` must be a single plain path component"
			),
		});
	}
	if root_path.is_none() && steam_id.is_none() {
		return Err(InputResolveError {
			kind: InputResolveErrorKind::PlaylistFormat,
			path: manifest_path.to_path_buf(),
			message: "[[project.mods]] entries require at least one of path or steam_id"
				.to_string(),
		});
	}
	let display_name = id
		.clone()
		.or_else(|| steam_id.as_ref().map(|steam_id| format!("ugc_{steam_id}")));
	Ok(PlaysetEntry {
		id,
		display_name,
		enabled: true,
		position: Some(manifest_mod.position.unwrap_or(next_position)),
		steam_id,
		root_path,
		workshop_identity: manifest_mod.workshop_identity.clone(),
	})
}

fn remove_duplicate_entries(entries: &mut Vec<PlaysetEntry>, explicit: &PlaysetEntry) {
	let keys = playlist_entry_identity_keys(explicit);
	if keys.is_empty() {
		return;
	}
	entries.retain(|entry| {
		playlist_entry_identity_keys(entry)
			.iter()
			.all(|key| !keys.contains(key))
	});
}

/// One way a playset entry names its mod. Roots compare as host paths.
#[derive(Debug, Eq, Hash, PartialEq)]
enum PlaylistEntryIdentity<'a> {
	Steam(&'a str),
	Id(&'a str),
	Root(&'a Path),
}

fn playlist_entry_identity_keys(entry: &PlaysetEntry) -> HashSet<PlaylistEntryIdentity<'_>> {
	let mut keys = HashSet::new();
	if let Some(steam_id) = entry
		.steam_id
		.as_deref()
		.filter(|value| !value.trim().is_empty())
	{
		keys.insert(PlaylistEntryIdentity::Steam(steam_id));
	}
	if let Some(id) = entry.id.as_deref().filter(|value| !value.trim().is_empty()) {
		keys.insert(PlaylistEntryIdentity::Id(id));
	}
	if let Some(root) = entry.root_path.as_deref() {
		keys.insert(PlaylistEntryIdentity::Root(root));
	}
	keys
}

fn source_root_for(path: &Path) -> PathBuf {
	path.parent()
		.map_or_else(|| PathBuf::from("."), Path::to_path_buf)
}

fn resolve_manifest_path(source_root: &Path, path: &Path) -> PathBuf {
	if path.is_absolute() {
		path.to_path_buf()
	} else {
		source_root.join(path)
	}
}

pub(crate) fn build_input_inventory(
	request: &InputRequest,
	include_game_base: bool,
) -> Result<InputInventory, InputResolveError> {
	build_input_inventory_for_paths(request, include_game_base, None)
}

pub fn resolve_input_summary(
	request: &InputRequest,
) -> Result<InputResolveSummary, InputResolveError> {
	let loaded = load_input_source(request)?;
	let mut mods =
		build_mod_candidates_metadata(&loaded.source_root, &loaded.config, &loaded.playlist)?;
	for mod_item in &mut mods {
		load_mod_candidate_descriptor(mod_item)?;
	}
	let game_root = resolve_game_root(&loaded.config, &loaded.playlist.game);
	Ok(InputResolveSummary {
		source_path: loaded.source_path,
		game: loaded.playlist.game,
		game_root,
		mods: mods
			.into_iter()
			.map(|mod_item| ResolvedInputMod {
				mod_id: mod_item.mod_id,
				display_name: mod_item.entry.display_name,
				steam_id: mod_item.entry.steam_id,
				root_path: mod_item.root_path,
				descriptor_error: mod_item.descriptor_error,
			})
			.collect(),
	})
}

pub fn resolve_input_targets(
	request: &InputRequest,
	include_game_root: bool,
) -> Result<Vec<InputTarget>, InputResolveError> {
	let summary = resolve_input_summary(request)?;
	let mut targets = Vec::new();
	if include_game_root
		&& let Some(path) = summary.game_root
		&& path.is_dir()
	{
		targets.push(InputTarget {
			path,
			role: InputTargetRole::Game,
			mod_id: None,
		});
	}
	for mod_item in summary.mods {
		if let Some(path) = mod_item.root_path.filter(|path| path.is_dir()) {
			targets.push(InputTarget {
				path,
				role: InputTargetRole::Mod,
				mod_id: Some(mod_item.mod_id),
			});
		}
	}
	Ok(targets)
}

/// Resolve the complete ordered product input manifest for a input.
/// Identity comes only from the read-only Steam Workshop ACF; no content file
/// is opened to construct this manifest.
pub fn resolve_product_input_manifest(
	request: &InputRequest,
) -> Result<ProductInputManifest, InputResolveError> {
	let loaded = load_input_source(request)?;
	let mut entries = loaded.playlist.mods.clone();
	entries.sort_by_key(|entry| entry.position.unwrap_or(usize::MAX));
	let mods = entries
		.iter()
		.enumerate()
		.map(|(index, entry)| {
			let mod_id = mod_id_for_entry(entry);
			let identity = entry
				.workshop_identity
				.clone()
				.ok_or_else(|| InputResolveError {
					kind: InputResolveErrorKind::Io,
					path: loaded.source_path.clone(),
					message: format!("product input {mod_id} has no trusted Workshop ACF identity"),
				})?;
			let root =
				resolve_mod_root(&loaded.source_root, &loaded.config, &loaded.playlist, entry)?;
			validate_workshop_lease(
				&mod_id,
				entry.steam_id.as_deref(),
				root.as_deref(),
				&identity,
			)
			.map_err(|error| InputResolveError {
				kind: InputResolveErrorKind::Io,
				path: root.unwrap_or_else(|| loaded.source_path.clone()),
				message: error.to_string(),
			})?;
			Ok(ProductInputMod {
				mod_id,
				precedence: index + 1,
				workshop_identity: identity,
			})
		})
		.collect::<Result<Vec<_>, InputResolveError>>()?;
	Ok(ProductInputManifest::new(mods))
}

fn retained_definition_modules(
	game: &Eu4,
	requested_paths: &BTreeSet<GamePathBuf>,
) -> BTreeMap<MergeUnitId, u32> {
	let profile = game;
	requested_paths
		.iter()
		.filter_map(|path| {
			let descriptor = profile.classify_content_family(path)?;
			let ContentLoadPolicy::DefinitionModule(policy) = descriptor.load_policy else {
				return None;
			};
			Some((
				MergeUnitId {
					family_id: descriptor.id.as_str().to_string(),
					module_name: module_name_for_descriptor(path, descriptor),
				},
				policy.policy_version,
			))
		})
		.collect()
}

/// The retained paths widened to every available input their merge unit
/// reads: a retained definition-module or database file brings in its whole
/// module, because a module is merged as one unit.
fn expand_retained_paths_for_game<'a>(
	game: &Eu4,
	game_version: Option<&str>,
	requested_paths: Option<&BTreeSet<GamePathBuf>>,
	available_paths: impl IntoIterator<Item = &'a GamePath>,
) -> Result<Option<BTreeSet<GamePathBuf>>, String> {
	let Some(requested_paths) = requested_paths else {
		return Ok(None);
	};
	let mut effective = requested_paths.clone();
	let selected_modules = retained_definition_modules(game, requested_paths);
	let rules = game_version.and_then(load_rules_for_version);
	let mut selected_databases: BTreeSet<&str> = BTreeSet::new();
	if let Some(rules) = rules {
		for path in requested_paths {
			if let Some(database) = rules.database_for(path)? {
				selected_databases.insert(database);
			}
		}
	}
	let profile = game;
	for game_path in available_paths {
		if let Some(database) = rules
			.map(|rules| rules.database_for(game_path))
			.transpose()?
			.flatten()
		{
			if selected_databases.contains(database) {
				effective.insert(game_path.to_owned());
			}
			continue;
		}
		let Some(descriptor) = profile.classify_content_family(game_path) else {
			continue;
		};
		let ContentLoadPolicy::DefinitionModule(policy) = descriptor.load_policy else {
			continue;
		};
		if rules
			.map(|rules| rules.database_for(policy.output_path))
			.transpose()?
			.flatten()
			.is_some()
		{
			continue;
		}
		let module = MergeUnitId {
			family_id: descriptor.id.as_str().to_string(),
			module_name: module_name_for_descriptor(game_path, descriptor),
		};
		if selected_modules.contains_key(&module) {
			effective.insert(game_path.to_owned());
		}
	}
	Ok(Some(effective))
}

pub(crate) fn build_input_inventory_for_paths(
	request: &InputRequest,
	include_game_base: bool,
	retained_paths: Option<&BTreeSet<GamePathBuf>>,
) -> Result<InputInventory, InputResolveError> {
	let loaded = load_input_source(request)?;
	let LoadedInputSource {
		source_path,
		source_root,
		playlist,
		config,
	} = loaded;

	let snapshot_filter = match FileFilter::new(playlist.game, &config.extra_ignore_patterns) {
		Ok(filter) => filter,
		Err(message) => {
			tracing::warn!(target: "crate::input::resolve", message, "falling back to filter without extra ignore globs");
			FileFilter::for_game(playlist.game)
		}
	};
	let mods = build_mod_candidates_metadata(&source_root, &config, &playlist)?;
	let unavailable: Vec<String> = mods
		.iter()
		.filter(|item| item.root_path.as_ref().is_none_or(|root| !root.is_dir()))
		.map(|item| match &item.root_path {
			Some(root) => format!("{} ({})", item.mod_id, root.display()),
			None => item.mod_id.clone(),
		})
		.collect();
	if !unavailable.is_empty() {
		return Err(InputResolveError {
			kind: InputResolveErrorKind::Io,
			path: source_path.clone(),
			message: format!(
				"unavailable enabled mod inputs: {}; install them or explicitly disable/remove them from the playset",
				unavailable.join(", ")
			),
		});
	}
	let optional_game_root = resolve_game_root(&config, &playlist.game);
	let (base_game_root, mod_cache_game_version) = if include_game_base {
		let (game_root, game_version) = resolve_game_root_and_version(&config, &playlist.game)
			.map_err(|message| InputResolveError {
				kind: InputResolveErrorKind::Io,
				path: source_path.clone(),
				message,
			})?;
		(Some(game_root), Some(game_version))
	} else {
		(
			None,
			optional_game_root
				.as_ref()
				.and_then(|game_root| detect_game_version(game_root)),
		)
	};
	if let Some(expected) = request.expected_game_root.as_ref() {
		let actual = base_game_root.as_ref().or(optional_game_root.as_ref());
		match actual {
			Some(actual) if actual == expected => {}
			Some(actual) => {
				return Err(InputResolveError {
					kind: InputResolveErrorKind::Io,
					path: source_path.clone(),
					message: format!(
						"inspected EU4 game root changed: expected {}, resolved {}",
						expected.display(),
						actual.display()
					),
				});
			}
			None => {
				return Err(InputResolveError {
					kind: InputResolveErrorKind::Io,
					path: source_path.clone(),
					message: format!(
						"inspected EU4 game root is no longer available: {}",
						expected.display()
					),
				});
			}
		}
	}
	let base_snapshot_identity = if let (Some(game_root), Some(game_version)) =
		(base_game_root.as_ref(), mod_cache_game_version.as_ref())
	{
		if let Some(lease) = request.base_snapshot_lease.as_ref() {
			Some(lease.clone())
		} else {
			Some(
				installed_base_snapshot_identity(playlist.game.key(), game_version)
					.map_err(|message| InputResolveError {
						kind: InputResolveErrorKind::Io,
						path: source_path.clone(),
						message,
					})?
					.ok_or_else(|| InputResolveError {
						kind: InputResolveErrorKind::Io,
						path: source_path.clone(),
						message: missing_base_data_message(&playlist.game, game_version, game_root),
					})?,
			)
		}
	} else {
		None
	};
	if request.base_snapshot_lease.is_some() && base_snapshot_identity.is_none() {
		return Err(InputResolveError {
			kind: InputResolveErrorKind::Io,
			path: source_path.clone(),
			message:
				"an exact base snapshot lease was supplied, but game-base resolution is disabled"
					.to_string(),
		});
	}
	if let Some(expected) = request.expected_base_snapshot_identity.as_deref() {
		let Some(actual) = base_snapshot_identity.as_ref() else {
			return Err(InputResolveError {
				kind: InputResolveErrorKind::Io,
				path: source_path.clone(),
				message: format!(
					"expected base snapshot identity {expected}, but game-base resolution is disabled"
				),
			});
		};
		if actual.as_label() != expected {
			return Err(InputResolveError {
				kind: InputResolveErrorKind::Io,
				path: source_path.clone(),
				message: format!(
					"installed base snapshot identity mismatch: expected {expected}, found {actual}"
				),
			});
		}
	}
	let cache_game_version = mod_cache_game_version.as_ref().map(|version| {
		let mut identity = format!("{} {version}", playlist.game.key());
		if let Some(base_snapshot_identity) = base_snapshot_identity.as_ref() {
			identity.push_str(" base=");
			identity.push_str(&base_snapshot_identity.as_label());
		}
		identity
	});
	for mod_item in &mods {
		validate_workshop_input(mod_item).map_err(|error| InputResolveError {
			kind: InputResolveErrorKind::Io,
			path: mod_item
				.root_path
				.clone()
				.unwrap_or_else(|| source_path.clone()),
			message: format!(
				"failed to validate Workshop ACF identity for {}: {error}",
				mod_item.mod_id
			),
		})?;
	}
	let mod_hashes = mods
		.iter()
		.map(|mod_item| {
			semantic_snapshot_key(&playlist.game, &config.extra_ignore_patterns, mod_item)
		})
		.collect::<Vec<_>>();
	let product_input_manifest = mods
		.iter()
		.enumerate()
		.map(|(index, mod_item)| {
			mod_item
				.workshop_identity
				.clone()
				.map(|workshop_identity| ProductInputMod {
					mod_id: mod_item.mod_id.clone(),
					precedence: index + 1,
					workshop_identity,
				})
		})
		.collect::<Option<Vec<_>>>()
		.map(ProductInputManifest::new);

	Ok(InputInventory {
		playlist_path: source_path,
		playlist,
		mods,
		base_game_root,
		mod_cache_game_version,
		base_snapshot_identity,
		base_snapshot_current_validation: if request.base_snapshot_lease.is_some() {
			BaseSnapshotCurrentValidation::Deferred
		} else {
			BaseSnapshotCurrentValidation::Immediate
		},
		cache_game_version,
		snapshot_filter,
		mod_hashes,
		product_input_manifest,
		requested_retained_paths: retained_paths.cloned(),
	})
}

pub(crate) fn resolve_input(
	request: &InputRequest,
	include_game_base: bool,
) -> Result<ResolvedInput, InputResolveError> {
	let inventory = build_input_inventory(request, include_game_base)?;
	resolve_input_from_inventory(inventory)
}

pub(crate) fn resolve_input_from_inventory(
	inventory: InputInventory,
) -> Result<ResolvedInput, InputResolveError> {
	let InputInventory {
		playlist_path,
		playlist,
		mut mods,
		base_game_root,
		mod_cache_game_version,
		base_snapshot_identity,
		base_snapshot_current_validation,
		cache_game_version,
		snapshot_filter,
		mod_hashes,
		product_input_manifest: _,
		requested_retained_paths,
	} = inventory;
	let installed_base_snapshot = match (
		base_game_root.as_ref(),
		mod_cache_game_version.as_ref(),
		base_snapshot_identity.as_ref(),
	) {
		(Some(_game_root), Some(game_version), Some(identity)) => Some(
			load_installed_base_snapshot_from_identity(
				playlist.game.key(),
				game_version,
				identity,
				base_snapshot_current_validation,
			)
			.map_err(|message| InputResolveError {
				kind: InputResolveErrorKind::Io,
				path: playlist_path.clone(),
				message,
			})?,
		),
		(Some(game_root), Some(game_version), None) => {
			return Err(InputResolveError {
				kind: InputResolveErrorKind::Io,
				path: playlist_path.clone(),
				message: missing_base_data_message(&playlist.game, game_version, game_root),
			});
		}
		_ => None,
	};
	let mut mod_snapshots: Vec<Option<LoadedModSnapshot>> = mods
		.iter()
		.enumerate()
		.map(|(idx, mod_item)| {
			load_or_build_mod_snapshot(
				playlist.game.key(),
				mod_item,
				&snapshot_filter,
				mod_hashes.get(idx).and_then(|hash| hash.as_deref()),
			)
			.map_err(|error| InputResolveError {
				kind: InputResolveErrorKind::Io,
				path: mod_item
					.root_path
					.clone()
					.unwrap_or_else(|| playlist_path.clone()),
				message: format!(
					"failed to load semantic snapshot for {}: {error}",
					mod_item.mod_id
				),
			})
		})
		.collect::<Result<_, _>>()?;
	// Descriptor metadata affects dependency and replace-path semantics, but it
	// is not needed to address an ACF-keyed semantic snapshot. Keep this read
	// after every process/disk snapshot lookup so a warm run never touches a
	// Workshop file before its semantic caches have had a chance to hit.
	for mod_item in &mut mods {
		load_mod_candidate_descriptor(mod_item)?;
	}
	for (mod_item, snapshot) in mods.iter_mut().zip(mod_snapshots.iter()) {
		if let Some(snapshot) = snapshot {
			mod_item.files = snapshot.inventory_paths.clone();
		}
	}
	let mut available_paths = mods
		.iter()
		.flat_map(|mod_item| mod_item.files.iter())
		.map(GamePathBuf::as_game_path)
		.collect::<Vec<_>>();
	if let Some(base_snapshot) = installed_base_snapshot.as_ref() {
		available_paths.extend(
			base_snapshot
				.snapshot
				.inventory_paths
				.iter()
				.map(GamePathBuf::as_game_path),
		);
	}
	let effective_retained_paths = expand_retained_paths_for_game(
		&playlist.game,
		mod_cache_game_version.as_deref(),
		requested_retained_paths.as_ref(),
		available_paths,
	)
	.map_err(|message| InputResolveError {
		kind: InputResolveErrorKind::Io,
		path: playlist_path.clone(),
		message,
	})?;
	if let Some(effective_retained_paths) = effective_retained_paths.as_ref() {
		for mod_item in &mut mods {
			mod_item
				.files
				.retain(|relative| effective_retained_paths.contains(relative));
		}
		for (mod_item, snapshot) in mods.iter().zip(mod_snapshots.iter_mut()) {
			let Some(full_snapshot) = snapshot.as_ref() else {
				continue;
			};
			if mod_item.files == full_snapshot.inventory_paths {
				continue;
			}
			*snapshot = build_transient_mod_snapshot(mod_item, &snapshot_filter, full_snapshot)
				.map_err(|error| InputResolveError {
					kind: InputResolveErrorKind::Io,
					path: mod_item
						.root_path
						.clone()
						.unwrap_or_else(|| playlist_path.clone()),
					message: format!(
						"failed to build retained semantic snapshot for {}: {error}",
						mod_item.mod_id
					),
				})?;
		}
	}
	let mut file_inventory = build_file_inventory(
		&playlist,
		&mods,
		&mod_snapshots,
		base_game_root.as_ref(),
		installed_base_snapshot.as_ref(),
		&mod_hashes,
		effective_retained_paths.as_ref(),
	);
	let verified_absent_base_paths = verify_absent_semantic_bases(
		&playlist,
		base_game_root.as_deref(),
		installed_base_snapshot.is_some(),
		&file_inventory,
	)?;
	inject_synthetic_bases(&mut file_inventory);
	let script_cache = InputScriptCache::from_parts(
		&mods,
		&mod_snapshots,
		installed_base_snapshot.as_ref(),
		base_game_root.as_deref(),
	)
	.map_err(|message| InputResolveError {
		kind: InputResolveErrorKind::Io,
		path: playlist_path.clone(),
		message,
	})?;

	Ok(ResolvedInput {
		playlist_path,
		playlist,
		game_version: mod_cache_game_version,
		mods,
		installed_base_snapshot,
		cache_game_version,
		mod_snapshots,
		script_cache,
		file_inventory,
		verified_absent_base_paths,
		requested_retained_paths,
		effective_retained_paths,
	})
}

fn verify_absent_semantic_bases(
	playlist: &Playset,
	base_game_root: Option<&Path>,
	base_snapshot_loaded: bool,
	file_inventory: &BTreeMap<GamePathBuf, Vec<ResolvedInputContributor>>,
) -> Result<BTreeSet<GamePathBuf>, InputResolveError> {
	let Some(root) = base_game_root else {
		return Ok(BTreeSet::new());
	};
	let profile = &playlist.game;
	if !base_snapshot_loaded {
		return Ok(BTreeSet::new());
	}

	let mut absent = BTreeSet::new();
	for (relative, contributors) in file_inventory {
		let descriptor = profile.classify_content_family(relative);
		if classify_document_family(relative) != Some(DocumentFamily::Clausewitz)
			|| !descriptor.is_some_and(ContentFamilyDescriptor::supports_verified_empty_file_base)
			|| contributors
				.iter()
				.any(|contributor| contributor.is_base_game)
			|| contributors
				.iter()
				.filter(|contributor| !contributor.is_base_game)
				.count() < 2
		{
			continue;
		}

		let absolute = relative.to_path(root);
		match fs::symlink_metadata(&absolute) {
			Ok(_) => {
				return Err(InputResolveError {
					kind: InputResolveErrorKind::Io,
					path: absolute,
					message: format!(
						"installed base snapshot omits the existing semantic merge base {relative}; rebuild and reinstall base data before merging"
					),
				});
			}
			Err(error) if error.kind() == io::ErrorKind::NotFound => {
				absent.insert(relative.clone());
			}
			Err(error) => {
				return Err(InputResolveError {
					kind: InputResolveErrorKind::Io,
					path: absolute,
					message: format!(
						"failed to verify whether semantic merge base {relative} exists: {error}"
					),
				});
			}
		}
	}
	Ok(absent)
}

fn missing_base_data_message(game: &Eu4, game_version: &str, game_root: &Path) -> String {
	format!(
		"missing installed base data for {} {}; run `foch data install {} --game-version auto` or `foch data build {} --from-game-path {} --game-version auto --install`, or use --no-game-base",
		game.key(),
		game_version,
		game.key(),
		game.key(),
		game_root.display()
	)
}

pub(crate) fn build_mod_candidates_metadata(
	source_root: &Path,
	config: &Config,
	playlist: &Playset,
) -> Result<Vec<ModCandidate>, InputResolveError> {
	let mut entries = playlist.mods.clone();
	entries.sort_by_key(|entry| entry.position.unwrap_or(usize::MAX));

	entries
		.into_iter()
		.filter(|entry| entry.enabled)
		.map(|entry| {
			let mod_id = mod_id_for_entry(&entry);

			let root_path = resolve_mod_root(source_root, config, playlist, &entry)?;
			let descriptor_path = root_path.as_ref().map(|path| path.join("descriptor.mod"));

			let workshop_identity = entry.workshop_identity.clone();
			Ok(ModCandidate {
				entry,
				mod_id,
				root_path,
				descriptor_path,
				descriptor: None,
				workshop_identity,
				descriptor_error: None,
				files: Vec::new(),
			})
		})
		.collect()
}

/// Reads a mod's descriptor. A descriptor that is missing or does not parse
/// is recorded on the mod, which then merges without descriptor metadata. A
/// `replace_path` value that names no directory under the game root is an
/// input error instead: it decides which earlier contributions the merge
/// drops, so there is no safe reading of it and no safe merge without it.
fn load_mod_candidate_descriptor(mod_item: &mut ModCandidate) -> Result<(), InputResolveError> {
	let (descriptor, descriptor_error) = match mod_item.descriptor_path.as_ref() {
		Some(path) if path.exists() => match load_descriptor(path) {
			Ok(descriptor) => (Some(descriptor), None),
			Err(error) if error.kind == ParseErrorKind::InvalidReplacePath => {
				return Err(InputResolveError {
					kind: InputResolveErrorKind::Io,
					path: path.clone(),
					message: format!(
						"mod {} descriptor {}: {}",
						mod_item.mod_id,
						path.display(),
						error.message
					),
				});
			}
			Err(error) => (None, Some(error.to_string())),
		},
		Some(path) => (None, Some(format!("{} does not exist", path.display()))),
		None => (None, None),
	};
	mod_item.descriptor = descriptor;
	mod_item.descriptor_error = descriptor_error;
	Ok(())
}

fn mod_id_for_entry(entry: &PlaysetEntry) -> String {
	entry
		.steam_id
		.clone()
		.filter(|value| !value.trim().is_empty())
		.or_else(|| entry.id.clone().filter(|value| !value.trim().is_empty()))
		.unwrap_or_else(|| "<missing-steam-id>".to_string())
}

fn validate_workshop_input(mod_item: &ModCandidate) -> Result<(), io::Error> {
	let Some(expected) = mod_item.workshop_identity.as_ref() else {
		return Ok(());
	};
	validate_workshop_lease(
		&mod_item.mod_id,
		mod_item.entry.steam_id.as_deref(),
		mod_item.root_path.as_deref(),
		expected,
	)
}

fn validate_workshop_lease(
	mod_id: &str,
	steam_id: Option<&str>,
	root: Option<&Path>,
	expected: &WorkshopInstallIdentity,
) -> Result<(), io::Error> {
	let root = root.ok_or_else(|| {
		io::Error::new(
			io::ErrorKind::NotFound,
			format!("Workshop mod {mod_id} has no content root"),
		)
	})?;
	if steam_id != Some(expected.workshop_id.as_str()) {
		return Err(io::Error::new(
			io::ErrorKind::InvalidInput,
			format!(
				"Workshop identity {} does not match steam_id for {}",
				expected.workshop_id, mod_id
			),
		));
	}
	let content_root = root.parent().ok_or_else(|| {
		io::Error::new(
			io::ErrorKind::InvalidInput,
			format!("Workshop root has no content parent: {}", root.display()),
		)
	})?;
	let workshop_root = content_root
		.parent()
		.and_then(Path::parent)
		.ok_or_else(|| {
			io::Error::new(
				io::ErrorKind::InvalidInput,
				format!("Workshop root has no ACF parent: {}", root.display()),
			)
		})?;
	let manifest_path = workshop_root.join(format!("appworkshop_{}.acf", expected.app_id));
	let catalog = SteamWorkshopCatalog::from_override(
		expected.app_id,
		content_root.to_path_buf(),
		manifest_path,
	)
	.map_err(|error| io::Error::other(error.to_string()))?;
	let observed = catalog
		.require_item(&expected.workshop_id)
		.map_err(|error| io::Error::other(error.to_string()))?;
	let observed_identity = observed
		.identity()
		.map_err(|error| io::Error::other(error.to_string()))?;
	let canonical_root = fs::canonicalize(root)?;
	if observed_identity != *expected || observed.content_path != canonical_root {
		return Err(io::Error::other(format!(
			"Workshop ACF identity changed for {}: expected {:?}, observed {:?}",
			mod_id, expected, observed_identity
		)));
	}
	Ok(())
}

fn semantic_snapshot_key(
	game: &Eu4,
	extra_ignore_patterns: &[String],
	mod_item: &ModCandidate,
) -> Option<String> {
	let identity: &WorkshopInstallIdentity = mod_item.workshop_identity.as_ref()?;
	let mut hasher = blake3::Hasher::new();
	update_cache_key_field(&mut hasher, "foch-workshop-semantic-snapshot-v2");
	update_cache_key_field(&mut hasher, game.key());
	let mut ignore_patterns = extra_ignore_patterns.to_vec();
	ignore_patterns.sort();
	ignore_patterns.dedup();
	hasher.update(&(ignore_patterns.len() as u64).to_le_bytes());
	for pattern in ignore_patterns {
		update_cache_key_field(&mut hasher, &pattern);
	}
	update_cache_key_field(&mut hasher, &mod_item.mod_id);
	hasher.update(&identity.app_id.to_le_bytes());
	update_cache_key_field(&mut hasher, identity.workshop_id.as_str());
	update_cache_key_field(&mut hasher, identity.manifest_id.as_str());
	Some(hasher.finalize().to_hex().to_string())
}

fn update_cache_key_field(hasher: &mut blake3::Hasher, value: &str) {
	hasher.update(&(value.len() as u64).to_le_bytes());
	hasher.update(value.as_bytes());
}

/// Finds an entry's mod root. A steam id or display name is joined onto a
/// search root only when it is a single plain path component; any other text
/// could name a directory outside that root, so it yields no candidate. A
/// `ugc_<id>.mod` descriptor that exists but cannot be read is an error.
fn resolve_mod_root(
	source_root: &Path,
	config: &Config,
	playlist: &Playset,
	entry: &PlaysetEntry,
) -> Result<Option<PathBuf>, InputResolveError> {
	if let Some(path) = entry.root_path.as_ref() {
		return Ok(Some(path.clone()));
	}

	let mut candidates = Vec::new();

	if let Some(steam_id) = entry.steam_id.as_deref().and_then(single_path_component) {
		candidates.push(source_root.join(steam_id));
		candidates.push(source_root.join(format!("mod_{steam_id}")));

		// The dlc_load.json's parent directory IS the paradox game data
		// directory by construction, so the sibling `mod/ugc_<id>.mod`
		// descriptor is always a valid lookup root regardless of whether the
		// user has separately configured `paradox_data_path`. This makes
		// playset discovery work end-to-end without forcing every test fixture
		// to additionally pin a config field.
		if let Some(root) = resolve_mod_from_ugc_descriptor(source_root, steam_id)? {
			candidates.push(root);
		}
		candidates.push(source_root.join("mod").join(steam_id));
		candidates.push(source_root.join("mod").join(format!("ugc_{steam_id}")));

		if let Some(path) = config.paradox_data_path.as_ref() {
			for game_data_dir in paradox_game_data_dirs(path, &playlist.game) {
				if let Some(root) = resolve_mod_from_ugc_descriptor(&game_data_dir, steam_id)? {
					candidates.push(root);
				}
				candidates.push(game_data_dir.join("mod").join(steam_id));
				candidates.push(game_data_dir.join("mod").join(format!("ugc_{steam_id}")));
			}
		}

		if let Some(steam_root) = config.steam_root_path.as_ref() {
			for app_id in playlist.game.steam_app_ids() {
				if let Some(path) = steam_workshop_mod_path(steam_root, *app_id, steam_id) {
					candidates.push(path);
				}
				candidates.push(
					steam_root
						.join("steamapps")
						.join("workshop")
						.join("content")
						.join(app_id.to_string())
						.join(steam_id),
				);
			}
		}
	}

	if let Some(name) = entry.display_name.as_deref() {
		for name in [name.to_string(), name.replace(' ', "_")] {
			if single_path_component(&name).is_some() {
				candidates.push(source_root.join(name));
			}
		}
	}

	Ok(dedup_candidates(candidates)
		.into_iter()
		.find(|candidate| candidate.is_dir()))
}

/// Drops repeated physical candidates, keeping the first. Candidates compare
/// as host paths: two spellings are the same candidate only when the host
/// parses them into the same components.
pub(crate) fn dedup_candidates(candidates: Vec<PathBuf>) -> Vec<PathBuf> {
	let mut seen = HashSet::new();
	candidates
		.into_iter()
		.filter(|candidate| seen.insert(candidate.clone()))
		.collect()
}

fn paradox_game_data_dirs(base: &Path, game: &Eu4) -> Vec<PathBuf> {
	let mut dirs = vec![base.to_path_buf()];
	if let Some(game_dir_name) = game.paradox_data_dir_name() {
		dirs.push(base.join(game_dir_name));
	}
	dedup_candidates(dirs)
}

/// The root a `mod/ugc_<id>.mod` descriptor points at. Only a missing
/// descriptor means "no candidate"; one that exists but is not a readable,
/// parseable regular file is reported with its path.
fn resolve_mod_from_ugc_descriptor(
	game_data_dir: &Path,
	steam_id: &str,
) -> Result<Option<PathBuf>, InputResolveError> {
	let metadata = game_data_dir
		.join("mod")
		.join(format!("ugc_{steam_id}.mod"));
	match fs::symlink_metadata(&metadata) {
		Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
		Err(err) => {
			return Err(input_error_from_playset_parse(
				crate::playset::ParseError::io(metadata, err),
			));
		}
		Ok(_) => {}
	}

	let Some(path) = load_launcher_descriptor(&metadata)
		.map_err(input_error_from_playset_parse)?
		.path
	else {
		return Ok(None);
	};
	Ok(descriptor_path_candidates(game_data_dir, &path)
		.into_iter()
		.find(|candidate| candidate.is_dir()))
}

/// Where a launcher descriptor's `path` may point. The descriptor reader has
/// already read it with host syntax only (see
/// [`crate::playset::descriptor::ModDescriptor::path`]). A relative `path` is
/// tried under the game data directory and under its `mod` directory.
fn descriptor_path_candidates(game_data_dir: &Path, path: &Path) -> Vec<PathBuf> {
	let mut candidates = Vec::new();
	if path.is_absolute() {
		candidates.push(path.to_path_buf());
	}
	candidates.push(game_data_dir.join(path));
	candidates.push(game_data_dir.join("mod").join(path));
	dedup_candidates(candidates)
}

/// Whose tree an inventory walk reads, for diagnostics.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum InventoryOwner<'a> {
	BaseGame,
	Mod(&'a str),
}

/// A file under a walked root whose name has no portable game path. It is
/// reported instead of rewritten: any rewrite could give it the identity of
/// another file (`a\b.txt` next to `a/b.txt`, or two non-UTF-8 names that
/// render alike) or place it outside the root.
#[derive(Debug)]
pub(crate) struct UnportableInventoryPath {
	/// `None` for the base game.
	pub mod_id: Option<String>,
	pub root: PathBuf,
	pub physical: PathBuf,
	pub source: GamePathError,
}

impl fmt::Display for UnportableInventoryPath {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match &self.mod_id {
			Some(mod_id) => write!(f, "mod {mod_id}")?,
			None => f.write_str("base game")?,
		}
		write!(
			f,
			": {} under root {} has no portable game path: {}",
			self.physical.display(),
			self.root.display(),
			self.source.kind
		)
	}
}

impl Error for UnportableInventoryPath {
	fn source(&self) -> Option<&(dyn Error + 'static)> {
		Some(&self.source)
	}
}

/// Lists every file the game would load under `root` as game paths in byte
/// order. This is the one place a walked physical file enters the game's
/// namespace: a name without a portable game path, and any walk error, fails
/// the whole inventory. Top-level directories that are not loadable roots are
/// pruned by name before descent; a top-level name that is not UTF-8 is not a
/// loadable root.
pub(crate) fn collect_relative_files(
	root: &Path,
	filter: &FileFilter,
	owner: InventoryOwner<'_>,
) -> io::Result<Vec<GamePathBuf>> {
	let loadable_roots = filter.game().loadable_content_roots();
	let entries = WalkDir::new(root)
		.follow_links(false)
		.into_iter()
		.filter_entry(|entry| {
			if entry.depth() != 1 {
				return true;
			}
			let Some(loadable_roots) = loadable_roots else {
				return true;
			};
			entry.file_name().to_str().is_some_and(|name| {
				loadable_roots
					.iter()
					.any(|root_name| name.eq_ignore_ascii_case(root_name))
			})
		})
		.map(walk_entry);
	collect_relative_files_from_entries(root, filter, owner, entries)
}

/// [`collect_relative_files`] restricted to the directories `within`, each
/// given by its component names under `root` and matched exactly as spelled
/// on disk. Nothing outside them is walked, so a name elsewhere under `root`
/// that has no portable game path does not fail the walk.
pub(crate) fn collect_relative_files_within(
	root: &Path,
	within: &[&[&str]],
	filter: &FileFilter,
	owner: InventoryOwner<'_>,
) -> io::Result<Vec<GamePathBuf>> {
	collect_relative_files_from_entries(root, filter, owner, walk_within(root, within))
}

/// The entries under `root` that [`collect_relative_files_within`] reads,
/// with one error for each entry the walk cannot read.
pub(crate) fn walk_within<'a>(
	root: &'a Path,
	within: &'a [&'a [&'a str]],
) -> impl Iterator<Item = io::Result<walkdir::DirEntry>> + 'a {
	WalkDir::new(root)
		.follow_links(false)
		.into_iter()
		.filter_entry(move |entry| {
			let Ok(relative) = entry.path().strip_prefix(root) else {
				return false;
			};
			// Keep the directories on the way to one of `within`, and
			// everything inside one.
			within.iter().any(|directory| {
				relative
					.components()
					.zip(directory.iter())
					.all(|(component, name)| component.as_os_str() == OsStr::new(name))
			})
		})
		.map(walk_entry)
}

fn walk_entry(entry: walkdir::Result<walkdir::DirEntry>) -> io::Result<walkdir::DirEntry> {
	entry.map_err(|error| {
		let kind = error
			.io_error()
			.map_or(io::ErrorKind::Other, io::Error::kind);
		io::Error::new(kind, error.to_string())
	})
}

fn collect_relative_files_from_entries(
	root: &Path,
	filter: &FileFilter,
	owner: InventoryOwner<'_>,
	entries: impl IntoIterator<Item = io::Result<walkdir::DirEntry>>,
) -> io::Result<Vec<GamePathBuf>> {
	let mut files = Vec::new();

	for entry in entries {
		let entry = entry?;
		if !entry.file_type().is_file() {
			continue;
		}

		let path = entry.path();
		if path.file_name() == Some(OsStr::new("descriptor.mod")) {
			continue;
		}

		let relative = inventory_path(owner, root, path)?;
		if filter.accepts(&relative) {
			files.push(relative);
		}
	}

	files.sort();
	Ok(files)
}

/// The game path of `physical`, a file walked under `root`.
fn inventory_path(
	owner: InventoryOwner<'_>,
	root: &Path,
	physical: &Path,
) -> io::Result<GamePathBuf> {
	GamePathBuf::from_physical(root, physical).map_err(|source| {
		io::Error::new(
			io::ErrorKind::InvalidData,
			UnportableInventoryPath {
				mod_id: match owner {
					InventoryOwner::BaseGame => None,
					InventoryOwner::Mod(mod_id) => Some(mod_id.to_string()),
				},
				root: root.to_path_buf(),
				physical: physical.to_path_buf(),
				source,
			},
		)
	})
}

pub(crate) fn build_file_inventory(
	playlist: &Playset,
	mods: &[ModCandidate],
	mod_snapshots: &[Option<LoadedModSnapshot>],
	base_game_root: Option<&PathBuf>,
	installed_base_snapshot: Option<&InstalledBaseSnapshot>,
	mod_hashes: &[Option<String>],
	retained_paths: Option<&BTreeSet<GamePathBuf>>,
) -> BTreeMap<GamePathBuf, Vec<ResolvedInputContributor>> {
	let mut inventory = BTreeMap::new();
	let mut precedence = 0;

	if let (Some(root), Some(snapshot)) = (base_game_root, installed_base_snapshot) {
		let mod_id = base_game_mod_id(playlist.game.key());
		let document_lookup = snapshot.snapshot.document_lookup();
		for relative in &snapshot.snapshot.inventory_paths {
			if retained_paths.is_some_and(|paths| !paths.contains(relative)) {
				continue;
			}
			let document = document_lookup.get(&relative.as_game_path());
			inventory
				.entry(relative.clone())
				.or_insert_with(Vec::new)
				.push(ResolvedInputContributor {
					mod_id: mod_id.clone(),
					root_path: root.clone(),
					relative_path: relative.clone(),
					precedence,
					is_base_game: true,
					is_synthetic_base: false,
					parse_ok_hint: document.map(|(_family, parse_ok)| *parse_ok),
					mod_hash: None,
				});
		}
		precedence += 1;
	}

	for (idx, mod_item) in mods.iter().enumerate() {
		let Some(root) = mod_item.root_path.as_ref() else {
			continue;
		};
		let parse_hints = mod_snapshots
			.get(idx)
			.and_then(|snapshot| snapshot.as_ref())
			.map(|snapshot| &snapshot.document_parse_hints);
		let mod_hash = mod_snapshots
			.get(idx)
			.and_then(|snapshot| snapshot.as_ref())
			.and_then(|snapshot| snapshot.mod_hash.clone())
			.or_else(|| mod_hashes.get(idx).cloned().flatten());
		for relative in &mod_item.files {
			let parse_ok_hint = parse_hints.and_then(|hints| hints.get(relative).copied());
			inventory
				.entry(relative.clone())
				.or_insert_with(Vec::new)
				.push(ResolvedInputContributor {
					mod_id: mod_item.mod_id.clone(),
					root_path: root.clone(),
					relative_path: relative.clone(),
					precedence,
					is_base_game: false,
					is_synthetic_base: false,
					parse_ok_hint,
					mod_hash: mod_hash.clone(),
				});
		}
		precedence += 1;
	}

	inventory
}

/// 当 file_inventory 中某个文件没有 base game 贡献者,但有 ≥2 个 mod 贡献者时,
/// 选取 precedence 最小的 mod(tie 用 mod_id 字典序)clone 一份作为合成 base,
/// 插入到 contributors 最前面。这样下游的 patch 引擎可以把所有 mod 视为对该 base 的 patch。
///
/// 合成 base 的特征:`is_synthetic_base = true`,`is_base_game = false`,`precedence = 0`。
/// 原贡献者保持不动。
pub(crate) fn inject_synthetic_bases(
	file_inventory: &mut BTreeMap<GamePathBuf, Vec<ResolvedInputContributor>>,
) {
	for contributors in file_inventory.values_mut() {
		if contributors.iter().any(|c| c.is_base_game) {
			continue;
		}
		let non_base_count = contributors.iter().filter(|c| !c.is_base_game).count();
		if non_base_count < 2 {
			continue;
		}
		let Some(seed) = contributors
			.iter()
			.filter(|c| !c.is_base_game)
			.min_by(|a, b| {
				a.precedence
					.cmp(&b.precedence)
					.then_with(|| a.mod_id.cmp(&b.mod_id))
			})
		else {
			continue;
		};
		let mut synthetic = seed.clone();
		synthetic.is_synthetic_base = true;
		synthetic.is_base_game = false;
		synthetic.precedence = 0;
		contributors.insert(0, synthetic);
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	#[cfg(unix)]
	use crate::model::GamePathErrorKind;
	use crate::playset::steam::SteamId;
	use std::fs;
	use tempfile::TempDir;

	fn descriptor_path_value(path: &Path) -> String {
		crate::playset::descriptor::descriptor_path_text(path)
			.expect("a fixture directory has descriptor text")
	}

	fn write_descriptor(root: &Path, name: &str, steam_id: Option<&str>) {
		fs::create_dir_all(root).expect("create descriptor root");
		let mut body = format!(
			"name=\"{name}\"\npath=\"{}\"\n",
			descriptor_path_value(root)
		);
		if let Some(steam_id) = steam_id {
			body.push_str(&format!("remote_file_id=\"{steam_id}\"\n"));
		}
		fs::write(root.join("descriptor.mod"), body).expect("write descriptor");
	}

	fn write_dlc_load(paradox_dir: &Path, mods: &[(&str, &Path)]) {
		fs::create_dir_all(paradox_dir.join("mod")).expect("create launcher mod dir");
		let entries = mods
			.iter()
			.map(|(steam_id, _root)| format!("mod/ugc_{steam_id}.mod"))
			.collect::<Vec<_>>();
		let payload =
			serde_json::json!({ "enabled_mods": entries, "disabled_dlcs": Vec::<String>::new() });
		fs::write(
			paradox_dir.join("dlc_load.json"),
			serde_json::to_string_pretty(&payload).expect("serialize dlc_load"),
		)
		.expect("write dlc_load");
		for (steam_id, root) in mods {
			fs::write(
				paradox_dir.join("mod").join(format!("ugc_{steam_id}.mod")),
				format!(
					"name=\"ugc_{steam_id}\"\npath=\"{}\"\nremote_file_id=\"{steam_id}\"\n",
					descriptor_path_value(root)
				),
			)
			.expect("write launcher descriptor");
		}
	}

	fn request_for_manifest(path: &Path) -> InputRequest {
		InputRequest::from_manifest_path(path.to_path_buf(), Config::default())
	}

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

	#[cfg(unix)]
	fn unportable(error: &io::Error) -> &UnportableInventoryPath {
		error
			.get_ref()
			.and_then(|source| source.downcast_ref::<UnportableInventoryPath>())
			.unwrap_or_else(|| panic!("expected an unportable inventory path, got {error}"))
	}

	/// A mod holding both `common/a/b.txt` and a file literally named
	/// `common/a\b.txt`. Only a Unix host can create the second name.
	#[cfg(unix)]
	fn write_backslash_alias_mod(root: &Path) -> PathBuf {
		fs::create_dir_all(root.join("common").join("a")).expect("create nested directory");
		fs::write(
			root.join("common").join("a").join("b.txt"),
			"nested = yes\n",
		)
		.expect("write nested file");
		let literal = root.join("common").join(r"a\b.txt");
		fs::write(&literal, "literal = yes\n").expect("write literal-backslash file");
		literal
	}

	#[cfg(unix)]
	#[test]
	fn a_literal_backslash_name_fails_the_inventory_instead_of_aliasing_a_nested_file() {
		let temp = TempDir::new().expect("tempdir");
		let root = temp.path().join("mod");
		let literal = write_backslash_alias_mod(&root);

		let error = collect_relative_files(
			&root,
			&FileFilter::for_game(Eu4),
			InventoryOwner::Mod("1001"),
		)
		.expect_err("a literal backslash has no portable game path");

		assert_eq!(error.kind(), io::ErrorKind::InvalidData);
		let diagnostic = unportable(&error);
		assert_eq!(diagnostic.mod_id.as_deref(), Some("1001"));
		assert_eq!(diagnostic.root, root);
		assert_eq!(diagnostic.physical, literal);
		assert_eq!(
			diagnostic.source.kind,
			GamePathErrorKind::ReservedCharacter {
				component: r"a\b.txt".to_string(),
				character: '\\',
			}
		);
		let message = error.to_string();
		assert!(message.starts_with("mod 1001: "), "{message}");
		assert!(
			message.contains(&literal.display().to_string()),
			"{message}"
		);
		assert!(message.contains(&root.display().to_string()), "{message}");
	}

	#[cfg(unix)]
	#[test]
	fn a_literal_backslash_name_reaches_the_user_as_an_input_error_for_its_mod() {
		let temp = TempDir::new().expect("tempdir");
		let mod_root = temp.path().join("alias_mod");
		write_descriptor(&mod_root, "Alias Mod", None);
		write_backslash_alias_mod(&mod_root);
		let manifest_path = temp.path().join("foch.toml");
		fs::write(
			&manifest_path,
			r#"
[project]
game = "eu4"

[[project.mods]]
id = "alias_id"
path = "alias_mod"
"#,
		)
		.expect("write manifest");

		let error = resolve_input(&request_for_manifest(&manifest_path), false)
			.expect_err("an unportable mod file must fail input resolution");

		assert_eq!(error.kind, InputResolveErrorKind::Io);
		assert_eq!(error.path, mod_root);
		// The id differs from the directory name, so only the walker's own
		// diagnostic can supply `mod alias_id: `.
		assert!(error.message.contains("mod alias_id: "), "{error}");
		assert!(
			error
				.message
				.contains(&format!("under root {} has", mod_root.display())),
			"{error}"
		);
		assert!(error.message.contains(r"a\b.txt"), "{error}");
		assert!(error.message.contains("no portable game path"), "{error}");
	}

	/// The strict inventory keeps the ordinary case: one file shipped by two
	/// mods is one game path with a contributor per mod, in playset order.
	#[test]
	fn one_game_path_shipped_by_two_mods_is_one_entry_with_both_contributors_in_playset_order() {
		let temp = TempDir::new().expect("tempdir");
		// Playset order is the reverse of id order, so an id sort would show.
		let mods: [(&str, &str); 2] = [("zeta", "zeta = yes\n"), ("alpha", "alpha = yes\n")];
		for (mod_id, content) in mods {
			let root = temp.path().join(mod_id);
			write_descriptor(&root, mod_id, None);
			fs::create_dir_all(root.join("common").join("ideas")).expect("create ideas");
			fs::write(root.join("common").join("ideas").join("x.txt"), content)
				.expect("write idea file");
		}
		let manifest_path = temp.path().join("foch.toml");
		fs::write(
			&manifest_path,
			r#"
[project]
game = "eu4"

[[project.mods]]
id = "zeta"
path = "zeta"

[[project.mods]]
id = "alpha"
path = "alpha"
"#,
		)
		.expect("write manifest");

		let input = resolve_input(&request_for_manifest(&manifest_path), false)
			.expect("two mods sharing a game path resolve");

		let key = game_path("common/ideas/x.txt");
		assert_eq!(input.file_inventory.keys().collect::<Vec<_>>(), vec![&key]);
		let contributors = &input.file_inventory[&key];
		assert_eq!(
			contributors
				.iter()
				.map(|contributor| (
					contributor.mod_id.as_str(),
					contributor.precedence,
					contributor.is_synthetic_base
				))
				.collect::<Vec<_>>(),
			vec![("zeta", 0, true), ("zeta", 0, false), ("alpha", 1, false)],
			"without a base game the first mod also seeds a synthetic base"
		);
		for contributor in contributors {
			assert_eq!(contributor.relative_path, key);
			let expected = mods
				.iter()
				.find(|(mod_id, _)| *mod_id == contributor.mod_id)
				.map(|(_, content)| *content);
			assert_eq!(
				fs::read_to_string(contributor.absolute_path())
					.ok()
					.as_deref(),
				expected,
				"{} reads its own mod's file",
				contributor.mod_id
			);
		}
	}

	#[cfg(unix)]
	#[test]
	fn distinct_non_utf8_names_are_rejected_instead_of_sharing_one_game_path() {
		// In-memory paths: some filesystems (APFS among them) refuse to create
		// names that are not valid UTF-8, so the walker's conversion step is
		// exercised directly.
		use std::ffi::OsString;
		use std::os::unix::ffi::OsStringExt;

		let root = Path::new("/base-game");
		let diagnostics = [b"\xff.txt".to_vec(), b"\xfe.txt".to_vec()].map(|name| {
			let physical = root.join("common").join(OsString::from_vec(name));
			let error = inventory_path(InventoryOwner::BaseGame, root, &physical)
				.expect_err("a non-UTF-8 name has no portable game path");
			let diagnostic = unportable(&error);
			assert_eq!(diagnostic.mod_id, None);
			assert_eq!(diagnostic.root, root);
			assert_eq!(diagnostic.source.kind, GamePathErrorKind::NonUtf8);
			assert!(error.to_string().starts_with("base game: "), "{error}");
			diagnostic.physical.clone()
		});
		assert_ne!(diagnostics[0], diagnostics[1]);
	}

	#[test]
	fn manifest_rejects_a_steam_id_that_is_not_one_path_component() {
		let temp = TempDir::new().expect("tempdir");
		let manifest_path = temp.path().join("foch.toml");
		for bad in ["..", "../../x", "a/b"] {
			fs::write(
				&manifest_path,
				format!("[project]\ngame = \"eu4\"\n\n[[project.mods]]\nsteam_id = \"{bad}\"\n"),
			)
			.expect("write manifest");
			let err = resolve_input_summary(&request_for_manifest(&manifest_path))
				.expect_err("a traversing steam id must fail");
			assert_eq!(err.path, manifest_path, "{err}");
			assert!(err.message.contains("single plain path component"), "{err}");
		}
	}

	/// A local descriptor's `name` is a mod-root candidate under the data
	/// directory only when it is one plain directory name. `..` would resolve
	/// to the data directory's parent, which exists, and be taken as the mod.
	#[test]
	fn a_display_name_that_leaves_the_data_directory_is_not_a_mod_root() {
		let temp = TempDir::new().expect("tempdir");
		let paradox_dir = temp.path().join("Europa Universalis IV");
		fs::create_dir_all(paradox_dir.join("mod")).expect("create launcher mod dir");
		fs::write(
			paradox_dir.join("dlc_load.json"),
			r#"{"enabled_mods":["mod/local.mod"],"disabled_dlcs":[]}"#,
		)
		.expect("write dlc_load");
		for name in ["..", "../Europa Universalis IV", "mod/.."] {
			fs::write(
				paradox_dir.join("mod").join("local.mod"),
				format!("name=\"{name}\"\n"),
			)
			.expect("write local descriptor");
			let summary = resolve_input_summary(&InputRequest::from_playset_path(
				paradox_dir.join("dlc_load.json"),
				Config::default(),
			))
			.expect("resolve summary");
			assert_eq!(summary.mods.len(), 1);
			assert_eq!(summary.mods[0].root_path, None, "name {name:?}");
		}
	}

	#[test]
	fn a_relative_descriptor_path_is_tried_under_the_data_directory_and_its_mod_directory() {
		let game_data_dir = Path::new("/paradox/Europa Universalis IV");
		assert_eq!(
			descriptor_path_candidates(game_data_dir, Path::new("mod/local_mod")),
			vec![
				game_data_dir.join("mod/local_mod"),
				game_data_dir.join("mod").join("mod/local_mod"),
			]
		);

		let absolute = std::env::temp_dir().join("workshop").join("1001");
		assert_eq!(
			descriptor_path_candidates(game_data_dir, &absolute),
			vec![absolute],
			"an absolute path is one candidate, not re-read under the data directory"
		);
	}

	/// A Windows launcher's `path="mod\local_mod"`, read from the descriptor's
	/// bytes on Unix, names a directory literally called `mod\local_mod`, never
	/// the nested `mod/local_mod`.
	#[cfg(unix)]
	#[test]
	fn a_foreign_separator_in_a_descriptor_path_stays_part_of_the_name() {
		let temp = TempDir::new().expect("tempdir");
		let game_data_dir = temp.path().join("Europa Universalis IV");
		fs::create_dir_all(game_data_dir.join("mod").join("local_mod")).expect("nested mod");
		fs::write(
			game_data_dir.join("mod").join("ugc_1001.mod"),
			"name=\"Local\"\npath=\"mod\\local_mod\"\n",
		)
		.expect("write launcher descriptor");

		assert_eq!(
			resolve_mod_from_ugc_descriptor(&game_data_dir, "1001").expect("readable descriptor"),
			None,
			"the nested directory is not what the descriptor names"
		);

		let literal = game_data_dir.join(r"mod\local_mod");
		fs::create_dir(&literal).expect("literal-backslash directory");
		assert_eq!(
			resolve_mod_from_ugc_descriptor(&game_data_dir, "1001").expect("readable descriptor"),
			Some(literal)
		);
	}

	#[cfg(unix)]
	#[test]
	fn physical_candidates_are_distinct_unless_the_host_parses_them_alike() {
		let nested = PathBuf::from("/mods/a/b");
		let literal = PathBuf::from(r"/mods/a\b");
		assert_eq!(
			dedup_candidates(vec![
				nested.clone(),
				literal.clone(),
				nested.clone(),
				PathBuf::from("/mods//a/b"),
			]),
			vec![nested.clone(), literal.clone()]
		);

		let entry = |root: &Path| PlaysetEntry {
			root_path: Some(root.to_path_buf()),
			..PlaysetEntry::default()
		};
		let mut entries = vec![entry(&literal)];
		remove_duplicate_entries(&mut entries, &entry(&nested));
		assert_eq!(entries.len(), 1, "distinct roots are distinct mods");
		remove_duplicate_entries(&mut entries, &entry(&literal));
		assert!(entries.is_empty(), "the same root is the same mod");
	}

	#[test]
	fn relative_file_inventory_propagates_walk_errors() {
		let filter = FileFilter::for_game(Eu4);
		let injected_error = io::Error::new(
			io::ErrorKind::PermissionDenied,
			"injected directory traversal failure",
		);
		let error = collect_relative_files_from_entries(
			Path::new("/synthetic-mod-root"),
			&filter,
			InventoryOwner::Mod("mod-a"),
			[Err(injected_error)],
		)
		.expect_err("directory traversal errors must fail the inventory");

		assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
		assert_eq!(error.to_string(), "injected directory traversal failure");
	}

	#[test]
	fn semantic_snapshot_key_binds_acf_and_behavior_but_not_root_or_inventory() {
		let identity = WorkshopInstallIdentity {
			app_id: 236_850,
			workshop_id: SteamId::new(1_001),
			manifest_id: SteamId::new(2_001),
		};
		let candidate = |mod_id: &str, root: &str, files: Vec<&str>| ModCandidate {
			entry: PlaysetEntry::default(),
			mod_id: mod_id.to_string(),
			root_path: Some(PathBuf::from(root)),
			descriptor_path: None,
			descriptor: None,
			workshop_identity: Some(identity.clone()),
			descriptor_error: None,
			files: files.into_iter().map(game_path).collect(),
		};
		let first = candidate(
			"mod-a",
			"/first/workshop/root",
			vec!["common/scripted_effects/shared.txt"],
		);
		let moved = candidate(
			"mod-a",
			"/second/workshop/root",
			vec!["events/new.txt", "gfx/large.dds"],
		);
		let base_patterns = vec!["**/.DS_Store".to_string(), "*.bak".to_string()];
		let reordered_patterns = vec![
			"*.bak".to_string(),
			"**/.DS_Store".to_string(),
			"*.bak".to_string(),
		];

		assert_eq!(
			semantic_snapshot_key(&Eu4, &base_patterns, &first),
			semantic_snapshot_key(&Eu4, &reordered_patterns, &moved),
			"root and discovered file-set changes must not precede an ACF-keyed lookup"
		);
		assert_ne!(
			semantic_snapshot_key(&Eu4, &base_patterns, &first),
			semantic_snapshot_key(
				&Eu4,
				&base_patterns,
				&candidate("mod-b", "/first/workshop/root", Vec::new()),
			)
		);
		assert_ne!(
			semantic_snapshot_key(&Eu4, &base_patterns, &first),
			semantic_snapshot_key(&Eu4, &["different/**".to_string()], &first,)
		);
		let mut updated_acf = first.clone();
		updated_acf
			.workshop_identity
			.as_mut()
			.expect("Workshop identity")
			.manifest_id = SteamId::new(2_002);
		assert_ne!(
			semantic_snapshot_key(&Eu4, &base_patterns, &first),
			semantic_snapshot_key(&Eu4, &base_patterns, &updated_acf)
		);
	}

	#[cfg(unix)]
	#[test]
	fn relative_file_inventory_prunes_non_loadable_subtrees_before_descent() {
		use std::os::unix::fs::PermissionsExt;

		let temp = TempDir::new().expect("tempdir");
		let root = temp.path().join("mod");
		let loadable = root.join("common/countries");
		let poison = root.join("irrelevant/blocked");
		fs::create_dir_all(&loadable).expect("create loadable root");
		fs::create_dir_all(&poison).expect("create poison root");
		fs::write(loadable.join("A.txt"), "AAA = { }\n").expect("write loadable file");
		fs::write(poison.join("large.bin"), b"must not be visited").expect("write poison file");
		fs::set_permissions(root.join("irrelevant"), fs::Permissions::from_mode(0o000))
			.expect("poison irrelevant subtree");

		let result = collect_relative_files(
			&root,
			&FileFilter::for_game(Eu4),
			InventoryOwner::Mod("mod-a"),
		);
		fs::set_permissions(root.join("irrelevant"), fs::Permissions::from_mode(0o700))
			.expect("restore irrelevant subtree");

		assert_eq!(
			result.expect("non-loadable subtree must be pruned"),
			vec![game_path("common/countries/A.txt")]
		);
	}

	#[test]
	fn relative_file_inventory_is_in_byte_order_not_component_order() {
		// The mod snapshot store accepts only a strictly byte-ordered
		// inventory, and nothing re-sorts the walker's result before it is
		// stored, so this order is what keeps the disk cache usable.
		let temp = TempDir::new().expect("tempdir");
		let root = temp.path().join("mod");
		fs::create_dir_all(root.join("common").join("a")).expect("create nested directory");
		fs::write(root.join("common").join("a").join("b.txt"), "b = { }\n")
			.expect("write nested file");
		fs::write(root.join("common").join("a-b.txt"), "a = { }\n").expect("write dashed file");

		let files = collect_relative_files(
			&root,
			&FileFilter::for_game(Eu4),
			InventoryOwner::Mod("mod-a"),
		)
		.expect("collect relative files");

		assert_eq!(
			files,
			vec![game_path("common/a-b.txt"), game_path("common/a/b.txt")]
		);
	}

	#[cfg(unix)]
	#[test]
	fn unportable_names_outside_loadable_roots_are_pruned_before_conversion() {
		let temp = TempDir::new().expect("tempdir");
		let root = temp.path().join("mod");
		fs::create_dir_all(root.join("common")).expect("create loadable root");
		fs::create_dir_all(root.join("irrelevant")).expect("create non-loadable root");
		fs::write(root.join("common").join("kept.txt"), "k = { }\n").expect("write kept file");
		// A root-level file whose name only looks like `common/foo.txt`, and a
		// backslash name below a folder the game never loads.
		fs::write(root.join(r"common\foo.txt"), "f = { }\n").expect("write root-level name");
		fs::write(root.join("irrelevant").join(r"x\y.txt"), "x = { }\n")
			.expect("write non-loadable name");

		let files = collect_relative_files(
			&root,
			&FileFilter::for_game(Eu4),
			InventoryOwner::Mod("mod-a"),
		)
		.expect("pruned names are never converted");

		assert_eq!(files, vec![game_path("common/kept.txt")]);
	}

	#[cfg(unix)]
	#[test]
	fn an_unportable_name_under_a_loadable_root_fails_even_when_a_glob_would_ignore_it() {
		// Conversion precedes the extra-ignore globs: a glob matches portable
		// text, and an unportable name has none to match.
		let temp = TempDir::new().expect("tempdir");
		let root = temp.path().join("mod");
		fs::create_dir_all(root.join("common")).expect("create loadable root");
		fs::write(root.join("common").join(r"a\b.bak"), "b = { }\n").expect("write ignored name");
		let filter = FileFilter::new(Eu4, &["*.bak".to_string()]).expect("valid glob");

		let error = collect_relative_files(&root, &filter, InventoryOwner::Mod("mod-a"))
			.expect_err("an unportable name has no portable game path");

		let diagnostic = unportable(&error);
		assert_eq!(diagnostic.physical, root.join("common").join(r"a\b.bak"));
		assert_eq!(
			diagnostic.source.kind,
			GamePathErrorKind::ReservedCharacter {
				component: r"a\b.bak".to_string(),
				character: '\\',
			}
		);
	}

	#[test]
	fn manifest_summary_imports_dlc_load_and_appends_path_mod() {
		let temp = TempDir::new().expect("tempdir");
		let game_root = temp.path().join("game-root");
		let paradox_dir = temp.path().join("Europa Universalis IV");
		let imported_root = temp.path().join("imported_mod");
		let local_root = temp.path().join("local_patch");
		fs::create_dir_all(&game_root).expect("create game root");
		write_descriptor(&imported_root, "Imported Mod", Some("1001"));
		write_descriptor(&local_root, "Local Patch", None);
		write_dlc_load(&paradox_dir, &[("1001", imported_root.as_path())]);
		let manifest_path = temp.path().join("foch.toml");
		fs::write(
			&manifest_path,
			r#"
[project]
game = "eu4"
game_path = "game-root"

[[project.imports]]
kind = "dlc_load"
path = "Europa Universalis IV/dlc_load.json"

[[project.mods]]
id = "local_patch"
path = "local_patch"
"#,
		)
		.expect("write manifest");

		let request = request_for_manifest(&manifest_path);
		let summary = resolve_input_summary(&request).expect("resolve manifest");
		assert_eq!(summary.game, Eu4);
		assert_eq!(summary.game_root.as_deref(), Some(game_root.as_path()));
		assert_eq!(summary.mods.len(), 2);
		assert_eq!(summary.mods[0].mod_id, "1001");
		assert_eq!(
			summary.mods[0].root_path.as_deref(),
			Some(imported_root.as_path())
		);
		assert_eq!(summary.mods[1].mod_id, "local_patch");
		assert_eq!(
			summary.mods[1].root_path.as_deref(),
			Some(local_root.as_path())
		);

		let targets = resolve_input_targets(&request, true).expect("resolve targets");
		assert_eq!(targets.len(), 3);
		assert!(
			targets
				.iter()
				.any(|target| target.role == InputTargetRole::Game)
		);
		assert!(targets.iter().any(|target| target.path == imported_root));
		assert!(targets.iter().any(|target| target.path == local_root));
	}

	#[cfg(unix)]
	#[test]
	fn input_summary_does_not_walk_mod_content() {
		use std::os::unix::fs::PermissionsExt;

		let temp = TempDir::new().expect("tempdir");
		let mod_root = temp.path().join("local_mod");
		write_descriptor(&mod_root, "Local Mod", None);
		let poison = mod_root.join("events/blocked");
		fs::create_dir_all(&poison).expect("create poison content");
		fs::write(poison.join("event.txt"), "namespace = poison\n").expect("write poison content");
		fs::set_permissions(mod_root.join("events"), fs::Permissions::from_mode(0o000))
			.expect("poison loadable subtree");
		let manifest_path = temp.path().join("foch.toml");
		fs::write(
			&manifest_path,
			r#"
[project]
game = "eu4"

[[project.mods]]
id = "local_mod"
path = "local_mod"
"#,
		)
		.expect("write manifest");

		let result = resolve_input_summary(&request_for_manifest(&manifest_path));
		fs::set_permissions(mod_root.join("events"), fs::Permissions::from_mode(0o700))
			.expect("restore content subtree");

		let summary = result.expect("summary must be metadata-only");
		assert_eq!(summary.mods.len(), 1);
		assert_eq!(summary.mods[0].mod_id, "local_mod");
	}

	#[test]
	fn manifest_explicit_mod_overrides_imported_duplicate() {
		let temp = TempDir::new().expect("tempdir");
		let paradox_dir = temp.path().join("Europa Universalis IV");
		let imported_root = temp.path().join("imported_mod");
		let override_root = temp.path().join("override_mod");
		write_descriptor(&imported_root, "Imported Mod", Some("1001"));
		write_descriptor(&override_root, "Override Mod", Some("1001"));
		write_dlc_load(&paradox_dir, &[("1001", imported_root.as_path())]);
		let manifest_path = temp.path().join("foch.toml");
		fs::write(
			&manifest_path,
			r#"
[project]
game = "eu4"

[[project.imports]]
kind = "dlc_load"
path = "Europa Universalis IV/dlc_load.json"

[[project.mods]]
id = "override"
steam_id = "1001"
path = "override_mod"
"#,
		)
		.expect("write manifest");

		let summary =
			resolve_input_summary(&request_for_manifest(&manifest_path)).expect("resolve manifest");
		assert_eq!(summary.mods.len(), 1);
		assert_eq!(summary.mods[0].mod_id, "1001");
		assert_eq!(
			summary.mods[0].root_path.as_deref(),
			Some(override_root.as_path())
		);
		assert_eq!(summary.mods[0].display_name.as_deref(), Some("override"));
	}

	#[test]
	fn manifest_rejects_mod_without_path_or_steam_id() {
		let temp = TempDir::new().expect("tempdir");
		let manifest_path = temp.path().join("foch.toml");
		fs::write(
			&manifest_path,
			r#"
[project]
game = "eu4"

[[project.mods]]
id = "broken"
"#,
		)
		.expect("write manifest");

		let err = resolve_input_summary(&request_for_manifest(&manifest_path))
			.expect_err("invalid manifest mod must fail");
		assert!(
			err.message.contains("at least one of path or steam_id"),
			"error was: {err}"
		);
	}

	#[test]
	fn manifest_explicit_missing_path_does_not_fall_back_to_id_directory() {
		let temp = TempDir::new().expect("tempdir");
		let fallback_root = temp.path().join("local_patch");
		write_descriptor(&fallback_root, "Fallback Root", None);
		let manifest_path = temp.path().join("foch.toml");
		fs::write(
			&manifest_path,
			r#"
[project]
game = "eu4"

[[project.mods]]
id = "local_patch"
path = "missing-local-patch"
"#,
		)
		.expect("write manifest");

		let summary =
			resolve_input_summary(&request_for_manifest(&manifest_path)).expect("resolve manifest");
		assert_eq!(summary.mods.len(), 1);
		let expected_root = temp.path().join("missing-local-patch");
		assert_eq!(
			summary.mods[0].root_path.as_deref(),
			Some(expected_root.as_path())
		);
		let targets =
			resolve_input_targets(&request_for_manifest(&manifest_path), false).expect("targets");
		assert!(targets.is_empty());
	}

	#[test]
	fn input_product_input_manifest_reads_acf_not_mod_content() {
		let temp = TempDir::new().expect("tempdir");
		let workshop_root = temp.path().join("steamapps/workshop");
		let content_root = workshop_root.join("content/236850");
		let mod_root = content_root.join("1001");
		let content_file = mod_root.join("gfx/sentinel.dds");
		fs::create_dir_all(content_file.parent().expect("sentinel parent"))
			.expect("create Workshop item");
		fs::write(&content_file, b"first payload").expect("write sentinel");
		fs::write(
			workshop_root.join("appworkshop_236850.acf"),
			r#""AppWorkshop"
{
	"appid" "236850"
	"WorkshopItemsInstalled"
	{
		"1001"
		{
			"size" "13"
			"timeupdated" "1780000000"
			"manifest" "2001"
		}
	}
}"#,
		)
		.expect("write Workshop ACF");
		let manifest_path = temp.path().join("foch.toml");
		fs::write(
			&manifest_path,
			r#"
[project]
game = "eu4"

[[project.mods]]
id = "mod-a"
steam_id = "1001"
path = "steamapps/workshop/content/236850/1001"
workshop_identity = { app_id = 236850, workshop_id = "1001", manifest_id = "2001" }
"#,
		)
		.expect("write manifest");

		let request = request_for_manifest(&manifest_path);
		let first = resolve_product_input_manifest(&request).expect("first manifest");
		fs::write(&content_file, b"changed bytes").expect("mutate content without changing ACF");
		#[cfg(unix)]
		{
			use std::os::unix::fs::PermissionsExt;
			fs::set_permissions(&content_file, fs::Permissions::from_mode(0o000))
				.expect("make sentinel unreadable");
		}
		let second = resolve_product_input_manifest(&request).expect("second manifest");
		#[cfg(unix)]
		{
			use std::os::unix::fs::PermissionsExt;
			fs::set_permissions(&content_file, fs::Permissions::from_mode(0o600))
				.expect("restore sentinel permissions");
		}

		assert_eq!(first.mods[0].mod_id, "1001");
		assert_eq!(first.mods[0].precedence, 1);
		assert_eq!(first.mods[0].workshop_identity.manifest_id.as_str(), "2001");
		assert!(first.digest_is_valid());
		assert_eq!(first, second);
	}

	#[test]
	fn retained_governments_path_expands_to_the_complete_definition_module() {
		let temp = TempDir::new().expect("tempdir");
		let mod_root = temp.path().join("governments_mod");
		write_descriptor(&mod_root, "Governments Mod", None);
		let governments = mod_root.join("common/governments");
		fs::create_dir_all(&governments).expect("create governments directory");
		fs::write(
			governments.join("00_governments.txt"),
			"early_government = { basic_reform = early_reform }\n",
		)
		.expect("write early government");
		fs::write(
			governments.join("zzz_governments.txt"),
			"late_government = { basic_reform = late_reform }\n",
		)
		.expect("write late government");
		let unrelated = mod_root.join("common/scripted_effects");
		fs::create_dir_all(&unrelated).expect("create unrelated directory");
		fs::write(unrelated.join("effect.txt"), "effect = { }\n").expect("write unrelated file");
		let manifest_path = temp.path().join("foch.toml");
		fs::write(
			&manifest_path,
			r#"
[project]
game = "eu4"

[[project.mods]]
id = "governments_mod"
path = "governments_mod"
"#,
		)
		.expect("write manifest");
		let requested = BTreeSet::from([game_path("common/governments/00_governments.txt")]);

		let inventory = build_input_inventory_for_paths(
			&request_for_manifest(&manifest_path),
			false,
			Some(&requested),
		)
		.expect("build retained input inventory");
		assert!(inventory.mods[0].files.is_empty());
		assert!(inventory.mods[0].descriptor.is_none());
		assert!(inventory.mods[0].descriptor_error.is_none());
		assert_eq!(inventory.requested_retained_paths, Some(requested));
		let input = resolve_input_from_inventory(inventory).expect("resolve input");
		assert_eq!(
			input.mods[0]
				.descriptor
				.as_ref()
				.map(|descriptor| descriptor.name.as_str()),
			Some("Governments Mod")
		);
		let retained_files = input.mods[0].files.iter().cloned().collect::<BTreeSet<_>>();
		assert_eq!(
			retained_files,
			BTreeSet::from([
				game_path("common/governments/00_governments.txt"),
				game_path("common/governments/zzz_governments.txt"),
			])
		);
		assert_eq!(input.effective_retained_paths, Some(retained_files));
	}

	#[test]
	fn retained_database_inputs_use_the_resolved_game_version_and_keep_playset_order() {
		let temp: TempDir = TempDir::new().unwrap();
		let game_root: PathBuf = temp.path().join("game-root");
		fs::create_dir_all(&game_root).unwrap();
		fs::write(game_root.join("version.txt"), "1.37.5\n").unwrap();
		for (mod_id, directory) in [
			("mod-z", "common/static_modifiers"),
			("mod-a", "common/event_modifiers"),
		] {
			let root: PathBuf = temp.path().join(mod_id);
			write_descriptor(&root, mod_id, None);
			fs::create_dir_all(root.join(directory)).unwrap();
			fs::write(root.join(directory).join("entry.txt"), "test = { }\n").unwrap();
		}
		let manifest: PathBuf = temp.path().join("foch.toml");
		fs::write(
			&manifest,
			r#"
[project]
game = "eu4"
game_path = "game-root"

[[project.mods]]
id = "mod-z"
path = "mod-z"

[[project.mods]]
id = "mod-a"
path = "mod-a"
"#,
		)
		.unwrap();
		let requested: BTreeSet<GamePathBuf> =
			BTreeSet::from([game_path("common/static_modifiers/entry.txt")]);
		let inventory = build_input_inventory_for_paths(
			&request_for_manifest(&manifest),
			false,
			Some(&requested),
		)
		.unwrap();
		let input = resolve_input_from_inventory(inventory).unwrap();
		assert_eq!(input.game_version.as_deref(), Some("1.37.5"));
		assert_eq!(input.cache_game_version.as_deref(), Some("eu4 1.37.5"));
		assert_eq!(input.requested_retained_paths, Some(requested));
		assert_eq!(
			input.effective_retained_paths,
			Some(BTreeSet::from([
				game_path("common/static_modifiers/entry.txt"),
				game_path("common/event_modifiers/entry.txt"),
			]))
		);
		assert_eq!(input.mods[0].mod_id, "mod-z");
		assert_eq!(input.mods[1].mod_id, "mod-a");
		assert_eq!(
			input.file_inventory[&game_path("common/static_modifiers/entry.txt")][0].precedence,
			0
		);
		assert_eq!(
			input.file_inventory[&game_path("common/event_modifiers/entry.txt")][0].precedence,
			1
		);
	}

	#[test]
	fn retained_database_selection_includes_other_directories_and_respects_file_filters() {
		let requested: BTreeSet<GamePathBuf> =
			BTreeSet::from([game_path("common/static_modifiers/mod.txt")]);
		let available: [GamePathBuf; 5] = [
			"common/static_modifiers/base.txt",
			"common/static_modifiers/notes.gui",
			"common/event_modifiers/base.txt",
			"common/event_modifiers/notes.gui",
			"common/policies/unrelated.txt",
		]
		.map(game_path);
		let expanded: Option<BTreeSet<GamePathBuf>> = expand_retained_paths_for_game(
			&Eu4,
			Some("1.37.5"),
			Some(&requested),
			available.iter().map(GamePathBuf::as_game_path),
		)
		.unwrap();
		assert_eq!(
			expanded,
			Some(BTreeSet::from([
				game_path("common/static_modifiers/mod.txt"),
				game_path("common/static_modifiers/base.txt"),
				game_path("common/event_modifiers/base.txt"),
			]))
		);
	}

	fn write_manifest_mod(temp: &Path, mod_id: &str, descriptor: &str) -> (PathBuf, PathBuf) {
		let root = temp.join(mod_id);
		fs::create_dir_all(root.join("events")).expect("create mod root");
		fs::write(root.join("events").join("a.txt"), "namespace = a\n").expect("write event");
		fs::write(root.join("descriptor.mod"), descriptor).expect("write descriptor");
		let manifest = temp.join("foch.toml");
		fs::write(
			&manifest,
			format!(
				"[project]\ngame = \"eu4\"\n\n[[project.mods]]\nid = \"{mod_id}\"\npath = \"{mod_id}\"\n"
			),
		)
		.expect("write manifest");
		(manifest, root.join("descriptor.mod"))
	}

	/// A `replace_path` decides which earlier contributions the merge drops,
	/// so a value that names no directory under the game root stops input
	/// resolution. It is not treated like an unreadable descriptor, which would
	/// merge the mod as if it declared no replacement at all.
	#[test]
	fn an_invalid_replace_path_stops_input_resolution_naming_the_mod_and_value() {
		let temp = TempDir::new().expect("tempdir");
		let (manifest, descriptor) = write_manifest_mod(
			temp.path(),
			"bad_mod",
			"name=\"Bad\"\nreplace_path=\"common/../events\"\n",
		);
		let request = request_for_manifest(&manifest);

		for error in [
			resolve_input(&request, false).expect_err("resolution must stop"),
			resolve_input_summary(&request).expect_err("the summary reads descriptors too"),
		] {
			assert_eq!(error.kind, InputResolveErrorKind::Io, "{error}");
			assert_eq!(error.path, descriptor, "{error}");
			for expected in [
				"mod bad_mod".to_string(),
				descriptor.display().to_string(),
				r#""common/../events""#.to_string(),
				"`..`".to_string(),
			] {
				assert!(
					error.message.contains(&expected),
					"{expected} not in {error}"
				);
			}
		}
	}

	/// The launcher's copy of a descriptor is read only for the mod's location,
	/// so its `replace_path` does not hide the mod: the mod is found, and its
	/// own descriptor then reports the value.
	#[test]
	fn a_launcher_descriptor_with_an_invalid_replace_path_still_locates_its_mod() {
		let temp = TempDir::new().expect("tempdir");
		let paradox_dir = temp.path().join("Europa Universalis IV");
		let mod_root = temp.path().join("workshop_mod");
		let bad = "replace_path=\"C:/events\"\n";
		fs::create_dir_all(mod_root.join("events")).expect("create mod root");
		fs::write(mod_root.join("events").join("a.txt"), "namespace = a\n").expect("write event");
		fs::write(
			mod_root.join("descriptor.mod"),
			format!("name=\"Bad\"\nremote_file_id=\"1001\"\n{bad}"),
		)
		.expect("write mod descriptor");
		write_dlc_load(&paradox_dir, &[("1001", mod_root.as_path())]);
		let launcher = paradox_dir.join("mod").join("ugc_1001.mod");
		let mut body = fs::read_to_string(&launcher).expect("read launcher descriptor");
		body.push_str(bad);
		fs::write(&launcher, body).expect("write launcher descriptor");

		let error = resolve_input(
			&InputRequest::from_playset_path(paradox_dir.join("dlc_load.json"), Config::default()),
			false,
		)
		.expect_err("the mod's own replace_path stops resolution");

		assert_eq!(error.path, mod_root.join("descriptor.mod"), "{error}");
		assert!(error.message.contains("mod 1001"), "{error}");
		assert!(error.message.contains(r#""C:/events""#), "{error}");
		assert!(!error.message.contains("unavailable"), "{error}");
	}

	#[test]
	fn retained_non_module_path_stays_exact() {
		let available = BTreeSet::from([
			game_path("common/countries/France.txt"),
			game_path("common/countries/England.txt"),
		]);
		let requested = BTreeSet::from([game_path("common/countries/France.txt")]);

		let effective = expand_retained_paths_for_game(
			&Eu4,
			None,
			Some(&requested),
			available.iter().map(GamePathBuf::as_game_path),
		)
		.unwrap();

		assert_eq!(effective, Some(requested));
	}

	#[test]
	fn retained_module_expansion_includes_available_basegame_siblings() {
		let requested = BTreeSet::from([game_path("common/governments/mod_override.txt")]);
		let available = BTreeSet::from([
			game_path("common/governments/00_vanilla.txt"),
			game_path("common/governments/mod_override.txt"),
			game_path("common/scripted_effects/unrelated.txt"),
		]);

		let effective = expand_retained_paths_for_game(
			&Eu4,
			None,
			Some(&requested),
			available.iter().map(GamePathBuf::as_game_path),
		)
		.unwrap();

		assert_eq!(
			effective,
			Some(BTreeSet::from([
				game_path("common/governments/00_vanilla.txt"),
				game_path("common/governments/mod_override.txt"),
			]))
		);
	}

	fn make_contributor(
		mod_id: &str,
		precedence: usize,
		is_base_game: bool,
	) -> ResolvedInputContributor {
		ResolvedInputContributor {
			mod_id: mod_id.to_string(),
			root_path: PathBuf::from(format!("/mods/{mod_id}")),
			relative_path: game_path("common/file.txt"),
			precedence,
			is_base_game,
			is_synthetic_base: false,
			parse_ok_hint: None,
			mod_hash: Some(format!("hash-{mod_id}")),
		}
	}

	fn two_mod_inventory(
		relative_path: &str,
	) -> BTreeMap<GamePathBuf, Vec<ResolvedInputContributor>> {
		let relative_path = game_path(relative_path);
		let contributor = |mod_id: &str, precedence: usize| ResolvedInputContributor {
			relative_path: relative_path.clone(),
			..make_contributor(mod_id, precedence, false)
		};
		BTreeMap::from([(
			relative_path.clone(),
			vec![contributor("mod_a", 1), contributor("mod_b", 2)],
		)])
	}

	fn eu4_test_playlist() -> Playset {
		Playset {
			game: Eu4,
			name: "semantic-base-proof".to_string(),
			mods: Vec::new(),
		}
	}

	#[test]
	fn absent_semantic_base_requires_a_loaded_snapshot_and_supported_file_family() {
		let temp = TempDir::new().expect("tempdir");
		let playlist = eu4_test_playlist();
		let defines_path = "common/defines/es_defines.lua";
		let defines_inventory = two_mod_inventory(defines_path);

		let absent =
			verify_absent_semantic_bases(&playlist, Some(temp.path()), true, &defines_inventory)
				.expect("verify absent defines base");
		assert_eq!(absent, BTreeSet::from([game_path(defines_path)]));

		let without_snapshot =
			verify_absent_semantic_bases(&playlist, Some(temp.path()), false, &defines_inventory)
				.expect("skip absence proof without a base snapshot");
		assert!(without_snapshot.is_empty());

		let events_inventory = two_mod_inventory("events/test.txt");
		let events =
			verify_absent_semantic_bases(&playlist, Some(temp.path()), true, &events_inventory)
				.expect("verify absent event base");
		assert_eq!(events, BTreeSet::from([game_path("events/test.txt")]));

		let gfx_path = "interface/000_expanded_mod_family.gfx";
		let gfx = verify_absent_semantic_bases(
			&playlist,
			Some(temp.path()),
			true,
			&two_mod_inventory(gfx_path),
		)
		.expect("verify absent GFX base");
		assert_eq!(gfx, BTreeSet::from([game_path(gfx_path)]));

		let module_inventory = two_mod_inventory("common/governments/test.txt");
		let module =
			verify_absent_semantic_bases(&playlist, Some(temp.path()), true, &module_inventory)
				.expect("aggregate definition module stays required");
		assert!(module.is_empty());

		let binary = verify_absent_semantic_bases(
			&playlist,
			Some(temp.path()),
			true,
			&two_mod_inventory("gfx/picture.dds"),
		)
		.expect("binary assets do not need semantic base verification");
		assert!(binary.is_empty());
	}

	#[test]
	fn live_semantic_base_rejects_a_filtered_snapshot_gap() {
		let temp = TempDir::new().expect("tempdir");
		let relative_path = "common/defines/es_defines.lua";
		let absolute_path = temp.path().join(relative_path);
		fs::create_dir_all(absolute_path.parent().expect("defines parent"))
			.expect("create defines parent");
		fs::write(&absolute_path, "NDefines.NGame.TEST = 1\n").expect("write live base");

		let error = verify_absent_semantic_bases(
			&eu4_test_playlist(),
			Some(temp.path()),
			true,
			&two_mod_inventory(relative_path),
		)
		.expect_err("filtered snapshot must not prove live base absence");

		assert_eq!(error.path, absolute_path);
		assert!(
			error
				.message
				.contains("omits the existing semantic merge base")
		);
	}

	#[test]
	fn inject_synthetic_bases_no_base_two_mods_creates_synthetic() {
		let mut inventory: BTreeMap<GamePathBuf, Vec<ResolvedInputContributor>> = BTreeMap::new();
		inventory.insert(
			game_path("common/file.txt"),
			vec![
				make_contributor("mod_b", 5, false),
				make_contributor("mod_a", 3, false),
			],
		);

		inject_synthetic_bases(&mut inventory);

		let contribs = &inventory[GamePath::new("common/file.txt").expect("valid game path")];
		assert_eq!(contribs.len(), 3, "synthetic base should be added");
		let synth = &contribs[0];
		assert!(synth.is_synthetic_base);
		assert!(!synth.is_base_game);
		assert_eq!(synth.precedence, 0);
		assert_eq!(synth.mod_id, "mod_a", "lowest-precedence mod is mod_a (3)");
		// originals preserved
		assert!(!contribs[1].is_synthetic_base);
		assert!(!contribs[2].is_synthetic_base);
		assert_eq!(contribs[1].mod_id, "mod_b");
		assert_eq!(contribs[2].mod_id, "mod_a");
		assert_eq!(contribs[2].precedence, 3);
	}

	#[test]
	fn inject_synthetic_bases_with_real_base_skipped() {
		let mut inventory: BTreeMap<GamePathBuf, Vec<ResolvedInputContributor>> = BTreeMap::new();
		inventory.insert(
			game_path("common/file.txt"),
			vec![
				make_contributor("base:eu4", 0, true),
				make_contributor("mod_a", 1, false),
				make_contributor("mod_b", 2, false),
			],
		);

		inject_synthetic_bases(&mut inventory);

		let contribs = &inventory[GamePath::new("common/file.txt").expect("valid game path")];
		assert_eq!(contribs.len(), 3, "no synthetic base should be added");
		assert!(!contribs.iter().any(|c| c.is_synthetic_base));
	}

	#[test]
	fn inject_synthetic_bases_single_mod_skipped() {
		let mut inventory: BTreeMap<GamePathBuf, Vec<ResolvedInputContributor>> = BTreeMap::new();
		inventory.insert(
			game_path("common/file.txt"),
			vec![make_contributor("mod_a", 1, false)],
		);

		inject_synthetic_bases(&mut inventory);

		let contribs = &inventory[GamePath::new("common/file.txt").expect("valid game path")];
		assert_eq!(contribs.len(), 1, "no synthetic base for single mod");
		assert!(!contribs[0].is_synthetic_base);
	}

	#[test]
	fn inject_synthetic_bases_tie_breaks_on_mod_id() {
		let mut inventory: BTreeMap<GamePathBuf, Vec<ResolvedInputContributor>> = BTreeMap::new();
		inventory.insert(
			game_path("common/file.txt"),
			vec![
				make_contributor("mod_z", 2, false),
				make_contributor("mod_a", 2, false),
			],
		);

		inject_synthetic_bases(&mut inventory);

		let contribs = &inventory[GamePath::new("common/file.txt").expect("valid game path")];
		assert_eq!(contribs.len(), 3);
		assert!(contribs[0].is_synthetic_base);
		assert_eq!(
			contribs[0].mod_id, "mod_a",
			"tie on precedence resolved by mod_id lex"
		);
	}
}