gwm-cli 1.6.1

git worktree manager — TUI + CLI, native libgit2, per-repo bootstrap
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
use gwm::config::{
  expand_placeholders, resolved_rows, review_tool_preset, BranchTypesSource, ClipboardMode, Config, ConfigRow,
  ConfigSource, MacroOpenMode, SidebarOrientation, SidebarPosition, TuiOpenMode, WorktreeConfig, CONFIG_FILE,
};
use tempfile::TempDir;

/// Process-global lock guarding every test in this binary that can **observe**
/// `$HOME`, not only the ones whose template mentions `{home}` (#503).
///
/// The narrower rule this doc used to state was the bug: `expand_placeholders`
/// resolves `dirs::home_dir` unconditionally, before it looks at a single
/// token (`src/config.rs`), so *every* call is a concurrent reader whatever
/// the pattern says. `set_var` is `unsafe` precisely because it races a
/// concurrent `getenv`, and a mutex only serialises the participants that take
/// it — so the rule has to be "can this test see `$HOME`?", which a reader
/// adding a test can answer, rather than "does this string contain `{home}`?",
/// which looks answerable and is not.
///
/// The other half of that rule is which functions can see `$HOME`, and the
/// note here used to answer it wrongly (#507): it claimed a layered load reads
/// it through `Config::load_layered`. It does not. `load_layered` and
/// `resolved_rows` take the global config path as a **parameter**, so they
/// resolve nothing; `Config::load_for_repo` is the one that calls
/// `global_config_path()`, and no test in this binary calls it. So
/// `expand_placeholders` is the only ambient reader reachable from here, and
/// #503 covered it completely.
///
/// The rule is no longer only stated: `tests/env_guard_invariant_tests.rs`
/// checks it by construction, for this binary and the three others that
/// rewrite an environment variable.
fn env_lock() -> &'static std::sync::Mutex<()> {
  static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
  LOCK.get_or_init(|| std::sync::Mutex::new(()))
}

#[cfg(unix)]
fn toml_absolute_path(unix: &'static str, _windows: &'static str) -> &'static str {
  unix
}

#[cfg(windows)]
fn toml_absolute_path(_unix: &'static str, windows: &'static str) -> &'static str {
  windows
}

// --- Labels section (issue #81) -----------------------------------------

#[test]
fn labels_default_is_empty() {
  // Absent `[[labels]]` block must resolve to an empty vec — never None or
  // a placeholder set. This is the "0 labels declared, nothing to push"
  // contract from the issue.
  let cfg = Config::default();
  assert!(cfg.labels.is_empty());
}

#[test]
fn labels_section_round_trips_through_toml() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[[labels]]
name = "bug"
description = "Something isn't working"
color = "d73a4a"

[[labels]]
name = "enhancement"
description = "New feature or request"

[[labels]]
name = "good first issue"
description = "Good for newcomers"
color = "7057ff"
"#,
  )
  .unwrap();

  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.labels.len(), 3);

  assert_eq!(cfg.labels[0].name, "bug");
  assert_eq!(cfg.labels[0].description.as_deref(), Some("Something isn't working"));
  assert_eq!(cfg.labels[0].color.as_deref(), Some("d73a4a"));

  assert_eq!(cfg.labels[1].name, "enhancement");
  // Omitted `color` reads as None — colour resolution happens later in the
  // labels module via deterministic hashing.
  assert_eq!(cfg.labels[1].color, None);

  // Names with whitespace must round-trip verbatim (issue mentioned
  // "good first issue" as the canary).
  assert_eq!(cfg.labels[2].name, "good first issue");
}

#[test]
fn labels_section_minimal_only_name_is_valid() {
  // `name` is the sole required field. Both `description` and `color`
  // are optional — gwm picks a deterministic colour and an empty
  // description for the latter.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[[labels]]
name = "wip"
"#,
  )
  .unwrap();

  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.labels.len(), 1);
  assert_eq!(cfg.labels[0].name, "wip");
  assert_eq!(cfg.labels[0].description, None);
  assert_eq!(cfg.labels[0].color, None);
}

#[test]
fn labels_load_rejects_leading_dash_name_at_load_time() {
  // Issue #100. A `[[labels]] name = "-h"` would be parsed by gh's
  // flag splitter and silently no-op the create call. The validation
  // runs in `Config::load_for_repo` so the user finds the offending
  // entry index in the error rather than discovering it through the
  // "0 created" mystery in the push report.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[worktree]
base = "/tmp/wt/{repo}"
path_pattern = "{type}-{issue}-{desc}"
branch_pattern = "{type}/#{issue}-{desc}"

[[labels]]
name = "-h"
"#,
  )
  .unwrap();

  let err = Config::load_layered(dir.path(), None).unwrap_err();
  let msg = format!("{}", err);
  assert!(
    msg.contains("labels[0]"),
    "error must surface the offending entry index; got: {}",
    msg
  );
  assert!(
    msg.contains("'-'") || msg.contains("- ") || msg.contains("\"-h\""),
    "error must explain the leading-dash refusal; got: {}",
    msg
  );
}

#[test]
fn labels_section_absent_keeps_empty_vec() {
  // Backwards-compatibility: a config defining only `[worktree]` (no
  // `[[labels]]`) must resolve to an empty list. Same contract as the
  // doctor / tui sections.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[worktree]
base = "/tmp/wt/{repo}"
path_pattern = "{type}-{issue}-{desc}"
branch_pattern = "{type}/#{issue}-{desc}"
"#,
  )
  .unwrap();

  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert!(cfg.labels.is_empty());
}

// --- Milestones section (issue #82) -------------------------------------

#[test]
fn milestones_default_is_empty() {
  // Absent `[[milestones]]` block must resolve to an empty vec. Same
  // "0 milestones declared, nothing to push" contract as labels.
  let cfg = Config::default();
  assert!(cfg.milestones.is_empty());
}

#[test]
fn milestones_section_round_trips_through_toml() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[[milestones]]
title = "v0.7.0"
description = "Configurability sprint"
due_on = "2026-07-15"
state = "open"

[[milestones]]
title = "v0.8.0"
due_on = "2026-10-01T17:00:00Z"

[[milestones]]
title = "v0.6.0"
state = "closed"
"#,
  )
  .unwrap();

  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.milestones.len(), 3);

  assert_eq!(cfg.milestones[0].title, "v0.7.0");
  assert_eq!(cfg.milestones[0].description.as_deref(), Some("Configurability sprint"));
  assert_eq!(cfg.milestones[0].due_on.as_deref(), Some("2026-07-15"));
  assert_eq!(cfg.milestones[0].state.as_deref(), Some("open"));

  assert_eq!(cfg.milestones[1].title, "v0.8.0");
  assert_eq!(cfg.milestones[1].description, None);
  // RFC3339 form round-trips verbatim — normalisation is the milestones
  // module's job, not the config loader's.
  assert_eq!(cfg.milestones[1].due_on.as_deref(), Some("2026-10-01T17:00:00Z"));
  assert_eq!(cfg.milestones[1].state, None);

  assert_eq!(cfg.milestones[2].title, "v0.6.0");
  assert_eq!(cfg.milestones[2].state.as_deref(), Some("closed"));
}

#[test]
fn milestones_section_minimal_only_title_is_valid() {
  // `title` is the sole required field. `description`, `due_on`, and
  // `state` are all optional; the module defaults `state` to "open"
  // and leaves the others as None.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[[milestones]]
title = "Backlog"
"#,
  )
  .unwrap();

  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.milestones.len(), 1);
  assert_eq!(cfg.milestones[0].title, "Backlog");
  assert_eq!(cfg.milestones[0].description, None);
  assert_eq!(cfg.milestones[0].due_on, None);
  assert_eq!(cfg.milestones[0].state, None);
}

#[test]
fn milestones_section_absent_keeps_empty_vec() {
  // Backwards-compatibility: a config with only `[worktree]` (no
  // `[[milestones]]`) must resolve to an empty list.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[worktree]
base = "/tmp/wt/{repo}"
path_pattern = "{type}-{issue}-{desc}"
branch_pattern = "{type}/#{issue}-{desc}"
"#,
  )
  .unwrap();

  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert!(cfg.milestones.is_empty());
}

#[test]
fn defaults_are_sane() {
  let cfg = Config::default();
  assert_eq!(cfg.worktree.branch_pattern, "{type}/#{issue}-{desc}");
  assert_eq!(cfg.worktree.path_pattern, "{type}-{issue}-{desc}");
  assert!(cfg.bootstrap.copy.is_empty());
  assert!(cfg.bootstrap.guard.is_empty());
  assert!(cfg.bootstrap.command.is_empty());
}

#[test]
fn doctor_section_defaults_to_dev_and_main() {
  // The hardcoded list previously living in `src/doctor.rs` is now a
  // configurable default — but the default value must stay
  // `["dev", "main"]` so existing repos see zero behaviour change.
  let cfg = Config::default();
  assert_eq!(cfg.doctor.trunks, vec!["dev".to_string(), "main".to_string()]);
}

#[test]
fn doctor_section_round_trips_through_toml() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[doctor]
trunks = ["master", "release-3.x", "release-4.x"]
"#,
  )
  .unwrap();

  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(
    cfg.doctor.trunks,
    vec![
      "master".to_string(),
      "release-3.x".to_string(),
      "release-4.x".to_string()
    ]
  );
}

#[test]
fn doctor_section_absent_keeps_defaults() {
  // A config that defines only `[worktree]` (no `[doctor]` section) must
  // still resolve `cfg.doctor.trunks` to the documented default — that's
  // the backwards-compatibility contract for repos predating the section.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[worktree]
base = "/tmp/wt/{repo}"
path_pattern = "{type}-{issue}-{desc}"
branch_pattern = "{type}/#{issue}-{desc}"
"#,
  )
  .unwrap();

  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.doctor.trunks, vec!["dev".to_string(), "main".to_string()]);
}

#[test]
fn doctor_section_empty_trunks_means_no_filter() {
  // An explicit empty list is a valid config choice — it tells doctor
  // "no merge filter, flag every gwm-style branch without a worktree".
  // Distinct from "section absent" (which falls back to defaults).
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[doctor]
trunks = []
"#,
  )
  .unwrap();

  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert!(cfg.doctor.trunks.is_empty());
}

#[test]
fn placeholders_expand() {
  let _guard = env_lock().lock().unwrap_or_else(|e| e.into_inner());
  let out = expand_placeholders(
    "{home}/cc-worktree/{repo}/{type}-{issue}-{desc}",
    "my-repo",
    Some("feat"),
    Some("123"),
    Some("foo"),
    None,
  )
  .unwrap();
  assert!(out.ends_with("/cc-worktree/my-repo/feat-123-foo"));
  assert!(!out.contains("{home}"));
  assert!(!out.contains("{repo}"));
}

#[test]
fn placeholders_no_optional_args_leave_repo_only() {
  let _guard = env_lock().lock().unwrap_or_else(|e| e.into_inner());
  let out = expand_placeholders("{home}/{repo}", "x", None, None, None, None).unwrap();
  assert!(out.ends_with("/x"));
}

#[test]
fn placeholders_expand_repo_path_and_parent() {
  let _guard = env_lock().lock().unwrap_or_else(|e| e.into_inner());
  let repo_path = std::path::Path::new("/Users/me/Projects/Perso/gwm-cli");
  // Derive the expected prefixes from `repo_path` itself rather than
  // duplicating the literal parent string — the contract under test is
  // "{repo_parent} → the repo's parent dir, {repo_path} → the repo dir".
  let parent = repo_path.parent().unwrap().to_string_lossy();
  let full_dir = repo_path.to_string_lossy();

  let out = expand_placeholders(
    "{repo_parent}/worktrees/{repo}-{type}-{issue}",
    "gwm-cli",
    Some("feat"),
    Some("42"),
    None,
    Some(repo_path),
  )
  .unwrap();
  assert_eq!(out, format!("{parent}/worktrees/gwm-cli-feat-42"));
  assert!(!out.contains("{repo_parent}"));

  let full = expand_placeholders("{repo_path}/.worktrees", "gwm-cli", None, None, None, Some(repo_path)).unwrap();
  assert_eq!(full, format!("{full_dir}/.worktrees"));
  assert!(!full.contains("{repo_path}"));
}

#[test]
fn placeholders_repo_path_tokens_left_literal_without_path() {
  let _guard = env_lock().lock().unwrap_or_else(|e| e.into_inner());
  // When no repo path is supplied the disk-path tokens are passed
  // through untouched rather than collapsing to an empty string.
  let out = expand_placeholders("{repo_parent}/x", "r", None, None, None, None).unwrap();
  assert_eq!(out, "{repo_parent}/x");
}

#[test]
fn load_returns_defaults_when_no_file() {
  let dir = TempDir::new().unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.worktree.branch_pattern, WorktreeConfig::default().branch_pattern);
}

#[test]
fn load_parses_repo_config() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[worktree]
base = "/tmp/wt/{repo}"
path_pattern = "{type}_{issue}_{desc}"
branch_pattern = "{type}/{issue}-{desc}"

[[bootstrap.copy]]
from = ".env"
to = ".env"
required = false
guards = ["safe-env"]

[[bootstrap.guard]]
name = "safe-env"
deny_patterns = ["secret"]
on_match = "abort"

[[bootstrap.command]]
name = "echo"
run = "echo hi"
"#,
  )
  .unwrap();

  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.worktree.base, "/tmp/wt/{repo}");
  assert_eq!(cfg.bootstrap.copy.len(), 1);
  assert_eq!(cfg.bootstrap.guard.len(), 1);
  assert_eq!(cfg.bootstrap.command.len(), 1);
  assert_eq!(cfg.bootstrap.guard[0].on_match, "abort");
  assert!(cfg.guard_by_name("safe-env").is_some());
  assert!(cfg.guard_by_name("nope").is_none());
}

#[test]
fn write_default_creates_file() {
  let dir = TempDir::new().unwrap();
  let path = Config::write_default(dir.path()).unwrap();
  assert!(path.exists());
  let raw = std::fs::read_to_string(&path).unwrap();
  assert!(raw.contains("[worktree]"));
}

#[test]
fn write_default_refuses_overwrite() {
  let dir = TempDir::new().unwrap();
  Config::write_default(dir.path()).unwrap();
  assert!(Config::write_default(dir.path()).is_err());
}

#[test]
fn malformed_config_returns_error() {
  let dir = TempDir::new().unwrap();
  std::fs::write(dir.path().join(CONFIG_FILE), "not valid toml [[[").unwrap();
  let res = Config::load_layered(dir.path(), None);
  assert!(res.is_err());
}

// Issue #30: the TUI confirm overlay has a configurable safety countdown
// when `delete_branch_on_remove` is armed. Default 3s (matches the
// example in the issue body); range 0..=5 where 0 means "no countdown —
// fall back to the classic single-keystroke confirm". Values above 5 are
// clamped on read so a misconfigured repo never strands a destructive
// action behind a 60s wait.

#[test]
fn tui_section_defaults_to_three_second_countdown() {
  let cfg = Config::default();
  assert_eq!(cfg.tui.confirm_countdown_secs, 3);
  assert_eq!(cfg.tui.effective_confirm_countdown_secs(), 3);
  assert_eq!(
    cfg.tui.auto_refresh_secs, 60,
    "TUI auto-refresh defaults to once per minute"
  );
}

#[test]
fn tui_section_absent_keeps_defaults() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[worktree]
base = "/tmp/wt/{repo}"
path_pattern = "{type}-{issue}-{desc}"
branch_pattern = "{type}/#{issue}-{desc}"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.tui.effective_confirm_countdown_secs(), 3);
}

#[test]
fn tui_sidebar_position_defaults_to_right() {
  // Pre-#188 behaviour: sidebar on the right. The default must hold so
  // existing users see no change until they set the knob or press `H`.
  let cfg = Config::default();
  assert_eq!(cfg.tui.sidebar_position, SidebarPosition::Right);
}

#[test]
fn tui_sidebar_position_absent_keeps_right() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui]
confirm_countdown_secs = 2
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.tui.sidebar_position, SidebarPosition::Right);
}

#[test]
fn tui_sidebar_position_parses_left() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui]
sidebar_position = "left"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.tui.sidebar_position, SidebarPosition::Left);
  assert!(cfg.tui.sidebar_position.is_left());
}

#[test]
fn tui_sidebar_orientation_defaults_to_stacked() {
  // #217 made `stacked` the launch layout: the status pane reads best
  // under the worktrees table where it gets the full width. Making the
  // orientation configurable (#365) must not move that default — the
  // `SidebarState::orientation` doc-comment claimed `auto` for two
  // releases, so pin the real value here rather than trust prose.
  let cfg = Config::default();
  assert_eq!(cfg.tui.sidebar_orientation, SidebarOrientation::Stacked);
}

#[test]
fn tui_sidebar_orientation_absent_keeps_stacked() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui]
confirm_countdown_secs = 2
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.tui.sidebar_orientation, SidebarOrientation::Stacked);
}

#[test]
fn tui_sidebar_orientation_parses_side_by_side() {
  // The hyphenated spelling is the contract: `rename_all = "lowercase"`
  // would deserialise this variant as `sidebyside`, the exact trap
  // `MacroOpenMode` hit on PR #292 (`mux_pane` → `muxpane`).
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui]
sidebar_orientation = "side-by-side"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.tui.sidebar_orientation, SidebarOrientation::SideBySide);
}

#[test]
fn tui_sidebar_orientation_parses_auto() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui]
sidebar_orientation = "auto"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.tui.sidebar_orientation, SidebarOrientation::Auto);
}

#[test]
fn tui_sidebar_orientation_serialises_back_to_its_label() {
  // The config panel writes the choice back as the label string, so the
  // serialised form and `label()` must agree or a panel edit would
  // produce a file that no longer loads.
  for orientation in [
    SidebarOrientation::Auto,
    SidebarOrientation::SideBySide,
    SidebarOrientation::Stacked,
  ] {
    let serialised = toml::Value::try_from(orientation).unwrap();
    assert_eq!(
      serialised.as_str(),
      Some(orientation.label()),
      "{orientation:?} must serialise as its status-bar label"
    );
  }
}

#[test]
fn tui_sidebar_orientation_invalid_value_errors_at_parse_time() {
  // Same contract as `tui.open.mode` and `sidebar_position`: an unknown
  // variant is a hard load error, never a silent fallback.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui]
sidebar_orientation = "diagonal"
"#,
  )
  .unwrap();
  assert!(Config::load_layered(dir.path(), None).is_err());
}

#[test]
fn tui_section_round_trips_through_toml() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui]
confirm_countdown_secs = 2
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.tui.confirm_countdown_secs, 2);
  assert_eq!(cfg.tui.effective_confirm_countdown_secs(), 2);
}

#[test]
fn tui_countdown_zero_disables_countdown() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui]
confirm_countdown_secs = 0
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.tui.effective_confirm_countdown_secs(), 0);
}

#[test]
fn tui_auto_refresh_zero_disables_periodic_refresh() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui]
auto_refresh_secs = 0
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.tui.auto_refresh_secs, 0);
}

#[test]
fn tui_auto_refresh_round_trips_through_toml() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui]
auto_refresh_secs = 15
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.tui.auto_refresh_secs, 15);
}

#[test]
fn tui_countdown_clamped_to_five_seconds() {
  // A user who types `confirm_countdown_secs = 30` in their .gwm.toml
  // wants more friction; we cap it at 5 so the destructive path is never
  // unreasonably slow. The raw field stays at the user's value (for
  // diagnostics / round-trip), only the accessor clamps.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui]
confirm_countdown_secs = 30
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.tui.confirm_countdown_secs, 30);
  assert_eq!(cfg.tui.effective_confirm_countdown_secs(), 5);
}

// Issue #75: configurable launchers for `l` (git_tui) and `R` (review).
// Two sibling sections share the same shape — `command` (shell line with
// placeholders) + `fullscreen` (suspend gwm TUI for TUI tools). The
// `[review]` section also takes a `tool = ...` sugar for built-in
// presets and a `skip_when_no_changes` knob (default true). Absent
// sections must keep gwm's previous behaviour: `l` → `lazygit -p {path}`
// fullscreen, `R` inert with a status-bar hint.

#[test]
fn git_tui_section_defaults_to_lazygit_preserving_legacy_behaviour() {
  // Backwards-compat contract: no `[git_tui]` in `.gwm.toml` must keep
  // the `l` keybinding pointed at `lazygit -p {path}` with fullscreen,
  // i.e. identical to the hardcoded behaviour before issue #75 landed.
  let cfg = Config::default();
  let r = cfg.git_tui.resolved();
  assert_eq!(r.command, "lazygit -p {path}");
  assert!(r.fullscreen, "lazygit is a TUI tool, gwm must suspend itself");
}

#[test]
fn git_tui_section_round_trips_through_toml() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[git_tui]
command = "gitui -d {path}"
fullscreen = true
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  let r = cfg.git_tui.resolved();
  assert_eq!(r.command, "gitui -d {path}");
  assert!(r.fullscreen);
}

#[test]
fn git_tui_can_opt_out_of_fullscreen() {
  // A user who wires `l` to launch a non-TUI editor (`code {path}`) needs
  // to keep gwm visible — fullscreen=false skips the suspend dance.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[git_tui]
command = "code {path}"
fullscreen = false
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  let r = cfg.git_tui.resolved();
  assert_eq!(r.command, "code {path}");
  assert!(!r.fullscreen);
}

#[test]
fn review_section_defaults_to_disabled_with_skip_true() {
  // No `[review]` block ⇒ `R` is inert; the TUI shows a status-bar
  // hint inviting the user to configure it. `skip_when_no_changes`
  // defaults to true so a deliberately-set-but-empty review run
  // doesn't shell out for nothing.
  let cfg = Config::default();
  assert!(
    cfg.review.resolved().is_none(),
    "default review must be inert until configured"
  );
  assert!(cfg.review.skip_when_no_changes);
  assert!(cfg.review.default_base.is_none());
  assert!(!cfg.review.has_shadowed_tool());
}

#[test]
fn review_section_explicit_command_wins() {
  // The primary contract: a free-form shell line. Placeholders are not
  // expanded here — that's the launcher module's job.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[review]
command = "my-review --base {base} --head {head}"
fullscreen = true
skip_when_no_changes = false
default_base = "trunk"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  let r = cfg.review.resolved().expect("explicit command must resolve");
  assert_eq!(r.command, "my-review --base {base} --head {head}");
  assert!(r.fullscreen);
  assert!(!cfg.review.skip_when_no_changes);
  assert_eq!(cfg.review.default_base.as_deref(), Some("trunk"));
}

#[test]
fn review_section_tool_preset_lumen_resolves_to_fullscreen_diff() {
  // `tool = "lumen"` is the canonical example from the issue.
  // Resolves to `lumen diff {base}..{head}` with fullscreen=true
  // because lumen is a ratatui TUI like gwm itself.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[review]
tool = "lumen"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  let r = cfg.review.resolved().expect("lumen preset must resolve");
  assert_eq!(r.command, "lumen diff {base}..{head}");
  assert!(r.fullscreen, "lumen is a TUI — gwm must suspend itself");
}

#[test]
fn review_tool_preset_table_covers_documented_set() {
  // Pin the canonical table the docs / SKILL.md reference. A regression
  // that renames or drops one of these would break the docs silently.
  assert_eq!(review_tool_preset("lumen"), Some(("lumen diff {base}..{head}", true)));
  assert_eq!(
    review_tool_preset("claude"),
    Some(("claude --print 'review the diff {base}..{head}'", false))
  );
  assert_eq!(
    review_tool_preset("codex"),
    Some(("codex review {base}..{head}", false))
  );
  assert_eq!(
    review_tool_preset("aider"),
    Some(("aider --message 'review {base}..{head}'", true))
  );
  assert_eq!(review_tool_preset("gh"), Some(("gh pr view --web", false)));
  assert_eq!(review_tool_preset("unknown"), None);
}

#[test]
fn review_unknown_tool_resolves_to_none() {
  // Unknown preset is a soft no-op — the resolved launcher is `None` so
  // the TUI can surface a status-bar hint instead of crashing.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[review]
tool = "made-up"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert!(
    cfg.review.resolved().is_none(),
    "unknown preset must not silently fall back to a real tool"
  );
}

#[test]
fn review_command_overrides_tool() {
  // Both `command` and `tool` set ⇒ command wins. The user can still
  // detect the shadow via `has_shadowed_tool()` for a startup warning.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[review]
tool = "lumen"
command = "my-bot --diff-file {diff}"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  let r = cfg.review.resolved().unwrap();
  assert_eq!(
    r.command, "my-bot --diff-file {diff}",
    "`command` must override `tool` when both are set"
  );
  assert!(cfg.review.has_shadowed_tool());
}

#[test]
fn review_fullscreen_overrides_preset_default() {
  // The preset for `tool = "lumen"` defaults fullscreen=true. The user
  // must be able to opt out per-repo (e.g. running lumen in a tmux pane).
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[review]
tool = "lumen"
fullscreen = false
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  let r = cfg.review.resolved().unwrap();
  assert!(
    !r.fullscreen,
    "explicit fullscreen=false must override the preset default"
  );
}

#[test]
fn tui_countdown_value_above_u8_max_still_clamps() {
  // Regression for Copilot review on PR #66: the documented contract is
  // "values above 5 are clamped on read". A `u8` field would cap at 255
  // *at parse time*, turning a typo like `confirm_countdown_secs = 300`
  // into a hard `Config::load_for_repo` error instead of the documented
  // clamp-to-5. The field must accept any non-negative integer so the
  // promise stays whole.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui]
confirm_countdown_secs = 300
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).expect("300 must parse, not error");
  assert_eq!(cfg.tui.effective_confirm_countdown_secs(), 5);
}

// Issue #73: [tui.open] table. The `o` key in the TUI dispatches to one of
// three behaviours (shell-in-worktree, editor, OS file manager) decided by
// config. Default is `shell` — lazygit-style — to match the worktree-manager
// workflow ("I want to *do work* in this worktree").

#[test]
fn tui_open_section_defaults_to_shell_mode() {
  let cfg = Config::default();
  assert_eq!(cfg.tui.open.mode, TuiOpenMode::Shell);
  assert!(cfg.tui.open.shell_cmd.is_none());
  assert!(cfg.tui.open.editor_cmd.is_none());
}

#[test]
fn tui_open_section_absent_keeps_defaults() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[worktree]
base = "/tmp/wt/{repo}"
path_pattern = "{type}-{issue}-{desc}"
branch_pattern = "{type}/#{issue}-{desc}"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.tui.open.mode, TuiOpenMode::Shell);
}

#[test]
fn tui_open_mode_editor_round_trips_through_toml() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.open]
mode = "editor"
editor_cmd = "hx"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.tui.open.mode, TuiOpenMode::Editor);
  assert_eq!(cfg.tui.open.editor_cmd.as_deref(), Some("hx"));
}

#[test]
fn tui_open_mode_finder_preserves_legacy_behaviour() {
  // Users who liked the pre-#73 default (`open` / `xdg-open` / `explorer`)
  // can opt back in. The variant is named `Finder` after the dominant macOS
  // use case but covers all three OS openers.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.open]
mode = "finder"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.tui.open.mode, TuiOpenMode::Finder);
}

#[test]
fn tui_open_mode_shell_with_custom_cmd_round_trips() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.open]
mode = "shell"
shell_cmd = "/usr/bin/fish"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.tui.open.mode, TuiOpenMode::Shell);
  assert_eq!(cfg.tui.open.shell_cmd.as_deref(), Some("/usr/bin/fish"));
}

#[test]
fn tui_open_mode_invalid_value_errors_at_parse_time() {
  // Unknown enum variants are a hard config error — we can't silently fall
  // back to a default without confusing the user about which mode is active.
  // Document the supported set in the example file; bad values surface here.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.open]
mode = "neovim"
"#,
  )
  .unwrap();
  assert!(Config::load_layered(dir.path(), None).is_err());
}

// ---- [[branch_types]] (issue #80) ------------------------------------------

#[test]
fn branch_types_absent_falls_back_to_built_in_defaults() {
  // The zero-friction contract: a repo without `[[branch_types]]` in
  // its `.gwm.toml` (or with no config at all) keeps the historical
  // built-in list. The source must report `Default` so `gwm types` can
  // surface a truthful footer.
  let cfg = Config::default();
  let resolved = cfg.resolved_branch_types();
  assert_eq!(resolved.source, BranchTypesSource::Default);
  assert!(
    resolved.types.iter().any(|t| t.name == "feat"),
    "default list must include the legacy `feat` entry"
  );
  assert!(
    resolved.types.iter().any(|t| t.name == "hotfix"),
    "default list must include `hotfix` (regression guard against partial defaults)"
  );
}

#[test]
fn branch_types_parsed_from_toml_replaces_defaults() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[[branch_types]]
name = "feat"
description = "New feature implementation"

[[branch_types]]
name = "fix"
description = "Bug fix"

[[branch_types]]
name = "migration"
description = "Database migration"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  let resolved = cfg.resolved_branch_types();
  assert_eq!(resolved.source, BranchTypesSource::Config);
  let names: Vec<_> = resolved.types.iter().map(|t| t.name.as_str()).collect();
  assert_eq!(names, vec!["feat", "fix", "migration"]);
  // Built-in entries that aren't in the config are dropped — the user's
  // list is authoritative once they opt in.
  assert!(!names.contains(&"hotfix"));
  assert!(!names.contains(&"chore"));
}

#[test]
fn branch_types_empty_block_treated_as_absent() {
  // An empty TOML array (`branch_types = []`) is observationally
  // identical to omitting the section — neither should replace the
  // built-in defaults with an empty list (which would lock the user
  // out of `gwm create`).
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
branch_types = []
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  let resolved = cfg.resolved_branch_types();
  assert_eq!(resolved.source, BranchTypesSource::Default);
  assert!(!resolved.types.is_empty());
}

#[test]
fn branch_types_source_label_is_user_facing() {
  // Footer strings rendered by `gwm types` — pin them so a label tweak
  // shows up in code review instead of slipping through.
  assert_eq!(BranchTypesSource::Default.label(), "built-in defaults");
  assert_eq!(BranchTypesSource::Config.label(), ".gwm.toml");
}

#[test]
fn branch_types_empty_name_is_rejected_at_load() {
  // An empty `name = ""` would silently produce a worktree on a branch
  // called `/#123-foo` (no prefix) which git rejects with a cryptic
  // error several layers down. Surface it as a config error early.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[[branch_types]]
name = ""
description = "Whoops"
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).unwrap_err();
  let msg = format!("{}", err);
  assert!(msg.contains("branch_types"), "{msg}");
  assert!(msg.contains("empty"), "{msg}");
}

#[test]
fn branch_types_invalid_name_format_is_rejected_at_load() {
  // `parse_branch` (the reverse mapping used by `gwm switch`, the TUI
  // list, and every helper that recovers a `BranchSpec` from a free-
  // form branch name) requires `^[a-z]+/#…$`. Anything that doesn't
  // match the type segment regex must be rejected at load so the user
  // sees one config-time error instead of a tangle of runtime
  // failures across surfaces.
  for bad in ["Feat", "feat-1", "wip task", "fix!", "1fix", ""].iter() {
    let dir = TempDir::new().unwrap();
    std::fs::write(
      dir.path().join(CONFIG_FILE),
      format!(
        r#"
[[branch_types]]
name = "{}"
description = "x"
"#,
        bad
      ),
    )
    .unwrap();
    assert!(
      Config::load_layered(dir.path(), None).is_err(),
      "name = {:?} must be rejected at load",
      bad
    );
  }
}

#[test]
fn branch_types_duplicate_name_is_rejected_at_load() {
  // Two entries with the same name would non-deterministically
  // override each other downstream (and the `gwm types` listing would
  // confusingly print the same row twice). Fail fast at load.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[[branch_types]]
name = "feat"
description = "Feature"

[[branch_types]]
name = "feat"
description = "Different description for the same name"
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).unwrap_err();
  let msg = format!("{}", err);
  assert!(msg.contains("duplicate"), "{msg}");
  assert!(msg.contains("feat"), "{msg}");
}

#[test]
fn branch_types_valid_names_load_successfully() {
  // Sanity: the validator must accept the canonical built-in names
  // and a few realistic custom additions, otherwise it's too tight
  // and the loosening of the rule would have to happen in a follow-up.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[[branch_types]]
name = "feat"
description = "Feature"

[[branch_types]]
name = "migration"
description = "Database migration"

[[branch_types]]
name = "wip"
description = "Work in progress"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).expect("valid config must load");
  let names: Vec<_> = cfg.branch_types.iter().map(|t| t.name.as_str()).collect();
  assert_eq!(names, vec!["feat", "migration", "wip"]);
}

// --------------------------------------------------------------------------
// Issue #94 — bootstrap path-traversal closure: load-time validation.
// --------------------------------------------------------------------------
//
// `CopyStep.to`, `Guard.example_file`, and `FallbackContent.target` are
// joined onto `ctx.worktree` / `ctx.main_repo` and passed to `fs::copy` /
// `write_no_follow`. A `..` segment or an absolute path slips past `join`
// and lands outside the worktree tree — write-anywhere primitive on
// `step.to`, read-anywhere primitive on `example_file`. Reject both at
// config-load so the violation surfaces with the TOML key in the error
// rather than mid-bootstrap.

#[test]
fn load_rejects_traversal_in_copy_to() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[[bootstrap.copy]]
from = "Cargo.toml"
to   = "../../OWNED"
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("traversal must be rejected at load");
  let msg = format!("{}", err);
  assert!(
    msg.contains("bootstrap.copy") && msg.contains("to"),
    "error must name the offending field, got: {}",
    msg
  );
  assert!(
    msg.contains("..") || msg.contains("traversal") || msg.contains("outside"),
    "error must explain WHY (../traversal/outside), got: {}",
    msg
  );
}

#[test]
fn load_rejects_absolute_path_in_copy_to() {
  let dir = TempDir::new().unwrap();
  let absolute_path = toml_absolute_path("/etc/passwd", r#"C:\\Windows\\win.ini"#);
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    format!(
      r#"
[[bootstrap.copy]]
from = ".env"
to   = "{absolute_path}"
"#,
    ),
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("absolute path must be rejected at load");
  let msg = format!("{}", err);
  assert!(
    msg.contains("bootstrap.copy") && msg.contains("to"),
    "error must name the offending field, got: {}",
    msg
  );
  assert!(
    msg.contains("absolute") || msg.contains(absolute_path),
    "error must explain absolute path rejection, got: {}",
    msg
  );
}

#[test]
fn load_rejects_traversal_in_guard_example_file() {
  // The example_file is joined onto ctx.main_repo and read to seed the
  // worktree dst when a guard trips. `../sensitive` reads files outside
  // the main repo — info-leak primitive — and must be rejected.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[[bootstrap.guard]]
name           = "leaky"
deny_patterns  = ["amazonaws"]
on_match       = "seed-from-example"
example_file   = "../../../etc/passwd"
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("traversal in example_file must be rejected");
  let msg = format!("{}", err);
  assert!(
    msg.contains("guard") && msg.contains("example_file"),
    "error must name the offending field, got: {}",
    msg
  );
  assert!(
    msg.contains("..") || msg.contains("traversal") || msg.contains("outside"),
    "error must explain WHY, got: {}",
    msg
  );
}

#[test]
fn load_rejects_absolute_path_in_guard_example_file() {
  let dir = TempDir::new().unwrap();
  let absolute_path = toml_absolute_path("/etc/shadow", r#"C:\\Windows\\System32\\config\\SAM"#);
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    format!(
      r#"
[[bootstrap.guard]]
name           = "leaky"
deny_patterns  = ["amazonaws"]
on_match       = "seed-from-example"
example_file   = "{absolute_path}"
"#,
    ),
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("absolute example_file must be rejected");
  let msg = format!("{}", err);
  assert!(
    msg.contains("guard") && msg.contains("example_file"),
    "error must name the offending field, got: {}",
    msg
  );
  assert!(
    msg.contains("absolute") || msg.contains(absolute_path),
    "error must explain absolute path rejection, got: {}",
    msg
  );
}

#[test]
fn load_rejects_traversal_in_fallback_target() {
  // FallbackContent.target is declarative today (the runtime uses the
  // joined dst from CopyStep.to instead), but a `..` segment there
  // still misrepresents intent and is rejected for consistency with
  // the other two fields.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[bootstrap.fallback.env_testing]
target  = "../../OWNED"
content = "FOO=bar"
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("traversal in fallback.target must be rejected");
  let msg = format!("{}", err);
  assert!(
    msg.contains("fallback") && msg.contains("target"),
    "error must name the offending field, got: {}",
    msg
  );
}

// Issue #94 hardening surfaced by Copilot on PR #111: on Windows,
// drive-relative inputs like `C:foo` are NOT absolute per
// `Path::is_absolute()` but contain a `Component::Prefix` segment
// that makes `PathBuf::join` discard the worktree base. Reject them
// at load time. The test is gated to Windows because `Path::new` on
// Unix never synthesises a `Prefix` component from such inputs.
#[cfg(windows)]
#[test]
fn load_rejects_windows_drive_prefix_in_copy_to() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[[bootstrap.copy]]
from = ".env"
to   = "C:foo"
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("drive-prefixed path must be rejected at load");
  let msg = format!("{}", err);
  assert!(
    msg.contains("bootstrap.copy") && msg.contains("to"),
    "error must name the offending field, got: {}",
    msg
  );
  assert!(
    msg.contains("drive") || msg.contains("prefix") || msg.contains("C:foo"),
    "error must explain Windows drive prefix rejection, got: {}",
    msg
  );
}

#[test]
fn load_accepts_benign_relative_paths_in_bootstrap_fields() {
  // Positive control: a fully relative path with no `..` and no
  // leading slash must continue to load. This is the canonical shape
  // documented in `examples/gwm.toml.example`.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[[bootstrap.copy]]
from = ".env"
to   = "config/local.env"

[[bootstrap.guard]]
name          = "no-aws"
deny_patterns = ["amazonaws\\.com"]
on_match      = "seed-from-example"
example_file  = "config/local.env.example"

[bootstrap.fallback.env_testing]
target  = "config/local.env"
content = "X=1"
"#,
  )
  .unwrap();
  Config::load_layered(dir.path(), None).expect("benign relative paths must load");
}

// --- Issue #96: guard deny_patterns must compile at load time ---------------
//
// Historically `bootstrap.rs::guard_match` wrapped `Regex::new(pat)` in
// `if let Ok(re) = …`, silently dropping invalid patterns. A guard whose
// only deny pattern failed to compile became fail-open: the file copied
// through as if no rule existed. The contract of `[[bootstrap.guard]]`
// is a refusal mechanism — a silently broken refusal is strictly worse
// than no refusal, because the user believes they are protected. Reject
// invalid patterns at `Config::load_for_repo` so bootstrap never runs
// against a partially broken guard.

#[test]
fn load_rejects_invalid_deny_pattern_in_guard() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[[bootstrap.guard]]
name          = "no-secrets"
deny_patterns = ["[+", "AWS_SECRET_ACCESS_KEY"]
on_match      = "abort"
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("invalid deny_patterns must be rejected at load");
  let msg = format!("{}", err);
  assert!(
    msg.contains("no-secrets"),
    "error must name the offending guard, got: {}",
    msg
  );
  assert!(
    msg.contains("[+"),
    "error must quote the offending pattern, got: {}",
    msg
  );
  assert!(
    msg.contains("deny_pattern") || msg.contains("regex"),
    "error must explain WHY (regex/deny_pattern), got: {}",
    msg
  );
}

#[test]
fn load_rejects_invalid_deny_pattern_when_only_pattern_in_guard() {
  // Even when the *only* pattern is invalid, the guard must fail at
  // load — never silently degrade into a "guard with no patterns",
  // which would be fail-open under any input.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[[bootstrap.guard]]
name          = "broken"
deny_patterns = ["*foo"]
on_match      = "abort"
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("invalid sole deny pattern must be rejected at load");
  let msg = format!("{}", err);
  assert!(
    msg.contains("broken") && msg.contains("*foo"),
    "error must name guard + pattern, got: {}",
    msg
  );
}

#[test]
fn load_accepts_valid_deny_patterns() {
  // Positive control: every well-formed pattern continues to load.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[[bootstrap.guard]]
name          = "no-aws"
deny_patterns = ["amazonaws\\.com", "AKIA[0-9A-Z]{16}", "(?i)aws_secret"]
on_match      = "abort"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).expect("valid patterns must load");
  assert_eq!(cfg.bootstrap.guard.len(), 1);
  assert_eq!(cfg.bootstrap.guard[0].deny_patterns.len(), 3);
}

#[test]
fn validate_bootstrap_guards_directly_rejects_invalid_pattern_without_load_for_repo() {
  // Direct unit test on the helper, called against a `Config` value
  // built in code without ever touching `Config::load_for_repo`.
  // Locks in the helper's contract independently of the loader, so a
  // future refactor that removes the call site from `load_for_repo`
  // doesn't go unnoticed by only the integration suite.
  use gwm::config::{BootstrapConfig, Guard};
  let mut cfg = Config {
    bootstrap: BootstrapConfig {
      guard: vec![Guard {
        name: "direct-test".into(),
        deny_patterns: vec!["(unclosed-group".into()],
        on_match: "abort".into(),
        example_file: None,
      }],
      ..Default::default()
    },
    ..Default::default()
  };
  let err = cfg
    .validate_bootstrap_guards()
    .expect_err("direct call on hand-built Config with invalid pattern must Err");
  let msg = format!("{}", err);
  assert!(
    msg.contains("direct-test") && msg.contains("(unclosed-group"),
    "error must name guard + pattern, got: {}",
    msg
  );

  // Positive control: clear the bad pattern and the same helper must
  // accept the Config, even with a non-trivial pattern set.
  cfg.bootstrap.guard[0].deny_patterns = vec!["AKIA[0-9A-Z]{16}".into(), "(?i)secret".into()];
  cfg
    .validate_bootstrap_guards()
    .expect("valid patterns must pass direct validation");
}

#[test]
fn load_rejects_invalid_deny_pattern_in_second_guard() {
  // The validator must walk every guard, not just the first one. A
  // bad pattern in guard #2 must still surface at load.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[[bootstrap.guard]]
name          = "guard-one"
deny_patterns = ["amazonaws\\.com"]
on_match      = "abort"

[[bootstrap.guard]]
name          = "guard-two"
deny_patterns = ["[unclosed"]
on_match      = "abort"
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("invalid pattern in second guard must be rejected");
  let msg = format!("{}", err);
  assert!(
    msg.contains("guard-two") && msg.contains("[unclosed"),
    "error must name the offending guard + pattern, got: {}",
    msg
  );
  // The error must also surface the TOML coordinates of the failing
  // entry so the user can jump straight to `.gwm.toml` line without
  // grepping for the pattern content (mirrors `bootstrap.copy[N].to`).
  assert!(
    msg.contains("bootstrap.guard[1]") && msg.contains("deny_patterns[0]"),
    "error must locate the failing entry by index, got: {}",
    msg
  );
}

// --- PR template section (issue #84) ------------------------------------

#[test]
fn pr_template_defaults_are_empty() {
  // Without a [pr_template] block, both `default` and `by_type`
  // resolve to empty so `gwm pr` falls back to the GitHub-side
  // PULL_REQUEST_TEMPLATE.md (same as before #84).
  let dir = TempDir::new().unwrap();
  std::fs::write(dir.path().join(CONFIG_FILE), "").unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert!(cfg.pr_template.default.is_none());
  assert!(cfg.pr_template.by_type.is_empty());
}

#[test]
fn pr_template_section_round_trips_through_toml() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r###"
[pr_template]
default = ".github/pull_request_template.md"

[pr_template.by_type]
feat = { path = ".github/pr-templates/feat.md" }
fix = { path = ".github/pr-templates/fix.md" }

[pr_template.by_type.chore]
body = "## Summary\n{desc}\n\nCloses #{issue}\n"
"###,
  )
  .unwrap();

  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(
    cfg.pr_template.default.as_deref(),
    Some(".github/pull_request_template.md")
  );

  let feat = cfg.pr_template.by_type.get("feat").expect("feat entry");
  assert_eq!(feat.path.as_deref(), Some(".github/pr-templates/feat.md"));
  assert_eq!(feat.body, None);

  let chore = cfg.pr_template.by_type.get("chore").expect("chore entry");
  assert_eq!(chore.path, None);
  assert_eq!(chore.body.as_deref(), Some("## Summary\n{desc}\n\nCloses #{issue}\n"));
}

#[test]
fn pr_template_unknown_root_field_is_rejected() {
  // `[pr_template]` mirrors `[issue_template]`'s `deny_unknown_fields`
  // contract so typos surface at load time, not as a silent no-op.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[pr_template]
default = ".github/pull_request_template.md"
mystery = "boom"
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("unknown field must reject");
  let msg = format!("{}", err);
  assert!(msg.contains("mystery"), "{msg}");
}

#[test]
fn pr_template_unknown_per_type_field_is_rejected() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[pr_template.by_type.feat]
path = ".github/pr-templates/feat.md"
bogus = true
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("unknown per-type field must reject");
  let msg = format!("{}", err);
  assert!(msg.contains("bogus"), "{msg}");
}

// --- [tui.keys] section (issue #87) -------------------------------------

#[test]
fn tui_keys_default_is_empty_map() {
  // Absent `[tui.keys]` block resolves to an empty map — the keymap
  // layer then keeps every built-in default. Mirrors the `labels` /
  // `milestones` "no override declared" contract.
  let cfg = Config::default();
  assert!(cfg.tui.keys.raw.is_empty());
}

#[test]
fn tui_keys_section_round_trips_through_toml() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.keys]
down = ["j", "Ctrl+n"]
up   = ["k", "Ctrl+p"]
top  = ["g g"]
"#,
  )
  .unwrap();

  let cfg = Config::load_layered(dir.path(), None).unwrap();
  // The raw `[tui.keys]` table preserves the user's source verbatim
  // (issue #219 stores it as a `toml::Table` to also carry contextual
  // sub-tables); pull each chord list back out as strings.
  let chords = |slug: &str| -> Vec<String> {
    cfg
      .tui
      .keys
      .raw
      .get(slug)
      .and_then(|v| v.as_array())
      .map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect())
      .unwrap_or_default()
  };
  assert_eq!(chords("down"), vec!["j".to_string(), "Ctrl+n".to_string()]);
  assert_eq!(chords("up"), vec!["k".to_string(), "Ctrl+p".to_string()]);
  assert_eq!(chords("top"), vec!["g g".to_string()]);
}

#[test]
fn tui_keys_rejects_unknown_action_at_load_time() {
  // `gallop` is not in `keymap::ACTIONS`. The user almost certainly
  // typo'd a real action name; surfacing the error here saves a
  // mystifying "my binding does nothing in the TUI" round trip.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.keys]
gallop = ["g"]
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("unknown action must reject");
  let msg = format!("{}", err).to_lowercase();
  assert!(
    msg.contains("gallop"),
    "expected message to name the bad action, got: {msg}"
  );
  assert!(
    msg.contains("unknown"),
    "expected message to flag it as unknown, got: {msg}"
  );
}

#[test]
fn tui_keys_rejects_invalid_key_string() {
  // `Foobar` is not a named key and is not a single character. The
  // parser surfaces it as a config error.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.keys]
down = ["Foobar"]
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("invalid key string must reject");
  let msg = format!("{}", err).to_lowercase();
  assert!(
    msg.contains("foobar"),
    "expected message to name the bad key, got: {msg}"
  );
}

#[test]
fn tui_keys_rejects_chord_that_is_strict_prefix() {
  // Binding `g` alone while the default `g g` is still in place
  // creates a chord/prefix ambiguity. Per the design note on PR #87
  // this is a hard error at load — never a runtime timeout.
  let dir = TempDir::new().unwrap();
  // `terminal_fullscreen` replaces the old `open` slug (#290).
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.keys]
terminal_fullscreen = ["g"]
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("prefix collision must reject");
  let msg = format!("{}", err).to_lowercase();
  assert!(msg.contains("prefix"), "expected prefix error, got: {msg}");
}

#[test]
fn tui_keys_rejects_chord_conflict_across_actions() {
  // `down` and `up` both rebound to `x` — same chord, two actions,
  // ambiguous dispatch. Refuse at load time.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.keys]
down = ["x"]
up   = ["x"]
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("conflict must reject");
  let msg = format!("{}", err).to_lowercase();
  assert!(msg.contains("conflict"), "expected conflict error, got: {msg}");
}

#[test]
fn tui_keys_empty_binding_list_unbinds_action() {
  // `down = []` removes every binding for the `down` action. Useful
  // for users who prefer to navigate with the arrow keys only.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.keys]
down = []
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  let km = cfg.tui.keys.resolved_keymap().unwrap();
  use gwm::tui::keymap::{Action, ChordResolution, KeyStroke};
  let j = KeyStroke::parse_chord("j").unwrap();
  assert!(matches!(km.lookup(&j), ChordResolution::NoMatch));
  // The other defaults survive.
  let k = KeyStroke::parse_chord("k").unwrap();
  assert!(matches!(km.lookup(&k), ChordResolution::Matched(Action::Up)));
}

// --- [theme] section (issue #33) ----------------------------------------

#[test]
fn theme_default_is_pre_issue_33_scheme() {
  // No `[theme]` block → the resolved theme matches the pre-#33
  // hardcoded scheme verbatim. Pinned at the config layer so a
  // regression in the loader is caught here rather than as a
  // surprise palette in someone's screenshot.
  use ratatui::style::Color;
  let cfg = Config::default();
  let theme = cfg.theme.resolve().unwrap();
  assert_eq!(theme.focus, Color::Cyan);
  assert_eq!(theme.branch, Color::Green);
}

#[test]
fn theme_preset_is_applied_at_load() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[theme]
preset = "catppuccin"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  let theme = cfg.theme.resolve().unwrap();
  // Catppuccin's focus role differs from the default `Cyan` —
  // assert the difference rather than the specific hex to keep
  // the test resilient to upstream palette tweaks.
  use gwm::tui::theme::Theme;
  let default = Theme::default();
  assert_ne!(
    theme.focus, default.focus,
    "preset must override the default focus colour"
  );
}

#[test]
fn theme_per_role_overrides_win_over_preset() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[theme]
preset = "catppuccin"
focus  = "red"
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  let theme = cfg.theme.resolve().unwrap();
  use ratatui::style::Color;
  assert_eq!(theme.focus, Color::Red, "explicit override must win over the preset");
}

#[test]
fn theme_rejects_unknown_preset() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[theme]
preset = "does-not-exist"
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("unknown preset must reject");
  let msg = format!("{}", err).to_lowercase();
  assert!(msg.contains("does-not-exist"), "got: {msg}");
}

#[test]
fn theme_rejects_unknown_role() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[theme]
phantom = "red"
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("unknown role must reject");
  let msg = format!("{}", err).to_lowercase();
  assert!(msg.contains("phantom"), "got: {msg}");
}

#[test]
fn theme_rejects_bad_color_value() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[theme]
focus = "not_a_color"
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("invalid color must reject");
  let msg = format!("{}", err).to_lowercase();
  assert!(msg.contains("not_a_color"), "got: {msg}");
}

// --- Resolved config rows + source attribution (issue #232) -------------

fn row_for<'a>(rows: &'a [ConfigRow], key: &str) -> &'a ConfigRow {
  rows
    .iter()
    .find(|r| r.key == key)
    .unwrap_or_else(|| panic!("key {key:?} missing from resolved rows"))
}

#[test]
fn resolved_rows_attributes_each_key_to_its_winning_layer() {
  let repo = TempDir::new().unwrap();
  let global_dir = TempDir::new().unwrap();
  let global_path = global_dir.path().join("config.toml");

  // User (global) layer sets worktree.base AND tui.confirm_countdown_secs.
  std::fs::write(
    &global_path,
    "[worktree]\nbase = \"/tmp/global-wt\"\n[tui]\nconfirm_countdown_secs = 7\n",
  )
  .unwrap();
  // Repo layer overrides worktree.base only.
  std::fs::write(repo.path().join(CONFIG_FILE), "[worktree]\nbase = \"/tmp/repo-wt\"\n").unwrap();

  let rows = resolved_rows(repo.path(), Some(&global_path)).unwrap();

  // Repo wins on a key set in both layers, and the resolved value is the
  // repo's — identical formatting to `gwm config list`.
  let base = row_for(&rows, "worktree.base");
  assert_eq!(base.source, ConfigSource::Repo);
  assert_eq!(base.value, "\"/tmp/repo-wt\"");

  // The user layer provides a key the repo never mentions.
  let countdown = row_for(&rows, "tui.confirm_countdown_secs");
  assert_eq!(countdown.source, ConfigSource::User);
  assert_eq!(countdown.value, "7");

  // A key set in neither layer falls back to the built-in default.
  assert_eq!(row_for(&rows, "worktree.path_pattern").source, ConfigSource::Default);
}

#[test]
fn resolved_rows_with_no_files_marks_everything_default() {
  let repo = TempDir::new().unwrap();
  let rows = resolved_rows(repo.path(), None).unwrap();
  assert!(!rows.is_empty(), "defaults still produce rows");
  assert!(
    rows.iter().all(|r| r.source == ConfigSource::Default),
    "with no repo/global config every row is a built-in default"
  );
}

#[test]
fn resolved_rows_attributes_array_of_tables_entries() {
  // The common real-world shape is an array-of-tables (`[[labels]]`,
  // `[[branch_types]]`), where the merged value goes through serde's struct
  // serialisation and the raw layer through a bare file parse. This pins
  // that those key shapes (`labels[0].name`, …) match so a repo-declared
  // entry attributes to Repo rather than silently reading as a default.
  let repo = TempDir::new().unwrap();
  std::fs::write(
    repo.path().join(CONFIG_FILE),
    "[[labels]]\nname = \"bug\"\ncolor = \"d73a4a\"\n\n[[branch_types]]\nname = \"feat\"\ndescription = \"a feature\"\n",
  )
  .unwrap();

  let rows = resolved_rows(repo.path(), None).unwrap();

  assert_eq!(row_for(&rows, "labels[0].name").source, ConfigSource::Repo);
  assert_eq!(row_for(&rows, "labels[0].name").value, "\"bug\"");
  assert_eq!(row_for(&rows, "labels[0].color").source, ConfigSource::Repo);
  assert_eq!(row_for(&rows, "branch_types[0].name").source, ConfigSource::Repo);

  // An unset optional sub-field (`labels[0].description`) is omitted by the
  // TOML serialiser (Option::None), so it produces no phantom default row.
  assert!(
    !rows.iter().any(|r| r.key == "labels[0].description"),
    "unset optional sub-fields must not surface as default rows"
  );
}

#[test]
fn config_source_labels_are_stable() {
  assert_eq!(ConfigSource::Repo.label(), "repo");
  assert_eq!(ConfigSource::User.label(), "user");
  assert_eq!(ConfigSource::Default.label(), "default");
}

#[test]
fn macro_open_in_accepts_documented_pty_and_mux_pane_values() {
  // #290 / Codex review on PR #292: `MacroOpenMode` must deserialize the
  // documented `open_in = "mux_pane"` (snake_case) — under the earlier
  // `rename_all = "lowercase"` serde expected "muxpane" and a config
  // following the docs failed to load, taking the whole TUI down.
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.macro1]
command = "make test"
open_in = "mux_pane"

[tui.macro2]
command = "codex"
open_in = "pty"
"#,
  )
  .unwrap();

  let cfg = Config::load_layered(dir.path(), None).unwrap();
  let m1 = cfg.tui.macro1.expect("macro1 must parse");
  assert_eq!(m1.command, "make test");
  assert_eq!(m1.open_in, MacroOpenMode::MuxPane, "\"mux_pane\" must map to MuxPane");
  let m2 = cfg.tui.macro2.expect("macro2 must parse");
  assert_eq!(m2.open_in, MacroOpenMode::Pty, "\"pty\" must map to Pty");
}

#[test]
fn macro_open_in_defaults_to_pty_when_omitted() {
  // `open_in` is optional and defaults to Pty (the in-overlay mode).
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.macro1]
command = "lazygit"
"#,
  )
  .unwrap();

  let cfg = Config::load_layered(dir.path(), None).unwrap();
  let m1 = cfg.tui.macro1.expect("macro1 must parse");
  assert_eq!(m1.open_in, MacroOpenMode::Pty);
}

// --- [tui.keys.modal.<context>] contextual modal bindings (issue #219) ---

use crossterm::event::{KeyCode, KeyModifiers};
use gwm::tui::keymap::KeyStroke;
use gwm::tui::modal_keymap::{KeyContext, ModalAction};

fn ks(code: KeyCode) -> KeyStroke {
  KeyStroke::new(code, KeyModifiers::empty())
}
fn kc(c: char) -> KeyStroke {
  KeyStroke::new(KeyCode::Char(c), KeyModifiers::empty())
}

#[test]
fn modal_keys_nested_context_resolves() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.keys.modal.confirm]
confirm = ["o"]
cancel  = ["n", "Esc"]
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  let mk = cfg.tui.keys.resolved_modal_keymap().unwrap();
  // new key fires, old default `y` is gone
  assert_eq!(
    mk.resolve(KeyContext::Confirm, &kc('o')),
    Some(ModalAction::ConfirmConfirm)
  );
  assert_eq!(mk.resolve(KeyContext::Confirm, &kc('y')), None);
}

#[test]
fn modal_keys_link_stage_uses_dotted_table() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.keys.modal.link.choose_target]
issue = ["x"]

[tui.keys.modal.link.input_number]
submit = ["Right"]
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  let mk = cfg.tui.keys.resolved_modal_keymap().unwrap();
  assert_eq!(
    mk.resolve(KeyContext::LinkChooseTarget, &kc('x')),
    Some(ModalAction::LinkChooseIssue)
  );
  assert_eq!(
    mk.resolve(KeyContext::LinkInputNumber, &ks(KeyCode::Right)),
    Some(ModalAction::LinkInputSubmit)
  );
}

#[test]
fn modal_keys_config_edit_substage_resolves() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.keys.modal.config]
close = ["q"]

[tui.keys.modal.config.edit]
cancel = ["Tab"]
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  let mk = cfg.tui.keys.resolved_modal_keymap().unwrap();
  assert_eq!(mk.resolve(KeyContext::Config, &kc('q')), Some(ModalAction::ConfigClose));
  assert_eq!(
    mk.resolve(KeyContext::ConfigEdit, &ks(KeyCode::Tab)),
    Some(ModalAction::ConfigEditCancel)
  );
}

#[test]
fn modal_keys_global_and_contextual_coexist() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.keys]
quit = ["Q"]

[tui.keys.modal.confirm]
confirm = ["o"]
"#,
  )
  .unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  // global path sees the array entry
  let km = cfg.tui.keys.resolved_keymap().unwrap();
  assert_eq!(km.primary_chord(gwm::tui::keymap::Action::Quit).as_deref(), Some("Q"));
  // contextual path sees the table entry
  let mk = cfg.tui.keys.resolved_modal_keymap().unwrap();
  assert_eq!(
    mk.resolve(KeyContext::Confirm, &kc('o')),
    Some(ModalAction::ConfirmConfirm)
  );
}

#[test]
fn modal_namespace_does_not_collide_with_a_same_named_global_action() {
  // #219 review (P2): before the dedicated `[tui.keys.modal]` namespace, a
  // global `[tui.keys] create = ["c"]` and a modal `[tui.keys.create]` shared
  // the `tui.keys.create` path. The layered merge saw array-vs-table at the
  // same path, replaced the global array with the modal table, and silently
  // dropped the user's global override (`resolved_keymap` then skipped the
  // table). With the disjoint namespace the two live at different paths
  // (`tui.keys.create` vs `tui.keys.modal.create`) and both survive the merge.
  let global = TempDir::new().unwrap();
  let global_path = global.path().join("global.toml");
  std::fs::write(&global_path, "[tui.keys]\ncreate = [\"c\"]\n").unwrap();
  let repo = TempDir::new().unwrap();
  // `next_type` is the create verb bindable on a bare letter (it lives on
  // the typing-free Type field — reserved-typing rejection, #456 it. 14).
  std::fs::write(
    repo.path().join(CONFIG_FILE),
    "[tui.keys.modal.create]\nnext_type = [\"x\"]\n",
  )
  .unwrap();

  let cfg = Config::load_layered(repo.path(), Some(&global_path)).unwrap();

  // The global `create` override survives the merge (was silently lost before).
  let km = cfg.tui.keys.resolved_keymap().unwrap();
  assert_eq!(
    km.primary_chord(gwm::tui::keymap::Action::Create).as_deref(),
    Some("c"),
    "the global create override must survive a same-named modal context"
  );

  // ...and the modal `create.next_type` override resolves independently.
  let mk = cfg.tui.keys.resolved_modal_keymap().unwrap();
  assert_eq!(
    mk.resolve(KeyContext::Create, &kc('x')),
    Some(ModalAction::CreateNextType)
  );
}

#[test]
fn modal_keys_reject_unknown_context() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.keys.modal.confrm]
confirm = ["y"]
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("typo'd context must reject");
  assert!(err.to_string().contains("unknown modal context"), "{err}");
}

#[test]
fn modal_keys_reject_unknown_verb() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.keys.modal.confirm]
gallop = ["y"]
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("unknown verb must reject");
  assert!(err.to_string().contains("unknown verb"), "{err}");
}

#[test]
fn modal_keys_reject_multistroke_chord() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.keys.modal.confirm]
confirm = ["g g"]
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("modal chords must be single strokes");
  assert!(err.to_string().contains("single keystroke"), "{err}");
}

#[test]
fn modal_keys_reject_in_context_conflict() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.keys.modal.confirm]
confirm = ["x"]
cancel  = ["x"]
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("two verbs sharing a key must conflict");
  assert!(err.to_string().contains("conflict"), "{err}");
}

#[test]
fn modal_keys_reject_array_directly_under_group() {
  let dir = TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(CONFIG_FILE),
    r#"
[tui.keys.modal.link]
issue = ["i"]
"#,
  )
  .unwrap();
  let err = Config::load_layered(dir.path(), None).expect_err("link needs a stage");
  assert!(err.to_string().contains("context group"), "{err}");
}

// --- [exec] / [clean] profiles (issue #324) ---------------------------------

fn load_toml(body: &str) -> gwm::error::Result<Config> {
  let dir = TempDir::new().unwrap();
  std::fs::write(dir.path().join(CONFIG_FILE), body).unwrap();
  Config::load_layered(dir.path(), None)
}

#[test]
fn exec_and_clean_default_to_no_profiles() {
  // Absent `[exec]` / `[clean]` blocks resolve to empty profile maps — the
  // inline `gwm exec -- <cmd>` and built-in `gwm clean` surfaces are unchanged.
  let cfg = Config::default();
  assert!(cfg.exec.profiles.is_empty());
  assert!(cfg.clean.profiles.is_empty());
}

#[test]
fn exec_profiles_parse_command_as_an_argv_array() {
  let cfg = load_toml(
    r#"
[exec.profiles.test]
command = ["cargo", "test"]

[exec.profiles.fmt]
command = ["cargo", "fmt", "--all"]
"#,
  )
  .expect("exec profiles parse");
  assert_eq!(
    cfg.exec.profiles["test"].command,
    vec!["cargo".to_string(), "test".to_string()]
  );
  assert_eq!(
    cfg.exec.profiles["fmt"].command,
    vec!["cargo".to_string(), "fmt".to_string(), "--all".to_string()]
  );
}

#[test]
fn exec_jobs_parse_global_and_per_profile() {
  let cfg = load_toml(
    r#"
[exec]
jobs = 4

[exec.profiles.fmt]
command = ["cargo", "fmt"]
jobs = 2
"#,
  )
  .expect("jobs parse");
  assert_eq!(cfg.exec.jobs, Some(4), "global [exec] jobs");
  assert_eq!(cfg.exec.profiles["fmt"].jobs, Some(2), "per-profile jobs");
}

#[test]
fn exec_jobs_default_honors_global_even_without_a_repo() {
  // A bare repo passes `repo = None`, but the GLOBAL `[exec] jobs` still
  // applies (#324 review). A repo `[exec] jobs` overrides the global.
  let global_dir = TempDir::new().unwrap();
  let global = global_dir.path().join("config.toml");
  std::fs::write(&global, "[exec]\njobs = 4\n").unwrap();

  // repo = None (bare): only the global is read.
  assert_eq!(
    Config::load_exec_jobs_default_layered(Some(&global), None).unwrap(),
    Some(4),
    "bare repo still honours the global [exec] jobs"
  );

  // A repo `.gwm.toml` overrides the global default.
  let repo_dir = TempDir::new().unwrap();
  std::fs::write(repo_dir.path().join(CONFIG_FILE), "[exec]\njobs = 2\n").unwrap();
  assert_eq!(
    Config::load_exec_jobs_default_layered(Some(&global), Some(repo_dir.path())).unwrap(),
    Some(2),
    "repo [exec] jobs overrides the global"
  );

  // No global, no repo ⇒ None (sequential).
  assert_eq!(Config::load_exec_jobs_default_layered(None, None).unwrap(), None);
}

#[test]
fn exec_jobs_default_to_none() {
  let cfg = load_toml(
    r#"
[exec.profiles.test]
command = ["cargo", "test"]
"#,
  )
  .expect("parse");
  assert!(cfg.exec.jobs.is_none(), "no [exec] jobs ⇒ None (sequential)");
  assert!(cfg.exec.profiles["test"].jobs.is_none());
}

#[test]
fn clean_profiles_parse_dirs_as_a_complete_set() {
  let cfg = load_toml(
    r#"
[clean.profiles.default]
dirs = ["target", "node_modules", "dist", "build", "coverage", ".turbo"]

[clean.profiles.deep]
dirs = ["target", ".cache", ".venv"]
"#,
  )
  .expect("clean profiles parse");
  assert_eq!(
    cfg.clean.profiles["default"].dirs,
    vec!["target", "node_modules", "dist", "build", "coverage", ".turbo"]
  );
  assert_eq!(cfg.clean.profiles["deep"].dirs, vec!["target", ".cache", ".venv"]);
}

#[test]
fn exec_profile_without_command_is_a_load_error() {
  // `command` is required within a profile — an empty `[exec.profiles.x]`
  // table is a config error, surfaced at load time.
  let err = load_toml(
    r#"
[exec.profiles.broken]
"#,
  )
  .expect_err("missing command must error");
  assert!(
    err.to_string().contains("command"),
    "error should name the missing field: {err}"
  );
}

#[test]
fn clean_profile_without_dirs_is_a_load_error() {
  let err = load_toml(
    r#"
[clean.profiles.broken]
"#,
  )
  .expect_err("missing dirs must error");
  assert!(
    err.to_string().contains("dirs"),
    "error should name the missing field: {err}"
  );
}

#[test]
fn exec_profile_rejects_unknown_fields() {
  // `deny_unknown_fields` guards the frozen schema — a stray key is refused
  // rather than silently ignored.
  let err = load_toml(
    r#"
[exec.profiles.test]
command = ["cargo", "test"]
nonsense = true
"#,
  )
  .expect_err("unknown field must error");
  assert!(
    err.to_string().contains("nonsense") || err.to_string().contains("unknown"),
    "{err}"
  );
}

#[test]
fn exec_profile_with_an_empty_command_fails_validation() {
  // `command = []` parses (it's a valid array) but is semantically invalid —
  // caught at config-load time so `gwm config validate` rejects what
  // `gwm exec --profile` would.
  let err = load_toml(
    r#"
[exec.profiles.empty]
command = []
"#,
  )
  .expect_err("empty command must fail validation");
  assert!(err.to_string().contains("empty `command`"), "{err}");
}

#[test]
fn clean_profile_with_an_escaping_dir_fails_validation() {
  // `dirs = [".."]` parses but escapes the worktree — caught at config-load
  // time, not only later in `gwm clean`.
  let err = load_toml(
    r#"
[clean.profiles.default]
dirs = [".."]
"#,
  )
  .expect_err("escaping dir must fail validation");
  assert!(err.to_string().contains(".."), "{err}");
}

// ---- [tui] clipboard (issue #367) ------------------------------------------

#[test]
fn tui_clipboard_defaults_to_auto() {
  // `auto` is what makes the SSH fix work without configuration; a default of
  // `tools` would leave the reported bug in place for everyone who never edits
  // their config.
  assert_eq!(Config::default().tui.clipboard, ClipboardMode::Auto);
}

#[test]
fn tui_clipboard_absent_keeps_auto() {
  let dir = TempDir::new().unwrap();
  std::fs::write(dir.path().join(CONFIG_FILE), "[tui]\nconfirm_countdown_secs = 2\n").unwrap();
  let cfg = Config::load_layered(dir.path(), None).unwrap();
  assert_eq!(cfg.tui.clipboard, ClipboardMode::Auto);
}

#[test]
fn tui_clipboard_parses_every_mode() {
  for (text, expected) in [
    ("auto", ClipboardMode::Auto),
    ("osc52", ClipboardMode::Osc52),
    ("tools", ClipboardMode::Tools),
  ] {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join(CONFIG_FILE), format!("[tui]\nclipboard = \"{text}\"\n")).unwrap();
    let cfg = Config::load_layered(dir.path(), None).unwrap();
    assert_eq!(cfg.tui.clipboard, expected, "{text:?} parses");
    assert_eq!(
      cfg.tui.clipboard.label(),
      text,
      "label round-trips to the TOML spelling"
    );
  }
}

#[test]
fn tui_clipboard_invalid_value_errors_at_parse_time() {
  // Same hard-error contract as the other [tui] enums — silently falling back
  // would leave the user unsure which clipboard path is live, and this one is
  // already hard to observe (OSC52 never acknowledges).
  let dir = TempDir::new().unwrap();
  std::fs::write(dir.path().join(CONFIG_FILE), "[tui]\nclipboard = \"osc-52\"\n").unwrap();
  assert!(Config::load_layered(dir.path(), None).is_err());
}

// --- single-pass substitution (issue #494) --------------------------------

/// `expand_placeholders` chained `str::replace` calls, so each one re-scanned
/// what the previous had just written. `{home}` and `{repo}` go first, which
/// means a repo whose own name contains `{type}` made `{repo}/{desc}` write a
/// type the template never mentions.
///
/// An expansion is a **value**, not more template. Nothing downstream can
/// reason about a pattern by reading it otherwise: `naming::editable_segments`
/// derived the create form's fields from the wrong set, and
/// `BranchParser::compile` had to refuse the whole class rather than mirror a
/// formatter it could not predict.
///
/// Same property `lifecycle::expand` has had since the security patch
/// (`97e4e09`), and for the same reason.
#[test]
fn a_token_produced_by_expanding_the_repo_name_stays_literal() {
  let _guard = env_lock().lock().unwrap_or_else(|e| e.into_inner());
  let out = expand_placeholders(
    "{repo}/{desc}",
    "api-{type}",
    Some("fix"),
    Some("42"),
    Some("foo"),
    None,
  )
  .unwrap();
  assert_eq!(
    out, "api-{type}/foo",
    "the repo name is a value; the `{{type}}` inside it is not a placeholder"
  );

  // Every token, so no single ordering of the replace chain passes by luck.
  for token in ["{type}", "{issue}", "{desc}", "{repo}", "{home}"] {
    let out = expand_placeholders(
      "{repo}-x",
      &format!("api-{token}"),
      Some("fix"),
      Some("42"),
      Some("foo"),
      None,
    )
    .unwrap();
    assert_eq!(
      out,
      format!("api-{token}-x"),
      "`{}` arrived through the repo name, so it is data",
      token
    );
  }
}

/// The same for `{home}`, which is substituted first of all and is the one token
/// whose value the user does not choose directly.
///
/// **Unix only, and the gate is the point rather than a shortcut.** `dirs 6` on
/// Windows resolves the home directory through `SHGetKnownFolderPath` and never
/// reads `$HOME`, so swapping the variable there changes nothing and the
/// assertion fails on every run. Caught by the `windows-latest` job on PR #495,
/// which is the CLAUDE.md rule about pre-validating environment-dependent tests
/// being paid for rather than followed.
///
/// The *property* is covered portably by the test above: `{home}` and `{repo}`
/// are two arms of one `value_for` match, and that one exercises all five tokens
/// arriving through a value. What this adds is the guarantee that `{home}` is
/// not special-cased back into a pre-pass, which is exactly how the defect was
/// shaped, so it is worth keeping on the platform that can express it.
#[cfg(unix)]
#[test]
fn a_token_produced_by_expanding_home_stays_literal() {
  let _guard = env_lock().lock().unwrap_or_else(|e| e.into_inner());
  let previous = std::env::var("HOME").ok();
  unsafe { std::env::set_var("HOME", "/tmp/h-{issue}") };

  let out = expand_placeholders("{home}/wt/{desc}", "r", Some("fix"), Some("42"), Some("foo"), None);

  match previous {
    Some(v) => unsafe { std::env::set_var("HOME", v) },
    None => unsafe { std::env::remove_var("HOME") },
  }

  assert_eq!(out.unwrap(), "/tmp/h-{issue}/wt/foo");
}

/// A token with no value is left **literal**, not emptied.
/// `BranchSpec::branch_name` passes no `repo_path` precisely so the disk-path
/// tokens survive verbatim into the branch name, and `BranchParser::compile`
/// mirrors that. Restated here against the rewritten expander, since the old
/// one got it by not calling `replace` at all.
#[test]
fn a_token_with_no_value_survives_the_single_pass_verbatim() {
  let _guard = env_lock().lock().unwrap_or_else(|e| e.into_inner());
  assert_eq!(
    expand_placeholders("{repo_parent}/{type}/{issue}/{desc}", "r", None, None, None, None).unwrap(),
    "{repo_parent}/{type}/{issue}/{desc}"
  );
  // And an unknown token is not a token.
  assert_eq!(
    expand_placeholders("{nope}/{repo}", "r", None, None, None, None).unwrap(),
    "{nope}/r"
  );
  // Nor is an unbalanced brace.
  assert_eq!(
    expand_placeholders("{repo}/{unclosed", "r", None, None, None, None).unwrap(),
    "r/{unclosed"
  );
}

/// The asymmetry the old nesting encoded by accident: with `repo_path` set but
/// its parent `None`, `{repo_path}` resolves and `{repo_parent}` does not. A
/// token lookup has to state that, where the nested `if let` fell into it.
#[test]
fn a_repo_path_without_a_parent_resolves_only_the_path_token() {
  let _guard = env_lock().lock().unwrap_or_else(|e| e.into_inner());
  let root = std::path::Path::new("/");
  assert!(root.parent().is_none(), "the fixture must actually have no parent");

  let out = expand_placeholders("{repo_path}|{repo_parent}", "r", None, None, None, Some(root)).unwrap();
  assert_eq!(out, "/|{repo_parent}");
}