worktrunk 0.37.0

A CLI for Git worktree management, designed for parallel AI agent workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
//! Deprecation detection and migration.
//!
//! Scans config files for deprecated patterns and surfaces them to the user:
//! - Deprecated template variables (repo_root → repo_path, etc.)
//! - Deprecated config sections (\[commit-generation\] → \[commit.generation\])
//! - Deprecated fields (args merged into command)
//! - Deprecated approved-commands in \[projects\] (moved to approvals.toml)
//!
//! Detection is purely in-memory — nothing writes to the filesystem from a
//! config load path. `check_and_migrate` returns the structurally migrated
//! content (for serde) and a `DeprecationInfo` describing what needs fixing.
//! Users materialize migrations explicitly via `wt config update` (which
//! overwrites the config file and copies approved-commands to `approvals.toml`)
//! or inspect them via `wt config show` / `wt config update --print`.
//!
//! Per-path warning dedup still applies within a process so `wt list` doesn't
//! spam the same deprecation message from multiple config layers.

use std::borrow::Cow;
use std::collections::HashSet;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex, OnceLock};

use color_print::cformat;
use minijinja::Environment;
use regex::Regex;
use shell_escape::unix::escape;

use crate::config::WorktrunkConfig;
use crate::shell_exec::Cmd;
use crate::styling::{
    eprintln, format_with_gutter, hint_message, info_message, suggest_command_in_dir,
    warning_message,
};

/// Tracks which config paths have already shown deprecation warnings this process.
/// Prevents repeated warnings when config is loaded multiple times.
static WARNED_DEPRECATED_PATHS: LazyLock<Mutex<HashSet<PathBuf>>> =
    LazyLock::new(|| Mutex::new(HashSet::new()));

/// Set once the "Run wt config show..." hint has been emitted this process,
/// so multiple deprecated configs (user + project) share a single hint line.
static DEPRECATION_HINT_EMITTED: OnceLock<()> = OnceLock::new();

/// Latch that silences config deprecation/unknown-field warnings for the rest
/// of the process. Set by shell completion, picker, statusline, and help paths
/// — surfaces where stderr output would appear above the user's prompt or TUI.
static SUPPRESS_WARNINGS: OnceLock<()> = OnceLock::new();

pub fn suppress_warnings() {
    let _ = SUPPRESS_WARNINGS.set(());
}

fn warnings_suppressed() -> bool {
    SUPPRESS_WARNINGS.get().is_some()
}

/// Pre-compiled regexes for deprecated variable word-boundary matching.
/// Compiled once on first use, shared across all calls to normalize/replace.
static DEPRECATED_VAR_REGEXES: LazyLock<Vec<(Regex, &'static str)>> = LazyLock::new(|| {
    DEPRECATED_VARS
        .iter()
        .map(|&(old, new)| {
            let re = Regex::new(&format!(r"\b{}\b", regex::escape(old))).unwrap();
            (re, new)
        })
        .collect()
});

/// Tracks which config paths have already shown unknown field warnings this process.
/// Prevents repeated warnings when config is loaded multiple times.
static WARNED_UNKNOWN_PATHS: LazyLock<Mutex<HashSet<PathBuf>>> =
    LazyLock::new(|| Mutex::new(HashSet::new()));

/// Mapping from deprecated variable name to its replacement
const DEPRECATED_VARS: &[(&str, &str)] = &[
    ("repo_root", "repo_path"),
    ("worktree", "worktree_path"),
    ("main_worktree", "repo"),
    ("main_worktree_path", "primary_worktree_path"),
];

/// Metadata for a deprecated top-level section key.
#[derive(Debug)]
pub struct DeprecatedSection {
    /// The deprecated key name (e.g., "commit-generation")
    pub key: &'static str,
    /// The canonical top-level key that replaces this, for determining which config type
    /// it belongs to via `WorktrunkConfig::is_valid_key()` (e.g., "commit")
    pub canonical_top_key: &'static str,
    /// Human-readable canonical form for display (e.g., "[commit.generation]")
    pub canonical_display: &'static str,
}

/// Top-level section keys that are deprecated and handled by the deprecation system.
///
/// When a deprecated key appears in the config type where its canonical replacement
/// is valid, `warn_unknown_fields` skips it (the deprecation system provides better
/// messaging). When it appears in the wrong config type, `warn_unknown_fields`
/// warns that it belongs in the other config with the canonical form.
pub const DEPRECATED_SECTION_KEYS: &[DeprecatedSection] = &[
    DeprecatedSection {
        key: "commit-generation",
        canonical_top_key: "commit",
        canonical_display: "[commit.generation]",
    },
    DeprecatedSection {
        key: "select",
        canonical_top_key: "switch",
        canonical_display: "[switch.picker]",
    },
    DeprecatedSection {
        key: "ci",
        canonical_top_key: "forge",
        canonical_display: "[forge]",
    },
];

/// Normalize a template string by replacing deprecated variables with their canonical names.
///
/// This allows approval matching to work regardless of whether the command was saved
/// with old or new variable names. For example, `{{ repo_root }}` and `{{ repo_path }}`
/// will both normalize to `{{ repo_path }}`.
///
/// Returns `Cow::Borrowed` if no replacements needed, avoiding allocation.
pub fn normalize_template_vars(template: &str) -> Cow<'_, str> {
    // Quick check: if none of the deprecated vars appear, return borrowed
    if !DEPRECATED_VARS
        .iter()
        .any(|(old, _)| template.contains(old))
    {
        return Cow::Borrowed(template);
    }

    let mut result = template.to_string();
    for (re, new) in DEPRECATED_VAR_REGEXES.iter() {
        result = re.replace_all(&result, *new).into_owned();
    }
    Cow::Owned(result)
}

/// Core logic for deprecated var detection, operating on pre-extracted template strings
fn find_deprecated_vars_from_strings(
    template_strings: &[String],
) -> Vec<(&'static str, &'static str)> {
    let mut used_vars = HashSet::new();
    let env = Environment::new();

    for template_str in template_strings {
        if let Ok(template) = env.template_from_str(template_str) {
            used_vars.extend(template.undeclared_variables(false));
        }
    }

    DEPRECATED_VARS
        .iter()
        .filter(|(old, _)| used_vars.contains(*old))
        .copied()
        .collect()
}

/// Extract all string values from an already-parsed TOML document
fn extract_template_strings_from_doc(doc: &toml_edit::DocumentMut) -> Vec<String> {
    let mut strings = Vec::new();
    collect_strings_from_edit_table(doc.as_table(), &mut strings);
    strings
}

/// Recursively collect all string values from a toml_edit table
fn collect_strings_from_edit_table(table: &toml_edit::Table, strings: &mut Vec<String>) {
    for (_, item) in table.iter() {
        collect_strings_from_edit_item(item, strings);
    }
}

/// Recursively collect all string values from a toml_edit item
fn collect_strings_from_edit_item(item: &toml_edit::Item, strings: &mut Vec<String>) {
    match item {
        toml_edit::Item::Value(v) => collect_strings_from_edit_value(v, strings),
        toml_edit::Item::Table(t) => collect_strings_from_edit_table(t, strings),
        toml_edit::Item::ArrayOfTables(arr) => {
            for t in arr.iter() {
                collect_strings_from_edit_table(t, strings);
            }
        }
        _ => {}
    }
}

/// Recursively collect all string values from a toml_edit value
fn collect_strings_from_edit_value(value: &toml_edit::Value, strings: &mut Vec<String>) {
    match value {
        toml_edit::Value::String(s) => strings.push(s.value().clone()),
        toml_edit::Value::Array(arr) => {
            for v in arr.iter() {
                collect_strings_from_edit_value(v, strings);
            }
        }
        toml_edit::Value::InlineTable(t) => {
            for (_, v) in t.iter() {
                collect_strings_from_edit_value(v, strings);
            }
        }
        _ => {}
    }
}

/// Core logic for variable replacement, operating on pre-extracted template strings
fn replace_deprecated_vars_from_strings(content: &str, template_strings: &[String]) -> String {
    let mut result = content.to_string();

    for original in template_strings {
        let mut modified = original.clone();
        for (re, new) in DEPRECATED_VAR_REGEXES.iter() {
            modified = re.replace_all(&modified, *new).into_owned();
        }
        if modified != *original {
            result = result.replace(original, &modified);
        }
    }

    result
}

/// Information about deprecated commit-generation sections found in config
#[derive(Debug, Default, Clone)]
pub struct CommitGenerationDeprecations {
    /// Has top-level [commit-generation] section
    pub has_top_level: bool,
    /// Project keys that have deprecated [projects."...".commit-generation]
    pub project_keys: Vec<String>,
}

impl CommitGenerationDeprecations {
    pub fn is_empty(&self) -> bool {
        !self.has_top_level && self.project_keys.is_empty()
    }
}

/// All deprecation information detected in a config file.
///
/// This is a pure data struct with no path/label context. Used by both
/// config loading (brief warnings) and `wt config show` (full details).
#[derive(Debug, Default, Clone)]
pub struct Deprecations {
    /// Deprecated template variables found: (old_name, new_name)
    pub vars: Vec<(&'static str, &'static str)>,
    /// Deprecated commit-generation sections found
    pub commit_gen: CommitGenerationDeprecations,
    /// Has `approved-commands` in any `[projects."..."]` section (moved to approvals.toml)
    pub approved_commands: bool,
    /// Has `[select]` section (moved to `[switch.picker]`)
    pub select: bool,
    /// Has `[hooks.post-create]` (renamed to `[hooks.pre-start]`)
    pub post_create: bool,
    /// Has `[ci]` section (moved to `[forge]`)
    pub ci_section: bool,
    /// Has `no-ff` in `[merge]` section (use `ff` instead)
    pub no_ff: bool,
    /// Has `no-cd` in `[switch]` section (use `cd` instead)
    pub no_cd: bool,
    /// Pre-* hooks using multi-entry table form (will become concurrent in a future version)
    pub pre_hook_table_form: Vec<String>,
}

impl Deprecations {
    /// Returns true if any deprecations were found
    pub fn is_empty(&self) -> bool {
        self.vars.is_empty()
            && self.commit_gen.is_empty()
            && !self.approved_commands
            && !self.select
            && !self.post_create
            && !self.ci_section
            && !self.no_ff
            && !self.no_cd
            && self.pre_hook_table_form.is_empty()
    }
}

/// Detect deprecations in config content. Pure function, no I/O.
///
/// Parses the TOML content once and checks all deprecation types against the
/// parsed document.
///
/// Returns a `Deprecations` struct containing all detected deprecation issues.
/// This is the recommended entry point for deprecation detection.
pub fn detect_deprecations(content: &str) -> Deprecations {
    let Ok(doc) = content.parse::<toml_edit::DocumentMut>() else {
        return Deprecations::default();
    };
    let template_strings = extract_template_strings_from_doc(&doc);
    detect_deprecations_from_doc(&doc, &template_strings)
}

/// Detect deprecations from an already-parsed document and pre-extracted template strings.
fn detect_deprecations_from_doc(
    doc: &toml_edit::DocumentMut,
    template_strings: &[String],
) -> Deprecations {
    Deprecations {
        vars: find_deprecated_vars_from_strings(template_strings),
        commit_gen: find_commit_generation_from_doc(doc),
        approved_commands: find_approved_commands_from_doc(doc),
        select: find_select_from_doc(doc),
        post_create: find_post_create_from_doc(doc),
        ci_section: find_ci_section_from_doc(doc),
        no_ff: find_negated_bool_from_doc(doc, "merge", "no-ff", "ff"),
        no_cd: find_negated_bool_from_doc(doc, "switch", "no-cd", "cd"),
        pre_hook_table_form: find_pre_hook_table_form_from_doc(doc),
    }
}

fn find_approved_commands_from_doc(doc: &toml_edit::DocumentMut) -> bool {
    let Some(projects) = doc.get("projects").and_then(|p| p.as_table()) else {
        return false;
    };

    for (_project_key, project_value) in projects.iter() {
        if let Some(project_table) = project_value.as_table()
            && let Some(approved) = project_table.get("approved-commands")
            && approved.as_array().is_some_and(|a| !a.is_empty())
        {
            return true;
        }
    }

    false
}

fn find_commit_generation_from_doc(doc: &toml_edit::DocumentMut) -> CommitGenerationDeprecations {
    let mut result = CommitGenerationDeprecations::default();

    // Check if new [commit.generation] already exists as a valid table
    // (skip deprecation warning if so)
    let has_new_section = doc
        .get("commit")
        .and_then(|c| c.as_table())
        .and_then(|t| t.get("generation"))
        .is_some_and(|g| g.is_table() || g.is_inline_table());

    // Check top-level [commit-generation] - only flag if non-empty and new section doesn't exist
    // Handle both regular tables and inline tables
    if !has_new_section && let Some(section) = doc.get("commit-generation") {
        if let Some(table) = section.as_table() {
            if !table.is_empty() {
                result.has_top_level = true;
            }
        } else if let Some(inline) = section.as_inline_table()
            && !inline.is_empty()
        {
            result.has_top_level = true;
        }
    }

    // Check [projects."...".commit-generation]
    if let Some(projects) = doc.get("projects").and_then(|p| p.as_table()) {
        for (project_key, project_value) in projects.iter() {
            if let Some(project_table) = project_value.as_table() {
                // Check if this project has new section as a valid table
                let has_new_project_section = project_table
                    .get("commit")
                    .and_then(|c| c.as_table())
                    .and_then(|t| t.get("generation"))
                    .is_some_and(|g| g.is_table() || g.is_inline_table());

                // Only flag if old section exists, is non-empty, and new doesn't exist
                // Handle both regular tables and inline tables
                if !has_new_project_section
                    && let Some(old_section) = project_table.get("commit-generation")
                {
                    let is_non_empty = old_section.as_table().is_some_and(|t| !t.is_empty())
                        || old_section.as_inline_table().is_some_and(|t| !t.is_empty());
                    if is_non_empty {
                        result.project_keys.push(project_key.to_string());
                    }
                }
            }
        }
    }

    result
}

fn migrate_commit_generation_doc(doc: &mut toml_edit::DocumentMut) -> bool {
    let mut modified = false;

    // Check if new [commit.generation] already exists as a valid table - if so, skip migration
    // (new format takes precedence, don't overwrite it)
    let has_new_section = doc
        .get("commit")
        .and_then(|c| c.as_table())
        .and_then(|t| t.get("generation"))
        .is_some_and(|g| g.is_table() || g.is_inline_table());

    // Migrate top-level [commit-generation] → [commit.generation]
    // Only if new section doesn't already exist
    // Handle both regular tables and inline tables
    if !has_new_section && let Some(old_section) = doc.remove("commit-generation") {
        // Convert to table - works for both regular tables and inline tables
        let table_opt = match old_section {
            toml_edit::Item::Table(t) => Some(t),
            toml_edit::Item::Value(toml_edit::Value::InlineTable(it)) => Some(it.into_table()),
            _ => None,
        };

        if let Some(mut table) = table_opt {
            // Merge args into command if present
            merge_args_into_command(&mut table);

            // Ensure [commit] section exists.
            // Mark as implicit so it doesn't render a separate [commit] header
            // (only [commit.generation] will render)
            if !doc.contains_key("commit") {
                let mut commit_table = toml_edit::Table::new();
                commit_table.set_implicit(true);
                doc.insert("commit", toml_edit::Item::Table(commit_table));
            }

            // Move to [commit.generation]
            if let Some(commit_table) = doc["commit"].as_table_mut() {
                commit_table.insert("generation", toml_edit::Item::Table(table));
            }

            modified = true;
        }
    }

    // Migrate [projects."...".commit-generation] → [projects."...".commit.generation]
    if let Some(projects) = doc.get_mut("projects").and_then(|p| p.as_table_mut()) {
        for (_project_key, project_value) in projects.iter_mut() {
            if let Some(project_table) = project_value.as_table_mut() {
                // Check if new section already exists as a valid table for this project
                let has_new_project_section = project_table
                    .get("commit")
                    .and_then(|c| c.as_table())
                    .and_then(|t| t.get("generation"))
                    .is_some_and(|g| g.is_table() || g.is_inline_table());

                if !has_new_project_section
                    && let Some(old_section) = project_table.remove("commit-generation")
                {
                    // Convert to table - works for both regular tables and inline tables
                    let table_opt = match old_section {
                        toml_edit::Item::Table(t) => Some(t),
                        toml_edit::Item::Value(toml_edit::Value::InlineTable(it)) => {
                            Some(it.into_table())
                        }
                        _ => None,
                    };

                    if let Some(mut table) = table_opt {
                        // Merge args into command if present
                        merge_args_into_command(&mut table);

                        // Ensure [projects."...".commit] section exists.
                        // Mark as implicit so it doesn't render a separate header
                        if !project_table.contains_key("commit") {
                            let mut commit_table = toml_edit::Table::new();
                            commit_table.set_implicit(true);
                            project_table.insert("commit", toml_edit::Item::Table(commit_table));
                        }

                        // Move to [projects."...".commit.generation]
                        if let Some(commit_table) = project_table["commit"].as_table_mut() {
                            commit_table.insert("generation", toml_edit::Item::Table(table));
                        }

                        modified = true;
                    }
                }
            }
        }
    }

    modified
}

/// Remove `approved-commands` from all `\[projects."..."\]` sections.
///
/// For each project section, removes the `approved-commands` key.
/// If a project section becomes empty after removal, removes the project entry.
/// If the `\[projects\]` table becomes empty, removes it.
fn remove_approved_commands_doc(doc: &mut toml_edit::DocumentMut) -> bool {
    let mut modified = false;

    if let Some(projects) = doc.get_mut("projects").and_then(|p| p.as_table_mut()) {
        // Collect project keys that should have approved-commands removed
        let mut remove_from: Vec<String> = Vec::new();
        let mut emptied: Vec<String> = Vec::new();

        for (project_key, project_value) in projects.iter() {
            if let Some(project_table) = project_value.as_table()
                && project_table.contains_key("approved-commands")
            {
                remove_from.push(project_key.to_string());
                // Will be empty after removal if approved-commands is the only key
                if project_table.len() == 1 {
                    emptied.push(project_key.to_string());
                }
            }
        }

        for key in &remove_from {
            if let Some(project_value) = projects.get_mut(key)
                && let Some(project_table) = project_value.as_table_mut()
            {
                project_table.remove("approved-commands");
                modified = true;
            }
        }

        for key in &emptied {
            projects.remove(key);
        }
    }

    // Remove empty [projects] table
    if doc
        .get("projects")
        .and_then(|p| p.as_table())
        .is_some_and(|t| t.is_empty())
    {
        doc.remove("projects");
        modified = true;
    }

    modified
}

fn find_select_from_doc(doc: &toml_edit::DocumentMut) -> bool {
    if has_select_without_picker(doc) {
        return true;
    }

    // Check project-level sections
    if let Some(projects) = doc.get("projects").and_then(|p| p.as_table()) {
        for (_key, project_value) in projects.iter() {
            if let Some(project_table) = project_value.as_table()
                && has_select_without_picker(project_table)
            {
                return true;
            }
        }
    }

    false
}

/// Check if a table has a non-empty `select` section without `switch.picker`.
fn has_select_without_picker(table: &toml_edit::Table) -> bool {
    let has_new_section = table
        .get("switch")
        .and_then(|s| s.as_table())
        .and_then(|t| t.get("picker"))
        .is_some_and(|p| p.is_table() || p.is_inline_table());

    if has_new_section {
        return false;
    }

    if let Some(section) = table.get("select") {
        if let Some(t) = section.as_table() {
            return !t.is_empty();
        }
        if let Some(t) = section.as_inline_table() {
            return !t.is_empty();
        }
    }

    false
}

fn find_post_create_from_doc(doc: &toml_edit::DocumentMut) -> bool {
    // Top-level (user config or project config): hooks are flattened here
    if doc.get("pre-start").is_none() && doc.get("post-create").is_some_and(is_non_empty_item) {
        return true;
    }

    // Per-project overrides (user config): hooks are flattened into `[projects."id"]`
    if let Some(projects) = doc.get("projects").and_then(|p| p.as_table()) {
        for (_key, project_value) in projects.iter() {
            if let Some(project_table) = project_value.as_table()
                && project_table.get("pre-start").is_none()
                && project_table
                    .get("post-create")
                    .is_some_and(is_non_empty_item)
            {
                return true;
            }
        }
    }

    false
}

/// Check if a TOML item is non-empty (strings are always non-empty, tables must have entries).
fn is_non_empty_item(item: &toml_edit::Item) -> bool {
    match item {
        toml_edit::Item::Value(toml_edit::Value::InlineTable(t)) => !t.is_empty(),
        toml_edit::Item::Table(t) => !t.is_empty(),
        _ => true, // strings and other values are always "non-empty"
    }
}

/// Migrate `post-create` hooks to `pre-start`.
///
/// Renames `post-create` to `pre-start` in hooks sections. Skips if `pre-start` already exists.
fn migrate_post_create_doc(doc: &mut toml_edit::DocumentMut) -> bool {
    let mut modified = false;

    // Top-level (user config or project config)
    if doc.get("pre-start").is_none()
        && let Some(value) = doc.remove("post-create")
    {
        doc.insert("pre-start", value);
        modified = true;
    }

    // Per-project overrides (user config)
    if let Some(projects) = doc.get_mut("projects").and_then(|p| p.as_table_mut()) {
        for (_key, project_value) in projects.iter_mut() {
            if let Some(project_table) = project_value.as_table_mut()
                && project_table.get("pre-start").is_none()
                && let Some(value) = project_table.remove("post-create")
            {
                project_table.insert("pre-start", value);
                modified = true;
            }
        }
    }

    modified
}

/// Migrate `[select]` sections to `[switch.picker]`.
///
/// Handles both top-level and project-level `[projects."...".select]` sections.
/// Skips each migration if `[switch.picker]` already exists at that level.
fn migrate_select_doc(doc: &mut toml_edit::DocumentMut) -> bool {
    let mut modified = false;

    // Migrate top-level [select] → [switch.picker]
    migrate_select_table(doc.as_table_mut(), &mut modified);

    // Migrate project-level [projects."...".select] → [projects."...".switch.picker]
    if let Some(projects) = doc.get_mut("projects").and_then(|p| p.as_table_mut()) {
        for (_key, project_value) in projects.iter_mut() {
            if let Some(project_table) = project_value.as_table_mut() {
                migrate_select_table(project_table, &mut modified);
            }
        }
    }

    modified
}

/// Migrate a `select` key to `switch.picker` within a table.
fn migrate_select_table(table: &mut toml_edit::Table, modified: &mut bool) {
    let has_new_section = table
        .get("switch")
        .and_then(|s| s.as_table())
        .and_then(|t| t.get("picker"))
        .is_some_and(|p| p.is_table() || p.is_inline_table());

    if has_new_section {
        return;
    }

    let Some(old_section) = table.remove("select") else {
        return;
    };

    let table_opt = match old_section {
        toml_edit::Item::Table(t) => Some(t),
        toml_edit::Item::Value(toml_edit::Value::InlineTable(it)) => Some(it.into_table()),
        _ => None,
    };

    let Some(select_table) = table_opt else {
        return;
    };

    if !table.contains_key("switch") {
        let mut switch_table = toml_edit::Table::new();
        switch_table.set_implicit(true);
        table.insert("switch", toml_edit::Item::Table(switch_table));
    }

    if let Some(switch_table) = table["switch"].as_table_mut() {
        switch_table.insert("picker", toml_edit::Item::Table(select_table));
    }

    *modified = true;
}

/// The 5 canonical pre-* hook keys.
const PRE_HOOK_KEYS: &[&str] = &[
    "pre-switch",
    "pre-start",
    "pre-commit",
    "pre-merge",
    "pre-remove",
];

/// Check if a table has a multi-entry pre-* hook (table form with 2+ named commands).
fn collect_pre_hook_table_form_keys(
    table: &toml_edit::Table,
    prefix: &str,
    found: &mut Vec<String>,
) {
    for &key in PRE_HOOK_KEYS {
        if let Some(item) = table.get(key)
            && item.as_table().is_some_and(|t| t.len() >= 2)
        {
            if prefix.is_empty() {
                found.push(key.to_string());
            } else {
                found.push(format!("{prefix}.{key}"));
            }
        }
    }
}

/// Find pre-* hooks using multi-entry table form.
///
/// Hooks are flattened into the top level of user config, project config, and
/// each `[projects."id"]` subtree. Returns display paths for each deprecated
/// hook found.
fn find_pre_hook_table_form_from_doc(doc: &toml_edit::DocumentMut) -> Vec<String> {
    let mut found = Vec::new();

    // Top-level (user config or project config)
    collect_pre_hook_table_form_keys(doc.as_table(), "", &mut found);

    // Per-project overrides (user config)
    if let Some(projects) = doc.get("projects").and_then(|p| p.as_table()) {
        for (project_key, project_value) in projects.iter() {
            if let Some(project_table) = project_value.as_table() {
                let prefix = format!("projects.\"{project_key}\"");
                collect_pre_hook_table_form_keys(project_table, &prefix, &mut found);
            }
        }
    }

    found
}

fn find_ci_section_from_doc(doc: &toml_edit::DocumentMut) -> bool {
    // Skip if [forge] already exists
    if doc
        .get("forge")
        .is_some_and(|f| f.is_table() || f.is_inline_table())
    {
        return false;
    }

    // Check if [ci] exists with a non-empty platform field
    doc.get("ci")
        .and_then(|ci| ci.as_table())
        .and_then(|t| t.get("platform"))
        .is_some_and(|p| p.as_str().is_some_and(|s| !s.is_empty()))
}

/// Migrate `[ci]` section to `[forge]`.
///
/// Moves `platform` from `[ci]` to `[forge]`, preserving the value.
/// Removes `[ci]` if `platform` was its only field.
/// Skips migration if `[forge]` already exists.
fn migrate_ci_doc(doc: &mut toml_edit::DocumentMut) -> bool {
    // Skip if [forge] already exists
    if doc
        .get("forge")
        .is_some_and(|f| f.is_table() || f.is_inline_table())
    {
        return false;
    }

    // Get platform value from [ci]
    let platform = doc
        .get("ci")
        .and_then(|ci| ci.as_table())
        .and_then(|t| t.get("platform"))
        .and_then(|p| p.as_str())
        .map(String::from);

    let Some(platform) = platform else {
        return false;
    };

    // Remove [ci] section (it only has platform)
    doc.remove("ci");

    // Create [forge] section with platform
    let mut forge_table = toml_edit::Table::new();
    forge_table.insert("platform", toml_edit::value(platform));
    doc.insert("forge", toml_edit::Item::Table(forge_table));

    true
}

/// Check if a section has a deprecated negated boolean field (e.g., `no-ff` without `ff`).
///
/// Checks both the top-level section and project-level sections.
fn find_negated_bool_from_doc(
    doc: &toml_edit::DocumentMut,
    section: &str,
    old_key: &str,
    new_key: &str,
) -> bool {
    // Check top-level section
    if let Some(table) = doc.get(section).and_then(|s| s.as_table())
        && !table.contains_key(new_key)
        && table.contains_key(old_key)
    {
        return true;
    }

    // Check project-level sections
    if let Some(projects) = doc.get("projects").and_then(|p| p.as_table()) {
        for (_key, project_value) in projects.iter() {
            if let Some(table) = project_value
                .as_table()
                .and_then(|t| t.get(section))
                .and_then(|s| s.as_table())
                && !table.contains_key(new_key)
                && table.contains_key(old_key)
            {
                return true;
            }
        }
    }

    false
}

/// Migrate a negated boolean field within a table (e.g., `no-ff = true` → `ff = false`).
///
/// Returns true if a migration was performed.
fn migrate_negated_bool(table: &mut toml_edit::Table, old_key: &str, new_key: &str) -> bool {
    if table.contains_key(new_key) {
        // New key takes precedence; remove the old one if present
        return table.remove(old_key).is_some();
    }
    let Some(old_item) = table.remove(old_key) else {
        return false;
    };
    if let Some(bool_val) = old_item.as_value().and_then(|v| v.as_bool()) {
        table.insert(new_key, toml_edit::value(!bool_val));
        true
    } else {
        // Put it back if we can't parse it
        table.insert(old_key, old_item);
        false
    }
}

/// Migrate a negated boolean field in a section and its project-level counterparts.
fn migrate_negated_bool_doc(
    doc: &mut toml_edit::DocumentMut,
    section: &str,
    old_key: &str,
    new_key: &str,
) -> bool {
    let mut modified = false;

    // Top-level section
    if let Some(table) = doc.get_mut(section).and_then(|s| s.as_table_mut())
        && migrate_negated_bool(table, old_key, new_key)
    {
        modified = true;
    }

    // Project-level sections
    if let Some(projects) = doc.get_mut("projects").and_then(|p| p.as_table_mut()) {
        for (_key, project_value) in projects.iter_mut() {
            if let Some(table) = project_value
                .as_table_mut()
                .and_then(|t| t.get_mut(section))
                .and_then(|s| s.as_table_mut())
                && migrate_negated_bool(table, old_key, new_key)
            {
                modified = true;
            }
        }
    }

    modified
}

/// Convert a multi-entry pre-* table section into an array-of-tables pipeline.
///
/// Removes `[key]` as a table section and inserts `[[key]]` blocks —
/// one block per named step, preserving insertion order.
///
/// Iterates pre-* keys in document order (not [`PRE_HOOK_KEYS`] order) so
/// migrated sections land in the same relative position they had in the
/// source file.
fn migrate_pre_hook_table_in(table: &mut toml_edit::Table, modified: &mut bool) {
    let keys_to_migrate: Vec<String> = table
        .iter()
        .filter(|(k, v)| {
            PRE_HOOK_KEYS.contains(k)
                && v.as_table()
                    .is_some_and(|t| t.len() >= 2 && t.iter().all(|(_, v)| v.as_str().is_some()))
        })
        .map(|(k, _)| k.to_string())
        .collect();

    for key in keys_to_migrate {
        let item = table.get_mut(&key).unwrap();
        let entries = item.as_table().unwrap();

        let mut arr = toml_edit::ArrayOfTables::new();
        for (name, value) in entries.iter() {
            let mut block = toml_edit::Table::new();
            block.insert(name, toml_edit::value(value.as_str().unwrap()));
            arr.push(block);
        }

        *item = toml_edit::Item::ArrayOfTables(arr);
        *modified = true;
    }
}

/// Migrate multi-entry pre-* hook table sections to pipeline arrays.
///
/// Hooks are flattened into the top level of user config, project config, and
/// each `[projects."id"]` subtree.
fn migrate_pre_hook_table_form_doc(doc: &mut toml_edit::DocumentMut) -> bool {
    let mut modified = false;

    // Top-level (user config or project config)
    migrate_pre_hook_table_in(doc.as_table_mut(), &mut modified);

    // Per-project overrides (user config)
    if let Some(projects) = doc.get_mut("projects").and_then(|p| p.as_table_mut()) {
        for (_key, project_value) in projects.iter_mut() {
            if let Some(project_table) = project_value.as_table_mut() {
                migrate_pre_hook_table_in(project_table, &mut modified);
            }
        }
    }

    modified
}

/// Apply all structural TOML migrations to a parsed document.
///
/// This is the single source of truth for config migration. Returns true if
/// any modifications were made.
///
/// Note: `replace_deprecated_vars` and `remove_approved_commands` are NOT
/// included here — template variable renaming is cosmetic (would break
/// `--var` overrides), and approved-commands is still a valid serde field.
fn migrate_content_doc(doc: &mut toml_edit::DocumentMut) -> bool {
    let mut modified = false;
    modified |= migrate_commit_generation_doc(doc);
    modified |= migrate_select_doc(doc);
    modified |= migrate_post_create_doc(doc);
    modified |= migrate_pre_hook_table_form_doc(doc);
    modified |= migrate_ci_doc(doc);
    modified |= migrate_negated_bool_doc(doc, "merge", "no-ff", "ff");
    modified |= migrate_negated_bool_doc(doc, "switch", "no-cd", "cd");
    modified
}

fn migrate_content_from_doc(content: &str, mut doc: toml_edit::DocumentMut) -> String {
    if migrate_content_doc(&mut doc) {
        doc.to_string()
    } else {
        content.to_string()
    }
}

/// Apply all TOML-level migrations to config content.
///
/// Parses the TOML, applies all structural migrations, and returns the result.
/// Called by load paths that only need structural migration. `check_and_migrate()`
/// reuses the same migration path when it also needs to emit warnings.
pub fn migrate_content(content: &str) -> String {
    let Ok(doc) = content.parse::<toml_edit::DocumentMut>() else {
        return content.to_string();
    };
    migrate_content_from_doc(content, doc)
}

/// Copy approved-commands from config.toml to approvals.toml.
///
/// Called by `wt config update` before overwriting the config with migrated
/// content, so the approvals data survives the rewrite. No-op if
/// `approvals.toml` already exists (already authoritative) or the config has
/// no approved-commands entries.
///
/// Returns `Some(path)` if approvals.toml was created, `None` otherwise.
pub fn copy_approved_commands_to_approvals_file(config_path: &Path) -> Option<PathBuf> {
    let approvals_path = config_path.with_file_name("approvals.toml");
    if approvals_path.exists() {
        return None; // Already authoritative, don't overwrite
    }

    let approvals = super::approvals::Approvals::load_from_config_file(config_path).ok()?;
    approvals.projects().next()?; // Nothing to copy if empty

    approvals.save_to(&approvals_path).ok()?;
    Some(approvals_path)
}

/// Merge args array into command string
///
/// Converts: command = "llm", args = ["-m", "haiku"]
/// To: command = "llm -m haiku"
///
/// Only removes `args` if it can be successfully merged into `command`.
/// Preserves `args` if:
/// - `command` is missing or not a string
/// - `args` is not an array
fn merge_args_into_command(table: &mut toml_edit::Table) {
    // Validate preconditions before removing args
    let can_merge = table.get("args").is_some_and(|a| a.as_array().is_some())
        && table
            .get("command")
            .and_then(|c| c.as_value())
            .is_some_and(|v| v.as_str().is_some());

    if !can_merge {
        return;
    }

    // Now safe to remove and merge
    let args = table.remove("args").unwrap();
    let args_array = args.as_array().unwrap();
    let command = table
        .get_mut("command")
        .and_then(|c| c.as_value_mut())
        .unwrap();
    let cmd_str = command.as_str().unwrap();

    // Filter to string args only (non-strings are dropped)
    let args_str: Vec<&str> = args_array.iter().filter_map(|a| a.as_str()).collect();
    if !args_str.is_empty() {
        // Only add space if command is non-empty
        let new_command = if cmd_str.is_empty() {
            shell_join(&args_str)
        } else {
            format!("{} {}", cmd_str, shell_join(&args_str))
        };
        *command = toml_edit::Value::from(new_command);
    }
}

/// Join arguments with proper shell quoting using shell_escape
fn shell_join(args: &[&str]) -> String {
    args.iter()
        .map(|arg| escape(Cow::Borrowed(*arg)).into_owned())
        .collect::<Vec<_>>()
        .join(" ")
}

/// Information about deprecated config patterns that were found.
///
/// Detection result plus display context (paths, labels). No filesystem side
/// effects — `check_and_migrate` never touches the filesystem; `wt config
/// update` rewrites the config and copies approvals under an explicit user
/// action.
#[derive(Debug)]
pub struct DeprecationInfo {
    /// Path to the config file with deprecations
    pub config_path: PathBuf,
    /// All detected deprecations
    pub deprecations: Deprecations,
    /// Label for this config (e.g., "User config", "Project config")
    pub label: String,
    /// Main worktree path when viewing from a linked worktree (for `-C` in hints)
    pub main_worktree_path: Option<PathBuf>,
}

impl DeprecationInfo {
    /// Returns true if any deprecations were found
    pub fn has_deprecations(&self) -> bool {
        !self.deprecations.is_empty()
    }
}

/// Result of checking config content for deprecations.
///
/// `migrated_content` is the structurally migrated TOML used for serde loading.
/// `info` is present only when user-visible deprecations were detected.
#[derive(Debug)]
pub struct CheckAndMigrateResult {
    pub info: Option<DeprecationInfo>,
    pub migrated_content: String,
}

/// Check config content for deprecated patterns.
///
/// Detects:
/// - Deprecated template variables (repo_root → repo_path, etc.)
/// - Deprecated [commit-generation] sections → [commit.generation]
/// - Deprecated args field (merged into command)
/// - Deprecated approved-commands in \[projects\] (moved to approvals.toml)
///
/// Pure with respect to the filesystem — never rewrites config or copies
/// approvals. The user materializes migrations by running `wt config update`
/// (or `wt config update --print`). Deprecation warnings still go to stderr
/// when `emit_inline_warnings` is set.
///
/// Set `warn_and_migrate` to false for project config on feature worktrees —
/// the warning is only actionable from the main worktree where the user would
/// run `wt config update`.
///
/// The `label` is used in the warning message (e.g., "User config" or "Project config").
///
/// `repo` is used to resolve the primary worktree path for the "run this from
/// the main worktree" hint when viewing project config from a linked worktree.
///
/// When `emit_inline_warnings` is true, per-kind deprecation warnings are printed to stderr
/// with a hint pointing at `wt config show`/`wt config update`. When false, nothing is
/// printed and the caller is expected to render via `format_deprecation_details`. Use this for commands other than `config show`.
///
/// Warnings are deduplicated per path per process.
///
/// Returns the structurally migrated content for serde loading, plus optional
/// deprecation info when user-visible deprecations were found.
pub fn check_and_migrate(
    path: &Path,
    content: &str,
    warn_and_migrate: bool,
    label: &str,
    repo: Option<&crate::git::Repository>,
    emit_inline_warnings: bool,
) -> anyhow::Result<CheckAndMigrateResult> {
    // Parse once — shared by detection and migration.
    // Contract: unparsable content collapses to empty deprecations so downstream
    // `compute_migrated_content` (invoked by `config show`/`config update` only when
    // `info` is `Some`) can assume the content parses.
    let (deprecations, migrated_content) = match content.parse::<toml_edit::DocumentMut>() {
        Ok(doc) => {
            let template_strings = extract_template_strings_from_doc(&doc);
            let deprecations = detect_deprecations_from_doc(&doc, &template_strings);
            let migrated_content = migrate_content_from_doc(content, doc);
            (deprecations, migrated_content)
        }
        Err(_) => (Deprecations::default(), content.to_string()),
    };

    if deprecations.is_empty() {
        return Ok(CheckAndMigrateResult {
            info: None,
            migrated_content,
        });
    }

    let info = DeprecationInfo {
        config_path: path.to_path_buf(),
        deprecations,
        label: label.to_string(),
        main_worktree_path: if !warn_and_migrate {
            repo.and_then(|r| r.repo_path().ok())
                .map(|p| p.to_path_buf())
        } else {
            None
        },
    };

    // Skip warning entirely if not in main worktree (for project config)
    if !warn_and_migrate {
        return Ok(CheckAndMigrateResult {
            info: Some(info),
            migrated_content,
        });
    }

    // Deduplicate warnings per path per process
    let canonical_path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
    {
        let mut guard = WARNED_DEPRECATED_PATHS
            .lock()
            .map_err(|e| anyhow::anyhow!("failed to lock deprecation warning tracker: {e}"))?;
        if guard.contains(&canonical_path) {
            return Ok(CheckAndMigrateResult {
                info: Some(info),
                migrated_content,
            });
        }
        guard.insert(canonical_path);
    }

    // For non-config-show commands, emit per-kind warnings but skip the diff.
    // The diff is reserved for `wt config show`, where the user has opted into details.
    if emit_inline_warnings && !warnings_suppressed() {
        eprint!("{}", format_deprecation_warnings(&info));
        if DEPRECATION_HINT_EMITTED.set(()).is_ok() {
            eprintln!(
                "{}",
                hint_message(cformat!(
                    "To see details, run <underline>wt config show</>; to apply updates, run <underline>wt config update</>"
                ))
            );
        }
        std::io::stderr().flush().ok();
    }

    Ok(CheckAndMigrateResult {
        info: Some(info),
        migrated_content,
    })
}

/// Apply all deprecation fixes to `content` in memory and return the migrated
/// TOML string.
///
/// Applies variable renames (cosmetic, string-level), structural section and
/// field migrations, and removes `approved-commands` under `[projects]` (which
/// `wt config update` copies to `approvals.toml` before overwriting).
///
/// Pure function — no filesystem access. Idempotent: feeding its own output
/// back in is a no-op. Callers materialize the result via `wt config update`
/// or display it via `wt config show`.
pub fn compute_migrated_content(content: &str) -> String {
    // Parse once to extract template strings and detect what needs migrating.
    // Callers (`wt config show`, `wt config update`, `format_deprecation_details`)
    // all run content through `check_and_migrate` first, so it is known to parse.
    let doc = content
        .parse::<toml_edit::DocumentMut>()
        .expect("compute_migrated_content called with content that failed TOML parse; callers must funnel through check_and_migrate first");
    let template_strings = extract_template_strings_from_doc(&doc);
    let deprecations = detect_deprecations_from_doc(&doc, &template_strings);

    // Apply string-level var replacement first (cosmetic, operates on raw content)
    let after_vars = if !deprecations.vars.is_empty() {
        replace_deprecated_vars_from_strings(content, &template_strings)
    } else {
        content.to_string()
    };

    // Re-parse for structural migrations (which operate on toml_edit::DocumentMut).
    // `replace_deprecated_vars_from_strings` substitutes one identifier for another
    // inside `template_strings`, which are values extracted from string literals —
    // they cannot collide with TOML syntactic tokens, so the replacement preserves
    // validity.
    let mut doc = after_vars
        .parse::<toml_edit::DocumentMut>()
        .expect("template-var replacement preserves TOML structure");
    let mut modified = migrate_content_doc(&mut doc);
    // Additionally remove approved-commands (not part of migrate_content because
    // approved-commands is still a valid serde field at runtime).
    if deprecations.approved_commands {
        modified |= remove_approved_commands_doc(&mut doc);
    }
    if modified {
        doc.to_string()
    } else {
        after_vars
    }
}

/// Render a colored unified diff between `original` and `migrated`, with
/// `label` shown as the file name in the diff header (e.g. `config.toml`).
///
/// Uses a private tempdir containing two files named `<label>/current` and
/// `<label>/migrated`; `git diff --no-index` is invoked from inside that
/// tempdir so the diff header shows clean relative paths. The tempdir is
/// dropped on return. Returns `None` when the contents match.
pub fn format_migration_diff(original: &str, migrated: &str, label: &str) -> Option<String> {
    let dir = tempfile::tempdir().expect("failed to create tempdir for migration diff");
    let subdir = dir.path().join(label);
    std::fs::create_dir(&subdir).expect("failed to create subdir in fresh tempdir");
    let current = subdir.join("current");
    let migrated_path = subdir.join("migrated");
    std::fs::write(&current, original).expect("failed to write current config to tempfile");
    std::fs::write(&migrated_path, migrated).expect("failed to write migrated config to tempfile");

    let output = Cmd::new("git")
        .args(["diff", "--no-index", "--color=always", "-U3", "--"])
        .arg(format!("{label}/current"))
        .arg(format!("{label}/migrated"))
        .current_dir(dir.path())
        .run()
        .expect("git diff --no-index failed");

    // git diff --no-index exits 1 when files differ, which is expected.
    let diff_output = String::from_utf8_lossy(&output.stdout);
    if diff_output.is_empty() {
        return None;
    }
    Some(format_with_gutter(diff_output.trim_end(), None))
}

/// Format deprecation warning lines (without apply hints or diff).
///
/// Lists which deprecated patterns were found: template variables, config sections,
/// approved-commands. Used by both `format_deprecation_details` (which adds the
/// `wt config update` hint and diff) and `wt config update` (which applies directly).
pub fn format_deprecation_warnings(info: &DeprecationInfo) -> String {
    use std::fmt::Write;
    let mut out = String::new();

    for (old, new) in &info.deprecations.vars {
        let _ = writeln!(
            out,
            "{}",
            warning_message(cformat!(
                "{label}: template variable <bold>{old}</> is deprecated in favor of <bold>{new}</>",
                label = info.label,
            ))
        );
    }

    if info.deprecations.commit_gen.has_top_level {
        let _ = writeln!(
            out,
            "{}",
            warning_message(cformat!(
                "{}: <bold>[commit-generation]</> is deprecated in favor of <bold>[commit.generation]</>",
                info.label
            ))
        );
    }
    for project_key in &info.deprecations.commit_gen.project_keys {
        let _ = writeln!(
            out,
            "{}",
            warning_message(cformat!(
                "{label}: <bold>[projects.\"{k}\".commit-generation]</> is deprecated in favor of <bold>[projects.\"{k}\".commit.generation]</>",
                label = info.label,
                k = project_key
            ))
        );
    }

    if info.deprecations.approved_commands {
        let _ = writeln!(
            out,
            "{}",
            warning_message(cformat!(
                "{}: <bold>approved-commands</> under <bold>[projects]</> is deprecated in favor of <bold>approvals.toml</>",
                info.label
            ))
        );
    }

    if info.deprecations.select {
        let _ = writeln!(
            out,
            "{}",
            warning_message(cformat!(
                "{}: <bold>[select]</> is deprecated in favor of <bold>[switch.picker]</>",
                info.label
            ))
        );
    }

    if info.deprecations.post_create {
        let _ = writeln!(
            out,
            "{}",
            warning_message(cformat!(
                "{}: <bold>post-create</> hook is deprecated in favor of <bold>pre-start</>",
                info.label
            ))
        );
    }

    if info.deprecations.ci_section {
        let _ = writeln!(
            out,
            "{}",
            warning_message(cformat!(
                "{}: <bold>[ci]</> is deprecated in favor of <bold>[forge]</>",
                info.label
            ))
        );
    }

    if info.deprecations.no_ff {
        let _ = writeln!(
            out,
            "{}",
            warning_message(cformat!(
                "{}: <bold>merge.no-ff</> is deprecated in favor of <bold>merge.ff</> (inverted)",
                info.label
            ))
        );
    }

    if info.deprecations.no_cd {
        let _ = writeln!(
            out,
            "{}",
            warning_message(cformat!(
                "{}: <bold>switch.no-cd</> is deprecated in favor of <bold>switch.cd</> (inverted)",
                info.label
            ))
        );
    }

    if !info.deprecations.pre_hook_table_form.is_empty() {
        let hook_list = info
            .deprecations
            .pre_hook_table_form
            .iter()
            .map(|h| cformat!("<bold>{h}</>"))
            .collect::<Vec<_>>()
            .join(", ");
        let _ = writeln!(
            out,
            "{}",
            warning_message(cformat!(
                "{}: table form for {} is deprecated in favor of the pipeline form. \
                 We're unifying pre-hooks, post-hooks, and aliases so that list form always runs serially \
                 and table form always runs in parallel — migrate now to keep the current serial behavior \
                 once the table form is repurposed.",
                info.label,
                hook_list
            ))
        );
    }

    out
}

/// Format deprecation details for display (for use by `wt config show`).
///
/// Returns formatted output including:
/// - Warning message listing deprecated patterns
/// - Migration hint with apply command
/// - Inline diff showing the changes
///
/// `original_content` is the current on-disk config; the migrated content is
/// derived in memory via [`compute_migrated_content`] so this function has no
/// filesystem side effects other than the tempdir used briefly for `git diff`.
pub fn format_deprecation_details(info: &DeprecationInfo, original_content: &str) -> String {
    use std::fmt::Write;
    let mut out = format_deprecation_warnings(info);

    if let Some(main_path) = &info.main_worktree_path {
        // In a linked worktree — the user needs to run update from the primary.
        let cmd = suggest_command_in_dir(main_path, "config", &["update"], &[]);
        let _ = writeln!(
            out,
            "{}",
            hint_message(cformat!("To apply: <underline>{cmd}</>"))
        );
        return out;
    }

    let _ = writeln!(
        out,
        "{}",
        hint_message(cformat!("To apply: <underline>wt config update</>"))
    );

    let migrated = compute_migrated_content(original_content);
    let label = info
        .config_path
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "config".to_string());
    if let Some(diff) = format_migration_diff(original_content, &migrated, &label) {
        let _ = writeln!(out, "{}", info_message("Proposed diff:"));
        let _ = writeln!(out, "{diff}");
    }

    out
}

/// Returns the config location where this key belongs, if it's in the wrong config.
///
/// Generic over `C`, the config type where the key was found. If the key would
/// be valid in `C::Other`, returns that config's description.
///
/// For example, `key_belongs_in::<ProjectConfig>("skip-shell-integration-prompt")`
/// returns `Some("user config")`.
/// Returns `None` if the key is truly unknown (not valid in either config).
pub fn key_belongs_in<C: WorktrunkConfig>(key: &str) -> Option<&'static str> {
    C::Other::is_valid_key(key).then(C::Other::description)
}

/// Classification of an unknown config key for warning purposes.
pub enum UnknownKeyKind {
    /// Deprecated key in its correct config type — deprecation system handles it
    DeprecatedHandled,
    /// Deprecated key in the wrong config type
    DeprecatedWrongConfig {
        other_description: &'static str,
        canonical_display: &'static str,
    },
    /// Non-deprecated key that belongs in the other config type
    WrongConfig { other_description: &'static str },
    /// Truly unknown key (not valid in either config type)
    Unknown,
}

/// Classify an unknown config key: deprecated (right/wrong file), misplaced, or unknown.
pub fn classify_unknown_key<C: WorktrunkConfig>(key: &str) -> UnknownKeyKind {
    if let Some(dep) = DEPRECATED_SECTION_KEYS.iter().find(|d| d.key == key) {
        return if C::is_valid_key(dep.canonical_top_key) {
            UnknownKeyKind::DeprecatedHandled
        } else {
            UnknownKeyKind::DeprecatedWrongConfig {
                other_description: C::Other::description(),
                canonical_display: dep.canonical_display,
            }
        };
    }
    match key_belongs_in::<C>(key) {
        Some(other) => UnknownKeyKind::WrongConfig {
            other_description: other,
        },
        None => UnknownKeyKind::Unknown,
    }
}

/// Warn about unknown fields in a config file.
///
/// Generic over `C`, the config type being loaded. Classification is shared
/// with `config show` via [`collect_unknown_warnings`](crate::config::collect_unknown_warnings);
/// this wrapper adds per-path deduplication and stderr emission.
///
/// The `label` is used in the warning message (e.g., "User config" or
/// "Project config").
pub fn warn_unknown_fields<C: WorktrunkConfig>(raw_contents: &str, path: &Path, label: &str) {
    if warnings_suppressed() {
        return;
    }

    let warnings = crate::config::collect_unknown_warnings::<C>(raw_contents);
    if warnings.is_empty() {
        return;
    }

    // Deduplicate warnings per path per process
    let canonical_path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
    {
        let mut guard = WARNED_UNKNOWN_PATHS.lock().unwrap();
        if guard.contains(&canonical_path) {
            return; // Already warned, skip
        }
        guard.insert(canonical_path);
    }

    for warning in warnings {
        eprintln!("{}", warning_message(format_load_warning(label, &warning)));
    }

    // Flush stderr to ensure output appears before any subsequent messages
    std::io::stderr().flush().ok();
}

fn format_load_warning(label: &str, warning: &crate::config::UnknownWarning) -> String {
    use crate::config::UnknownWarning;
    match warning {
        UnknownWarning::TopLevelUnknown { key } => {
            cformat!("{label} has unknown field <bold>{key}</> (will be ignored)")
        }
        UnknownWarning::TopLevelWrongConfig {
            key,
            other_description,
        } => cformat!(
            "{label} has key <bold>{key}</> which belongs in {other_description} (will be ignored)"
        ),
        UnknownWarning::TopLevelDeprecatedWrongConfig {
            key,
            other_description,
            canonical_display,
        } => cformat!(
            "{label} has key <bold>{key}</> which belongs in {other_description} as {canonical_display}"
        ),
        UnknownWarning::NestedUnknown { path } => {
            cformat!("{label} has unknown field <bold>{path}</> (will be ignored)")
        }
    }
}

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

    // Test helpers that parse from string and delegate to the internal functions.
    // These mirror the former pub wrappers that were inlined into
    // `detect_deprecations` and `compute_migrated_content`.

    fn extract_template_strings(content: &str) -> Vec<String> {
        let Ok(doc) = content.parse::<toml_edit::DocumentMut>() else {
            return vec![];
        };
        extract_template_strings_from_doc(&doc)
    }

    fn replace_deprecated_vars(content: &str) -> String {
        let strings = extract_template_strings(content);
        replace_deprecated_vars_from_strings(content, &strings)
    }

    fn find_deprecated_vars(content: &str) -> Vec<(&'static str, &'static str)> {
        let strings = extract_template_strings(content);
        find_deprecated_vars_from_strings(&strings)
    }

    fn find_commit_generation_deprecations(content: &str) -> CommitGenerationDeprecations {
        content
            .parse::<toml_edit::DocumentMut>()
            .map(|doc| find_commit_generation_from_doc(&doc))
            .unwrap_or_default()
    }

    fn find_approved_commands_deprecation(content: &str) -> bool {
        content
            .parse::<toml_edit::DocumentMut>()
            .ok()
            .is_some_and(|doc| find_approved_commands_from_doc(&doc))
    }

    fn find_select_deprecation(content: &str) -> bool {
        content
            .parse::<toml_edit::DocumentMut>()
            .ok()
            .is_some_and(|doc| find_select_from_doc(&doc))
    }

    fn find_post_create_deprecation(content: &str) -> bool {
        content
            .parse::<toml_edit::DocumentMut>()
            .ok()
            .is_some_and(|doc| find_post_create_from_doc(&doc))
    }

    fn migrate_commit_generation_sections(content: &str) -> String {
        let Ok(mut doc) = content.parse::<toml_edit::DocumentMut>() else {
            return content.to_string();
        };
        if migrate_commit_generation_doc(&mut doc) {
            doc.to_string()
        } else {
            content.to_string()
        }
    }

    fn remove_approved_commands_from_config(content: &str) -> String {
        let Ok(mut doc) = content.parse::<toml_edit::DocumentMut>() else {
            return content.to_string();
        };
        if remove_approved_commands_doc(&mut doc) {
            doc.to_string()
        } else {
            content.to_string()
        }
    }

    fn migrate_select_to_switch_picker(content: &str) -> String {
        let Ok(mut doc) = content.parse::<toml_edit::DocumentMut>() else {
            return content.to_string();
        };
        if migrate_select_doc(&mut doc) {
            doc.to_string()
        } else {
            content.to_string()
        }
    }

    fn migrate_post_create_to_pre_start(content: &str) -> String {
        let Ok(mut doc) = content.parse::<toml_edit::DocumentMut>() else {
            return content.to_string();
        };
        if migrate_post_create_doc(&mut doc) {
            doc.to_string()
        } else {
            content.to_string()
        }
    }

    #[test]
    fn test_find_deprecated_vars_empty() {
        let content = r#"
worktree-path = "../{{ repo }}.{{ branch | sanitize }}"
"#;
        let found = find_deprecated_vars(content);
        assert!(found.is_empty());
    }

    #[test]
    fn test_find_deprecated_vars_repo_root() {
        let content = r#"
post-create = "ln -sf {{ repo_root }}/node_modules node_modules"
"#;
        let found = find_deprecated_vars(content);
        assert_eq!(found, vec![("repo_root", "repo_path")]);
    }

    #[test]
    fn test_find_deprecated_vars_worktree() {
        let content = r#"
post-create = "cd {{ worktree }} && npm install"
"#;
        let found = find_deprecated_vars(content);
        assert_eq!(found, vec![("worktree", "worktree_path")]);
    }

    #[test]
    fn test_find_deprecated_vars_main_worktree() {
        let content = r#"
worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"
"#;
        let found = find_deprecated_vars(content);
        assert_eq!(found, vec![("main_worktree", "repo")]);
    }

    #[test]
    fn test_find_deprecated_vars_main_worktree_path() {
        let content = r#"
post-create = "ln -sf {{ main_worktree_path }}/node_modules ."
"#;
        let found = find_deprecated_vars(content);
        assert_eq!(found, vec![("main_worktree_path", "primary_worktree_path")]);
    }

    #[test]
    fn test_find_deprecated_vars_multiple() {
        let content = r#"
worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"
post-create = "ln -sf {{ repo_root }}/node_modules {{ worktree }}/node_modules"
"#;
        let found = find_deprecated_vars(content);
        assert_eq!(
            found,
            vec![
                ("repo_root", "repo_path"),
                ("worktree", "worktree_path"),
                ("main_worktree", "repo"),
            ]
        );
    }

    #[test]
    fn test_find_deprecated_vars_with_filter() {
        let content = r#"
post-create = "ln -sf {{ repo_root | something }}/node_modules"
"#;
        let found = find_deprecated_vars(content);
        assert_eq!(found, vec![("repo_root", "repo_path")]);
    }

    #[test]
    fn test_find_deprecated_vars_deduplicates() {
        let content = r#"
post-create = "{{ repo_root }}/a {{ repo_root }}/b"
"#;
        let found = find_deprecated_vars(content);
        assert_eq!(found, vec![("repo_root", "repo_path")]);
    }

    #[test]
    fn test_find_deprecated_vars_does_not_match_suffix() {
        // Should NOT match "worktree_path" when looking for "worktree"
        let content = r#"
post-create = "cd {{ worktree_path }} && npm install"
"#;
        let found = find_deprecated_vars(content);
        assert!(
            found.is_empty(),
            "Should not match worktree_path as worktree"
        );
    }

    #[test]
    fn test_replace_deprecated_vars_simple() {
        let content = r#"cmd = "{{ repo_root }}""#;
        let result = replace_deprecated_vars(content);
        assert_eq!(result, r#"cmd = "{{ repo_path }}""#);
    }

    #[test]
    fn test_replace_deprecated_vars_with_filter() {
        let content = r#"cmd = "{{ repo_root | sanitize }}""#;
        let result = replace_deprecated_vars(content);
        assert_eq!(result, r#"cmd = "{{ repo_path | sanitize }}""#);
    }

    #[test]
    fn test_replace_deprecated_vars_no_spaces() {
        let content = r#"cmd = "{{repo_root}}""#;
        let result = replace_deprecated_vars(content);
        assert_eq!(result, r#"cmd = "{{repo_path}}""#); // Preserves original formatting
    }

    #[test]
    fn test_replace_deprecated_vars_filter_no_spaces() {
        let content = r#"cmd = "{{repo_root|sanitize}}""#;
        let result = replace_deprecated_vars(content);
        assert_eq!(result, r#"cmd = "{{repo_path|sanitize}}""#); // Preserves original formatting
    }

    #[test]
    fn test_replace_deprecated_vars_multiple() {
        let content = r#"
worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"
post-create = "ln -sf {{ repo_root }}/node_modules {{ worktree }}/node_modules"
"#;
        let result = replace_deprecated_vars(content);
        assert_eq!(
            result,
            r#"
worktree-path = "../{{ repo }}.{{ branch | sanitize }}"
post-create = "ln -sf {{ repo_path }}/node_modules {{ worktree_path }}/node_modules"
"#
        );
    }

    #[test]
    fn test_replace_deprecated_vars_preserves_other_content() {
        let content = r#"
# This is a comment
worktree-path = "../{{ repo }}.{{ branch }}"

[hooks]
post-create = "echo hello"
"#;
        let result = replace_deprecated_vars(content);
        assert_eq!(result, content); // No changes since no deprecated vars
    }

    #[test]
    fn test_replace_deprecated_vars_preserves_whitespace() {
        let content = r#"cmd = "{{  repo_root  }}""#;
        let result = replace_deprecated_vars(content);
        assert_eq!(result, r#"cmd = "{{  repo_path  }}""#); // Preserves original formatting
    }

    #[test]
    fn test_replace_does_not_match_suffix() {
        // Should NOT replace "worktree_path" when looking for "worktree"
        let content = r#"cmd = "{{ worktree_path }}""#;
        let result = replace_deprecated_vars(content);
        assert_eq!(
            result, r#"cmd = "{{ worktree_path }}""#,
            "Should not modify worktree_path"
        );
    }

    #[test]
    fn test_replace_in_statement_blocks() {
        // Word boundary replacement handles {% %} blocks too
        let content = r#"cmd = "{% if repo_root %}echo {{ repo_root }}{% endif %}""#;
        let result = replace_deprecated_vars(content);
        assert_eq!(
            result,
            r#"cmd = "{% if repo_path %}echo {{ repo_path }}{% endif %}""#
        );
    }

    // Tests for normalize_template_vars (single template string normalization)

    #[test]
    fn test_normalize_no_deprecated_vars() {
        let template = "ln -sf {{ repo_path }}/node_modules";
        let result = normalize_template_vars(template);
        assert!(matches!(result, Cow::Borrowed(_)), "Should not allocate");
        assert_eq!(result, template);
    }

    #[test]
    fn test_normalize_repo_root() {
        let template = "ln -sf {{ repo_root }}/node_modules";
        let result = normalize_template_vars(template);
        assert_eq!(result, "ln -sf {{ repo_path }}/node_modules");
    }

    #[test]
    fn test_normalize_worktree() {
        let template = "cd {{ worktree }} && npm install";
        let result = normalize_template_vars(template);
        assert_eq!(result, "cd {{ worktree_path }} && npm install");
    }

    #[test]
    fn test_normalize_main_worktree() {
        let template = "../{{ main_worktree }}.{{ branch }}";
        let result = normalize_template_vars(template);
        assert_eq!(result, "../{{ repo }}.{{ branch }}");
    }

    #[test]
    fn test_normalize_multiple_vars() {
        let template = "ln -sf {{ repo_root }}/node_modules {{ worktree }}/node_modules";
        let result = normalize_template_vars(template);
        assert_eq!(
            result,
            "ln -sf {{ repo_path }}/node_modules {{ worktree_path }}/node_modules"
        );
    }

    #[test]
    fn test_normalize_does_not_match_suffix() {
        // Should NOT replace "worktree_path" when looking for "worktree"
        let template = "cd {{ worktree_path }}";
        let result = normalize_template_vars(template);
        // Note: may allocate due to coarse quick check, but result is unchanged
        assert_eq!(result, template);
    }

    #[test]
    fn test_normalize_with_filter() {
        let template = "{{ repo_root | sanitize }}";
        let result = normalize_template_vars(template);
        assert_eq!(result, "{{ repo_path | sanitize }}");
    }

    // Tests for approved-commands array handling

    #[test]
    fn test_find_deprecated_vars_in_array_of_tables() {
        // Exercises the ArrayOfTables arm in collect_strings_from_edit_item
        let content = r#"
[[hooks]]
command = "ln -sf {{ repo_root }}/node_modules"
"#;
        let found = find_deprecated_vars(content);
        assert_eq!(found, vec![("repo_root", "repo_path")]);
    }

    #[test]
    fn test_find_deprecated_vars_in_approved_commands() {
        let content = r#"
[projects."github.com/user/repo"]
approved-commands = [
    "ln -sf {{ repo_root }}/node_modules",
    "cd {{ worktree }} && npm install",
]
"#;
        let found = find_deprecated_vars(content);
        assert_eq!(
            found,
            vec![("repo_root", "repo_path"), ("worktree", "worktree_path"),]
        );
    }

    #[test]
    fn test_replace_deprecated_vars_in_approved_commands() {
        let content = r#"
[projects."github.com/user/repo"]
approved-commands = [
    "ln -sf {{ repo_root }}/node_modules",
    "cd {{ worktree }} && npm install",
]
"#;
        let result = replace_deprecated_vars(content);
        assert_eq!(
            result,
            r#"
[projects."github.com/user/repo"]
approved-commands = [
    "ln -sf {{ repo_path }}/node_modules",
    "cd {{ worktree_path }} && npm install",
]
"#
        );
    }

    #[test]
    fn test_check_and_migrate_write_failure() {
        // Test the write error path by using a non-existent directory
        let content = r#"post-create = "{{ repo_root }}/script.sh""#;
        let non_existent_path = std::path::Path::new("/nonexistent/dir/config.toml");

        // Should return Ok(Some(_)) even if write fails - the function logs error but doesn't fail
        let result =
            check_and_migrate(non_existent_path, content, true, "Test config", None, false);
        assert!(result.is_ok());
        assert!(result.unwrap().info.is_some());
    }

    #[test]
    fn test_check_and_migrate_deduplicates_warnings() {
        // Test that calling twice with same path skips the second warning
        let content = r#"post-create = "{{ repo_root }}/script.sh""#;
        // Use a unique path that won't collide with other tests
        let unique_path = std::path::Path::new("/nonexistent/dedup_test_12345/config.toml");

        // First call should process normally
        let result1 = check_and_migrate(unique_path, content, true, "Test config", None, false);
        assert!(result1.is_ok());
        assert!(result1.unwrap().info.is_some());

        // Second call with same path should early-return (hits the deduplication branch)
        let result2 = check_and_migrate(unique_path, content, true, "Test config", None, false);
        assert!(result2.is_ok());
        assert!(result2.unwrap().info.is_some());
    }

    #[test]
    fn test_check_and_migrate_returns_migrated_content() {
        let content = r#"
[select]
pager = "delta"
"#;

        let result = check_and_migrate(
            std::path::Path::new("/tmp/config.toml"),
            content,
            true,
            "Test config",
            None,
            false,
        )
        .unwrap();

        assert_eq!(result.migrated_content, migrate_content(content));
        assert!(result.info.is_some());
    }

    // Tests for commit-generation section migration

    #[test]
    fn test_find_commit_generation_deprecations_none() {
        let content = r#"
[commit.generation]
command = "llm -m haiku"
"#;
        let result = find_commit_generation_deprecations(content);
        assert!(result.is_empty());
    }

    #[test]
    fn test_find_commit_generation_deprecations_top_level() {
        let content = r#"
[commit-generation]
command = "llm -m haiku"
"#;
        let result = find_commit_generation_deprecations(content);
        assert!(result.has_top_level);
        assert!(result.project_keys.is_empty());
    }

    #[test]
    fn test_find_commit_generation_deprecations_project_level() {
        let content = r#"
[projects."github.com/user/repo".commit-generation]
command = "llm -m gpt-4"
"#;
        let result = find_commit_generation_deprecations(content);
        assert!(!result.has_top_level);
        assert_eq!(result.project_keys, vec!["github.com/user/repo"]);
    }

    #[test]
    fn test_find_commit_generation_deprecations_multiple_projects() {
        let content = r#"
[commit-generation]
command = "llm -m haiku"

[projects."github.com/user/repo1".commit-generation]
command = "llm -m gpt-4"

[projects."github.com/user/repo2".commit-generation]
command = "llm -m opus"
"#;
        let result = find_commit_generation_deprecations(content);
        assert!(result.has_top_level);
        assert_eq!(result.project_keys.len(), 2);
        assert!(
            result
                .project_keys
                .contains(&"github.com/user/repo1".to_string())
        );
        assert!(
            result
                .project_keys
                .contains(&"github.com/user/repo2".to_string())
        );
    }

    #[test]
    fn test_migrate_commit_generation_args_with_spaces() {
        let content = r#"
[commit-generation]
command = "llm"
args = ["-m", "claude haiku 4.5"]
"#;
        let result = migrate_commit_generation_sections(content);
        insta::assert_snapshot!(result, @r#"

        [commit.generation]
        command = "llm -m 'claude haiku 4.5'"
        "#);
    }

    #[test]
    fn test_migrate_commit_generation_preserves_other_fields() {
        let content = r#"
[commit-generation]
command = "llm -m haiku"
template = "Write commit: {{ diff }}"
"#;
        let result = migrate_commit_generation_sections(content);
        insta::assert_snapshot!(result, @r#"

        [commit.generation]
        command = "llm -m haiku"
        template = "Write commit: {{ diff }}"
        "#);
    }

    #[test]
    fn test_migrate_no_changes_needed() {
        let content = r#"
[commit.generation]
command = "llm -m haiku"
"#;
        let result = migrate_commit_generation_sections(content);
        assert_eq!(result, content);
    }

    #[test]
    fn test_migrate_skips_when_new_section_exists() {
        let content = r#"
[commit.generation]
command = "new-command"

[commit-generation]
command = "old-command"
"#;
        let result = migrate_commit_generation_sections(content);
        // Old section left as-is since new already exists
        insta::assert_snapshot!(result, @r#"

        [commit.generation]
        command = "new-command"

        [commit-generation]
        command = "old-command"
        "#);
    }

    #[test]
    fn test_find_deprecations_skips_when_new_section_exists() {
        // When new section exists, don't flag old section as deprecated
        let content = r#"
[commit.generation]
command = "new-command"

[commit-generation]
command = "old-command"
"#;
        let result = find_commit_generation_deprecations(content);
        assert!(
            !result.has_top_level,
            "Should not flag deprecation when new section exists"
        );
    }

    #[test]
    fn test_find_deprecations_skips_empty_section() {
        // Empty old section should not be flagged
        let content = r#"
[commit-generation]
"#;
        let result = find_commit_generation_deprecations(content);
        assert!(
            !result.has_top_level,
            "Should not flag empty deprecated section"
        );
    }

    #[test]
    fn test_shell_join_simple() {
        assert_eq!(shell_join(&["-m", "haiku"]), "-m haiku");
    }

    #[test]
    fn test_shell_join_with_spaces() {
        assert_eq!(shell_join(&["-m", "claude haiku"]), "-m 'claude haiku'");
    }

    #[test]
    fn test_shell_join_with_quotes() {
        assert_eq!(shell_join(&["echo", "it's"]), r"echo 'it'\''s'");
    }

    #[test]
    fn test_combined_migrations_template_vars_and_section_rename() {
        let content = r#"
worktree-path = "../{{ main_worktree }}.{{ branch }}"

[commit-generation]
command = "llm"
args = ["-m", "haiku"]
"#;
        let step1 = replace_deprecated_vars(content);
        let step2 = migrate_commit_generation_sections(&step1);
        insta::assert_snapshot!(step2, @r#"

        worktree-path = "../{{ repo }}.{{ branch }}"

        [commit.generation]
        command = "llm -m haiku"
        "#);
    }

    // Tests for inline table handling

    #[test]
    fn test_find_deprecations_inline_table_top_level() {
        // Inline table format: commit-generation = { command = "llm" }
        let content = r#"
commit-generation = { command = "llm -m haiku" }
"#;
        let result = find_commit_generation_deprecations(content);
        assert!(result.has_top_level, "Should detect inline table format");
    }

    #[test]
    fn test_find_deprecations_inline_table_project_level() {
        let content = r#"
[projects."github.com/user/repo"]
commit-generation = { command = "llm -m gpt-4" }
"#;
        let result = find_commit_generation_deprecations(content);
        assert_eq!(
            result.project_keys,
            vec!["github.com/user/repo"],
            "Should detect project-level inline table"
        );
    }

    #[test]
    fn test_migrate_inline_table_top_level() {
        let content = r#"
commit-generation = { command = "llm", args = ["-m", "haiku"] }
"#;
        let result = migrate_commit_generation_sections(content);
        assert!(
            result.contains("[commit.generation]") || result.contains("[commit]"),
            "Should migrate inline table"
        );
        assert!(
            result.contains("command = \"llm -m haiku\""),
            "Should merge args into command"
        );
        assert!(
            !result.contains("commit-generation"),
            "Should remove old inline table"
        );
    }

    #[test]
    fn test_find_deprecations_malformed_generation_not_table() {
        // If commit.generation is a string (malformed), should still warn about old format
        let content = r#"
[commit]
generation = "not a table"

[commit-generation]
command = "llm -m haiku"
"#;
        let result = find_commit_generation_deprecations(content);
        assert!(
            result.has_top_level,
            "Should flag deprecated section when new section is malformed"
        );
    }

    #[test]
    fn test_migrate_inline_table_project_level() {
        let content = r#"
[projects."github.com/user/repo"]
commit-generation = { command = "llm", args = ["-m", "gpt-4"] }
"#;
        let result = migrate_commit_generation_sections(content);
        assert!(
            result.contains("[projects.\"github.com/user/repo\".commit.generation]")
                || result.contains("[projects.\"github.com/user/repo\".commit]"),
            "Should migrate project-level inline table"
        );
        assert!(
            result.contains("command = \"llm -m gpt-4\""),
            "Should merge args into command"
        );
        assert!(
            !result.contains("commit-generation"),
            "Should remove old inline table"
        );
    }

    #[test]
    fn test_find_deprecations_empty_inline_table() {
        // Empty inline table should not be flagged
        let content = r#"
commit-generation = {}
"#;
        let result = find_commit_generation_deprecations(content);
        assert!(
            !result.has_top_level,
            "Should not flag empty inline table as deprecated"
        );
    }

    #[test]
    fn test_migrate_args_without_command_preserved() {
        // Args preserved when no command to merge into
        let content = r#"
[commit-generation]
args = ["-m", "haiku"]
template = "some template"
"#;
        let result = migrate_commit_generation_sections(content);
        insta::assert_snapshot!(result, @r#"

        [commit.generation]
        args = ["-m", "haiku"]
        template = "some template"
        "#);
    }

    #[test]
    fn test_migrate_args_with_non_string_command() {
        // Args preserved when command is not a string
        let content = r#"
[commit-generation]
command = 123
args = ["-m", "haiku"]
"#;
        let result = migrate_commit_generation_sections(content);
        insta::assert_snapshot!(result, @r#"

        [commit.generation]
        command = 123
        args = ["-m", "haiku"]
        "#);
    }

    #[test]
    fn test_migrate_empty_command_with_args() {
        let content = r#"
[commit-generation]
command = ""
args = ["-m", "haiku"]
"#;
        let result = migrate_commit_generation_sections(content);
        insta::assert_snapshot!(result, @r#"

        [commit.generation]
        command = "-m haiku"
        "#);
    }

    #[test]
    fn test_migrate_malformed_string_value_unchanged() {
        // When commit-generation is a string (malformed), migration skips it
        // This exercises the `_ => None` branch in the match
        let content = r#"
commit-generation = "not a table"
other = "value"
"#;
        let result = migrate_commit_generation_sections(content);
        // Malformed value is removed (doc.remove happens), but no migration occurs
        // The content stays mostly unchanged since we don't add [commit.generation]
        assert!(
            !result.contains("[commit.generation]"),
            "Should not create new section for malformed input"
        );
    }

    #[test]
    fn test_migrate_malformed_project_level_string_unchanged() {
        // When project-level commit-generation is a string, migration skips it
        let content = r#"
[projects."github.com/user/repo"]
commit-generation = "not a table"
other = "value"
"#;
        let result = migrate_commit_generation_sections(content);
        assert!(
            !result.contains("[projects.\"github.com/user/repo\".commit.generation]"),
            "Should not create new section for malformed project-level input"
        );
    }

    #[test]
    fn test_migrate_invalid_toml_returns_unchanged() {
        // When content is not valid TOML, return it unchanged
        let content = "this is [not valid {toml";
        let result = migrate_commit_generation_sections(content);
        assert_eq!(result, content, "Invalid TOML should be returned unchanged");
    }

    // Snapshot tests for migration output (showing diffs)

    /// Generate a unified diff between original and migrated content
    fn migration_diff(original: &str, migrated: &str) -> String {
        use similar::{ChangeTag, TextDiff};
        let diff = TextDiff::from_lines(original, migrated);
        let mut output = String::new();
        for change in diff.iter_all_changes() {
            let sign = match change.tag() {
                ChangeTag::Delete => "-",
                ChangeTag::Insert => "+",
                ChangeTag::Equal => " ",
            };
            output.push_str(&format!("{}{}", sign, change));
        }
        output
    }

    #[test]
    fn snapshot_migrate_commit_generation_simple() {
        let content = r#"
[commit-generation]
command = "llm -m haiku"
"#;
        let result = migrate_commit_generation_sections(content);
        insta::assert_snapshot!(migration_diff(content, &result));
    }

    #[test]
    fn snapshot_migrate_commit_generation_with_args() {
        let content = r#"
[commit-generation]
command = "llm"
args = ["-m", "claude-haiku-4.5"]
"#;
        let result = migrate_commit_generation_sections(content);
        insta::assert_snapshot!(migration_diff(content, &result));
    }

    #[test]
    fn snapshot_migrate_with_trailing_sections() {
        // This is the bug case: [commit-generation] in the middle of the file
        // followed by other sections. The migration should not add an extra
        // [commit] section at the end.
        let content = r#"# Config file
worktree-path = "../{{ repo }}.{{ branch | sanitize }}"

[commit-generation]
command = "llm"
args = ["-m", "claude-haiku-4.5"]

[list]
branches = true
remotes = false
"#;
        let result = migrate_commit_generation_sections(content);
        insta::assert_snapshot!(migration_diff(content, &result));
    }

    #[test]
    fn snapshot_migrate_preserves_existing_commit_section() {
        let content = r#"
[commit]
stage = "all"

[commit-generation]
command = "llm -m haiku"
"#;
        let result = migrate_commit_generation_sections(content);
        insta::assert_snapshot!(migration_diff(content, &result));
    }

    #[test]
    fn snapshot_migrate_project_level() {
        let content = r#"
[projects."github.com/user/repo"]
approved-commands = ["npm test"]

[projects."github.com/user/repo".commit-generation]
command = "llm"
args = ["-m", "gpt-4"]
"#;
        let result = migrate_commit_generation_sections(content);
        insta::assert_snapshot!(migration_diff(content, &result));
    }

    #[test]
    fn snapshot_migrate_combined_top_and_project() {
        let content = r#"
[commit-generation]
command = "llm -m haiku"

[projects."github.com/user/repo".commit-generation]
command = "llm -m gpt-4"

[list]
branches = true
"#;
        let result = migrate_commit_generation_sections(content);
        insta::assert_snapshot!(migration_diff(content, &result));
    }

    // Tests for approved-commands deprecation detection

    #[test]
    fn test_find_approved_commands_deprecation_none() {
        let content = r#"
[commit.generation]
command = "llm -m haiku"
"#;
        assert!(!find_approved_commands_deprecation(content));
    }

    #[test]
    fn test_find_approved_commands_deprecation_present() {
        let content = r#"
[projects."github.com/user/repo"]
approved-commands = ["npm install", "npm test"]
"#;
        assert!(find_approved_commands_deprecation(content));
    }

    #[test]
    fn test_find_approved_commands_deprecation_empty_array() {
        let content = r#"
[projects."github.com/user/repo"]
approved-commands = []
"#;
        assert!(!find_approved_commands_deprecation(content));
    }

    #[test]
    fn test_find_approved_commands_deprecation_no_projects() {
        let content = r#"
worktree-path = "../{{ repo }}.{{ branch }}"
"#;
        assert!(!find_approved_commands_deprecation(content));
    }

    #[test]
    fn test_find_approved_commands_deprecation_project_without_approvals() {
        let content = r#"
[projects."github.com/user/repo"]
worktree-path = ".worktrees/{{ branch | sanitize }}"
"#;
        assert!(!find_approved_commands_deprecation(content));
    }

    // Tests for remove_approved_commands_from_config

    #[test]
    fn test_remove_approved_commands_multiple_projects() {
        let content = r#"
[projects."github.com/user/repo1"]
approved-commands = ["npm install"]

[projects."github.com/user/repo2"]
approved-commands = ["cargo test"]
worktree-path = ".worktrees/{{ branch | sanitize }}"
"#;
        let result = remove_approved_commands_from_config(content);
        insta::assert_snapshot!(result, @r#"

        [projects."github.com/user/repo2"]
        worktree-path = ".worktrees/{{ branch | sanitize }}"
        "#);
    }

    #[test]
    fn test_remove_approved_commands_no_change() {
        let content = r#"
[projects."github.com/user/repo"]
worktree-path = ".worktrees/{{ branch | sanitize }}"
"#;
        let result = remove_approved_commands_from_config(content);
        assert_eq!(result, content);
    }

    #[test]
    fn snapshot_remove_approved_commands() {
        let content = r#"worktree-path = "../{{ repo }}.{{ branch | sanitize }}"

[projects."github.com/user/repo"]
approved-commands = ["npm install", "npm test"]
worktree-path = ".worktrees/{{ branch | sanitize }}"
"#;
        let result = remove_approved_commands_from_config(content);
        insta::assert_snapshot!(migration_diff(content, &result));
    }

    #[test]
    fn snapshot_remove_approved_commands_entire_section() {
        let content = r#"worktree-path = "../{{ repo }}.{{ branch | sanitize }}"

[projects."github.com/user/repo"]
approved-commands = ["npm install"]
"#;
        let result = remove_approved_commands_from_config(content);
        insta::assert_snapshot!(migration_diff(content, &result));
    }

    #[test]
    fn test_detect_deprecations_includes_approved_commands() {
        let content = r#"
[projects."github.com/user/repo"]
approved-commands = ["npm install"]
"#;
        let deprecations = detect_deprecations(content);
        assert!(deprecations.approved_commands);
        assert!(!deprecations.is_empty());
    }

    #[test]
    fn test_remove_approved_commands_invalid_toml() {
        let content = "this is { not valid toml";
        let result = remove_approved_commands_from_config(content);
        assert_eq!(result, content, "Invalid TOML should be returned unchanged");
    }

    #[test]
    fn test_format_deprecation_details_approved_commands() {
        let content = r#"
[projects."github.com/user/repo"]
approved-commands = ["npm install"]
"#;
        let info = DeprecationInfo {
            config_path: std::path::PathBuf::from("/tmp/test-config.toml"),
            deprecations: Deprecations {
                vars: vec![],
                commit_gen: CommitGenerationDeprecations::default(),
                approved_commands: true,
                select: false,
                post_create: false,
                ci_section: false,
                no_ff: false,
                no_cd: false,
                pre_hook_table_form: vec![],
            },
            label: "User config".to_string(),
            main_worktree_path: None,
        };
        let output = format_deprecation_details(&info, content);
        assert!(
            output.contains("approved-commands"),
            "Should mention approved-commands in output: {}",
            output
        );
        assert!(
            output.contains("approvals.toml"),
            "Should mention approvals.toml: {}",
            output
        );
    }

    #[test]
    fn test_compute_migrated_content_removes_approved_commands() {
        let content = r#"worktree-path = "../{{ repo }}.{{ branch | sanitize }}"

[projects."github.com/user/repo"]
approved-commands = ["npm install"]
"#;
        let migrated = compute_migrated_content(content);
        assert!(!migrated.contains("approved-commands"));
    }

    #[test]
    fn test_copy_approved_commands_creates_approvals_file() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.toml");
        let content = r#"
[projects."github.com/user/repo"]
approved-commands = ["npm install", "npm test"]

[projects."github.com/other/repo"]
approved-commands = ["cargo build"]
"#;
        std::fs::write(&config_path, content).unwrap();

        let result = copy_approved_commands_to_approvals_file(&config_path);
        assert!(result.is_some(), "Should create approvals.toml");

        let approvals_path = result.unwrap();
        assert_eq!(approvals_path, temp_dir.path().join("approvals.toml"));

        let approvals_content = std::fs::read_to_string(&approvals_path).unwrap();
        assert!(
            approvals_content.contains("npm install"),
            "Should contain npm install: {}",
            approvals_content
        );
        assert!(
            approvals_content.contains("npm test"),
            "Should contain npm test: {}",
            approvals_content
        );
        assert!(
            approvals_content.contains("cargo build"),
            "Should contain cargo build: {}",
            approvals_content
        );
    }

    #[test]
    fn test_copy_approved_commands_skips_when_approvals_exists() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.toml");
        let approvals_path = temp_dir.path().join("approvals.toml");
        let content = r#"
[projects."github.com/user/repo"]
approved-commands = ["npm install"]
"#;
        std::fs::write(&config_path, content).unwrap();
        std::fs::write(&approvals_path, "# existing approvals\n").unwrap();

        let result = copy_approved_commands_to_approvals_file(&config_path);
        assert!(result.is_none(), "Should skip when approvals.toml exists");

        // Verify existing file was not overwritten
        let existing = std::fs::read_to_string(&approvals_path).unwrap();
        assert_eq!(existing, "# existing approvals\n");
    }

    #[test]
    fn test_copy_approved_commands_skips_when_empty() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.toml");
        let content = r#"
[projects."github.com/user/repo"]
worktree-path = ".worktrees/{{ branch | sanitize }}"
"#;
        std::fs::write(&config_path, content).unwrap();

        let result = copy_approved_commands_to_approvals_file(&config_path);
        assert!(
            result.is_none(),
            "Should skip when no approved-commands exist"
        );
    }

    #[test]
    fn test_set_implicit_suppresses_parent_header() {
        // Verifies that set_implicit(true) prevents an empty parent table from
        // rendering its own header. This is the key technique used in
        // migrate_commit_generation_sections to avoid creating spurious [commit]
        // headers when migrating [commit-generation] to [commit.generation].
        use toml_edit::{DocumentMut, Item, Table};

        let mut doc: DocumentMut = "[foo]\nbar = 1\n".parse().unwrap();
        let mut commit_table = Table::new();
        commit_table.set_implicit(true);
        let mut gen_table = Table::new();
        gen_table.insert("command", toml_edit::value("llm"));
        commit_table.insert("generation", Item::Table(gen_table));
        doc.insert("commit", Item::Table(commit_table));
        let result = doc.to_string();

        assert!(
            !result.contains("\n[commit]\n"),
            "set_implicit should suppress separate [commit] header"
        );
        assert!(
            result.contains("[commit.generation]"),
            "Should have [commit.generation] header"
        );
    }

    // Tests for [select] → [switch.picker] deprecation

    #[test]
    fn test_find_select_deprecation_none() {
        let content = r#"
[switch.picker]
pager = "delta --paging=never"
"#;
        assert!(!find_select_deprecation(content));
    }

    #[test]
    fn test_find_select_deprecation_present() {
        let content = r#"
[select]
pager = "delta --paging=never"
"#;
        assert!(find_select_deprecation(content));
    }

    #[test]
    fn test_find_select_deprecation_empty_not_flagged() {
        let content = r#"
[select]
"#;
        assert!(!find_select_deprecation(content));
    }

    #[test]
    fn test_find_select_deprecation_skips_when_new_exists() {
        // When both [select] and [switch.picker] exist, don't flag
        let content = r#"
[select]
pager = "old"

[switch.picker]
pager = "new"
"#;
        assert!(!find_select_deprecation(content));
    }

    #[test]
    fn test_find_select_deprecation_inline_table() {
        let content = r#"
select = { pager = "delta" }
"#;
        assert!(find_select_deprecation(content));
    }

    #[test]
    fn test_find_select_deprecation_empty_inline_table() {
        let content = r#"
select = {}
"#;
        assert!(!find_select_deprecation(content));
    }

    #[test]
    fn test_migrate_select_simple() {
        let content = r#"
[select]
pager = "delta --paging=never"
"#;
        let result = migrate_select_to_switch_picker(content);
        assert!(
            result.contains("[switch.picker]"),
            "Should have [switch.picker]: {result}"
        );
        assert!(
            result.contains("pager = \"delta --paging=never\""),
            "Should preserve pager: {result}"
        );
        assert!(
            !result.contains("[select]"),
            "Should remove [select]: {result}"
        );
    }

    #[test]
    fn test_migrate_select_skips_when_new_exists() {
        let content = r#"
[select]
pager = "old"

[switch.picker]
pager = "new"
"#;
        let result = migrate_select_to_switch_picker(content);
        assert_eq!(
            result, content,
            "Should not migrate when new section exists"
        );
    }

    #[test]
    fn test_migrate_select_invalid_toml() {
        let content = "this is { not valid toml";
        let result = migrate_select_to_switch_picker(content);
        assert_eq!(result, content, "Invalid TOML should be returned unchanged");
    }

    #[test]
    fn test_migrate_select_no_select_section() {
        let content = r#"
[list]
full = true
"#;
        let result = migrate_select_to_switch_picker(content);
        assert_eq!(result, content, "No [select] section means no migration");
    }

    #[test]
    fn test_detect_deprecations_includes_select() {
        let content = r#"
[select]
pager = "delta"
"#;
        let deprecations = detect_deprecations(content);
        assert!(deprecations.select);
        assert!(!deprecations.is_empty());
    }

    #[test]
    fn snapshot_migrate_select_to_switch_picker() {
        let content = r#"worktree-path = "../{{ repo }}.{{ branch | sanitize }}"

[select]
pager = "delta --paging=never"

[list]
branches = true
"#;
        let result = migrate_select_to_switch_picker(content);
        insta::assert_snapshot!(migration_diff(content, &result));
    }

    #[test]
    fn test_format_deprecation_details_select() {
        let content = r#"[select]
pager = "delta --paging=never"
"#;
        let info = DeprecationInfo {
            config_path: std::path::PathBuf::from("/tmp/test-config.toml"),
            deprecations: Deprecations {
                vars: vec![],
                commit_gen: CommitGenerationDeprecations::default(),
                approved_commands: false,
                select: true,
                post_create: false,
                ci_section: false,
                no_ff: false,
                no_cd: false,
                pre_hook_table_form: vec![],
            },
            label: "User config".to_string(),
            main_worktree_path: None,
        };
        let output = format_deprecation_details(&info, content);
        assert!(
            output.contains("[select]"),
            "Should mention [select] in output: {output}"
        );
        assert!(
            output.contains("[switch.picker]"),
            "Should mention [switch.picker]: {output}"
        );
    }

    #[test]
    fn test_compute_migrated_content_renames_select() {
        let content = r#"worktree-path = "../{{ repo }}.{{ branch | sanitize }}"

[select]
pager = "delta --paging=never"
"#;
        let migrated = compute_migrated_content(content);
        assert!(
            migrated.contains("[switch.picker]"),
            "Migrated content should have [switch.picker]: {migrated}"
        );
        assert!(
            !migrated.contains("[select]"),
            "Migrated content should not have [select]: {migrated}"
        );
    }

    // --- post-create → pre-start deprecation tests ---

    #[test]
    fn test_find_post_create_deprecation_none() {
        // No post-create, no deprecation
        let content = r#"
pre-start = "npm install"
"#;
        assert!(!find_post_create_deprecation(content));
    }

    #[test]
    fn test_find_post_create_deprecation_top_level() {
        // Project config format: bare key
        let content = r#"
post-create = "npm install"
"#;
        assert!(find_post_create_deprecation(content));
    }

    #[test]
    fn test_find_post_create_deprecation_project_level() {
        // User config format: hooks flattened into [projects."..."]
        let content = r#"
[projects."my-project"]
post-create = "npm install"
"#;
        assert!(find_post_create_deprecation(content));
    }

    #[test]
    fn test_find_post_create_deprecation_named_commands() {
        // Named command table format
        let content = r#"
[post-create]
lint = "npm run lint"
build = "npm run build"
"#;
        assert!(find_post_create_deprecation(content));
    }

    #[test]
    fn test_find_post_create_deprecation_empty_table_not_flagged() {
        // Empty [post-create] table is a no-op — don't warn
        let content = r#"
[post-create]
"#;
        assert!(!find_post_create_deprecation(content));
    }

    #[test]
    fn test_find_post_create_deprecation_skips_when_pre_start_exists_top_level() {
        // Both present at top level — don't flag
        let content = r#"
post-create = "old"
pre-start = "new"
"#;
        assert!(!find_post_create_deprecation(content));
    }

    #[test]
    fn test_find_post_create_deprecation_skips_when_pre_start_exists_project() {
        // Both present in project hooks — don't flag
        let content = r#"
[projects."my-project"]
post-create = "old"
pre-start = "new"
"#;
        assert!(!find_post_create_deprecation(content));
    }

    #[test]
    fn test_migrate_post_create_top_level() {
        let content = r#"
post-create = "npm install"

[post-start]
server = "npm run dev"
"#;
        let result = migrate_post_create_to_pre_start(content);
        assert!(
            result.contains("pre-start"),
            "Should have pre-start: {result}"
        );
        assert!(
            !result.contains("post-create"),
            "Should not have post-create: {result}"
        );
        assert!(
            result.contains("[post-start]"),
            "Should preserve other sections: {result}"
        );
    }

    #[test]
    fn test_migrate_post_create_project_level() {
        let content = r#"
[projects."my-project"]
post-create = "npm install"
"#;
        let result = migrate_post_create_to_pre_start(content);
        assert!(
            result.contains("pre-start"),
            "Should have pre-start: {result}"
        );
        assert!(
            !result.contains("post-create"),
            "Should not have post-create: {result}"
        );
    }

    #[test]
    fn test_migrate_post_create_named_commands() {
        let content = r#"
[post-create]
lint = "npm run lint"
build = "npm run build"
"#;
        let result = migrate_post_create_to_pre_start(content);
        assert!(
            result.contains("[pre-start]"),
            "Should rename section header: {result}"
        );
        assert!(
            !result.contains("[post-create]"),
            "Should not have old section header: {result}"
        );
        assert!(
            result.contains("lint = \"npm run lint\""),
            "Should preserve named commands: {result}"
        );
    }

    #[test]
    fn test_migrate_post_create_skips_when_pre_start_exists() {
        let content = r#"
post-create = "old"
pre-start = "new"
"#;
        let result = migrate_post_create_to_pre_start(content);
        assert_eq!(
            result, content,
            "Should not migrate when pre-start already exists"
        );
    }

    #[test]
    fn test_migrate_post_create_invalid_toml() {
        let content = "this is { not valid toml";
        let result = migrate_post_create_to_pre_start(content);
        assert_eq!(result, content, "Invalid TOML should be returned unchanged");
    }

    #[test]
    fn test_migrate_post_create_no_post_create() {
        let content = r#"
pre-start = "npm install"
"#;
        let result = migrate_post_create_to_pre_start(content);
        assert_eq!(result, content, "No post-create means no migration");
    }

    #[test]
    fn test_detect_deprecations_includes_post_create() {
        let content = r#"
post-create = "npm install"
"#;
        let deprecations = detect_deprecations(content);
        assert!(deprecations.post_create);
        assert!(!deprecations.is_empty());
    }

    #[test]
    fn snapshot_migrate_post_create_to_pre_start() {
        let content = r#"post-create = "npm install"

[post-start]
server = "npm run dev"
"#;
        let result = migrate_post_create_to_pre_start(content);
        insta::assert_snapshot!(migration_diff(content, &result));
    }

    #[test]
    fn test_format_deprecation_details_post_create() {
        let content = r#"post-create = "npm install"
"#;
        let info = DeprecationInfo {
            config_path: std::path::PathBuf::from("/tmp/test-config.toml"),
            deprecations: Deprecations {
                vars: vec![],
                commit_gen: CommitGenerationDeprecations::default(),
                approved_commands: false,
                select: false,
                post_create: true,
                ci_section: false,
                no_ff: false,
                no_cd: false,
                pre_hook_table_form: vec![],
            },
            label: "Project config".to_string(),
            main_worktree_path: None,
        };
        let output = format_deprecation_details(&info, content);
        assert!(
            output.contains("post-create"),
            "Should mention post-create: {output}"
        );
        assert!(
            output.contains("pre-start"),
            "Should mention pre-start: {output}"
        );
    }

    #[test]
    fn test_compute_migrated_content_renames_post_create() {
        let content = r#"post-create = "npm install"

[post-start]
server = "npm run dev"
"#;
        let migrated = compute_migrated_content(content);
        assert!(
            migrated.contains("pre-start"),
            "Migrated content should have pre-start: {migrated}"
        );
        assert!(
            !migrated.contains("post-create"),
            "Migrated content should not have post-create: {migrated}"
        );
    }

    // ==================== negated bool format + migration tests ====================

    #[test]
    fn test_format_deprecation_warnings_no_ff_and_no_cd() {
        let info = DeprecationInfo {
            config_path: std::path::PathBuf::from("/tmp/test-config.toml"),
            deprecations: Deprecations {
                vars: vec![],
                commit_gen: CommitGenerationDeprecations::default(),
                approved_commands: false,
                select: false,
                post_create: false,
                ci_section: false,
                no_ff: true,
                no_cd: true,
                pre_hook_table_form: vec![],
            },
            label: "User config".to_string(),
            main_worktree_path: None,
        };
        let output = format_deprecation_warnings(&info);
        assert!(output.contains("no-ff"), "Should mention no-ff: {output}");
        assert!(output.contains("no-cd"), "Should mention no-cd: {output}");
    }

    #[test]
    fn test_detect_no_ff_deprecation() {
        let deprecations = detect_deprecations("[merge]\nno-ff = true\n");
        assert!(deprecations.no_ff);
    }

    #[test]
    fn test_detect_no_ff_not_flagged_when_ff_exists() {
        let deprecations = detect_deprecations("[merge]\nff = true\nno-ff = true\n");
        assert!(!deprecations.no_ff);
    }

    #[test]
    fn test_detect_no_cd_deprecation() {
        let deprecations = detect_deprecations("[switch]\nno-cd = true\n");
        assert!(deprecations.no_cd);
    }

    #[test]
    fn test_detect_no_ff_project_level() {
        let content = r#"
[projects."github.com/user/repo".merge]
no-ff = true
"#;
        let deprecations = detect_deprecations(content);
        assert!(deprecations.no_ff);
    }

    #[test]
    fn test_migrate_no_ff_to_ff() {
        let content = "[merge]\nno-ff = true\n";
        let result = migrate_content(content);
        assert!(result.contains("ff = false"), "Should invert: {result}");
        assert!(!result.contains("no-ff"), "Should remove no-ff: {result}");
    }

    #[test]
    fn test_migrate_no_cd_to_cd() {
        let content = "[switch]\nno-cd = false\n";
        let result = migrate_content(content);
        assert!(result.contains("cd = true"), "Should invert: {result}");
        assert!(!result.contains("no-cd"), "Should remove no-cd: {result}");
    }

    #[test]
    fn test_migrate_no_ff_project_level() {
        let content = r#"
[projects."github.com/user/repo".merge]
no-ff = true
"#;
        let result = migrate_content(content);
        assert!(result.contains("ff = false"), "Should migrate: {result}");
        assert!(!result.contains("no-ff"), "Should remove no-ff: {result}");
    }

    #[test]
    fn test_migrate_negated_bool_non_boolean_value_preserved() {
        // Non-boolean `no-ff` value should be left alone
        let content = "[merge]\nno-ff = \"not-a-bool\"\n";
        let result = migrate_content(content);
        assert!(
            result.contains("no-ff"),
            "Non-boolean value should be preserved: {result}"
        );
    }

    #[test]
    fn test_migrate_no_ff_skips_when_ff_exists() {
        let content = "[merge]\nff = true\nno-ff = true\n";
        let result = migrate_content(content);
        assert!(result.contains("ff = true"), "ff should be kept: {result}");
        assert!(
            !result.contains("no-ff"),
            "no-ff should be removed: {result}"
        );
    }

    // ==================== project-level select migration tests ====================

    #[test]
    fn test_detect_select_project_level() {
        let content = r#"
[projects."github.com/user/repo".select]
pager = "bat"
"#;
        let deprecations = detect_deprecations(content);
        assert!(deprecations.select);
    }

    #[test]
    fn test_migrate_select_project_level() {
        let content = r#"
[projects."github.com/user/repo".select]
pager = "bat"
"#;
        let result = migrate_content(content);
        assert!(
            result.contains("[projects.\"github.com/user/repo\".switch.picker]"),
            "Should migrate project select: {result}"
        );
        assert!(
            !result.contains("[projects.\"github.com/user/repo\".select]"),
            "Should remove project select: {result}"
        );
    }

    // ==================== migrate_content tests ====================

    #[test]
    fn test_migrate_content_applies_all_structural_migrations() {
        let content = r#"
[commit-generation]
command = "llm"

[select]
pager = "delta"

[merge]
no-ff = true

[switch]
no-cd = true
"#;
        let result = migrate_content(content);
        assert!(
            result.contains("[commit.generation]"),
            "commit-generation: {result}"
        );
        assert!(
            result.contains("[switch.picker]"),
            "select to switch.picker: {result}"
        );
        assert!(result.contains("ff = false"), "no-ff to ff: {result}");
        assert!(result.contains("cd = false"), "no-cd to cd: {result}");
    }

    #[test]
    fn test_migrate_content_is_no_op_for_canonical_config() {
        let content = r#"
[commit.generation]
command = "llm"

[merge]
ff = true
"#;
        let result = migrate_content(content);
        assert_eq!(result, content);
    }

    #[test]
    fn test_warn_unknown_fields_deprecated_key_in_wrong_config() {
        use crate::config::{ProjectConfig, UserConfig};

        // commit-generation in project config → should warn "belongs in user config"
        let path = std::env::temp_dir().join("test-deprecated-wrong-config-project.toml");
        warn_unknown_fields::<ProjectConfig>(
            "[commit-generation]\ncommand = \"llm\"\n",
            &path,
            "Project config",
        );

        // ci in user config → should warn "belongs in project config"
        let path = std::env::temp_dir().join("test-deprecated-wrong-config-user.toml");
        warn_unknown_fields::<UserConfig>("[ci]\nplatform = \"github\"\n", &path, "User config");
    }

    // ==================== pre-hook table form tests ====================

    fn find_pre_hook_table_form(content: &str) -> Vec<String> {
        content
            .parse::<toml_edit::DocumentMut>()
            .map(|doc| find_pre_hook_table_form_from_doc(&doc))
            .unwrap_or_default()
    }

    fn migrate_pre_hook_table_form(content: &str) -> String {
        let Ok(mut doc) = content.parse::<toml_edit::DocumentMut>() else {
            return content.to_string();
        };
        if migrate_pre_hook_table_form_doc(&mut doc) {
            doc.to_string()
        } else {
            content.to_string()
        }
    }

    #[test]
    fn test_detect_pre_hook_table_form() {
        // Multi-entry table → detected
        let found = find_pre_hook_table_form("[pre-merge]\ntest = \"t\"\nlint = \"l\"\n");
        assert_eq!(found, vec!["pre-merge"]);

        // Single-entry table → not detected
        let found = find_pre_hook_table_form("[pre-merge]\ntest = \"t\"\n");
        assert!(found.is_empty());

        // String form → not detected
        let found = find_pre_hook_table_form("pre-merge = \"cargo test\"\n");
        assert!(found.is_empty());

        // Array/pipeline form → not detected
        let found = find_pre_hook_table_form("pre-merge = [{test = \"t\"}, {lint = \"l\"}]\n");
        assert!(found.is_empty());

        // Post-* hooks → not detected (table form is canonical for post-*)
        let found = find_pre_hook_table_form("[post-merge]\ntest = \"t\"\nlint = \"l\"\n");
        assert!(found.is_empty());

        // All 5 pre-* keys detected
        let content = r#"
[pre-switch]
a = "1"
b = "2"

[pre-start]
a = "1"
b = "2"

[pre-commit]
a = "1"
b = "2"

[pre-merge]
a = "1"
b = "2"

[pre-remove]
a = "1"
b = "2"
"#;
        let found = find_pre_hook_table_form(content);
        assert_eq!(
            found,
            vec![
                "pre-switch",
                "pre-start",
                "pre-commit",
                "pre-merge",
                "pre-remove"
            ]
        );
    }

    #[test]
    fn test_detect_pre_hook_table_form_per_project() {
        // Per-project overrides: hooks are flattened under [projects."id"]
        let content = r#"
[projects."github.com/user/repo".pre-start]
install = "npm ci"
build = "npm run build"
"#;
        let found = find_pre_hook_table_form(content);
        assert_eq!(found, vec!["projects.\"github.com/user/repo\".pre-start"]);
    }

    #[test]
    fn test_migrate_pre_hook_table_form_converts_to_pipeline() {
        let content = r#"
[pre-merge]
test = "cargo test"
lint = "cargo clippy"
"#;
        let result = migrate_pre_hook_table_form(content);
        // Should produce `[[pre-merge]]` array-of-tables blocks
        assert!(
            result.contains("[[pre-merge]]"),
            "Should emit [[pre-merge]] blocks: {result}"
        );
        // Verify it parses back as valid TOML with the right structure
        let doc: toml_edit::DocumentMut = result.parse().unwrap();
        let arr = doc["pre-merge"]
            .as_array_of_tables()
            .expect("should be array of tables");
        assert_eq!(arr.len(), 2);
        let first = arr.get(0).unwrap();
        assert_eq!(first.get("test").unwrap().as_str().unwrap(), "cargo test");
        let second = arr.get(1).unwrap();
        assert_eq!(
            second.get("lint").unwrap().as_str().unwrap(),
            "cargo clippy"
        );
    }

    #[test]
    fn test_migrate_pre_hook_table_form_preserves_order() {
        let content = r#"
[pre-merge]
first = "1"
second = "2"
third = "3"
"#;
        let result = migrate_pre_hook_table_form(content);
        let doc: toml_edit::DocumentMut = result.parse().unwrap();
        let arr = doc["pre-merge"].as_array_of_tables().unwrap();
        let names: Vec<&str> = arr.iter().map(|t| t.iter().next().unwrap().0).collect();
        assert_eq!(names, vec!["first", "second", "third"]);
    }

    #[test]
    fn test_migrate_pre_hook_table_form_single_entry_untouched() {
        let content = "[pre-merge]\ntest = \"t\"\n";
        let result = migrate_pre_hook_table_form(content);
        assert_eq!(result, content, "Single-entry table should not be migrated");
    }

    #[test]
    fn test_migrate_pre_hook_table_form_per_project() {
        let content = r#"
[projects."web".pre-start]
install = "npm ci"
build = "npm run build"
"#;
        let result = migrate_pre_hook_table_form(content);
        let doc: toml_edit::DocumentMut = result.parse().unwrap();
        let project = doc["projects"]["web"].as_table().unwrap();
        let arr = project["pre-start"]
            .as_array_of_tables()
            .expect("should be array of tables");
        assert_eq!(arr.len(), 2);
    }

    #[test]
    fn test_migrate_pre_hook_table_form_after_post_create_rename() {
        // post-create → pre-start rename should happen first, then table form migration
        let content = r#"
[post-create]
install = "npm ci"
build = "npm run build"
"#;
        let result = migrate_content(content);
        // post-create should be renamed to pre-start AND converted to pipeline
        assert!(
            !result.contains("post-create"),
            "post-create should be renamed: {result}"
        );
        let doc: toml_edit::DocumentMut = result.parse().unwrap();
        let arr = doc["pre-start"]
            .as_array_of_tables()
            .expect("should be pipeline array of tables");
        assert_eq!(arr.len(), 2);
    }

    #[test]
    fn test_migrate_content_includes_pre_hook_table_form() {
        let content = r#"
[pre-merge]
test = "cargo test"
lint = "cargo clippy"

[merge]
no-ff = true
"#;
        let result = migrate_content(content);
        assert!(
            result.contains("[[pre-merge]]"),
            "Table section should become [[pre-merge]] blocks: {result}"
        );
        assert!(
            result.contains("ff = false"),
            "no-ff should also migrate: {result}"
        );
    }

    #[test]
    fn snapshot_migrate_pre_hook_table_form() {
        let content = r#"[pre-merge]
test = "cargo test"
lint = "cargo clippy"

[post-start]
server = "npm run dev"
"#;
        let result = migrate_pre_hook_table_form(content);
        insta::assert_snapshot!(migration_diff(content, &result));
    }
}