curie-build 0.5.0

The Curie build tool
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
use anyhow::{bail, Context, Result};
use serde::Deserialize;
use std::collections::BTreeMap;
use std::path::Path;

/// A fully-validated Curie project descriptor.
///
/// The mutually-exclusive `[application]` / `[library]` / `[workspace]`
/// sections are reified as the [`DescriptorKind`] enum: a Descriptor with
/// `kind: DescriptorKind::Application(_)` is statically guaranteed to be
/// an application, no `unreachable!()` branches needed.  Serde-side
/// parsing happens via a private flat-shape struct in [`load`].
#[derive(Debug)]
pub struct Descriptor {
    pub kind: DescriptorKind,
    pub java: Java,
    /// Populated from `[test]` (only `junitPlatformVersion` today).
    /// Workspace inheritance is applied by `workspace::inherit_from_workspace`
    /// before any build pipeline reads the value.
    pub test: Test,
    /// Populated from `[kotlin]`.  Workspace inheritance works exactly like
    /// the `[java]` scalar: a member's value wins; when absent the workspace
    /// value (if any) is copied in.
    pub kotlin: Kotlin,
    pub groovy: Groovy,
    /// Populated from `[spock]`.  `enabled` is set by [`load`] after a
    /// raw-TOML presence check — absent section = Spock disabled.
    pub spock: Spock,
    /// Populated from `[native-image]`.  The `section_present` flag is set
    /// by [`load`] after a raw-TOML presence check, because an absent section
    /// and a section with all-default values produce the same deserialised
    /// struct — but only the former disables native-image compilation.
    pub native_image: NativeImage,
    pub docker: Docker,
    pub build_info: BuildInfo,
    pub dependencies: BTreeMap<String, DependencyValue>,
    pub test_dependencies: BTreeMap<String, DependencyValue>,
    pub repositories: Vec<RepositoryEntry>,
    pub bom_imports: BTreeMap<String, String>,
    pub test_bom_imports: BTreeMap<String, String>,
    /// BOMs inherited from the surrounding workspace's `[bom-imports]`,
    /// populated by `workspace::load` during inheritance merge.  Empty in
    /// single-module mode.  Lower priority than the member's own
    /// [`bom_imports`]: in `prod_bom_gavs()` these are emitted first so the
    /// resolver's later-wins semantics let the member override the workspace.
    pub inherited_bom_imports: BTreeMap<String, String>,
    /// Same as [`inherited_bom_imports`] for `[test-bom-imports]`.  Lower
    /// priority than the member's own [`test_bom_imports`].
    pub inherited_test_bom_imports: BTreeMap<String, String>,
    pub workspace_dependencies: BTreeMap<String, WorkspaceDep>,
    /// `[annotation-processors]` — coordinates of processor jars to put on
    /// javac's `-processorpath` during production compilation.  Entries are
    /// resolved through the same Maven resolver as `[dependencies]` and
    /// honour `[bom-imports]` for version-less coordinates.
    pub annotation_processors: BTreeMap<String, AnnotationProcessor>,
    /// `[test-annotation-processors]` — same shape, only added to the
    /// processor path when compiling test sources.
    pub test_annotation_processors: BTreeMap<String, AnnotationProcessor>,
    /// Workspace-inherited counterparts, populated by
    /// `workspace::inherit_from_workspace`.  Member-declared entries take
    /// precedence on a key collision.
    pub inherited_annotation_processors: BTreeMap<String, AnnotationProcessor>,
    pub inherited_test_annotation_processors: BTreeMap<String, AnnotationProcessor>,
    /// `[annotation-processor-options.<prefix>]` — nested table keyed by
    /// processor namespace.  Each inner key/value emits a single
    /// `-A<prefix>.<key>=<value>` to javac.  Examples:
    ///
    /// ```toml
    /// [annotation-processor-options.dagger]
    /// fastInit = "enabled"
    ///
    /// [annotation-processor-options.mapstruct]
    /// suppressGeneratorTimestamp = "true"
    /// ```
    pub annotation_processor_options: BTreeMap<String, BTreeMap<String, String>>,
    /// Test-only counterpart of [`annotation_processor_options`].
    pub test_annotation_processor_options: BTreeMap<String, BTreeMap<String, String>>,
    pub inherited_annotation_processor_options: BTreeMap<String, BTreeMap<String, String>>,
    pub inherited_test_annotation_processor_options: BTreeMap<String, BTreeMap<String, String>>,
    /// `[publish]` — empty/default when the section is absent.  Validated at
    /// publish time, not load time.
    pub publish: PublishConfig,
}

/// One entry in `[annotation-processors]` or `[test-annotation-processors]`.
///
/// Two shapes accepted, via serde's untagged enum:
///
/// ```toml
/// # Shorthand: the value is just the version string.
/// "com.google.dagger:dagger-compiler" = "2.50"
///
/// # Detailed: extra knobs.  Today the only knob is on-compile-classpath,
/// # which Lombok needs because its annotation types live in the same jar
/// # as the processor itself.
/// "org.projectlombok:lombok" = { version = "1.18.30", on-compile-classpath = true }
/// ```
#[derive(Debug, Deserialize, Clone)]
#[serde(untagged)]
pub enum AnnotationProcessor {
    /// `"key" = "1.0.0"` form — equivalent to detailed with defaults.
    Version(String),
    /// `"key" = { version = "1.0.0", on-compile-classpath = bool }` form.
    Detailed(AnnotationProcessorDetailed),
}

#[derive(Debug, Deserialize, Clone)]
pub struct AnnotationProcessorDetailed {
    pub version: String,
    /// When `true`, the processor jar is added to javac's `-cp` in addition
    /// to `-processorpath`.  Needed for processors whose annotation types
    /// are referenced from user code and live in the same jar as the
    /// processor (Lombok is the canonical case).  Default `false`: most
    /// processors (Dagger, MapStruct, AutoValue, Micronaut) split their
    /// API into a separate jar that the user declares under `[dependencies]`.
    #[serde(default, rename = "on-compile-classpath")]
    pub on_compile_classpath: bool,
}

impl AnnotationProcessor {
    /// Version string as the user wrote it.  `""` means "supply via a BOM".
    pub fn version(&self) -> &str {
        match self {
            AnnotationProcessor::Version(v) => v,
            AnnotationProcessor::Detailed(d) => &d.version,
        }
    }

    pub fn on_compile_classpath(&self) -> bool {
        match self {
            AnnotationProcessor::Version(_) => false,
            AnnotationProcessor::Detailed(d) => d.on_compile_classpath,
        }
    }
}

/// Which top-level section the descriptor declares.  Exactly one variant
/// per descriptor — enforced by [`load`] at parse time.
#[derive(Debug)]
pub enum DescriptorKind {
    Application(Application),
    Library(Library),
    /// Workspace root: lists members but is not itself buildable.
    Workspace(Workspace),
    /// BOM (Bill of Materials): publishes a POM-only artifact that declares
    /// managed versions for a set of dependencies.  No JAR is produced.
    Bom(Bom),
}

/// Flat shape for serde — every section is `Option`, and [`load`]
/// validates exactly-one-of and converts to [`DescriptorKind`].  Kept
/// private to descriptor.rs; consumers only see the validated
/// [`Descriptor`].
#[derive(Debug, Deserialize)]
struct RawDescriptor {
    application: Option<Application>,
    library: Option<Library>,
    workspace: Option<Workspace>,
    bom: Option<Bom>,
    #[serde(default)]
    java: Java,
    #[serde(default)]
    docker: Docker,
    #[serde(rename = "build-info", default)]
    build_info: BuildInfo,
    #[serde(default)]
    dependencies: BTreeMap<String, DependencyValue>,
    #[serde(rename = "test-dependencies", default)]
    test_dependencies: BTreeMap<String, DependencyValue>,
    #[serde(default)]
    repositories: Vec<RepositoryEntry>,
    #[serde(rename = "bom-imports", default)]
    bom_imports: BTreeMap<String, String>,
    #[serde(rename = "test-bom-imports", default)]
    test_bom_imports: BTreeMap<String, String>,
    #[serde(rename = "workspace-dependencies", default)]
    workspace_dependencies: BTreeMap<String, WorkspaceDep>,
    #[serde(rename = "annotation-processors", default)]
    annotation_processors: BTreeMap<String, AnnotationProcessor>,
    #[serde(rename = "test-annotation-processors", default)]
    test_annotation_processors: BTreeMap<String, AnnotationProcessor>,
    #[serde(rename = "annotation-processor-options", default)]
    annotation_processor_options: BTreeMap<String, BTreeMap<String, String>>,
    #[serde(rename = "test-annotation-processor-options", default)]
    test_annotation_processor_options: BTreeMap<String, BTreeMap<String, String>>,
    #[serde(default)]
    test: Test,
    #[serde(default)]
    kotlin: Kotlin,
    #[serde(default)]
    groovy: Groovy,
    #[serde(default)]
    spock: Spock,
    #[serde(rename = "native-image", default)]
    native_image: NativeImage,
    #[serde(default)]
    publish: PublishConfig,
}

/// One entry in `[workspace-dependencies]`.
///
/// Today only `path` is supported.  In future this may grow `features`,
/// optional flags, or scope hints — the struct shape leaves room for that
/// without breaking the table key.
#[derive(Debug, Deserialize, Clone)]
pub struct WorkspaceDep {
    pub path: String,
    /// Catch-all so a user who tries `version = "1.0"` (a common Cargo
    /// muscle-memory mistake) gets a precise rejection at load time.
    /// Validated in [`load`]; never read after that.
    #[serde(default)]
    #[allow(dead_code)]
    pub version: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct Application {
    pub name: String,
    pub version: String,
    /// Maven `groupId` — required only when publishing.  When absent, build
    /// and test paths work normally; `curie publish` errors with a clear
    /// message asking the user to add it.
    #[serde(rename = "groupId", default)]
    pub group_id: Option<String>,
    /// The fully-qualified main class name.  When omitted, curie will scan
    /// production sources and compiled bytecode to detect it automatically.
    #[serde(rename = "mainClass")]
    pub main_class: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct Library {
    pub name: String,
    pub version: String,
    /// Maven `groupId` — required only when publishing.  See [`Application::group_id`].
    #[serde(rename = "groupId", default)]
    pub group_id: Option<String>,
}

/// Workspace descriptor: lists member directories whose own `Curie.toml`
/// files are buildable modules.  Member paths are relative to the workspace
/// `Curie.toml` directory.
#[derive(Debug, Deserialize)]
pub struct Workspace {
    pub members: Vec<String>,
}

/// BOM (Bill of Materials) descriptor: declares managed dependency versions
/// that consumers can import via `[bom-imports]`.  Produces a POM-only
/// artifact; no JAR, no compilation.
#[derive(Debug, Deserialize)]
pub struct Bom {
    pub name: String,
    pub version: String,
    /// Maven `groupId` — required for publishing.  See [`Application::group_id`].
    #[serde(rename = "groupId", default)]
    pub group_id: Option<String>,
}

#[derive(Debug, Deserialize, Default)]
pub struct Java {
    /// `[java].sourceCompatibility` as the user wrote it, or `None` when
    /// the key was absent.  Use [`Self::effective`] to get the
    /// resolved value (default `"21"`) — never read this field directly
    /// from compile/test paths, because `None` is meaningful: it signals
    /// "inherit from the workspace if any, else use the default".
    #[serde(rename = "sourceCompatibility")]
    pub source_compatibility: Option<String>,
    /// When `true`, passes `--enable-preview` to javac and to the java
    /// runtime.  Required for preview features on Java 21–22 (e.g. unnamed
    /// classes and instance main methods).  Not needed on Java 23+ where
    /// those features became standard (JEP 463).
    ///
    /// ```toml
    /// [java]
    /// sourceCompatibility = "21"
    /// enablePreview = true
    /// ```
    /// `None` when `enablePreview` was absent — meaningful, so it can be
    /// distinguished from an explicit `false`: a workspace member that omits
    /// the key inherits the workspace value, whereas `enablePreview = false`
    /// opts out even when the workspace enabled it.  Use
    /// [`Self::preview_enabled`] to read the resolved boolean.
    #[serde(rename = "enablePreview")]
    pub enable_preview: Option<bool>,
}

impl Java {
    /// Resolved `--release` argument for `javac`.  Workspace inheritance
    /// happens upstream of this call (in `workspace::load`), so by the
    /// time the build pipeline reads it the member's `source_compatibility`
    /// has already been populated with the workspace value if applicable.
    pub fn effective(&self) -> &str {
        self.source_compatibility.as_deref().unwrap_or("21")
    }

    /// Resolved `--enable-preview` flag (default `false`).  Like
    /// [`Self::effective`], member/workspace inheritance has already been
    /// applied by the time the build pipeline reads this.
    pub fn preview_enabled(&self) -> bool {
        self.enable_preview.unwrap_or(false)
    }
}

/// Default version of the JUnit Platform Console Standalone launcher
/// that Curie downloads (into `~/.m2`) to execute tests.  Users may
/// override it (including at the workspace root) via:
///
/// ```toml
/// [test]
/// junitPlatformVersion = "6.0.3"
/// ```
pub const DEFAULT_JUNIT_PLATFORM_VERSION: &str = "6.0.3";

/// Default Kotlin version used to resolve `kotlin-compiler-embeddable`
/// and `kotlin-stdlib` from Maven Central whenever any `.kt` sources are
/// present.  Override (workspace-inheritable) with:
///
/// ```toml
/// [kotlin]
/// version = "2.1.21"
/// ```
pub const DEFAULT_KOTLIN_VERSION: &str = "2.1.21";

/// Configuration for the `[test]` table (currently only the version of the
/// JUnit Platform Console Standalone runner that Curie itself downloads).
#[derive(Debug, Deserialize, Default, Clone)]
pub struct Test {
    /// `junitPlatformVersion` — matches the camelCase style of
    /// `sourceCompatibility`, `mainClass`, `baseImage`, etc.
    #[serde(rename = "junitPlatformVersion", default)]
    pub junit_platform_version: Option<String>,
}

impl Test {
    /// The version string that will be passed to the resolver for the
    /// `junit-platform-console-standalone` artifact.  After
    /// `workspace::inherit_from_workspace`, a member's field already
    /// contains the workspace value when the member omitted the key.
    pub fn junit_platform_version(&self) -> &str {
        self.junit_platform_version
            .as_deref()
            .unwrap_or(DEFAULT_JUNIT_PLATFORM_VERSION)
    }

    /// `true` when the user explicitly set `junitPlatformVersion` in
    /// `Curie.toml` (or inherited it from a workspace).  Used by the test
    /// runner to decide whether to override the version for Spock compatibility.
    pub fn junit_platform_version_is_user_set(&self) -> bool {
        self.junit_platform_version.is_some()
    }
}

/// Configuration for the `[kotlin]` table (the version of kotlinc + stdlib
/// that Curie downloads when it sees Kotlin sources).
#[derive(Debug, Deserialize, Default, Clone)]
pub struct Kotlin {
    /// Simple `version` key inside the `[kotlin]` table.  The table name
    /// makes the meaning unambiguous.
    #[serde(default)]
    pub version: Option<String>,
}

impl Kotlin {
    /// Effective version passed to the resolver for both the Kotlin
    /// compiler and the stdlib JARs (they are published at the same
    /// version).
    pub fn version(&self) -> &str {
        self.version.as_deref().unwrap_or(DEFAULT_KOTLIN_VERSION)
    }
}

/// Default version of Apache Groovy resolved from Maven Central when `.groovy`
/// sources are present.  Override (workspace-inheritable) with:
///
/// ```toml
/// [groovy]
/// version = "4.0.23"
/// ```
pub const DEFAULT_GROOVY_VERSION: &str = "5.0.6";

/// Configuration for the `[native-image]` table.
///
/// Native image compilation is opt-in: the section must be explicitly present
/// in `Curie.toml` to trigger `native-image` after JAR packaging.  Only
/// meaningful for `[application]` projects.
///
/// ```toml
/// [native-image]
/// # Name of the output binary written to target/ (default: application.name)
/// outputName = "my-app"
///
/// # Path to a directory containing GraalVM reachability-metadata config files
/// # (reflect-config.json, resource-config.json, proxy-config.json, …).
/// # Passed as -H:ConfigurationFileDirectories=<path>.
/// configDir = "src/main/resources/META-INF/native-image"
///
/// # Additional flags forwarded verbatim to native-image (appended last).
/// extraArgs = ["--no-fallback", "-H:+ReportExceptionStackTraces"]
/// ```
///
/// Curie locates the `native-image` executable by checking, in order:
///   1. `$GRAALVM_HOME/bin/native-image`
///   2. `native-image` on `$PATH`
///
/// Install GraalVM from <https://www.graalvm.org/downloads/> or via sdkman.
#[derive(Debug, Deserialize, Default, Clone)]
pub struct NativeImage {
    /// Name of the output binary written to `target/`.
    /// Defaults to the application name (hyphens replaced with hyphens — kept
    /// as-is since native-image accepts hyphens in output names).
    #[serde(rename = "outputName", default)]
    pub output_name: Option<String>,

    /// Path to a directory that contains GraalVM reachability-metadata JSON
    /// files (relative to the project root).  Passed as
    /// `-H:ConfigurationFileDirectories=<abs-path>`.
    #[serde(rename = "configDir", default)]
    pub config_dir: Option<String>,

    /// Extra flags appended verbatim to the `native-image` invocation.
    #[serde(rename = "extraArgs", default)]
    pub extra_args: Vec<String>,

    /// Whether the `[native-image]` section was explicitly present in
    /// `Curie.toml`.  Set by [`load`] after the raw-TOML presence check;
    /// never written by serde.
    #[serde(skip)]
    pub section_present: bool,
}

impl NativeImage {
    /// Resolved output binary name: descriptor override or application name.
    /// `app_name` is the fallback when `outputName` was omitted.
    pub fn resolved_output_name<'a>(&'a self, app_name: &'a str) -> &'a str {
        self.output_name.as_deref().unwrap_or(app_name)
    }
}

/// Configuration for the `[groovy]` table.
#[derive(Debug, Deserialize, Default, Clone)]
pub struct Groovy {
    #[serde(default)]
    pub version: Option<String>,
}

impl Groovy {
    /// Effective version passed to the resolver for the Groovy compiler and
    /// runtime JARs (`org.apache.groovy:groovy:VERSION`).
    pub fn version(&self) -> &str {
        self.version.as_deref().unwrap_or(DEFAULT_GROOVY_VERSION)
    }
}

/// Default `spock-core` version resolved from Maven Central when `[spock]`
/// is present.  The version string includes a Groovy compatibility suffix
/// (e.g. `groovy-4.0`).  Override with:
///
/// ```toml
/// [spock]
/// version = "2.3-groovy-4.0"
/// ```
pub const DEFAULT_SPOCK_VERSION: &str = "2.4-groovy-5.0";

/// Configuration for the `[spock]` table.  The section's mere presence
/// (even with no keys) activates Spock support — `section_present` is set
/// by [`load`] from the raw TOML.
#[derive(Debug, Deserialize, Default, Clone)]
pub struct Spock {
    #[serde(default)]
    pub version: Option<String>,
    /// Explicit `enabled = true/false` from `[spock]`.  `None` when the key
    /// was absent → fall back to section presence.  Lets a workspace member
    /// write `enabled = false` to opt out of Spock that the workspace enabled.
    #[serde(default)]
    pub enabled: Option<bool>,
    /// `true` when the `[spock]` section appeared in `Curie.toml`.  Set by
    /// [`load`]; never written by serde.
    #[serde(skip)]
    pub section_present: bool,
}

impl Spock {
    pub fn version(&self) -> &str {
        self.version.as_deref().unwrap_or(DEFAULT_SPOCK_VERSION)
    }

    /// Resolved enabled state: an explicit `enabled` key wins, otherwise the
    /// mere presence of the `[spock]` section activates Spock.
    pub fn enabled(&self) -> bool {
        self.enabled.unwrap_or(self.section_present)
    }
}

#[derive(Debug, Deserialize)]
pub struct Docker {
    #[serde(rename = "baseImage", default = "default_base_image")]
    pub base_image: String,
    #[serde(rename = "imageName")]
    pub image_name: Option<String>,
    #[serde(rename = "imageTag")]
    pub image_tag: Option<String>,
    /// Tracks whether the [docker] section was explicitly present in Curie.toml.
    /// Set by Descriptor::load after deserialisation via a raw TOML check.
    #[serde(skip)]
    pub section_present: bool,
}

fn default_base_image() -> String {
    "eclipse-temurin:21-jre-alpine".to_string()
}

impl Default for Docker {
    fn default() -> Self {
        Docker {
            base_image: default_base_image(),
            image_name: None,
            image_tag: None,
            section_present: false,
        }
    }
}

/// Controls generation of `META-INF/build-info.properties` inside the JAR.
///
/// By default (when the `[build-info]` section is absent) Curie generates the
/// file whenever the project directory is inside a Git repository.  Set
/// `enabled = false` to suppress it unconditionally.
///
/// ```toml
/// [build-info]
/// enabled = false
/// ```
#[derive(Debug, Deserialize)]
pub struct BuildInfo {
    /// `true` (default) — generate the file when Git information is available.
    /// `false` — never generate the file.
    #[serde(default = "default_build_info_enabled")]
    pub enabled: bool,
}

fn default_build_info_enabled() -> bool {
    true
}

impl Default for BuildInfo {
    fn default() -> Self {
        BuildInfo { enabled: true }
    }
}

/// `[publish]` — settings for `curie publish`.
///
/// All POM-metadata fields are optional in the type so that descriptors
/// without a `[publish]` section parse fine; they are validated at publish
/// time by `publish::validate_for_publish`.
#[derive(Debug, Deserialize, Default, Clone)]
pub struct PublishConfig {
    /// Named repository id from `[[repositories]]` to publish to.
    /// Mutually exclusive with [`url`].
    pub repository: Option<String>,
    /// Inline target URL.  Mutually exclusive with [`repository`].
    pub url: Option<String>,

    /// Default: GPG-sign every artifact.  Maven Central requires this.
    #[serde(default = "default_true")]
    pub sign: bool,
    /// Default: build a javadoc jar.  Maven Central requires this.
    #[serde(default = "default_true")]
    pub javadoc: bool,

    pub description: Option<String>,
    /// Project homepage for the POM `<url>` element.  Named `homepage` to
    /// disambiguate from the `url` field above (which is the publish target).
    pub homepage: Option<String>,
    #[serde(default)]
    pub licenses: Vec<String>,
    #[serde(default)]
    pub developers: Vec<Developer>,
    pub scm: Option<Scm>,
}

#[derive(Debug, Deserialize, Default, Clone)]
pub struct Developer {
    pub id: Option<String>,
    pub name: Option<String>,
    pub email: Option<String>,
}

#[derive(Debug, Deserialize, Default, Clone)]
pub struct Scm {
    pub url: Option<String>,
    pub connection: Option<String>,
    #[serde(rename = "developerConnection")]
    pub developer_connection: Option<String>,
}

fn default_true() -> bool {
    true
}

/// An additional Maven-compatible repository declared in `[[repositories]]`.
#[derive(Debug, Deserialize, Clone)]
pub struct RepositoryEntry {
    /// Unique identifier used when deps select this repo via `repository = "id"`.
    pub id: String,
    /// Human-readable display label.  Defaults to [`id`] when absent.
    pub name: Option<String>,
    pub url: String,
}

impl RepositoryEntry {
    pub fn display_name(&self) -> &str {
        self.name.as_deref().unwrap_or(&self.id)
    }
}

/// One value in `[dependencies]` or `[test-dependencies]`.
///
/// Two shapes accepted, via serde's untagged enum:
///
/// ```toml
/// # Shorthand: the value is just the version string.
/// "com.example:foo" = "1.2.3"
///
/// # Detailed: include an explicit repository id.
/// "net.example:bar" = { version = "2.0.0", repository = "my-repo" }
/// ```
#[derive(Debug, Deserialize, Clone)]
#[serde(untagged)]
pub enum DependencyValue {
    /// `"key" = "1.0.0"` shorthand form.
    Version(String),
    /// `"key" = { version = "1.0.0", repository = "id" }` detailed form.
    Detailed(DependencyDetailed),
}

#[derive(Debug, Deserialize, Clone)]
pub struct DependencyDetailed {
    pub version: String,
    /// Id of the repository to fetch this artifact from (must match a
    /// `[[repositories]]` entry's `id`).  When absent, Maven Central is used.
    #[serde(default)]
    pub repository: Option<String>,
}

impl DependencyValue {
    /// Version string as the user wrote it.  `""` means "supply via a BOM".
    pub fn version(&self) -> &str {
        match self {
            DependencyValue::Version(v) => v,
            DependencyValue::Detailed(d) => &d.version,
        }
    }

    /// Repository id override, if present.
    pub fn repository(&self) -> Option<&str> {
        match self {
            DependencyValue::Version(_) => None,
            DependencyValue::Detailed(d) => d.repository.as_deref(),
        }
    }
}

impl Descriptor {
    pub fn is_library(&self) -> bool {
        matches!(self.kind, DescriptorKind::Library(_))
    }

    /// Workspace roots are not themselves buildable — they list member
    /// directories whose own `Curie.toml` files are the buildable modules.
    pub fn is_workspace(&self) -> bool {
        matches!(self.kind, DescriptorKind::Workspace(_))
    }

    /// BOM projects produce a POM-only artifact with no JAR.
    pub fn is_bom(&self) -> bool {
        matches!(self.kind, DescriptorKind::Bom(_))
    }

    /// View the `[application]` section if this descriptor is one.
    pub fn application(&self) -> Option<&Application> {
        match &self.kind {
            DescriptorKind::Application(a) => Some(a),
            _ => None,
        }
    }

    /// View the `[workspace]` section if this descriptor is a workspace root.
    pub fn workspace(&self) -> Option<&Workspace> {
        match &self.kind {
            DescriptorKind::Workspace(w) => Some(w),
            _ => None,
        }
    }

    /// Short human-readable kind for `curie list` output and error messages.
    pub fn kind_label(&self) -> &'static str {
        match &self.kind {
            DescriptorKind::Application(_) => "application",
            DescriptorKind::Library(_) => "library",
            DescriptorKind::Workspace(_) => "workspace",
            DescriptorKind::Bom(_) => "bom",
        }
    }

    /// Project name.  `None` for a workspace root, which has no name of
    /// its own — only its members do.
    pub fn project_name(&self) -> Option<&str> {
        match &self.kind {
            DescriptorKind::Application(a) => Some(&a.name),
            DescriptorKind::Library(l) => Some(&l.name),
            DescriptorKind::Workspace(_) => None,
            DescriptorKind::Bom(b) => Some(&b.name),
        }
    }

    /// Maven `groupId`.  `None` for a workspace root and when the buildable
    /// section omitted the key.  `publish::validate_for_publish` errors on
    /// `None` for buildable projects.
    pub fn group_id(&self) -> Option<&str> {
        match &self.kind {
            DescriptorKind::Application(a) => a.group_id.as_deref(),
            DescriptorKind::Library(l) => l.group_id.as_deref(),
            DescriptorKind::Workspace(_) => None,
            DescriptorKind::Bom(b) => b.group_id.as_deref(),
        }
    }

    /// Project version.  `None` for a workspace root.
    pub fn project_version(&self) -> Option<&str> {
        match &self.kind {
            DescriptorKind::Application(a) => Some(&a.version),
            DescriptorKind::Library(l) => Some(&l.version),
            DescriptorKind::Workspace(_) => None,
            DescriptorKind::Bom(b) => Some(&b.version),
        }
    }

    /// Convenience: panic-with-context wrapper around [`project_name`]
    /// for use in build/test/compile paths where the caller knows the
    /// descriptor is buildable (those paths never run on a workspace
    /// root — workspaces are unwrapped to their members by `workspace::*`).
    ///
    /// Prefer matching on `kind` directly where ambiguity is possible.
    pub fn buildable_name(&self) -> &str {
        self.project_name()
            .expect("buildable_name() called on a workspace descriptor")
    }

    /// See [`buildable_name`]; same contract for the version.
    pub fn buildable_version(&self) -> &str {
        self.project_version()
            .expect("buildable_version() called on a workspace descriptor")
    }

    /// Resolved Docker image name: descriptor override or application name.
    /// Only meaningful for application descriptors; the helper falls back
    /// on `project_name()` which is `Some` for any buildable kind.
    pub fn image_name(&self) -> &str {
        self.docker
            .image_name
            .as_deref()
            .or_else(|| self.project_name())
            .expect("image_name() called on a workspace descriptor")
    }

    /// Resolved Docker image tag: descriptor override or application version.
    pub fn image_tag(&self) -> &str {
        self.docker
            .image_tag
            .as_deref()
            .or_else(|| self.project_version())
            .expect("image_tag() called on a workspace descriptor")
    }

    /// Full image reference, e.g. "hello-world:0.1.0".
    pub fn image_ref(&self) -> String {
        format!("{}:{}", self.image_name(), self.image_tag())
    }

    /// Parse `[bom-imports]` into a `Vec<curie_deps::Gav>` for the
    /// resolver, in priority-ascending order (later wins).
    ///
    /// Order:
    ///   1. workspace-inherited prod BOMs (lowest)
    ///   2. member's own prod BOMs (override 1)
    pub fn prod_bom_gavs(&self) -> anyhow::Result<Vec<curie_deps::Gav>> {
        let mut v: Vec<curie_deps::Gav> = self
            .inherited_bom_imports
            .iter()
            .map(|(k, ver)| curie_deps::Gav::from_key_version(k, ver))
            .collect::<anyhow::Result<_>>()
            .context("invalid coordinate in workspace [bom-imports]")?;
        let own: Vec<curie_deps::Gav> = self
            .bom_imports
            .iter()
            .map(|(k, ver)| curie_deps::Gav::from_key_version(k, ver))
            .collect::<anyhow::Result<_>>()
            .context("invalid coordinate in [bom-imports]")?;
        v.extend(own);
        Ok(v)
    }

    /// Parse `[bom-imports]` + `[test-bom-imports]` into a merged
    /// `Vec<curie_deps::Gav>` for the test resolver, priority-ascending.
    ///
    /// Order:
    ///   1. workspace-inherited prod BOMs (lowest)
    ///   2. member's own prod BOMs
    ///   3. workspace-inherited test BOMs
    ///   4. member's own test BOMs (highest)
    pub fn test_bom_gavs(&self) -> anyhow::Result<Vec<curie_deps::Gav>> {
        let mut v = self.prod_bom_gavs()?;
        let inherited_test: Vec<curie_deps::Gav> = self
            .inherited_test_bom_imports
            .iter()
            .map(|(k, ver)| curie_deps::Gav::from_key_version(k, ver))
            .collect::<anyhow::Result<_>>()
            .context("invalid coordinate in workspace [test-bom-imports]")?;
        v.extend(inherited_test);
        let own_test: Vec<curie_deps::Gav> = self
            .test_bom_imports
            .iter()
            .map(|(k, ver)| curie_deps::Gav::from_key_version(k, ver))
            .collect::<anyhow::Result<_>>()
            .context("invalid coordinate in [test-bom-imports]")?;
        v.extend(own_test);
        Ok(v)
    }

    /// `(group:artifact, version)` pairs for production annotation
    /// processors, in the order the resolver wants: workspace-inherited
    /// first, then member-declared.  On a collision (same coordinate
    /// declared in both), the member-declared one wins — its entry is
    /// later in the returned Vec.
    pub fn ap_pairs(&self) -> Vec<(&str, &str)> {
        ap_pairs_merged(&self.inherited_annotation_processors, &self.annotation_processors)
    }

    /// Same as [`ap_pairs`] for `[test-annotation-processors]`.
    pub fn test_ap_pairs(&self) -> Vec<(&str, &str)> {
        ap_pairs_merged(
            &self.inherited_test_annotation_processors,
            &self.test_annotation_processors,
        )
    }

    /// `group:artifact` strings of AP entries marked
    /// `on-compile-classpath = true`.  These coordinates also need to be
    /// resolved (already done as part of `ap_pairs`) and added to javac's
    /// `-cp` so user code can reference their annotation types.
    ///
    /// Test entries are merged in too: a Lombok-style processor declared
    /// only in `[test-annotation-processors]` should be visible on test
    /// compile's `-cp`.
    pub fn ap_on_compile_classpath_coords(&self) -> Vec<&str> {
        let mut out: Vec<&str> = Vec::new();
        for map in [&self.inherited_annotation_processors, &self.annotation_processors] {
            for (k, v) in map {
                if v.on_compile_classpath() {
                    out.push(k.as_str());
                }
            }
        }
        out
    }

    /// Same as [`ap_on_compile_classpath_coords`] but covers
    /// test-annotation-processors too.  Used by test compile.
    pub fn test_ap_on_compile_classpath_coords(&self) -> Vec<&str> {
        let mut out = self.ap_on_compile_classpath_coords();
        for map in [
            &self.inherited_test_annotation_processors,
            &self.test_annotation_processors,
        ] {
            for (k, v) in map {
                if v.on_compile_classpath() {
                    out.push(k.as_str());
                }
            }
        }
        out
    }

    /// Flatten the nested production-AP options into the `<prefix>.<key> = <value>`
    /// list javac wants on `-A`.  Inherited options come first; member
    /// entries override per (prefix, key).
    pub fn flat_ap_options(&self) -> Vec<(String, String)> {
        flatten_ap_options(
            &self.inherited_annotation_processor_options,
            &self.annotation_processor_options,
        )
    }

    /// Same as [`flat_ap_options`] for test-compile.  Test options layer
    /// on top of production options (a test-only override beats both).
    pub fn flat_test_ap_options(&self) -> Vec<(String, String)> {
        let mut merged = self.flat_ap_options();
        let test = flatten_ap_options(
            &self.inherited_test_annotation_processor_options,
            &self.test_annotation_processor_options,
        );
        // Test entries with the same `prefix.key` override production.
        for (k, v) in test {
            if let Some(existing) = merged.iter_mut().find(|(ek, _)| ek == &k) {
                existing.1 = v;
            } else {
                merged.push((k, v));
            }
        }
        merged
    }
}

/// Concatenate two AP maps in inherited-then-own order.  When the same
/// coordinate appears in both, the own-map entry is emitted (the
/// inherited one is dropped) so callers see exactly one resolve target.
fn ap_pairs_merged<'a>(
    inherited: &'a BTreeMap<String, AnnotationProcessor>,
    own: &'a BTreeMap<String, AnnotationProcessor>,
) -> Vec<(&'a str, &'a str)> {
    let mut out: Vec<(&'a str, &'a str)> = Vec::with_capacity(inherited.len() + own.len());
    for (k, v) in inherited {
        if !own.contains_key(k) {
            out.push((k.as_str(), v.version()));
        }
    }
    for (k, v) in own {
        out.push((k.as_str(), v.version()));
    }
    out
}

/// Two-pass merge of nested option tables, then flatten to
/// `("prefix.key", "value")` pairs ready for `-A`.
fn flatten_ap_options(
    inherited: &BTreeMap<String, BTreeMap<String, String>>,
    own: &BTreeMap<String, BTreeMap<String, String>>,
) -> Vec<(String, String)> {
    let mut merged: BTreeMap<String, BTreeMap<String, String>> = inherited.clone();
    for (prefix, inner) in own {
        let dst = merged.entry(prefix.clone()).or_default();
        for (k, v) in inner {
            dst.insert(k.clone(), v.clone());
        }
    }
    let mut out: Vec<(String, String)> = Vec::new();
    for (prefix, inner) in &merged {
        for (k, v) in inner {
            out.push((format!("{}.{}", prefix, k), v.clone()));
        }
    }
    out
}

pub fn load(project_root: &Path) -> Result<Descriptor> {
    let path = project_root.join("Curie.toml");

    if !path.exists() {
        bail!(
            "no Curie.toml found in {}",
            project_root.display()
        );
    }

    let content = std::fs::read_to_string(&path)
        .with_context(|| format!("failed to read {}", path.display()))?;

    // Detect which top-level sections are explicitly present via a raw
    // first-pass parse.  We can't infer this from the deserialised
    // RawDescriptor alone because `[docker]` with no fields would still
    // populate a default Docker struct — but its absence in the user's
    // file is meaningful (Docker is off unless [docker] OR a project
    // root Dockerfile exists).
    let raw: toml::Value = toml::from_str(&content)
        .map_err(|e| format_parse_error(e, &content, &path))?;
    let table = raw.as_table();
    let docker_section_present = table.map(|t| t.contains_key("docker")).unwrap_or(false);

    let parsed: RawDescriptor = toml::from_str(&content)
        .map_err(|e| format_parse_error(e, &content, &path))?;

    // Exactly one of [application] / [library] / [workspace] / [bom] — enforced
    // both as a count check (for the diagnostic message) and by reifying
    // the kind into the DescriptorKind enum.
    let kind = match (parsed.application, parsed.library, parsed.workspace, parsed.bom) {
        (Some(a), None, None, None) => DescriptorKind::Application(a),
        (None, Some(l), None, None) => DescriptorKind::Library(l),
        (None, None, Some(w), None) => DescriptorKind::Workspace(w),
        (None, None, None, Some(b)) => DescriptorKind::Bom(b),
        (None, None, None, None) => bail!(
            "Curie.toml must contain one of [application], [library], [workspace], or [bom]"
        ),
        _ => bail!(
            "Curie.toml must contain only one of [application], [library], [workspace], or [bom]"
        ),
    };

    let mut docker = parsed.docker;
    docker.section_present = docker_section_present;

    let native_image_section_present = table.map(|t| t.contains_key("native-image")).unwrap_or(false);
    let mut native_image = parsed.native_image;
    native_image.section_present = native_image_section_present;

    let spock_section_present = table.map(|t| t.contains_key("spock")).unwrap_or(false);
    let mut spock = parsed.spock;
    spock.section_present = spock_section_present;

    let descriptor = Descriptor {
        kind,
        java: parsed.java,
        test: parsed.test,
        kotlin: parsed.kotlin,
        groovy: parsed.groovy,
        spock,
        native_image,
        docker,
        build_info: parsed.build_info,
        dependencies: parsed.dependencies,
        test_dependencies: parsed.test_dependencies,
        repositories: parsed.repositories,
        bom_imports: parsed.bom_imports,
        test_bom_imports: parsed.test_bom_imports,
        inherited_bom_imports: BTreeMap::new(),
        inherited_test_bom_imports: BTreeMap::new(),
        workspace_dependencies: parsed.workspace_dependencies,
        annotation_processors: parsed.annotation_processors,
        test_annotation_processors: parsed.test_annotation_processors,
        inherited_annotation_processors: BTreeMap::new(),
        inherited_test_annotation_processors: BTreeMap::new(),
        annotation_processor_options: parsed.annotation_processor_options,
        test_annotation_processor_options: parsed.test_annotation_processor_options,
        inherited_annotation_processor_options: BTreeMap::new(),
        inherited_test_annotation_processor_options: BTreeMap::new(),
        publish: parsed.publish,
    };

    // Workspace-only restrictions: they describe member layout, not
    // build inputs of their own.  These checks need the now-built
    // `descriptor` because that's where the deserialised collections live.
    if descriptor.is_workspace() {
        if !descriptor.dependencies.is_empty() {
            bail!("workspace Curie.toml must not declare [dependencies] — declare them in each member");
        }
        if !descriptor.test_dependencies.is_empty() {
            bail!("workspace Curie.toml must not declare [test-dependencies] — declare them in each member");
        }
        if !descriptor.workspace_dependencies.is_empty() {
            bail!("workspace Curie.toml must not declare [workspace-dependencies] — declare them on each member");
        }
        if docker_section_present {
            bail!("workspace Curie.toml must not declare [docker] — declare it on each application member");
        }
    }

    // [workspace-dependencies] entries must be version-less.  The
    // depended-on member's own version is authoritative; declaring one
    // here is almost certainly Cargo muscle-memory and would silently
    // mask a version mismatch.
    for (label, dep) in &descriptor.workspace_dependencies {
        if dep.version.is_some() {
            bail!(
                "workspace-dependency \"{}\" must not declare a version — \
                 the depended-on member's own version is used.  Remove the \
                 `version` key from [workspace-dependencies.{}].",
                label, label,
            );
        }
        if dep.path.trim().is_empty() {
            bail!("workspace-dependency \"{}\" has an empty `path`", label);
        }
    }

    if descriptor.is_library() && docker_section_present {
        bail!(
            "library projects do not support Docker: remove the [docker] section from Curie.toml"
        );
    }

    if descriptor.is_library() && native_image_section_present {
        bail!(
            "library projects do not support native-image compilation: \
             remove the [native-image] section from Curie.toml"
        );
    }

    if descriptor.is_bom() {
        validate_bom_restrictions(&descriptor, docker_section_present, native_image_section_present,
            table.map(|t| t.contains_key("test")).unwrap_or(false),
            table.map(|t| t.contains_key("test-dependencies")).unwrap_or(false),
            table.map(|t| t.contains_key("test-bom-imports")).unwrap_or(false),
            table.map(|t| t.contains_key("annotation-processors")).unwrap_or(false),
            table.map(|t| t.contains_key("test-annotation-processors")).unwrap_or(false),
        )?;
    }

    validate_dep_repo_refs(&descriptor)?;

    Ok(descriptor)
}

/// Enforce restrictions that apply exclusively to BOM projects.
#[allow(clippy::too_many_arguments)]
fn validate_bom_restrictions(
    desc: &Descriptor,
    docker_present: bool,
    native_image_present: bool,
    test_present: bool,
    test_deps_present: bool,
    test_bom_imports_present: bool,
    annotation_processors_present: bool,
    test_annotation_processors_present: bool,
) -> Result<()> {
    if docker_present {
        bail!("BOM projects do not support Docker: remove the [docker] section from Curie.toml");
    }
    if native_image_present {
        bail!("BOM projects do not support native-image compilation: remove the [native-image] section from Curie.toml");
    }
    if test_present {
        bail!("BOM projects must not declare a [test] section");
    }
    if test_deps_present {
        bail!("BOM projects must not declare [test-dependencies]");
    }
    if test_bom_imports_present {
        bail!("BOM projects must not declare [test-bom-imports]");
    }
    if annotation_processors_present {
        bail!("BOM projects must not declare [annotation-processors]");
    }
    if test_annotation_processors_present {
        bail!("BOM projects must not declare [test-annotation-processors]");
    }
    for (coord, dep) in &desc.dependencies {
        if dep.version().is_empty() {
            bail!(
                "BOM dependency \"{}\" must have an explicit version; \
                 BOM-delegated versions (\"\") are not allowed in [bom] projects",
                coord
            );
        }
    }
    Ok(())
}

/// Validate that every `repository = "id"` reference in `[dependencies]` and
/// `[test-dependencies]` names a repository declared in `[[repositories]]`.
///
/// Called once at the end of single-module [`load`] and again after workspace
/// inheritance so workspace-level repos are visible.
pub fn validate_dep_repo_refs(desc: &Descriptor) -> Result<()> {
    let known_ids: std::collections::HashSet<&str> =
        desc.repositories.iter().map(|r| r.id.as_str()).collect();

    for (coord, dep) in &desc.dependencies {
        if let Some(repo_id) = dep.repository() {
            if !known_ids.contains(repo_id) {
                bail!(
                    "dependency \"{}\" references unknown repository \"{}\"; \
                     declare it with [[repositories]]",
                    coord, repo_id
                );
            }
        }
    }
    for (coord, dep) in &desc.test_dependencies {
        if let Some(repo_id) = dep.repository() {
            if !known_ids.contains(repo_id) {
                bail!(
                    "test-dependency \"{}\" references unknown repository \"{}\"; \
                     declare it with [[repositories]]",
                    coord, repo_id
                );
            }
        }
    }
    Ok(())
}

/// Returns true when Docker support is active:
/// either a [docker] section exists in Curie.toml (non-default base image or
/// explicit name/tag counts as intentional) OR a Dockerfile is present at the
/// project root.
pub fn docker_enabled(project_root: &Path, desc: &Descriptor) -> bool {
    desc.docker.section_present || project_root.join("Dockerfile").exists()
}

/// Native-image compilation is enabled when the `[native-image]` section is
/// explicitly present in `Curie.toml`.  Unlike Docker, there is no implicit
/// trigger (no Dockerfile analogue); the section must always be declared.
pub fn native_image_enabled(desc: &Descriptor) -> bool {
    desc.native_image.section_present
}

// ---------------------------------------------------------------------------
// Parse error formatting
// ---------------------------------------------------------------------------

/// Reformat a `toml::de::Error` into a contextual error with:
///   • a `failed to parse <path>` header
///   • the TOML source line with a caret pointing at the problem
///   • an optional actionable hint for common mistakes
///
/// `toml 0.8` already produces a multi-line display in the form:
///
///   TOML parse error at line N, column M
///     |
///   N | <source line>
///     | ^^^^^^^^^^^^
///   <message>
///
/// We keep that display but swap the generic first line for one that names
/// the file, and append a hint where the error message matches a known
/// pattern.
fn format_parse_error(err: toml::de::Error, _source: &str, path: &Path) -> anyhow::Error {
    let file_name = path
        .file_name()
        .map(|f| f.to_string_lossy().into_owned())
        .unwrap_or_else(|| path.to_string_lossy().into_owned());

    // toml's Display always starts with "TOML parse error at line N, column M".
    // Replace that prefix with one that names the file, keeping the rest of
    // the contextual block (the source line + caret) unchanged.
    let raw_display = err.to_string();
    let contextual = if let Some(rest) = raw_display.strip_prefix("TOML parse error at ") {
        // `rest` is now "line N, column M\n  |\nN | <src>\n  | ^^^^\n<msg>"
        // Reformat as "  --> <file>:N:M\n   |\n ..."
        let reformatted = rest
            .replacen("line ", "", 1)
            .replacen(", column ", ":", 1);
        format!(
            "failed to parse {}\n\n  --> {}:{}",
            path.display(),
            file_name,
            reformatted
        )
    } else {
        format!("failed to parse {}\n\n{}", path.display(), raw_display)
    };

    // Extract the bare error message (last non-empty line of toml's output).
    let message = raw_display
        .lines()
        .rev()
        .find(|l| !l.trim().is_empty())
        .unwrap_or("")
        .trim();

    // Append a hint for known, actionable error patterns.
    let hint = hint_for(message, &file_name);

    let full = if let Some(h) = hint {
        format!("{}\n\n  hint: {}", contextual, h)
    } else {
        contextual
    };

    anyhow::anyhow!("{}", full)
}

/// Return a hint string for well-known error messages, or `None` if the
/// error is already self-explanatory from the caret context alone.
fn hint_for(message: &str, _file_name: &str) -> Option<String> {
    // missing field `name` or `version` — could be in [application], [library], or [bom]
    if message.contains("missing field") && message.contains("name") {
        return Some(
            "[application], [library], and [bom] all require a `name` field.".to_string(),
        );
    }
    if message.contains("missing field") && message.contains("version") {
        return Some(
            "[application], [library], and [bom] all require a `version` field.".to_string(),
        );
    }

    // unknown field — suggest checking for typos
    if message.contains("unknown field") {
        return Some(
            "check for typos in field names; see the README for all supported fields.".to_string(),
        );
    }

    None
}

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

    /// Write `content` as Curie.toml under a fresh tempdir and call `load`.
    fn load_str(content: &str) -> Result<Descriptor> {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("Curie.toml"), content).unwrap();
        load(dir.path())
    }

    #[test]
    fn parse_workspace_with_members() {
        let toml = r#"
[workspace]
members = ["a", "b", "nested/c"]
"#;
        let d = load_str(toml).unwrap();
        assert!(d.is_workspace());
        assert_eq!(d.kind_label(), "workspace");
        let ws = d.workspace().expect("workspace section present");
        assert_eq!(ws.members, vec!["a", "b", "nested/c"]);
        // Workspaces have no project-level name or version.
        assert_eq!(d.project_name(), None);
        assert_eq!(d.project_version(), None);
    }

    #[test]
    fn parse_application_still_works() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
"#;
        let d = load_str(toml).unwrap();
        assert!(!d.is_workspace());
        assert_eq!(d.kind_label(), "application");
        assert_eq!(d.project_name(), Some("x"));
        assert_eq!(d.project_version(), Some("1.0"));
        assert!(d.application().is_some());
    }

    #[test]
    fn workspace_with_application_is_rejected() {
        let toml = r#"
[workspace]
members = ["a"]
[application]
name = "x"
version = "1.0"
"#;
        let err = load_str(toml).unwrap_err().to_string();
        assert!(err.contains("only one"), "got: {err}");
    }

    #[test]
    fn workspace_with_library_is_rejected() {
        let toml = r#"
[workspace]
members = ["a"]
[library]
name = "x"
version = "1.0"
"#;
        let err = load_str(toml).unwrap_err().to_string();
        assert!(err.contains("only one"), "got: {err}");
    }

    #[test]
    fn workspace_with_dependencies_is_rejected() {
        let toml = r#"
[workspace]
members = ["a"]
[dependencies]
"com.example:foo" = "1.0"
"#;
        let err = load_str(toml).unwrap_err().to_string();
        assert!(err.contains("[dependencies]"), "got: {err}");
    }

    #[test]
    fn workspace_with_docker_is_rejected() {
        let toml = r#"
[workspace]
members = ["a"]
[docker]
"#;
        let err = load_str(toml).unwrap_err().to_string();
        assert!(err.contains("[docker]"), "got: {err}");
    }

    #[test]
    fn workspace_allows_shared_java_and_repositories() {
        // These are inheritable config; workspace may carry them.
        let toml = r#"
[workspace]
members = ["a"]
[java]
sourceCompatibility = "17"
[[repositories]]
id = "nexus"
url = "https://example.com/m2"
"#;
        let d = load_str(toml).unwrap();
        assert_eq!(d.java.effective(), "17");
        assert_eq!(d.repositories.len(), 1);
        assert_eq!(d.repositories[0].id, "nexus");
    }

    #[test]
    fn empty_descriptor_is_rejected() {
        let err = load_str("").unwrap_err().to_string();
        assert!(err.contains("must contain one of"), "got: {err}");
    }

    // -- build-info ----------------------------------------------------------

    #[test]
    fn build_info_enabled_by_default() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
"#;
        let d = load_str(toml).unwrap();
        assert!(d.build_info.enabled, "build-info must be enabled by default");
    }

    #[test]
    fn build_info_can_be_disabled() {
        let toml = r#"
[application]
name = "x"
version = "1.0"

[build-info]
enabled = false
"#;
        let d = load_str(toml).unwrap();
        assert!(!d.build_info.enabled);
    }

    #[test]
    fn build_info_explicitly_enabled() {
        let toml = r#"
[application]
name = "x"
version = "1.0"

[build-info]
enabled = true
"#;
        let d = load_str(toml).unwrap();
        assert!(d.build_info.enabled);
    }

    // -- workspace-dependencies ---------------------------------------------

    #[test]
    fn parse_workspace_dependencies_path_only() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
mainClass = "X"
[workspace-dependencies]
core = { path = "../core" }
data = { path = "../sibling/data" }
"#;
        let d = load_str(toml).unwrap();
        let core = d.workspace_dependencies.get("core").unwrap();
        assert_eq!(core.path, "../core");
        assert!(core.version.is_none());
        assert_eq!(d.workspace_dependencies.len(), 2);
    }

    #[test]
    fn workspace_dependency_with_version_is_rejected() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
mainClass = "X"
[workspace-dependencies]
core = { path = "../core", version = "1.0" }
"#;
        let err = load_str(toml).unwrap_err().to_string();
        assert!(err.contains("must not declare a version"), "got: {err}");
        assert!(err.contains("core"), "got: {err}");
    }

    #[test]
    fn workspace_dependency_with_empty_path_is_rejected() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
mainClass = "X"
[workspace-dependencies]
core = { path = "" }
"#;
        let err = load_str(toml).unwrap_err().to_string();
        assert!(err.contains("empty `path`"), "got: {err}");
    }

    #[test]
    fn workspace_root_with_workspace_dependencies_is_rejected() {
        let toml = r#"
[workspace]
members = ["a"]
[workspace-dependencies]
core = { path = "../core" }
"#;
        let err = load_str(toml).unwrap_err().to_string();
        assert!(err.contains("[workspace-dependencies]"), "got: {err}");
    }

    // -- annotation-processors ----------------------------------------------

    #[test]
    fn parse_annotation_processors_both_forms() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
mainClass = "X"

[annotation-processors]
"com.google.dagger:dagger-compiler" = "2.50"
"org.projectlombok:lombok" = { version = "1.18.30", on-compile-classpath = true }
"#;
        let d = load_str(toml).unwrap();
        let dagger = d.annotation_processors.get("com.google.dagger:dagger-compiler").unwrap();
        assert_eq!(dagger.version(), "2.50");
        assert!(!dagger.on_compile_classpath());

        let lombok = d.annotation_processors.get("org.projectlombok:lombok").unwrap();
        assert_eq!(lombok.version(), "1.18.30");
        assert!(lombok.on_compile_classpath());
    }

    #[test]
    fn ap_pairs_returns_inherited_then_own() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
mainClass = "X"

[annotation-processors]
"own:proc" = "2.0"
"#;
        let mut d = load_str(toml).unwrap();
        // Simulate inheritance — what workspace::inherit_from_workspace
        // would do at member-load time.
        d.inherited_annotation_processors.insert(
            "ws:proc".into(),
            AnnotationProcessor::Version("1.0".into()),
        );
        let pairs = d.ap_pairs();
        assert_eq!(
            pairs,
            vec![("ws:proc", "1.0"), ("own:proc", "2.0")],
            "inherited entries should come first so own can override on collision",
        );
    }

    #[test]
    fn ap_pairs_own_overrides_inherited_on_same_coord() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
mainClass = "X"

[annotation-processors]
"shared:proc" = "2.0"
"#;
        let mut d = load_str(toml).unwrap();
        d.inherited_annotation_processors.insert(
            "shared:proc".into(),
            AnnotationProcessor::Version("1.0".into()),
        );
        let pairs = d.ap_pairs();
        // Inherited entry is dropped because member redeclared it.
        assert_eq!(pairs, vec![("shared:proc", "2.0")]);
    }

    #[test]
    fn test_ap_pairs_uses_test_table_only() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
mainClass = "X"

[annotation-processors]
"prod:proc" = "1.0"

[test-annotation-processors]
"test:proc" = "2.0"
"#;
        let d = load_str(toml).unwrap();
        // Prod path: only "prod:proc"
        assert_eq!(d.ap_pairs(), vec![("prod:proc", "1.0")]);
        // Test path: only "test:proc" (test_ap_pairs is just the test table;
        // compile.rs/test.rs concatenates the two when invoking javac).
        assert_eq!(d.test_ap_pairs(), vec![("test:proc", "2.0")]);
    }

    #[test]
    fn on_compile_classpath_coords_listed() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
mainClass = "X"

[annotation-processors]
"org.projectlombok:lombok" = { version = "1.18.30", on-compile-classpath = true }
"com.google.dagger:dagger-compiler" = "2.50"
"#;
        let d = load_str(toml).unwrap();
        let on_cp = d.ap_on_compile_classpath_coords();
        assert_eq!(on_cp, vec!["org.projectlombok:lombok"]);
    }

    // -- annotation-processor-options (nested form) ------------------------

    #[test]
    fn parse_nested_ap_options_emits_dotted_flags() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
mainClass = "X"

[annotation-processor-options.dagger]
fastInit = "enabled"
formatGeneratedSource = "disabled"

[annotation-processor-options.mapstruct]
suppressGeneratorTimestamp = "true"
"#;
        let d = load_str(toml).unwrap();
        let flat = d.flat_ap_options();
        // BTreeMap iteration is sorted, so flat is stable.
        assert_eq!(
            flat,
            vec![
                ("dagger.fastInit".to_string(), "enabled".to_string()),
                ("dagger.formatGeneratedSource".to_string(), "disabled".to_string()),
                ("mapstruct.suppressGeneratorTimestamp".to_string(), "true".to_string()),
            ],
        );
    }

    #[test]
    fn ap_options_inheritance_member_overrides_per_key() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
mainClass = "X"

[annotation-processor-options.dagger]
fastInit = "enabled"
"#;
        let mut d = load_str(toml).unwrap();
        // Simulate workspace-inherited options: a different `fastInit`
        // value PLUS a sibling key the member doesn't redeclare.
        let mut ws_dagger = BTreeMap::new();
        ws_dagger.insert("fastInit".to_string(), "disabled".to_string());
        ws_dagger.insert("formatGeneratedSource".to_string(), "disabled".to_string());
        d.inherited_annotation_processor_options.insert("dagger".to_string(), ws_dagger);

        let flat = d.flat_ap_options();
        // Member's `fastInit = enabled` wins over workspace's `disabled`.
        // Workspace's `formatGeneratedSource = disabled` survives because
        // the member didn't redeclare it.
        assert_eq!(
            flat,
            vec![
                ("dagger.fastInit".to_string(), "enabled".to_string()),
                ("dagger.formatGeneratedSource".to_string(), "disabled".to_string()),
            ],
        );
    }

    #[test]
    fn flat_test_ap_options_layers_test_on_top_of_prod() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
mainClass = "X"

[annotation-processor-options.dagger]
fastInit = "enabled"

[test-annotation-processor-options.dagger]
fastInit = "disabled"
"#;
        let d = load_str(toml).unwrap();
        // Production path: just fastInit=enabled.
        assert_eq!(
            d.flat_ap_options(),
            vec![("dagger.fastInit".to_string(), "enabled".to_string())],
        );
        // Test path: production options layered first, then test ones
        // override per (prefix, key).
        assert_eq!(
            d.flat_test_ap_options(),
            vec![("dagger.fastInit".to_string(), "disabled".to_string())],
        );
    }

    // -- [test] / [kotlin] tool version configuration -----------------------

    #[test]
    fn workspace_may_declare_test_and_kotlin_versions() {
        let toml = r#"
[workspace]
members = ["a"]

[test]
junitPlatformVersion = "6.0.3"

[kotlin]
version = "2.1.21"
"#;
        let d = load_str(toml).unwrap();
        assert!(d.is_workspace());
        assert_eq!(d.test.junit_platform_version(), "6.0.3");
        assert_eq!(d.kotlin.version(), "2.1.21");
    }

    #[test]
    fn test_and_kotlin_versions_inherit_from_workspace_when_omitted() {
        // Member has no [test] or [kotlin] — must pick up workspace values.
        let toml = r#"
[workspace]
members = ["member"]

[test]
junitPlatformVersion = "6.1.0"

[kotlin]
version = "2.2.0"
"#;
        let dir = tempfile::tempdir().unwrap();
        let ws_path = dir.path();
        std::fs::write(ws_path.join("Curie.toml"), toml).unwrap();
        std::fs::create_dir(ws_path.join("member")).unwrap();
        let member_toml = r#"
[application]
name = "member"
version = "0.0.0"
mainClass = "M"
"#;
        std::fs::write(ws_path.join("member").join("Curie.toml"), member_toml).unwrap();

        // Use the real workspace loading path (not the single-file load_str)
        // so inherit_from_workspace runs.
        let ws = crate::workspace::load(ws_path).unwrap();
        let member_desc = &ws.members[0].descriptor;
        assert_eq!(member_desc.test.junit_platform_version(), "6.1.0");
        assert_eq!(member_desc.kotlin.version(), "2.2.0");
    }

    #[test]
    fn member_version_overrides_workspace_version() {
        let toml = r#"
[workspace]
members = ["m"]

[test]
junitPlatformVersion = "6.0.3"

[kotlin]
version = "2.1.21"
"#;
        let dir = tempfile::tempdir().unwrap();
        let ws_path = dir.path();
        std::fs::write(ws_path.join("Curie.toml"), toml).unwrap();
        std::fs::create_dir(ws_path.join("m")).unwrap();
        let member_toml = r#"
[application]
name = "m"
version = "0.0.0"
mainClass = "M"

[test]
junitPlatformVersion = "6.5.0"

[kotlin]
version = "1.9.25"
"#;
        std::fs::write(ws_path.join("m").join("Curie.toml"), member_toml).unwrap();

        let ws = crate::workspace::load(ws_path).unwrap();
        let m = &ws.members[0].descriptor;
        assert_eq!(m.test.junit_platform_version(), "6.5.0");
        assert_eq!(m.kotlin.version(), "1.9.25");
    }

    #[test]
    fn tool_versions_fall_back_to_defaults_when_absent() {
        let toml = r#"
[application]
name = "x"
version = "0.1"
mainClass = "X"
"#;
        let d = load_str(toml).unwrap();
        assert_eq!(d.test.junit_platform_version(), crate::descriptor::DEFAULT_JUNIT_PLATFORM_VERSION);
        assert_eq!(d.kotlin.version(), crate::descriptor::DEFAULT_KOTLIN_VERSION);
    }

    // -- DependencyValue / RepositoryEntry ----------------------------------------

    #[test]
    fn parse_dependency_shorthand_form() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
[dependencies]
"com.example:foo" = "1.2.3"
"#;
        let d = load_str(toml).unwrap();
        let v = d.dependencies.get("com.example:foo").unwrap();
        assert_eq!(v.version(), "1.2.3");
        assert_eq!(v.repository(), None);
    }

    #[test]
    fn parse_dependency_detailed_form_without_repo() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
[dependencies]
"com.example:foo" = { version = "2.0.0" }
"#;
        let d = load_str(toml).unwrap();
        let v = d.dependencies.get("com.example:foo").unwrap();
        assert_eq!(v.version(), "2.0.0");
        assert_eq!(v.repository(), None);
    }

    #[test]
    fn parse_dependency_detailed_form_with_repo() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
[[repositories]]
id = "my-repo"
url = "https://repo.example.com/m2"
[dependencies]
"com.example:bar" = { version = "3.0.0", repository = "my-repo" }
"#;
        let d = load_str(toml).unwrap();
        let v = d.dependencies.get("com.example:bar").unwrap();
        assert_eq!(v.version(), "3.0.0");
        assert_eq!(v.repository(), Some("my-repo"));
    }

    #[test]
    fn dep_with_unknown_repo_id_is_rejected() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
[dependencies]
"com.example:foo" = { version = "1.0", repository = "does-not-exist" }
"#;
        let err = load_str(toml).unwrap_err().to_string();
        assert!(err.contains("does-not-exist"), "expected unknown-repo error, got: {err}");
        assert!(err.contains("[[repositories]]"), "should hint about [[repositories]], got: {err}");
    }

    #[test]
    fn dep_with_known_repo_id_is_accepted() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
[[repositories]]
id = "shibboleth"
url = "https://build.shibboleth.net/nexus/content/repositories/releases/"
[dependencies]
"net.shibboleth.oidc:oidc-common-crypto-api" = { version = "3.3.0", repository = "shibboleth" }
"#;
        let d = load_str(toml).unwrap();
        let v = d.dependencies.get("net.shibboleth.oidc:oidc-common-crypto-api").unwrap();
        assert_eq!(v.version(), "3.3.0");
        assert_eq!(v.repository(), Some("shibboleth"));
    }

    #[test]
    fn test_dep_with_unknown_repo_id_is_rejected() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
[test-dependencies]
"com.example:foo" = { version = "1.0", repository = "ghost" }
"#;
        let err = load_str(toml).unwrap_err().to_string();
        assert!(err.contains("ghost"), "expected unknown-repo error, got: {err}");
    }

    #[test]
    fn repository_entry_display_name_defaults_to_id() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
[[repositories]]
id = "shibboleth"
url = "https://example.com"
"#;
        let d = load_str(toml).unwrap();
        assert_eq!(d.repositories[0].display_name(), "shibboleth");
    }

    #[test]
    fn repository_entry_display_name_uses_name_when_set() {
        let toml = r#"
[application]
name = "x"
version = "1.0"
[[repositories]]
id = "shibboleth"
name = "Shibboleth Releases"
url = "https://example.com"
"#;
        let d = load_str(toml).unwrap();
        assert_eq!(d.repositories[0].id, "shibboleth");
        assert_eq!(d.repositories[0].display_name(), "Shibboleth Releases");
    }

    // -- [groovy] ---------------------------------------------------------------

    // -- [spock] ---------------------------------------------------------------

    #[test]
    fn spock_section_absent_is_disabled() {
        let toml = r#"
[application]
name = "x"
version = "0.1"
mainClass = "X"
"#;
        let d = load_str(toml).unwrap();
        assert!(!d.spock.enabled(), "absent [spock] must leave enabled = false");
    }

    #[test]
    fn spock_section_present_but_enabled_false_is_disabled() {
        let toml = r#"
[application]
name = "x"
version = "0.1"
mainClass = "X"

[spock]
enabled = false
"#;
        let d = load_str(toml).unwrap();
        assert!(!d.spock.enabled(), "explicit enabled=false must override section presence");
    }

    #[test]
    fn spock_section_present_is_enabled() {
        let toml = r#"
[application]
name = "x"
version = "0.1"
mainClass = "X"

[spock]
"#;
        let d = load_str(toml).unwrap();
        assert!(d.spock.enabled(), "[spock] present must set enabled = true");
        assert_eq!(d.spock.version(), crate::descriptor::DEFAULT_SPOCK_VERSION);
    }

    #[test]
    fn spock_version_can_be_set() {
        let toml = r#"
[application]
name = "x"
version = "0.1"
mainClass = "X"

[spock]
version = "2.4-groovy-4.0"
"#;
        let d = load_str(toml).unwrap();
        assert!(d.spock.enabled());
        assert_eq!(d.spock.version(), "2.4-groovy-4.0");
    }

    #[test]
    fn groovy_version_defaults_to_constant() {
        let toml = r#"
[application]
name = "x"
version = "0.1"
mainClass = "X"
"#;
        let d = load_str(toml).unwrap();
        assert_eq!(d.groovy.version(), crate::descriptor::DEFAULT_GROOVY_VERSION);
    }

    #[test]
    fn groovy_version_can_be_set() {
        let toml = r#"
[application]
name = "x"
version = "0.1"
mainClass = "X"

[groovy]
version = "3.0.22"
"#;
        let d = load_str(toml).unwrap();
        assert_eq!(d.groovy.version(), "3.0.22");
    }

    // -- enablePreview -------------------------------------------------------

    #[test]
    fn enable_preview_defaults_to_false() {
        let toml = r#"
[application]
name = "x"
version = "0.1"
mainClass = "X"
"#;
        let d = load_str(toml).unwrap();
        assert!(!d.java.preview_enabled(), "enablePreview must default to false");
        assert!(d.java.enable_preview.is_none(), "absent key must stay None for inheritance");
    }

    #[test]
    fn enable_preview_explicit_false_is_distinguished_from_absent() {
        let toml = r#"
[application]
name = "x"
version = "0.1"
mainClass = "X"

[java]
enablePreview = false
"#;
        let d = load_str(toml).unwrap();
        assert!(!d.java.preview_enabled());
        assert_eq!(d.java.enable_preview, Some(false), "explicit false must be Some(false), not None");
    }

    #[test]
    fn enable_preview_can_be_set_true() {
        let toml = r#"
[application]
name = "x"
version = "0.1"
mainClass = "X"

[java]
sourceCompatibility = "21"
enablePreview = true
"#;
        let d = load_str(toml).unwrap();
        assert!(d.java.preview_enabled());
        assert_eq!(d.java.effective(), "21");
    }

    // -- native-image --------------------------------------------------------

    #[test]
    fn native_image_absent_means_disabled() {
        let toml = r#"
[application]
name = "x"
version = "0.1"
mainClass = "X"
"#;
        let d = load_str(toml).unwrap();
        assert!(!d.native_image.section_present);
        assert!(!native_image_enabled(&d));
    }

    #[test]
    fn native_image_section_present_enables_it() {
        let toml = r#"
[application]
name = "x"
version = "0.1"
mainClass = "X"

[native-image]
"#;
        let d = load_str(toml).unwrap();
        assert!(d.native_image.section_present);
        assert!(native_image_enabled(&d));
    }

    #[test]
    fn native_image_output_name_defaults_to_app_name() {
        let toml = r#"
[application]
name = "my-app"
version = "0.1"
mainClass = "X"

[native-image]
"#;
        let d = load_str(toml).unwrap();
        assert_eq!(d.native_image.resolved_output_name("my-app"), "my-app");
    }

    #[test]
    fn native_image_output_name_override() {
        let toml = r#"
[application]
name = "my-app"
version = "0.1"
mainClass = "X"

[native-image]
outputName = "my-binary"
"#;
        let d = load_str(toml).unwrap();
        assert_eq!(d.native_image.output_name.as_deref(), Some("my-binary"));
        assert_eq!(d.native_image.resolved_output_name("my-app"), "my-binary");
    }

    #[test]
    fn native_image_config_dir_parsed() {
        let toml = r#"
[application]
name = "x"
version = "0.1"
mainClass = "X"

[native-image]
configDir = "src/main/resources/META-INF/native-image"
"#;
        let d = load_str(toml).unwrap();
        assert_eq!(
            d.native_image.config_dir.as_deref(),
            Some("src/main/resources/META-INF/native-image")
        );
    }

    #[test]
    fn native_image_extra_args_parsed() {
        let toml = r#"
[application]
name = "x"
version = "0.1"
mainClass = "X"

[native-image]
extraArgs = ["--no-fallback", "-H:+ReportExceptionStackTraces"]
"#;
        let d = load_str(toml).unwrap();
        assert_eq!(
            d.native_image.extra_args,
            vec!["--no-fallback", "-H:+ReportExceptionStackTraces"]
        );
    }

    #[test]
    fn native_image_on_library_is_rejected() {
        let toml = r#"
[library]
name = "x"
version = "0.1"

[native-image]
"#;
        let err = load_str(toml).unwrap_err().to_string();
        assert!(err.contains("library") && err.contains("native-image"), "got: {err}");
    }

    // -- [bom] ---------------------------------------------------------------

    #[test]
    fn parse_bom_section() {
        let toml = r#"
[bom]
name = "my-platform"
version = "1.0.0"
groupId = "com.example"
"#;
        let d = load_str(toml).unwrap();
        assert!(d.is_bom(), "should be recognised as a BOM project");
        assert_eq!(d.kind_label(), "bom");
        assert_eq!(d.project_name(), Some("my-platform"));
        assert_eq!(d.project_version(), Some("1.0.0"));
        assert_eq!(d.group_id(), Some("com.example"));
    }

    #[test]
    fn bom_with_docker_is_rejected() {
        let toml = r#"
[bom]
name = "x"
version = "0.1"
[docker]
"#;
        let err = load_str(toml).unwrap_err().to_string();
        assert!(err.contains("BOM") && err.contains("docker"), "got: {err}");
    }

    #[test]
    fn bom_with_test_dependencies_is_rejected() {
        let toml = r#"
[bom]
name = "x"
version = "0.1"
[test-dependencies]
"com.example:foo" = "1.0"
"#;
        let err = load_str(toml).unwrap_err().to_string();
        assert!(err.contains("BOM") && err.contains("test-dependencies"), "got: {err}");
    }

    #[test]
    fn bom_dep_without_explicit_version_is_rejected() {
        let toml = r#"
[bom]
name = "x"
version = "0.1"
[dependencies]
"com.example:foo" = ""
"#;
        let err = load_str(toml).unwrap_err().to_string();
        assert!(err.contains("explicit version"), "got: {err}");
        assert!(err.contains("com.example:foo"), "got: {err}");
    }

    #[test]
    fn bom_with_two_sections_is_rejected() {
        let toml = r#"
[bom]
name = "x"
version = "0.1"
[library]
name = "y"
version = "0.1"
"#;
        let err = load_str(toml).unwrap_err().to_string();
        assert!(err.contains("only one"), "got: {err}");
    }

    #[test]
    fn bom_with_explicit_deps_is_accepted() {
        let toml = r#"
[bom]
name = "my-platform"
version = "1.0.0"
groupId = "com.example"
[dependencies]
"com.google.guava:guava" = "33.0.0-jre"
[bom-imports]
"io.micronaut:micronaut-bom" = "4.3.2"
"#;
        let d = load_str(toml).unwrap();
        assert!(d.is_bom());
        assert_eq!(d.dependencies.len(), 1);
        assert_eq!(d.bom_imports.len(), 1);
    }
}

// ---------------------------------------------------------------------------
// Test helpers (available to sibling modules via `crate::descriptor::tests`)
// ---------------------------------------------------------------------------

/// Shared test helper: build a minimal BOM [`Descriptor`] with the given
/// coordinates, managed deps, BOM imports, and publish config.
#[cfg(test)]
pub(crate) fn fake_bom_desc(
    group_id: Option<&str>,
    name: &str,
    version: &str,
    dependencies: BTreeMap<String, DependencyValue>,
    bom_imports: BTreeMap<String, String>,
    publish: PublishConfig,
) -> Descriptor {
    Descriptor {
        kind: DescriptorKind::Bom(Bom {
            name: name.to_string(),
            version: version.to_string(),
            group_id: group_id.map(String::from),
        }),
        java: Java::default(),
        test: Test::default(),
        kotlin: Kotlin::default(),
        groovy: Groovy::default(),
        spock: Spock::default(),
        native_image: NativeImage::default(),
        docker: Docker::default(),
        build_info: BuildInfo::default(),
        dependencies,
        test_dependencies: BTreeMap::new(),
        repositories: vec![],
        bom_imports,
        test_bom_imports: BTreeMap::new(),
        inherited_bom_imports: BTreeMap::new(),
        inherited_test_bom_imports: BTreeMap::new(),
        workspace_dependencies: BTreeMap::new(),
        annotation_processors: BTreeMap::new(),
        test_annotation_processors: BTreeMap::new(),
        inherited_annotation_processors: BTreeMap::new(),
        inherited_test_annotation_processors: BTreeMap::new(),
        annotation_processor_options: BTreeMap::new(),
        test_annotation_processor_options: BTreeMap::new(),
        inherited_annotation_processor_options: BTreeMap::new(),
        inherited_test_annotation_processor_options: BTreeMap::new(),
        publish,
    }
}

/// Shared test helper: build a minimal library [`Descriptor`] with the given
/// coordinates and publish config.  Used by `pom_writer` and `publish` tests.
///
/// `group_id` is `Option<&str>` so callers that want to test the "missing
/// groupId" error path can pass `None`.
#[cfg(test)]
pub(crate) fn fake_library_desc(
    group_id: Option<&str>,
    name: &str,
    version: &str,
    publish: PublishConfig,
) -> Descriptor {
    use std::collections::BTreeMap;
    Descriptor {
        kind: DescriptorKind::Library(Library {
            name: name.to_string(),
            version: version.to_string(),
            group_id: group_id.map(String::from),
        }),
        java: Java::default(),
        test: Test::default(),
        kotlin: Kotlin::default(),
        groovy: Groovy::default(),
        spock: Spock::default(),
        native_image: NativeImage::default(),
        docker: Docker::default(),
        build_info: BuildInfo::default(),
        dependencies: BTreeMap::new(),
        test_dependencies: BTreeMap::new(),
        repositories: vec![],
        bom_imports: BTreeMap::new(),
        test_bom_imports: BTreeMap::new(),
        inherited_bom_imports: BTreeMap::new(),
        inherited_test_bom_imports: BTreeMap::new(),
        workspace_dependencies: BTreeMap::new(),
        annotation_processors: BTreeMap::new(),
        test_annotation_processors: BTreeMap::new(),
        inherited_annotation_processors: BTreeMap::new(),
        inherited_test_annotation_processors: BTreeMap::new(),
        annotation_processor_options: BTreeMap::new(),
        test_annotation_processor_options: BTreeMap::new(),
        inherited_annotation_processor_options: BTreeMap::new(),
        inherited_test_annotation_processor_options: BTreeMap::new(),
        publish,
    }
}