autom8-cli 0.3.0

CLI automation tool for orchestrating Claude-powered development
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
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
use crate::error::{Autom8Error, Result};
use serde::{Deserialize, Serialize};
use std::env;
use std::fs;
use std::path::PathBuf;

/// The base config directory name under ~/.config/
const CONFIG_DIR_NAME: &str = "autom8";

// ============================================================================
// State Machine Configuration
// ============================================================================

/// Configuration for controlling which states are executed in the autom8 state machine.
///
/// This struct represents the user's preferences for which steps of the automation
/// pipeline should be executed. Each field corresponds to a state in the state machine.
///
/// # Default Behavior
///
/// By default, all states are enabled (`true`), meaning the full pipeline runs:
/// review → commit → pull request.
///
/// # Serialization
///
/// This struct supports TOML serialization via serde. Missing fields in a config file
/// will default to `true`, allowing partial configs to work correctly.
///
/// # Example
///
/// ```toml
/// # Enable/disable the review state (code review before committing)
/// review = true
///
/// # Enable/disable the commit state (creating git commits)
/// commit = true
///
/// # Enable/disable the pull request state (creating PRs)
/// pull_request = true
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Config {
    /// Whether to run the review state.
    ///
    /// When `true`, code changes are reviewed before committing.
    /// When `false`, the review step is skipped.
    #[serde(default = "default_true")]
    pub review: bool,

    /// Whether to run the commit state.
    ///
    /// When `true`, changes are committed to git.
    /// When `false`, changes are left uncommitted.
    #[serde(default = "default_true")]
    pub commit: bool,

    /// Whether to run the pull request state.
    ///
    /// When `true`, a pull request is created after committing.
    /// When `false`, no PR is created.
    #[serde(default = "default_true")]
    pub pull_request: bool,

    /// Whether to create pull requests in draft mode.
    ///
    /// When `true`, PRs are created as drafts (not ready for review).
    /// When `false`, PRs are created as regular (ready for review) PRs.
    ///
    /// Note: Only applies when `pull_request = true`. Has no effect otherwise.
    #[serde(default = "default_false")]
    pub pull_request_draft: bool,

    /// Whether to automatically create worktrees for runs.
    ///
    /// When `true`, autom8 creates a dedicated worktree for each run,
    /// enabling multiple parallel sessions for the same project.
    /// When `false`, autom8 runs on the current branch (default behavior).
    ///
    /// Note: Requires a git repository. Has no effect outside of git repos.
    #[serde(default = "default_true")]
    pub worktree: bool,

    /// Pattern for worktree directory names.
    ///
    /// Placeholders:
    /// - `{repo}` - The repository name
    /// - `{branch}` - The branch name (slugified: slashes replaced with dashes)
    ///
    /// Default: `{repo}-wt-{branch}`
    /// Example: For repo "myproject" and branch "feature/login", creates "myproject-wt-feature-login"
    #[serde(default = "default_worktree_path_pattern")]
    pub worktree_path_pattern: String,

    /// Whether to remove worktrees after successful completion.
    ///
    /// When `true`, autom8 automatically removes the worktree directory after
    /// a successful run (Completed state). Failed runs keep their worktrees.
    /// When `false`, worktrees are preserved for manual inspection/cleanup.
    ///
    /// Note: Only applies when `worktree = true`. Has no effect otherwise.
    #[serde(default = "default_false")]
    pub worktree_cleanup: bool,
}

/// Default worktree path pattern.
fn default_worktree_path_pattern() -> String {
    "{repo}-wt-{branch}".to_string()
}

/// Helper function for serde default values (true).
fn default_true() -> bool {
    true
}

/// Helper function for serde default values (false).
fn default_false() -> bool {
    false
}

impl Default for Config {
    fn default() -> Self {
        Self {
            review: true,
            commit: true,
            pull_request: true,
            pull_request_draft: false,
            worktree: true,
            worktree_path_pattern: default_worktree_path_pattern(),
            worktree_cleanup: false,
        }
    }
}

// ============================================================================
// Config Validation
// ============================================================================

use std::error::Error;
use std::fmt;

/// Error type for configuration validation failures.
///
/// This enum represents specific validation errors that can occur when
/// validating configuration settings. Each variant provides a clear,
/// actionable error message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigError {
    /// Pull request is enabled but commit is disabled.
    ///
    /// Creating a pull request requires commits to exist, so this
    /// configuration combination is invalid.
    PullRequestWithoutCommit,
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConfigError::PullRequestWithoutCommit => {
                write!(
                    f,
                    "Cannot create pull request without commits. \
                    Either set `commit = true` or set `pull_request = false`"
                )
            }
        }
    }
}

impl Error for ConfigError {}

/// Validate a configuration for logical consistency.
///
/// This function checks that the configuration settings are valid and
/// consistent with each other. It should be called after loading a config
/// and before the state machine starts.
///
/// # Validation Rules
///
/// - `pull_request = true` requires `commit = true`
///   (Cannot create a PR without commits)
///
/// # Arguments
///
/// * `config` - The configuration to validate
///
/// # Returns
///
/// * `Ok(())` if the configuration is valid
/// * `Err(ConfigError)` if the configuration is invalid, with a clear error message
///
/// # Example
///
/// ```
/// use autom8::config::{Config, validate_config};
///
/// let valid_config = Config::default();
/// assert!(validate_config(&valid_config).is_ok());
///
/// let invalid_config = Config {
///     review: true,
///     commit: false,
///     pull_request: true, // Invalid: PR without commit
///     ..Default::default()
/// };
/// assert!(validate_config(&invalid_config).is_err());
/// ```
pub fn validate_config(config: &Config) -> std::result::Result<(), ConfigError> {
    // Rule: pull_request = true requires commit = true
    if config.pull_request && !config.commit {
        return Err(ConfigError::PullRequestWithoutCommit);
    }

    Ok(())
}

// ============================================================================
// Global Config File Management
// ============================================================================

/// The filename for the global configuration file.
const GLOBAL_CONFIG_FILENAME: &str = "config.toml";

/// Default config file content with explanatory comments.
///
/// This is written when creating a new config file to help users understand
/// each option without needing to reference documentation.
const DEFAULT_CONFIG_WITH_COMMENTS: &str = r#"# Autom8 Configuration
# This file controls which states in the autom8 state machine are executed.

# Review state: Code review before committing
# - true: Run code review step to check implementation quality
# - false: Skip code review and proceed directly to commit
review = true

# Commit state: Creating git commits
# - true: Automatically commit changes after implementation
# - false: Leave changes uncommitted (manual commit required)
commit = true

# Pull request state: Creating pull requests
# - true: Automatically create a PR after committing
# - false: Skip PR creation (commits remain on local branch)
# Note: Requires commit = true to work
pull_request = true

# Pull request draft mode: Create PRs as drafts
# - true: Create PRs as drafts (not ready for review)
# - false: Create PRs as regular (ready for review) PRs (default)
# Note: Only applies when pull_request = true. Has no effect otherwise.
pull_request_draft = false

# Worktree mode: Automatic worktree creation for parallel runs
# - true: Create a dedicated worktree for each run (enables parallel sessions, default)
# - false: Run on the current branch (single session per project)
# Note: Requires a git repository. Has no effect outside of git repos.
worktree = true

# Worktree path pattern: Pattern for naming worktree directories
# Placeholders: {repo} = repository name, {branch} = branch name (slugified)
# Default: {repo}-wt-{branch} (e.g., "myproject-wt-feature-login")
worktree_path_pattern = "{repo}-wt-{branch}"

# Worktree cleanup: Automatically remove worktrees after successful completion
# - true: Remove worktree directory after run completes successfully
# - false: Preserve worktrees for manual inspection/cleanup (default)
# Note: Failed runs always keep their worktrees. Only applies when worktree = true.
worktree_cleanup = false
"#;

/// Get the path to the global config file.
///
/// Returns the path to `~/.config/autom8/config.toml`.
pub fn global_config_path() -> Result<PathBuf> {
    Ok(config_dir()?.join(GLOBAL_CONFIG_FILENAME))
}

/// Load the global configuration from `~/.config/autom8/config.toml`.
///
/// If the config file doesn't exist, it creates one with default values
/// and helpful comments explaining each option.
///
/// # Returns
///
/// The loaded or newly-created default configuration.
///
/// # Errors
///
/// Returns an error if:
/// - The home directory cannot be determined
/// - The config directory cannot be created
/// - The config file cannot be read (other than not existing)
/// - The config file contains invalid TOML
pub fn load_global_config() -> Result<Config> {
    let config_path = global_config_path()?;

    if !config_path.exists() {
        // Ensure the config directory exists
        ensure_config_dir()?;

        // Create the config file with default values and comments
        fs::write(&config_path, DEFAULT_CONFIG_WITH_COMMENTS)?;

        return Ok(Config::default());
    }

    // Read and parse the existing config file
    let content = fs::read_to_string(&config_path)?;
    let config: Config = toml::from_str(&content).map_err(|e| {
        Autom8Error::Config(format!(
            "Failed to parse config file at {:?}: {}",
            config_path, e
        ))
    })?;

    Ok(config)
}

/// Save the global configuration to `~/.config/autom8/config.toml`.
///
/// This writes the configuration with explanatory comments. Note that this
/// will overwrite any existing file, including any user-added comments.
///
/// # Arguments
///
/// * `config` - The configuration to save
///
/// # Errors
///
/// Returns an error if:
/// - The home directory cannot be determined
/// - The config directory cannot be created
/// - The config file cannot be written
pub fn save_global_config(config: &Config) -> Result<()> {
    let config_path = global_config_path()?;

    // Ensure the config directory exists
    ensure_config_dir()?;

    // Generate config content with comments
    let content = generate_config_with_comments(config);

    fs::write(&config_path, content)?;

    Ok(())
}

/// Generate config file content with explanatory comments.
///
/// Creates a TOML string that includes comments explaining each option,
/// using the actual values from the provided config.
fn generate_config_with_comments(config: &Config) -> String {
    format!(
        r#"# Autom8 Configuration
# This file controls which states in the autom8 state machine are executed.

# Review state: Code review before committing
# - true: Run code review step to check implementation quality
# - false: Skip code review and proceed directly to commit
review = {}

# Commit state: Creating git commits
# - true: Automatically commit changes after implementation
# - false: Leave changes uncommitted (manual commit required)
commit = {}

# Pull request state: Creating pull requests
# - true: Automatically create a PR after committing
# - false: Skip PR creation (commits remain on local branch)
# Note: Requires commit = true to work
pull_request = {}

# Pull request draft mode: Create PRs as drafts
# - true: Create PRs as drafts (not ready for review)
# - false: Create PRs as regular (ready for review) PRs (default)
# Note: Only applies when pull_request = true. Has no effect otherwise.
pull_request_draft = {}

# Worktree mode: Automatic worktree creation for parallel runs
# - true: Create a dedicated worktree for each run (enables parallel sessions, default)
# - false: Run on the current branch (single session per project)
# Note: Requires a git repository. Has no effect outside of git repos.
worktree = {}

# Worktree path pattern: Pattern for naming worktree directories
# Placeholders: {{repo}} = repository name, {{branch}} = branch name (slugified)
# Default: {{repo}}-wt-{{branch}} (e.g., "myproject-wt-feature-login")
worktree_path_pattern = "{}"

# Worktree cleanup: Automatically remove worktrees after successful completion
# - true: Remove worktree directory after run completes successfully
# - false: Preserve worktrees for manual inspection/cleanup (default)
# Note: Failed runs always keep their worktrees. Only applies when worktree = true.
worktree_cleanup = {}
"#,
        config.review,
        config.commit,
        config.pull_request,
        config.pull_request_draft,
        config.worktree,
        config.worktree_path_pattern,
        config.worktree_cleanup
    )
}

// ============================================================================
// Project Config File Management
// ============================================================================

/// The filename for project-specific configuration files.
const PROJECT_CONFIG_FILENAME: &str = "config.toml";

/// Get the path to a project's config file.
///
/// Returns the path to `~/.config/autom8/<project>/config.toml`.
pub fn project_config_path() -> Result<PathBuf> {
    Ok(project_config_dir()?.join(PROJECT_CONFIG_FILENAME))
}

/// Get the path to a specific project's config file by name.
///
/// Returns the path to `~/.config/autom8/<project_name>/config.toml`.
pub fn project_config_path_for(project_name: &str) -> Result<PathBuf> {
    Ok(project_config_dir_for(project_name)?.join(PROJECT_CONFIG_FILENAME))
}

/// Load the project-specific configuration from `~/.config/autom8/<project>/config.toml`.
///
/// If the project config file doesn't exist, it copies the global config (with comments)
/// to the project config directory and returns the global config values.
///
/// # Returns
///
/// The loaded or inherited configuration.
///
/// # Errors
///
/// Returns an error if:
/// - The home directory cannot be determined
/// - The project config directory cannot be created
/// - The config file cannot be read (other than not existing)
/// - The config file contains invalid TOML
pub fn load_project_config() -> Result<Config> {
    let config_path = project_config_path()?;

    if !config_path.exists() {
        // Ensure the project config directory exists
        ensure_project_config_dir()?;

        // Copy global config (with comments) to project config
        let global_config = load_global_config()?;
        let content = generate_config_with_comments(&global_config);
        fs::write(&config_path, content)?;

        return Ok(global_config);
    }

    // Read and parse the existing project config file
    let content = fs::read_to_string(&config_path)?;
    let config: Config = toml::from_str(&content).map_err(|e| {
        Autom8Error::Config(format!(
            "Failed to parse project config file at {:?}: {}",
            config_path, e
        ))
    })?;

    Ok(config)
}

/// Save a project-specific configuration to `~/.config/autom8/<project>/config.toml`.
///
/// This writes the configuration with explanatory comments. Note that this
/// will overwrite any existing file, including any user-added comments.
///
/// # Arguments
///
/// * `config` - The configuration to save
///
/// # Errors
///
/// Returns an error if:
/// - The home directory cannot be determined
/// - The project config directory cannot be created
/// - The config file cannot be written
pub fn save_project_config(config: &Config) -> Result<()> {
    let config_path = project_config_path()?;

    // Ensure the project config directory exists
    ensure_project_config_dir()?;

    // Generate config content with comments
    let content = generate_config_with_comments(config);

    fs::write(&config_path, content)?;

    Ok(())
}

/// Save configuration to a specific project's config file by name.
///
/// This writes the configuration with explanatory comments to
/// `~/.config/autom8/<project_name>/config.toml`.
///
/// # Arguments
///
/// * `project_name` - The name of the project
/// * `config` - The configuration to save
///
/// # Errors
///
/// Returns an error if:
/// - The home directory cannot be determined
/// - The project config directory cannot be created
/// - The config file cannot be written
pub fn save_project_config_for(project_name: &str, config: &Config) -> Result<()> {
    let config_path = project_config_path_for(project_name)?;

    // Ensure the project config directory exists
    let config_dir = project_config_dir_for(project_name)?;
    fs::create_dir_all(&config_dir)?;

    // Generate config content with comments
    let content = generate_config_with_comments(config);

    fs::write(&config_path, content)?;

    Ok(())
}

/// Get the effective configuration for the current project.
///
/// This function returns the resolved configuration by checking:
/// 1. If a project config exists at `~/.config/autom8/<project>/config.toml`, return it
/// 2. Otherwise, return the global config from `~/.config/autom8/config.toml`
///
/// Unlike `load_project_config()`, this function does NOT create a project config
/// if one doesn't exist. It simply returns whichever config is applicable.
///
/// **Important:** This function validates the configuration before returning it.
/// Invalid configurations will result in an error.
///
/// # Returns
///
/// The effective configuration (project config if exists, else global config).
///
/// # Errors
///
/// Returns an error if:
/// - The home directory cannot be determined
/// - The config file cannot be read
/// - The config file contains invalid TOML
/// - The configuration is invalid (e.g., pull_request=true with commit=false)
pub fn get_effective_config() -> Result<Config> {
    let project_config_path = project_config_path()?;

    let config = if project_config_path.exists() {
        // Project config exists, load it directly (no auto-creation)
        let content = fs::read_to_string(&project_config_path)?;
        toml::from_str(&content).map_err(|e| {
            Autom8Error::Config(format!(
                "Failed to parse project config file at {:?}: {}",
                project_config_path, e
            ))
        })?
    } else {
        // No project config, load global config
        load_global_config()?
    };

    // Validate the configuration before returning
    validate_config(&config).map_err(|e| Autom8Error::Config(e.to_string()))?;

    Ok(config)
}

// ============================================================================
// Directory Management
// ============================================================================

/// Subdirectory names within a project config directory
const SPEC_SUBDIR: &str = "spec";
const RUNS_SUBDIR: &str = "runs";
const SESSIONS_SUBDIR: &str = "sessions";

/// Filename for project metadata
const PROJECT_METADATA_FILENAME: &str = "project.json";

/// Project metadata stored in `~/.config/autom8/<project>/project.json`.
///
/// Contains persistent information about the project that doesn't change
/// between runs, such as the path to the git repository.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectMetadata {
    /// The absolute path to the git repository root.
    pub repo_path: PathBuf,
}

/// Get the autom8 config directory path (~/.config/autom8/).
///
/// Returns the path to the config directory. Does not create the directory.
pub fn config_dir() -> Result<PathBuf> {
    let home = dirs::home_dir()
        .ok_or_else(|| Autom8Error::Config("Could not determine home directory".to_string()))?;
    Ok(home.join(".config").join(CONFIG_DIR_NAME))
}

/// Ensure the autom8 config directory exists (~/.config/autom8/).
///
/// Creates the directory if it doesn't exist. Returns whether the directory
/// was newly created (true) or already existed (false).
pub fn ensure_config_dir() -> Result<(PathBuf, bool)> {
    let dir = config_dir()?;
    let created = !dir.exists();
    fs::create_dir_all(&dir)?;
    Ok((dir, created))
}

/// Get the current project name.
///
/// Uses the git repository name (basename of the main repo root) when in a git
/// repository, ensuring consistent project identification across all worktrees.
/// Falls back to the current working directory basename if not in a git repo.
pub fn current_project_name() -> Result<String> {
    // Try to get the git repository name first
    if let Ok(Some(repo_name)) = crate::worktree::get_git_repo_name() {
        return Ok(repo_name);
    }

    // Fallback: use CWD basename for non-git directories
    let cwd = env::current_dir().map_err(|e| {
        Autom8Error::Config(format!("Could not determine current directory: {}", e))
    })?;
    cwd.file_name()
        .and_then(|n| n.to_str())
        .map(|s| s.to_string())
        .ok_or_else(|| {
            Autom8Error::Config("Could not determine project name from path".to_string())
        })
}

/// Get the project-specific config directory path (~/.config/autom8/<project-name>/).
///
/// Returns the path to the project config directory. Does not create the directory.
pub fn project_config_dir() -> Result<PathBuf> {
    let base = config_dir()?;
    let project_name = current_project_name()?;
    Ok(base.join(project_name))
}

/// Get the project-specific config directory path for a given project name.
pub fn project_config_dir_for(project_name: &str) -> Result<PathBuf> {
    let base = config_dir()?;
    Ok(base.join(project_name))
}

/// Ensure the project-specific config directory and its subdirectories exist.
///
/// Creates:
/// - `~/.config/autom8/<project-name>/`
/// - `~/.config/autom8/<project-name>/spec/`
/// - `~/.config/autom8/<project-name>/runs/`
/// - `~/.config/autom8/<project-name>/project.json` (with repo path)
///
/// Returns the project config directory path and whether it was newly created.
pub fn ensure_project_config_dir() -> Result<(PathBuf, bool)> {
    let dir = project_config_dir()?;
    let created = !dir.exists();

    // Create all subdirectories
    fs::create_dir_all(dir.join(SPEC_SUBDIR))?;
    fs::create_dir_all(dir.join(RUNS_SUBDIR))?;

    // Save project metadata with repo path (only if it doesn't exist yet)
    let metadata_path = dir.join(PROJECT_METADATA_FILENAME);
    if !metadata_path.exists() {
        if let Ok(repo_path) = crate::worktree::get_main_repo_root() {
            let metadata = ProjectMetadata { repo_path };
            if let Ok(content) = serde_json::to_string_pretty(&metadata) {
                let _ = fs::write(&metadata_path, content);
            }
        }
    }

    Ok((dir, created))
}

/// Get the repository path for a project by name.
///
/// Reads the `project.json` file from the project's config directory
/// and returns the stored `repo_path`.
///
/// Returns `None` if the project doesn't exist or has no metadata.
pub fn get_project_repo_path(project_name: &str) -> Option<PathBuf> {
    let project_dir = project_config_dir_for(project_name).ok()?;
    let metadata_path = project_dir.join(PROJECT_METADATA_FILENAME);

    let content = fs::read_to_string(&metadata_path).ok()?;
    let metadata: ProjectMetadata = serde_json::from_str(&content).ok()?;

    // Only return if the path still exists
    if metadata.repo_path.exists() {
        Some(metadata.repo_path)
    } else {
        None
    }
}

/// Get the spec subdirectory path for the current project.
pub fn spec_dir() -> Result<PathBuf> {
    Ok(project_config_dir()?.join(SPEC_SUBDIR))
}

/// Get the runs subdirectory path for the current project.
pub fn runs_dir() -> Result<PathBuf> {
    Ok(project_config_dir()?.join(RUNS_SUBDIR))
}

/// List all project directories in the config directory.
///
/// Returns a sorted list of project names (directory basenames) from `~/.config/autom8/`.
/// Only includes directories, not files.
pub fn list_projects() -> Result<Vec<String>> {
    let base = config_dir()?;

    if !base.exists() {
        return Ok(Vec::new());
    }

    let mut projects = Vec::new();

    let entries = fs::read_dir(&base)
        .map_err(|e| Autom8Error::Config(format!("Could not read config directory: {}", e)))?;

    for entry in entries {
        let entry = entry
            .map_err(|e| Autom8Error::Config(format!("Could not read directory entry: {}", e)))?;

        let path = entry.path();
        if path.is_dir() {
            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                projects.push(name.to_string());
            }
        }
    }

    projects.sort();
    Ok(projects)
}

/// Check if a file is already inside the autom8 config directory.
///
/// Returns true if the file path is inside `~/.config/autom8/` (any project).
/// This prevents moving files that are already in the config area, even if they're
/// in a different project's directory (e.g., a worktree-named project).
pub fn is_in_config_dir(file_path: &std::path::Path) -> Result<bool> {
    let base_config = config_dir()?;

    // Canonicalize both paths to handle relative paths and symlinks
    let canonical_file = file_path
        .canonicalize()
        .unwrap_or_else(|_| file_path.to_path_buf());
    let canonical_config = base_config.canonicalize().unwrap_or(base_config);

    Ok(canonical_file.starts_with(&canonical_config))
}

/// Result of moving a file to the config directory.
#[derive(Debug)]
pub struct MoveResult {
    /// The destination path where the file was moved.
    pub dest_path: PathBuf,
    /// Whether the file was actually moved (false if already in config dir).
    pub was_moved: bool,
}

/// Move a file to the appropriate config subdirectory if it's not already there.
///
/// Both markdown (`.md`) and JSON (`.json`) files are moved to `~/.config/autom8/<project-name>/spec/`
///
/// Uses `fs::rename()` when possible, falls back to copy+delete for cross-filesystem moves.
///
/// Returns the path to use for processing (either the original or the moved location).
pub fn move_to_config_dir(file_path: &std::path::Path) -> Result<MoveResult> {
    // If already in config directory, return original path
    if is_in_config_dir(file_path)? {
        let canonical = file_path
            .canonicalize()
            .unwrap_or_else(|_| file_path.to_path_buf());
        return Ok(MoveResult {
            dest_path: canonical,
            was_moved: false,
        });
    }

    // All files go to spec/ directory
    let dest_dir = spec_dir()?;

    // Ensure destination directory exists
    fs::create_dir_all(&dest_dir)?;

    // Get filename and create destination path
    let filename = file_path
        .file_name()
        .ok_or_else(|| Autom8Error::Config("Could not determine filename".to_string()))?;
    let dest_path = dest_dir.join(filename);

    // Try rename first (fast, atomic), fall back to copy+delete for cross-filesystem
    if fs::rename(file_path, &dest_path).is_err() {
        // Cross-filesystem move: copy then delete original
        fs::copy(file_path, &dest_path)?;
        fs::remove_file(file_path)?;
    }

    Ok(MoveResult {
        dest_path,
        was_moved: true,
    })
}

/// Status information for a single project.
#[derive(Debug, Clone)]
pub struct ProjectStatus {
    /// The project name (directory basename).
    pub name: String,
    /// Whether there is an active or failed run.
    pub has_active_run: bool,
    /// The run status (if any run exists).
    pub run_status: Option<crate::state::RunStatus>,
    /// Count of incomplete specs.
    pub incomplete_spec_count: usize,
    /// Total spec count.
    pub total_spec_count: usize,
}

impl ProjectStatus {
    /// Returns true if this project needs attention (active/failed run or incomplete specs).
    pub fn needs_attention(&self) -> bool {
        self.has_active_run
            || self.run_status == Some(crate::state::RunStatus::Failed)
            || self.incomplete_spec_count > 0
    }

    /// Returns true if this project is idle (no active work).
    pub fn is_idle(&self) -> bool {
        !self.needs_attention()
    }
}

/// Information about a project's directory contents for tree display.
#[derive(Debug, Clone)]
pub struct ProjectTreeInfo {
    /// The project name (directory basename).
    pub name: String,
    /// Whether there is an active run.
    pub has_active_run: bool,
    /// The run status (if any run exists).
    pub run_status: Option<crate::state::RunStatus>,
    /// Number of spec files in spec/ directory.
    pub spec_count: usize,
    /// Number of incomplete specs.
    pub incomplete_spec_count: usize,
    /// Number of markdown spec files in spec/ directory.
    pub spec_md_count: usize,
    /// Number of archived runs in runs/ directory.
    pub runs_count: usize,
    /// The date of the most recent run (archived or current).
    pub last_run_date: Option<chrono::DateTime<chrono::Utc>>,
}

impl ProjectTreeInfo {
    /// Returns a status label for the project.
    pub fn status_label(&self) -> &'static str {
        if self.has_active_run {
            "running"
        } else if self.run_status == Some(crate::state::RunStatus::Failed) {
            "failed"
        } else if self.incomplete_spec_count > 0 {
            "incomplete"
        } else if self.spec_count > 0 {
            "complete"
        } else {
            "empty"
        }
    }

    /// Returns true if this project has any content.
    pub fn has_content(&self) -> bool {
        self.spec_count > 0 || self.spec_md_count > 0 || self.runs_count > 0 || self.has_active_run
    }
}

/// Get detailed tree information for all projects.
///
/// Returns a list of `ProjectTreeInfo` for each project in `~/.config/autom8/`.
/// Projects are sorted alphabetically by name.
pub fn list_projects_tree() -> Result<Vec<ProjectTreeInfo>> {
    use crate::spec::Spec;
    use crate::state::{RunState, RunStatus, SessionMetadata};

    let projects = list_projects()?;
    let mut tree_info = Vec::new();

    for project_name in projects {
        let project_dir = project_config_dir_for(&project_name)?;

        // Check for active run by scanning all session metadata files directly
        // This avoids spawning git subprocess that StateManager::for_project() does
        let sessions_dir = project_dir.join(SESSIONS_SUBDIR);
        let mut has_active_run = false;
        let mut run_status: Option<RunStatus> = None;
        let mut active_run_started_at: Option<chrono::DateTime<chrono::Utc>> = None;

        if sessions_dir.exists() {
            if let Ok(entries) = fs::read_dir(&sessions_dir) {
                for entry in entries.filter_map(|e| e.ok()) {
                    let session_path = entry.path();
                    if !session_path.is_dir() {
                        continue;
                    }

                    // Check metadata.json for is_running flag
                    let metadata_path = session_path.join("metadata.json");
                    if let Ok(content) = fs::read_to_string(&metadata_path) {
                        if let Ok(metadata) = serde_json::from_str::<SessionMetadata>(&content) {
                            if metadata.is_running {
                                // Also load state.json to get the RunStatus
                                let state_path = session_path.join("state.json");
                                if let Ok(state_content) = fs::read_to_string(&state_path) {
                                    if let Ok(state) =
                                        serde_json::from_str::<RunState>(&state_content)
                                    {
                                        if state.status == RunStatus::Running {
                                            has_active_run = true;
                                            run_status = Some(state.status);
                                            active_run_started_at = Some(state.started_at);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // Count specs and incomplete specs by reading spec directory directly
        let spec_dir = project_dir.join(SPEC_SUBDIR);
        let mut specs: Vec<PathBuf> = Vec::new();
        let mut incomplete_count = 0;

        if spec_dir.exists() {
            if let Ok(entries) = fs::read_dir(&spec_dir) {
                for entry in entries.filter_map(|e| e.ok()) {
                    let path = entry.path();
                    if path.extension().is_some_and(|e| e == "json") {
                        specs.push(path.clone());
                        if let Ok(spec) = Spec::load(&path) {
                            if spec.is_incomplete() {
                                incomplete_count += 1;
                            }
                        }
                    }
                }
            }
        }

        // Count spec files (markdown specs)
        let spec_md_count = if spec_dir.exists() {
            fs::read_dir(&spec_dir)
                .map(|entries| {
                    entries
                        .filter_map(|e| e.ok())
                        .filter(|e| {
                            e.path().is_file()
                                && e.path().extension().is_some_and(|ext| ext == "md")
                        })
                        .count()
                })
                .unwrap_or(0)
        } else {
            0
        };

        // Get archived runs by reading runs directory directly
        let runs_dir = project_dir.join(RUNS_SUBDIR);
        let mut archived_runs: Vec<RunState> = Vec::new();

        if runs_dir.exists() {
            if let Ok(entries) = fs::read_dir(&runs_dir) {
                for entry in entries.filter_map(|e| e.ok()) {
                    let path = entry.path();
                    if path.extension().is_some_and(|e| e == "json") {
                        if let Ok(content) = fs::read_to_string(&path) {
                            if let Ok(state) = serde_json::from_str::<RunState>(&content) {
                                archived_runs.push(state);
                            }
                        }
                    }
                }
            }
        }
        // Sort by start date, newest first
        archived_runs.sort_by(|a, b| b.started_at.cmp(&a.started_at));
        let runs_count = archived_runs.len();

        // Determine last run date from archived runs or current run.
        // For active runs: use started_at (shows how long it's been running).
        // For completed runs: use finished_at (shows when it finished), falling back to started_at.
        let last_run_date = if has_active_run {
            // Active run: show when it started
            active_run_started_at
        } else {
            // No active run: fall back to most recent archived run
            archived_runs
                .first()
                .and_then(|r| r.finished_at.or(Some(r.started_at)))
        };

        tree_info.push(ProjectTreeInfo {
            name: project_name,
            has_active_run,
            run_status,
            spec_count: specs.len(),
            incomplete_spec_count: incomplete_count,
            spec_md_count,
            runs_count,
            last_run_date,
        });
    }

    Ok(tree_info)
}

/// Detailed information about a project for the describe command.
#[derive(Debug, Clone)]
pub struct ProjectDescription {
    /// The project name.
    pub name: String,
    /// Path to the project config directory.
    pub path: PathBuf,
    /// Whether there is an active run.
    pub has_active_run: bool,
    /// The run status (if any run exists).
    pub run_status: Option<crate::state::RunStatus>,
    /// Current story being worked on (if any).
    pub current_story: Option<String>,
    /// Current branch from state (if any).
    pub current_branch: Option<String>,
    /// List of specs with their details.
    pub specs: Vec<SpecSummary>,
    /// Number of markdown spec files.
    pub spec_md_count: usize,
    /// Number of archived runs.
    pub runs_count: usize,
}

/// Summary of a single spec.
#[derive(Debug, Clone)]
pub struct SpecSummary {
    /// The spec filename.
    pub filename: String,
    /// Full path to the spec file.
    pub path: PathBuf,
    /// Project name from the spec.
    pub project_name: String,
    /// Branch name from the spec.
    pub branch_name: String,
    /// Description from the spec.
    pub description: String,
    /// All user stories with their status.
    pub stories: Vec<StorySummary>,
    /// Number of completed stories.
    pub completed_count: usize,
    /// Total number of stories.
    pub total_count: usize,
    /// Whether this spec is currently being executed (has an active run).
    pub is_active: bool,
}

/// Summary of a user story.
#[derive(Debug, Clone)]
pub struct StorySummary {
    /// Story ID (e.g., "US-001").
    pub id: String,
    /// Story title.
    pub title: String,
    /// Whether the story passes.
    pub passes: bool,
}

/// Check if a project exists in the config directory.
pub fn project_exists(project_name: &str) -> Result<bool> {
    let project_dir = project_config_dir_for(project_name)?;
    Ok(project_dir.exists())
}

/// Get detailed description of a project.
///
/// Returns `None` if the project doesn't exist.
pub fn get_project_description(project_name: &str) -> Result<Option<ProjectDescription>> {
    use crate::spec::Spec;
    use crate::state::StateManager;

    let project_dir = project_config_dir_for(project_name)?;

    if !project_dir.exists() {
        return Ok(None);
    }

    let sm = StateManager::for_project(project_name)?;

    // Check for active run
    let run_state = sm.load_current().ok().flatten();
    let has_active_run = run_state
        .as_ref()
        .map(|s| s.status == crate::state::RunStatus::Running)
        .unwrap_or(false);
    let run_status = run_state.as_ref().map(|s| s.status);
    let current_story = run_state.as_ref().and_then(|s| s.current_story.clone());
    let current_branch = run_state.map(|s| s.branch);

    // Load specs with details
    let spec_paths = sm.list_specs().unwrap_or_default();
    let mut specs = Vec::new();

    for spec_path in spec_paths {
        if let Ok(spec) = Spec::load(&spec_path) {
            let stories: Vec<StorySummary> = spec
                .user_stories
                .iter()
                .map(|s| StorySummary {
                    id: s.id.clone(),
                    title: s.title.clone(),
                    passes: s.passes,
                })
                .collect();

            let completed_count = stories.iter().filter(|s| s.passes).count();
            let total_count = stories.len();

            let filename = spec_path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("unknown")
                .to_string();

            // A spec is active if there's an active run and the spec's branch matches the current branch
            let is_active = has_active_run
                && current_branch
                    .as_ref()
                    .is_some_and(|b| b == &spec.branch_name);

            specs.push(SpecSummary {
                filename,
                path: spec_path,
                project_name: spec.project,
                branch_name: spec.branch_name.clone(),
                description: spec.description,
                stories,
                completed_count,
                total_count,
                is_active,
            });
        }
    }

    // Count spec files (markdown specs)
    let spec_dir = project_dir.join(SPEC_SUBDIR);
    let spec_md_count = if spec_dir.exists() {
        fs::read_dir(&spec_dir)
            .map(|entries| {
                entries
                    .filter_map(|e| e.ok())
                    .filter(|e| {
                        e.path().is_file() && e.path().extension().is_some_and(|ext| ext == "md")
                    })
                    .count()
            })
            .unwrap_or(0)
    } else {
        0
    };

    // Count archived runs
    let runs_count = sm.list_archived().unwrap_or_default().len();

    Ok(Some(ProjectDescription {
        name: project_name.to_string(),
        path: project_dir,
        has_active_run,
        run_status,
        current_story,
        current_branch,
        specs,
        spec_md_count,
        runs_count,
    }))
}

/// Get status for all projects across the config directory.
///
/// Returns a list of `ProjectStatus` for each project in `~/.config/autom8/`.
/// Projects are sorted alphabetically by name.
pub fn global_status() -> Result<Vec<ProjectStatus>> {
    use crate::spec::Spec;
    use crate::state::StateManager;

    let projects = list_projects()?;
    let mut statuses = Vec::new();

    for project_name in projects {
        let sm = StateManager::for_project(&project_name)?;

        // Check for active run
        let run_state = sm.load_current().ok().flatten();
        let has_active_run = run_state
            .as_ref()
            .map(|s| s.status == crate::state::RunStatus::Running)
            .unwrap_or(false);
        let run_status = run_state.map(|s| s.status);

        // Count incomplete specs
        let specs = sm.list_specs().unwrap_or_default();
        let mut incomplete_count = 0;
        let mut total_count = 0;

        for spec_path in &specs {
            if let Ok(spec) = Spec::load(spec_path) {
                total_count += 1;
                if spec.is_incomplete() {
                    incomplete_count += 1;
                }
            }
        }

        statuses.push(ProjectStatus {
            name: project_name,
            has_active_run,
            run_status,
            incomplete_spec_count: incomplete_count,
            total_spec_count: total_count,
        });
    }

    Ok(statuses)
}

/// Get status for all projects at a given config directory (for testing).
#[cfg(test)]
fn global_status_at(base_config_dir: &std::path::Path) -> Result<Vec<ProjectStatus>> {
    use crate::spec::Spec;
    use crate::state::StateManager;

    let projects = list_projects_at(base_config_dir)?;
    let mut statuses = Vec::new();

    for project_name in projects {
        let project_dir = base_config_dir.join(&project_name);
        let sm = StateManager::with_dir(project_dir);

        // Check for active run
        let run_state = sm.load_current().ok().flatten();
        let has_active_run = run_state
            .as_ref()
            .map(|s| s.status == crate::state::RunStatus::Running)
            .unwrap_or(false);
        let run_status = run_state.map(|s| s.status);

        // Count incomplete specs
        let specs = sm.list_specs().unwrap_or_default();
        let mut incomplete_count = 0;
        let mut total_count = 0;

        for spec_path in &specs {
            if let Ok(spec) = Spec::load(spec_path) {
                total_count += 1;
                if spec.is_incomplete() {
                    incomplete_count += 1;
                }
            }
        }

        statuses.push(ProjectStatus {
            name: project_name,
            has_active_run,
            run_status,
            incomplete_spec_count: incomplete_count,
            total_spec_count: total_count,
        });
    }

    Ok(statuses)
}

/// List all project directories at a given base config path.
///
/// This is a testable version that allows specifying a custom base path.
/// Returns a sorted list of project names (directory basenames).
#[cfg(test)]
fn list_projects_at(base_config_dir: &std::path::Path) -> Result<Vec<String>> {
    if !base_config_dir.exists() {
        return Ok(Vec::new());
    }

    let mut projects = Vec::new();

    let entries = fs::read_dir(base_config_dir)
        .map_err(|e| Autom8Error::Config(format!("Could not read config directory: {}", e)))?;

    for entry in entries {
        let entry = entry
            .map_err(|e| Autom8Error::Config(format!("Could not read directory entry: {}", e)))?;

        let path = entry.path();
        if path.is_dir() {
            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                projects.push(name.to_string());
            }
        }
    }

    projects.sort();
    Ok(projects)
}

/// Ensure a config directory exists at the given base path.
///
/// This is a testable version that allows specifying a custom base path.
/// Creates `<base>/.config/autom8/` if it doesn't exist.
///
/// Returns the full path and whether the directory was newly created.
#[cfg(test)]
fn ensure_config_dir_at(base: &std::path::Path) -> Result<(PathBuf, bool)> {
    let dir = base.join(".config").join(CONFIG_DIR_NAME);
    let created = !dir.exists();
    fs::create_dir_all(&dir)?;
    Ok((dir, created))
}

/// Ensure a project config directory with subdirectories exists at the given base path.
///
/// This is a testable version that allows specifying a custom base path and project name.
/// Creates:
/// - `<base>/.config/autom8/<project-name>/`
/// - `<base>/.config/autom8/<project-name>/spec/`
/// - `<base>/.config/autom8/<project-name>/runs/`
///
/// Returns the full project path and whether it was newly created.
#[cfg(test)]
fn ensure_project_config_dir_at(
    base: &std::path::Path,
    project_name: &str,
) -> Result<(PathBuf, bool)> {
    let dir = base
        .join(".config")
        .join(CONFIG_DIR_NAME)
        .join(project_name);
    let created = !dir.exists();

    fs::create_dir_all(dir.join(SPEC_SUBDIR))?;
    fs::create_dir_all(dir.join(RUNS_SUBDIR))?;

    Ok((dir, created))
}

/// Get the spec subdirectory path for a given project config directory.
///
/// This is a testable version that allows specifying a custom project config directory path.
/// Unlike the real `spec_dir()`, this doesn't perform filesystem operations or require
/// the directory to exist.
#[cfg(test)]
fn spec_dir_at(project_config_dir: &std::path::Path) -> PathBuf {
    project_config_dir.join(SPEC_SUBDIR)
}

/// Check if a file path is within a given config directory.
///
/// This is a testable version of `is_in_config_dir` that allows specifying a custom
/// base config directory path instead of using the real `~/.config/autom8` directory.
/// Handles path canonicalization like the original function.
#[cfg(test)]
fn is_in_config_dir_at(
    base_config_dir: &std::path::Path,
    file_path: &std::path::Path,
) -> Result<bool> {
    // Canonicalize both paths to handle relative paths and symlinks
    let canonical_file = file_path
        .canonicalize()
        .unwrap_or_else(|_| file_path.to_path_buf());
    let canonical_config = base_config_dir
        .canonicalize()
        .unwrap_or_else(|_| base_config_dir.to_path_buf());

    Ok(canonical_file.starts_with(&canonical_config))
}

/// Move a file to a specified spec directory if it's not already there.
///
/// This is a testable version of `move_to_config_dir` that allows specifying a custom
/// destination spec directory instead of using the real `~/.config/autom8/<project>/spec/` directory.
///
/// Uses `fs::rename()` when possible, falls back to copy+delete for cross-filesystem moves.
///
/// Returns `MoveResult` with the destination path and whether the file was moved.
#[cfg(test)]
fn move_to_config_dir_at(
    dest_spec_dir: &std::path::Path,
    file_path: &std::path::Path,
) -> Result<MoveResult> {
    // If already in the destination spec directory, return original path
    if is_in_config_dir_at(dest_spec_dir, file_path)? {
        let canonical = file_path
            .canonicalize()
            .unwrap_or_else(|_| file_path.to_path_buf());
        return Ok(MoveResult {
            dest_path: canonical,
            was_moved: false,
        });
    }

    // Ensure destination directory exists
    fs::create_dir_all(dest_spec_dir)?;

    // Get filename and create destination path
    let filename = file_path
        .file_name()
        .ok_or_else(|| Autom8Error::Config("Could not determine filename".to_string()))?;
    let dest_path = dest_spec_dir.join(filename);

    // Try rename first (fast, atomic), fall back to copy+delete for cross-filesystem
    if fs::rename(file_path, &dest_path).is_err() {
        // Cross-filesystem move: copy then delete original
        fs::copy(file_path, &dest_path)?;
        fs::remove_file(file_path)?;
    }

    Ok(MoveResult {
        dest_path,
        was_moved: true,
    })
}

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

    #[test]
    fn test_ensure_config_dir_at_creates_directory() {
        let temp_dir = TempDir::new().unwrap();
        let expected_path = temp_dir.path().join(".config").join("autom8");
        assert!(!expected_path.exists());

        let (path, created) = ensure_config_dir_at(temp_dir.path()).unwrap();

        assert_eq!(path, expected_path);
        assert!(created);
        assert!(expected_path.exists());
        assert!(expected_path.is_dir());
    }

    #[test]
    fn test_ensure_config_dir_at_reports_existing_directory() {
        let temp_dir = TempDir::new().unwrap();
        let expected_path = temp_dir.path().join(".config").join("autom8");

        // Create the directory first
        fs::create_dir_all(&expected_path).unwrap();
        assert!(expected_path.exists());

        let (path, created) = ensure_config_dir_at(temp_dir.path()).unwrap();

        assert_eq!(path, expected_path);
        assert!(!created); // Directory already existed
        assert!(expected_path.exists());
    }

    #[test]
    fn test_ensure_config_dir_at_creates_parent_directories() {
        let temp_dir = TempDir::new().unwrap();

        // Neither .config nor .config/autom8 should exist initially
        let config_path = temp_dir.path().join(".config");
        assert!(!config_path.exists());

        let (path, created) = ensure_config_dir_at(temp_dir.path()).unwrap();

        assert!(created);
        assert!(path.exists());
        assert!(config_path.exists()); // Parent was also created
    }

    #[test]
    fn test_spec_dir_at_returns_spec_subdirectory() {
        let project_config_dir = PathBuf::from("/some/project/config/dir");
        let result = spec_dir_at(&project_config_dir);
        assert_eq!(result, PathBuf::from("/some/project/config/dir/spec"));
    }

    #[test]
    fn test_spec_dir_at_with_temp_dir() {
        let temp_dir = TempDir::new().unwrap();
        let (project_dir, _) =
            ensure_project_config_dir_at(temp_dir.path(), "test-project").unwrap();

        let spec_dir = spec_dir_at(&project_dir);

        // Verify it points to the spec subdirectory
        assert_eq!(spec_dir, project_dir.join("spec"));
        // Since ensure_project_config_dir_at creates the spec dir, it should exist
        assert!(spec_dir.exists());
        assert!(spec_dir.is_dir());
    }

    #[test]
    fn test_is_in_config_dir_at_returns_true_for_file_inside_config() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join("config");
        fs::create_dir_all(&config_dir).unwrap();

        let file_inside = config_dir.join("subdir").join("file.txt");
        fs::create_dir_all(file_inside.parent().unwrap()).unwrap();
        fs::write(&file_inside, "test").unwrap();

        let result = is_in_config_dir_at(&config_dir, &file_inside).unwrap();
        assert!(result);
    }

    #[test]
    fn test_is_in_config_dir_at_returns_false_for_file_outside_config() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join("config");
        let other_dir = temp_dir.path().join("other");
        fs::create_dir_all(&config_dir).unwrap();
        fs::create_dir_all(&other_dir).unwrap();

        let file_outside = other_dir.join("file.txt");
        fs::write(&file_outside, "test").unwrap();

        let result = is_in_config_dir_at(&config_dir, &file_outside).unwrap();
        assert!(!result);
    }

    #[test]
    fn test_is_in_config_dir_at_handles_nonexistent_path() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join("config");
        fs::create_dir_all(&config_dir).unwrap();

        // Use canonicalized config_dir to construct path - mimics real usage
        // where paths are typically derived from the config dir itself
        let canonical_config = config_dir.canonicalize().unwrap();
        let nonexistent_file = canonical_config.join("does_not_exist.txt");

        // Should return true because the path starts with canonicalized config_dir
        let result = is_in_config_dir_at(&config_dir, &nonexistent_file).unwrap();
        assert!(result);
    }

    #[test]
    fn test_move_to_config_dir_at_moves_file_to_dest_dir() {
        let temp_dir = TempDir::new().unwrap();
        let source_dir = temp_dir.path().join("source");
        let dest_spec_dir = temp_dir.path().join("dest_config").join("spec");
        fs::create_dir_all(&source_dir).unwrap();

        let source_file = source_dir.join("test-file.json");
        let content = r#"{"test": "data"}"#;
        fs::write(&source_file, content).unwrap();

        let result = move_to_config_dir_at(&dest_spec_dir, &source_file).unwrap();

        assert!(result.was_moved, "File should have been moved");
        assert!(result.dest_path.exists(), "Destination file should exist");
        assert!(
            !source_file.exists(),
            "Source file should be deleted after move"
        );
        assert!(
            result.dest_path.starts_with(&dest_spec_dir),
            "File should be in the specified dest_spec_dir"
        );
        assert_eq!(
            fs::read_to_string(&result.dest_path).unwrap(),
            content,
            "Content should match"
        );
    }

    #[test]
    fn test_move_to_config_dir_at_returns_unchanged_if_already_in_dest() {
        let temp_dir = TempDir::new().unwrap();
        let dest_spec_dir = temp_dir.path().join("config").join("spec");
        fs::create_dir_all(&dest_spec_dir).unwrap();

        let existing_file = dest_spec_dir.join("already-here.md");
        fs::write(&existing_file, "# Already here").unwrap();

        let result = move_to_config_dir_at(&dest_spec_dir, &existing_file).unwrap();

        assert!(!result.was_moved, "File should not have been moved");
        assert!(
            existing_file.exists(),
            "File should still exist in original location"
        );
        assert_eq!(
            result.dest_path.canonicalize().unwrap(),
            existing_file.canonicalize().unwrap(),
            "Path should be the canonical original"
        );
    }

    #[test]
    fn test_move_to_config_dir_at_preserves_filename() {
        let temp_dir = TempDir::new().unwrap();
        let source_dir = temp_dir.path().join("source");
        let dest_spec_dir = temp_dir.path().join("config").join("spec");
        fs::create_dir_all(&source_dir).unwrap();

        let source_file = source_dir.join("my-custom-filename.txt");
        fs::write(&source_file, "test content").unwrap();

        let result = move_to_config_dir_at(&dest_spec_dir, &source_file).unwrap();

        assert_eq!(
            result.dest_path.file_name().unwrap().to_str().unwrap(),
            "my-custom-filename.txt",
            "Filename should be preserved"
        );
    }

    #[test]
    fn test_move_to_config_dir_at_creates_dest_dir_if_missing() {
        let temp_dir = TempDir::new().unwrap();
        let source_dir = temp_dir.path().join("source");
        let dest_spec_dir = temp_dir
            .path()
            .join("nonexistent")
            .join("nested")
            .join("spec");
        fs::create_dir_all(&source_dir).unwrap();
        // Note: dest_spec_dir does not exist yet

        let source_file = source_dir.join("test.md");
        fs::write(&source_file, "# Test").unwrap();

        let result = move_to_config_dir_at(&dest_spec_dir, &source_file).unwrap();

        assert!(result.was_moved, "File should have been moved");
        assert!(
            dest_spec_dir.exists(),
            "Destination directory should be created"
        );
        assert!(result.dest_path.exists(), "Destination file should exist");
    }

    #[test]
    fn test_ensure_project_config_dir_at_creates_all_subdirs() {
        let temp_dir = TempDir::new().unwrap();
        let project_name = "test-project";

        let (path, created) = ensure_project_config_dir_at(temp_dir.path(), project_name).unwrap();

        assert!(created);
        assert!(path.exists());
        assert!(path.ends_with(project_name));

        // Verify all subdirectories were created
        assert!(path.join("spec").exists());
        assert!(path.join("spec").is_dir());
        assert!(path.join("runs").exists());
        assert!(path.join("runs").is_dir());
    }

    #[test]
    fn test_ensure_project_config_dir_at_reports_existing() {
        let temp_dir = TempDir::new().unwrap();
        let project_name = "existing-project";

        // Create the directory first
        let (path1, created1) =
            ensure_project_config_dir_at(temp_dir.path(), project_name).unwrap();
        assert!(created1);

        // Call again - should report as existing
        let (path2, created2) =
            ensure_project_config_dir_at(temp_dir.path(), project_name).unwrap();
        assert!(!created2);
        assert_eq!(path1, path2);
    }

    #[test]
    fn test_ensure_project_config_dir_at_different_projects_share_nothing() {
        let temp_dir = TempDir::new().unwrap();

        let (path1, _) = ensure_project_config_dir_at(temp_dir.path(), "project-a").unwrap();
        let (path2, _) = ensure_project_config_dir_at(temp_dir.path(), "project-b").unwrap();

        // Each project has its own directory
        assert_ne!(path1, path2);
        assert!(path1.exists());
        assert!(path2.exists());

        // Each has its own subdirs
        assert!(path1.join("spec").exists());
        assert!(path2.join("spec").exists());
    }

    #[test]
    fn test_ensure_project_config_dir_creates_directory_structure() {
        // Use TempDir for isolation - does not touch ~/.config/autom8/
        let temp_dir = TempDir::new().unwrap();

        let result = ensure_project_config_dir_at(temp_dir.path(), "test-project");
        assert!(result.is_ok());
        let (path, created) = result.unwrap();

        // Verify the directory was created
        assert!(created);

        // Verify structure
        assert!(path.exists());
        assert!(path.join("spec").exists());
        assert!(path.join("runs").exists());
    }

    #[test]
    fn test_is_in_config_dir_true_for_file_in_config() {
        // Create a file inside a temp config directory
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join("config");
        fs::create_dir_all(&config_dir).unwrap();
        let test_file = config_dir.join("test.json");
        fs::write(&test_file, "{}").unwrap();

        let result = is_in_config_dir_at(&config_dir, &test_file).unwrap();
        assert!(result, "File in config dir should return true");
    }

    #[test]
    fn test_is_in_config_dir_false_for_file_outside_config() {
        let temp_dir = TempDir::new().unwrap();
        let test_file = temp_dir.path().join("test.json");
        fs::write(&test_file, "{}").unwrap();

        let result = is_in_config_dir(&test_file).unwrap();
        assert!(!result, "File outside config dir should return false");
    }

    #[test]
    fn test_is_in_config_dir_true_for_file_in_subdirectory() {
        // Create a file in a subdirectory of config
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join("config");
        let spec_dir = config_dir.join("spec");
        fs::create_dir_all(&spec_dir).unwrap();
        let test_file = spec_dir.join("test.md");
        fs::write(&test_file, "# Test").unwrap();

        let result = is_in_config_dir_at(&config_dir, &test_file).unwrap();
        assert!(result, "File in config subdirectory should return true");
    }

    #[test]
    fn test_is_in_config_dir_true_for_file_in_different_project() {
        // Create a file in a different project's directory within the config area
        // This simulates a file in a worktree-named project directory
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join("config");
        let other_project_spec_dir = config_dir
            .join("some-other-project-wt-feature")
            .join("spec");
        fs::create_dir_all(&other_project_spec_dir).unwrap();
        let test_file = other_project_spec_dir.join("test.md");
        fs::write(&test_file, "# Test").unwrap();

        let result = is_in_config_dir_at(&config_dir, &test_file).unwrap();
        assert!(
            result,
            "File in different project's config dir should return true"
        );
    }

    #[test]
    fn test_move_to_config_dir_moves_md_to_spec() {
        let temp_dir = TempDir::new().unwrap();
        let source_dir = temp_dir.path().join("source");
        let dest_spec_dir = temp_dir.path().join("config").join("spec");
        fs::create_dir_all(&source_dir).unwrap();

        let source_file = source_dir.join("test-spec.md");
        let content = "# Test Spec\n\nThis is a test.";
        fs::write(&source_file, content).unwrap();

        let result = move_to_config_dir_at(&dest_spec_dir, &source_file).unwrap();

        assert!(result.was_moved, "File should have been moved");
        assert!(result.dest_path.exists(), "Destination file should exist");
        assert!(
            !source_file.exists(),
            "Source file should be deleted after move"
        );
        assert!(
            result.dest_path.parent().unwrap().ends_with("spec"),
            "MD files should go to spec/ directory"
        );
        assert_eq!(
            fs::read_to_string(&result.dest_path).unwrap(),
            content,
            "Content should match"
        );
        // No cleanup needed - TempDir handles it
    }

    #[test]
    fn test_move_to_config_dir_no_move_if_already_in_config() {
        // Create a file already in the destination spec directory
        let temp_dir = TempDir::new().unwrap();
        let dest_spec_dir = temp_dir.path().join("config").join("spec");
        fs::create_dir_all(&dest_spec_dir).unwrap();

        let existing_file = dest_spec_dir.join("existing-test.md");
        fs::write(&existing_file, "# Already here").unwrap();

        let result = move_to_config_dir_at(&dest_spec_dir, &existing_file).unwrap();

        assert!(!result.was_moved, "File should not have been moved");
        assert!(
            existing_file.exists(),
            "File should still exist in original location"
        );
        assert_eq!(
            result.dest_path.canonicalize().unwrap(),
            existing_file.canonicalize().unwrap(),
            "Path should be the original"
        );
        // No cleanup needed - TempDir handles it
    }

    #[test]
    fn test_move_to_config_dir_unknown_extension_goes_to_spec() {
        let temp_dir = TempDir::new().unwrap();
        let source_dir = temp_dir.path().join("source");
        let dest_spec_dir = temp_dir.path().join("config").join("spec");
        fs::create_dir_all(&source_dir).unwrap();

        let source_file = source_dir.join("test-file.txt");
        fs::write(&source_file, "Some content").unwrap();

        let result = move_to_config_dir_at(&dest_spec_dir, &source_file).unwrap();

        assert!(result.was_moved, "File should have been moved");
        assert!(
            !source_file.exists(),
            "Source file should be deleted after move"
        );
        assert!(
            result.dest_path.parent().unwrap().ends_with("spec"),
            "Unknown extensions should default to spec/ directory"
        );
        // No cleanup needed - TempDir handles it
    }

    #[test]
    fn test_move_result_struct() {
        // Verify MoveResult fields work correctly
        let result = MoveResult {
            dest_path: PathBuf::from("/test/path"),
            was_moved: true,
        };
        assert_eq!(result.dest_path, PathBuf::from("/test/path"));
        assert!(result.was_moved);
    }

    #[test]
    fn test_list_projects_empty_when_no_projects() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        fs::create_dir_all(&config_dir).unwrap();

        let projects = list_projects_at(&config_dir).unwrap();
        assert!(
            projects.is_empty(),
            "Should return empty list when no projects exist"
        );
    }

    #[test]
    fn test_list_projects_returns_sorted_list() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");

        // Create projects in non-alphabetical order
        fs::create_dir_all(config_dir.join("zebra")).unwrap();
        fs::create_dir_all(config_dir.join("alpha")).unwrap();
        fs::create_dir_all(config_dir.join("mango")).unwrap();

        let projects = list_projects_at(&config_dir).unwrap();

        assert_eq!(projects.len(), 3);
        assert_eq!(projects[0], "alpha", "First project should be 'alpha'");
        assert_eq!(projects[1], "mango", "Second project should be 'mango'");
        assert_eq!(projects[2], "zebra", "Third project should be 'zebra'");
    }

    #[test]
    fn test_list_projects_ignores_files() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        fs::create_dir_all(&config_dir).unwrap();

        // Create a project directory and a file
        fs::create_dir_all(config_dir.join("my-project")).unwrap();
        fs::write(config_dir.join("some-file.txt"), "not a project").unwrap();

        let projects = list_projects_at(&config_dir).unwrap();

        assert_eq!(projects.len(), 1, "Should only include directories");
        assert_eq!(projects[0], "my-project");
    }

    #[test]
    fn test_list_projects_empty_when_dir_does_not_exist() {
        let temp_dir = TempDir::new().unwrap();
        let non_existent_dir = temp_dir.path().join("does-not-exist");

        let projects = list_projects_at(&non_existent_dir).unwrap();
        assert!(
            projects.is_empty(),
            "Should return empty list for non-existent directory"
        );
    }

    // ========================================================================
    // US-010: Global status tests
    // ========================================================================

    #[test]
    fn test_project_status_needs_attention_with_active_run() {
        let status = ProjectStatus {
            name: "test-project".to_string(),
            has_active_run: true,
            run_status: Some(crate::state::RunStatus::Running),
            incomplete_spec_count: 0,
            total_spec_count: 0,
        };
        assert!(status.needs_attention(), "Active run should need attention");
        assert!(!status.is_idle());
    }

    #[test]
    fn test_project_status_needs_attention_with_failed_run() {
        let status = ProjectStatus {
            name: "test-project".to_string(),
            has_active_run: false,
            run_status: Some(crate::state::RunStatus::Failed),
            incomplete_spec_count: 0,
            total_spec_count: 0,
        };
        assert!(status.needs_attention(), "Failed run should need attention");
        assert!(!status.is_idle());
    }

    #[test]
    fn test_project_status_needs_attention_with_incomplete_specs() {
        let status = ProjectStatus {
            name: "test-project".to_string(),
            has_active_run: false,
            run_status: None,
            incomplete_spec_count: 2,
            total_spec_count: 3,
        };
        assert!(
            status.needs_attention(),
            "Incomplete specs should need attention"
        );
        assert!(!status.is_idle());
    }

    #[test]
    fn test_project_status_idle_when_no_work() {
        let status = ProjectStatus {
            name: "test-project".to_string(),
            has_active_run: false,
            run_status: Some(crate::state::RunStatus::Completed),
            incomplete_spec_count: 0,
            total_spec_count: 1,
        };
        assert!(
            !status.needs_attention(),
            "Completed project should not need attention"
        );
        assert!(status.is_idle());
    }

    #[test]
    fn test_project_status_idle_when_no_runs_no_specs() {
        let status = ProjectStatus {
            name: "test-project".to_string(),
            has_active_run: false,
            run_status: None,
            incomplete_spec_count: 0,
            total_spec_count: 0,
        };
        assert!(!status.needs_attention());
        assert!(status.is_idle());
    }

    #[test]
    fn test_global_status_empty_when_no_projects() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        fs::create_dir_all(&config_dir).unwrap();

        let statuses = global_status_at(&config_dir).unwrap();
        assert!(
            statuses.is_empty(),
            "Should return empty list when no projects exist"
        );
    }

    #[test]
    fn test_global_status_returns_all_projects() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");

        // Create project directories with spec subdirs
        fs::create_dir_all(config_dir.join("project-a").join("spec")).unwrap();
        fs::create_dir_all(config_dir.join("project-b").join("spec")).unwrap();

        let statuses = global_status_at(&config_dir).unwrap();

        assert_eq!(statuses.len(), 2);
        assert_eq!(statuses[0].name, "project-a");
        assert_eq!(statuses[1].name, "project-b");
    }

    #[test]
    fn test_global_status_detects_active_run() {
        use crate::state::{RunState, StateManager};

        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        let project_dir = config_dir.join("active-project");
        fs::create_dir_all(project_dir.join("spec")).unwrap();

        // Create an active run
        let sm = StateManager::with_dir(project_dir);
        let run_state = RunState::new(PathBuf::from("test.json"), "test-branch".to_string());
        sm.save(&run_state).unwrap();

        let statuses = global_status_at(&config_dir).unwrap();

        assert_eq!(statuses.len(), 1);
        assert!(statuses[0].has_active_run);
        assert_eq!(
            statuses[0].run_status,
            Some(crate::state::RunStatus::Running)
        );
    }

    #[test]
    fn test_global_status_counts_incomplete_specs() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        let project_dir = config_dir.join("spec-project");
        let spec_dir = project_dir.join("spec");
        fs::create_dir_all(&spec_dir).unwrap();

        // Create an incomplete PRD
        let incomplete_prd = r#"{
            "project": "Test Project",
            "branchName": "test",
            "description": "Test",
            "userStories": [
                {"id": "US-001", "title": "Story 1", "description": "Desc", "acceptanceCriteria": [], "priority": 1, "passes": false}
            ]
        }"#;
        fs::write(spec_dir.join("spec-test.json"), incomplete_prd).unwrap();

        // Create a complete PRD
        let complete_prd = r#"{
            "project": "Complete Project",
            "branchName": "test",
            "description": "Test",
            "userStories": [
                {"id": "US-001", "title": "Story 1", "description": "Desc", "acceptanceCriteria": [], "priority": 1, "passes": true}
            ]
        }"#;
        fs::write(spec_dir.join("spec-complete.json"), complete_prd).unwrap();

        let statuses = global_status_at(&config_dir).unwrap();

        assert_eq!(statuses.len(), 1);
        assert_eq!(statuses[0].incomplete_spec_count, 1);
        assert_eq!(statuses[0].total_spec_count, 2);
    }

    // ========================================================================
    // US-007: Project tree view tests
    // ========================================================================

    #[test]
    fn test_project_tree_info_status_label_running() {
        let info = ProjectTreeInfo {
            name: "test".to_string(),
            has_active_run: true,
            run_status: Some(crate::state::RunStatus::Running),
            spec_count: 1,
            incomplete_spec_count: 0,
            spec_md_count: 0,
            runs_count: 0,
            last_run_date: None,
        };
        assert_eq!(info.status_label(), "running");
    }

    #[test]
    fn test_project_tree_info_status_label_failed() {
        let info = ProjectTreeInfo {
            name: "test".to_string(),
            has_active_run: false,
            run_status: Some(crate::state::RunStatus::Failed),
            spec_count: 1,
            incomplete_spec_count: 0,
            spec_md_count: 0,
            runs_count: 0,
            last_run_date: None,
        };
        assert_eq!(info.status_label(), "failed");
    }

    #[test]
    fn test_project_tree_info_status_label_incomplete() {
        let info = ProjectTreeInfo {
            name: "test".to_string(),
            has_active_run: false,
            run_status: None,
            spec_count: 2,
            incomplete_spec_count: 1,
            spec_md_count: 0,
            runs_count: 0,
            last_run_date: None,
        };
        assert_eq!(info.status_label(), "incomplete");
    }

    #[test]
    fn test_project_tree_info_status_label_complete() {
        let info = ProjectTreeInfo {
            name: "test".to_string(),
            has_active_run: false,
            run_status: None,
            spec_count: 2,
            incomplete_spec_count: 0,
            spec_md_count: 1,
            runs_count: 0,
            last_run_date: None,
        };
        assert_eq!(info.status_label(), "complete");
    }

    #[test]
    fn test_project_tree_info_status_label_empty() {
        let info = ProjectTreeInfo {
            name: "test".to_string(),
            has_active_run: false,
            run_status: None,
            spec_count: 0,
            incomplete_spec_count: 0,
            spec_md_count: 0,
            runs_count: 0,
            last_run_date: None,
        };
        assert_eq!(info.status_label(), "empty");
    }

    #[test]
    fn test_project_tree_info_has_content_true() {
        let info = ProjectTreeInfo {
            name: "test".to_string(),
            has_active_run: false,
            run_status: None,
            spec_count: 1,
            incomplete_spec_count: 0,
            spec_md_count: 0,
            runs_count: 0,
            last_run_date: None,
        };
        assert!(info.has_content());
    }

    #[test]
    fn test_project_tree_info_has_content_false() {
        let info = ProjectTreeInfo {
            name: "test".to_string(),
            has_active_run: false,
            run_status: None,
            spec_count: 0,
            incomplete_spec_count: 0,
            spec_md_count: 0,
            runs_count: 0,
            last_run_date: None,
        };
        assert!(!info.has_content());
    }

    #[test]
    fn test_project_tree_info_has_content_with_active_run() {
        let info = ProjectTreeInfo {
            name: "test".to_string(),
            has_active_run: true,
            run_status: Some(crate::state::RunStatus::Running),
            spec_count: 0,
            incomplete_spec_count: 0,
            spec_md_count: 0,
            runs_count: 0,
            last_run_date: None,
        };
        assert!(info.has_content());
    }

    // ========================================================================
    // US-008: Describe command tests
    // ========================================================================

    #[test]
    fn test_us008_project_exists_false_for_nonexistent() {
        let result = project_exists("nonexistent-project-xyz-12345");
        assert!(result.is_ok());
        assert!(!result.unwrap(), "nonexistent project should return false");
    }

    #[test]
    fn test_us008_get_project_description_nonexistent_project() {
        // Test getting description for a nonexistent project
        let result = get_project_description("nonexistent-project-xyz-12345");
        assert!(result.is_ok());
        assert!(
            result.unwrap().is_none(),
            "nonexistent project should return None"
        );
    }

    #[test]
    fn test_us008_spec_summary_struct_fields() {
        // Verify SpecSummary struct has all fields
        let summary = SpecSummary {
            filename: "test.json".to_string(),
            path: PathBuf::from("/test"),
            project_name: "Test Project".to_string(),
            branch_name: "feature/test".to_string(),
            description: "Test description".to_string(),
            stories: vec![StorySummary {
                id: "US-001".to_string(),
                title: "Test Story".to_string(),
                passes: true,
            }],
            completed_count: 1,
            total_count: 1,
            is_active: false,
        };

        assert_eq!(summary.filename, "test.json");
        assert_eq!(summary.project_name, "Test Project");
        assert_eq!(summary.branch_name, "feature/test");
        assert_eq!(summary.completed_count, 1);
        assert_eq!(summary.total_count, 1);
        assert!(!summary.is_active);
    }

    #[test]
    fn test_us008_story_summary_struct_fields() {
        // Verify StorySummary struct has all fields
        let story = StorySummary {
            id: "US-001".to_string(),
            title: "Test Story".to_string(),
            passes: false,
        };

        assert_eq!(story.id, "US-001");
        assert_eq!(story.title, "Test Story");
        assert!(!story.passes);
    }

    // ========================================================================
    // US-001: Config struct tests
    // ========================================================================

    #[test]
    fn test_config_default_all_true() {
        let config = Config::default();
        assert!(config.review, "review should default to true");
        assert!(config.commit, "commit should default to true");
        assert!(config.pull_request, "pull_request should default to true");
        assert!(config.worktree, "worktree should default to true");
    }

    #[test]
    fn test_config_serialize_to_toml() {
        let config = Config::default();
        let toml_str = toml::to_string(&config).unwrap();

        assert!(toml_str.contains("review = true"));
        assert!(toml_str.contains("commit = true"));
        assert!(toml_str.contains("pull_request = true"));
        assert!(toml_str.contains("worktree = true"));
    }

    #[test]
    fn test_config_deserialize_from_toml() {
        let toml_str = r#"
            review = false
            commit = true
            pull_request = false
            worktree = true
        "#;

        let config: Config = toml::from_str(toml_str).unwrap();

        assert!(!config.review);
        assert!(config.commit);
        assert!(!config.pull_request);
        assert!(config.worktree);
    }

    #[test]
    fn test_config_deserialize_partial_toml_uses_defaults() {
        // Only specify one field - others should default to their respective defaults
        let toml_str = r#"
            commit = false
        "#;

        let config: Config = toml::from_str(toml_str).unwrap();

        assert!(config.review, "missing review should default to true");
        assert!(!config.commit, "commit should be false as specified");
        assert!(
            config.pull_request,
            "missing pull_request should default to true"
        );
        assert!(config.worktree, "missing worktree should default to true");
    }

    #[test]
    fn test_config_deserialize_empty_toml_uses_all_defaults() {
        let toml_str = "";

        let config: Config = toml::from_str(toml_str).unwrap();

        assert!(config.review);
        assert!(config.commit);
        assert!(config.pull_request);
        assert!(config.worktree);
    }

    #[test]
    fn test_config_roundtrip() {
        let original = Config {
            review: false,
            commit: true,
            pull_request: false,
            worktree: true,
            ..Default::default()
        };

        let toml_str = toml::to_string(&original).unwrap();
        let deserialized: Config = toml::from_str(&toml_str).unwrap();

        assert_eq!(original, deserialized);
    }

    #[test]
    fn test_config_equality() {
        let config1 = Config::default();
        let config2 = Config::default();
        assert_eq!(config1, config2);

        let config3 = Config {
            review: false,
            ..Default::default()
        };
        assert_ne!(config1, config3);
    }

    #[test]
    fn test_config_clone() {
        let original = Config {
            review: false,
            commit: true,
            pull_request: false,
            worktree: true,
            ..Default::default()
        };

        let cloned = original.clone();
        assert_eq!(original, cloned);
    }

    #[test]
    fn test_config_debug_format() {
        let config = Config::default();
        let debug_str = format!("{:?}", config);

        assert!(debug_str.contains("Config"));
        assert!(debug_str.contains("review"));
        assert!(debug_str.contains("commit"));
        assert!(debug_str.contains("pull_request"));
        assert!(debug_str.contains("worktree"));
    }

    // ========================================================================
    // US-002: Global Config File Management tests
    // ========================================================================

    #[test]
    fn test_generate_config_with_comments_includes_all_fields() {
        let config = Config::default();
        let content = generate_config_with_comments(&config);

        // Check that all field values are present
        assert!(content.contains("review = true"));
        assert!(content.contains("commit = true"));
        assert!(content.contains("pull_request = true"));
        assert!(content.contains("worktree = true"));
    }

    #[test]
    fn test_generate_config_with_comments_has_explanatory_comments() {
        let config = Config::default();
        let content = generate_config_with_comments(&config);

        // Check that comments explain each option
        assert!(content.contains("# Review state"));
        assert!(content.contains("# Commit state"));
        assert!(content.contains("# Pull request state"));
        assert!(content.contains("# Worktree mode"));

        // Check that true/false meanings are explained
        assert!(content.contains("- true:"));
        assert!(content.contains("- false:"));
    }

    #[test]
    fn test_generate_config_with_comments_preserves_custom_values() {
        let config = Config {
            review: false,
            commit: true,
            pull_request: false,
            worktree: true,
            ..Default::default()
        };
        let content = generate_config_with_comments(&config);

        assert!(content.contains("review = false"));
        assert!(content.contains("commit = true"));
        assert!(content.contains("pull_request = false"));
        assert!(content.contains("worktree = true"));
    }

    #[test]
    fn test_default_config_with_comments_is_valid_toml() {
        // Verify the default config string can be parsed
        let config: Config = toml::from_str(DEFAULT_CONFIG_WITH_COMMENTS).unwrap();

        assert!(config.review);
        assert!(config.commit);
        assert!(config.pull_request);
        assert!(config.worktree);
    }

    #[test]
    fn test_load_global_config_creates_file_when_missing() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        fs::create_dir_all(&config_dir).unwrap();

        let config_path = config_dir.join("config.toml");
        assert!(
            !config_path.exists(),
            "Config file should not exist initially"
        );

        // We can't easily test the real load_global_config because it uses the real home dir,
        // but we can test the underlying logic by simulating it
        let content = DEFAULT_CONFIG_WITH_COMMENTS;
        fs::write(&config_path, content).unwrap();

        let loaded: Config = toml::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();
        assert_eq!(loaded, Config::default());
    }

    #[test]
    fn test_save_and_load_global_config_roundtrip() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        fs::create_dir_all(&config_dir).unwrap();

        let config_path = config_dir.join("config.toml");

        // Create a custom config
        let custom_config = Config {
            review: false,
            commit: true,
            pull_request: false,
            ..Default::default()
        };

        // Write it
        let content = generate_config_with_comments(&custom_config);
        fs::write(&config_path, content).unwrap();

        // Read it back
        let loaded: Config = toml::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();

        assert_eq!(loaded, custom_config);
    }

    #[test]
    fn test_load_global_config_handles_partial_config() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        fs::create_dir_all(&config_dir).unwrap();

        let config_path = config_dir.join("config.toml");

        // Write a partial config (missing pull_request)
        let partial_content = r#"
# Partial config
review = false
commit = true
"#;
        fs::write(&config_path, partial_content).unwrap();

        // Read it back - missing fields should use defaults
        let loaded: Config = toml::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();

        assert!(!loaded.review);
        assert!(loaded.commit);
        assert!(
            loaded.pull_request,
            "Missing pull_request should default to true"
        );
    }

    #[test]
    fn test_generated_config_includes_note_about_pr_requiring_commit() {
        let config = Config::default();
        let content = generate_config_with_comments(&config);

        // The config should mention that PR requires commit
        assert!(
            content.contains("Requires commit = true"),
            "Config should note that PR requires commit"
        );
    }

    #[test]
    fn test_global_config_file_has_comments_after_save() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        fs::create_dir_all(&config_dir).unwrap();

        let config_path = config_dir.join("config.toml");

        // Save a config
        let config = Config::default();
        let content = generate_config_with_comments(&config);
        fs::write(&config_path, content).unwrap();

        // Read raw content and verify comments are present
        let raw_content = fs::read_to_string(&config_path).unwrap();
        assert!(
            raw_content.contains("#"),
            "Config file should contain comments"
        );
        assert!(
            raw_content.contains("# Autom8 Configuration"),
            "Config file should have header comment"
        );
    }

    // ========================================================================
    // US-003: Per-Project Config Inheritance tests
    // ========================================================================

    #[test]
    fn test_us003_project_config_path_for_returns_correct_path() {
        let path = project_config_path_for("my-test-project").unwrap();
        assert!(path.ends_with("config.toml"));
        assert!(path.parent().unwrap().ends_with("my-test-project"));
    }

    #[test]
    fn test_us003_load_project_config_creates_from_global_when_missing() {
        // Use temp directory to avoid race conditions
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        fs::create_dir_all(&config_dir).unwrap();

        // Create global config
        let global_config = Config {
            review: true,
            commit: false,
            pull_request: false,
            ..Default::default()
        };
        let global_path = config_dir.join("config.toml");
        let global_content = generate_config_with_comments(&global_config);
        fs::write(&global_path, &global_content).unwrap();

        // Create project directory (no config file yet)
        let project_dir = config_dir.join("test-project");
        fs::create_dir_all(project_dir.join("spec")).unwrap();
        fs::create_dir_all(project_dir.join("runs")).unwrap();

        let project_config_path = project_dir.join("config.toml");
        assert!(
            !project_config_path.exists(),
            "Project config should not exist initially"
        );

        // Simulate load_project_config: when project config doesn't exist,
        // copy global config content to project config
        fs::write(&project_config_path, &global_content).unwrap();

        // Verify project config was created
        assert!(
            project_config_path.exists(),
            "Project config should be created when missing"
        );

        // Verify it matches global config
        let loaded: Config =
            toml::from_str(&fs::read_to_string(&project_config_path).unwrap()).unwrap();
        assert_eq!(
            loaded, global_config,
            "Project config should match global config"
        );
    }

    #[test]
    fn test_us003_load_project_config_preserves_comments() {
        // Use temp directory to avoid race conditions
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        let project_dir = config_dir.join("test-project");
        fs::create_dir_all(&project_dir).unwrap();

        // Create global config (used as source for project config creation)
        let global_config = Config::default();
        let global_path = config_dir.join("config.toml");
        let global_content = generate_config_with_comments(&global_config);
        fs::write(&global_path, &global_content).unwrap();

        // Simulate load_project_config: copy global to project when missing
        let project_config_path = project_dir.join("config.toml");
        assert!(!project_config_path.exists());

        // Copy global config content to project config (as load_project_config does)
        fs::write(&project_config_path, &global_content).unwrap();

        // Verify comments are present
        let raw_content = fs::read_to_string(&project_config_path).unwrap();

        assert!(
            raw_content.contains("#"),
            "Project config should contain comments"
        );
        assert!(
            raw_content.contains("# Autom8 Configuration"),
            "Project config should have header comment"
        );
        assert!(
            raw_content.contains("# Review state"),
            "Project config should have review state comment"
        );
    }

    #[test]
    fn test_us003_save_project_config_creates_file() {
        // Use temp directory to avoid race conditions
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        let project_dir = config_dir.join("test-project");
        fs::create_dir_all(project_dir.join("spec")).unwrap();
        fs::create_dir_all(project_dir.join("runs")).unwrap();

        let config = Config {
            review: false,
            commit: true,
            pull_request: true,
            ..Default::default()
        };

        // Simulate save_project_config
        let project_config_path = project_dir.join("config.toml");
        let content = generate_config_with_comments(&config);
        fs::write(&project_config_path, &content).unwrap();

        // Verify file exists and can be loaded
        assert!(project_config_path.exists());

        let loaded: Config =
            toml::from_str(&fs::read_to_string(&project_config_path).unwrap()).unwrap();
        assert_eq!(loaded, config);
    }

    #[test]
    fn test_us003_save_project_config_preserves_comments() {
        // Use temp directory to avoid race conditions
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        let project_dir = config_dir.join("test-project");
        fs::create_dir_all(&project_dir).unwrap();

        let config = Config::default();
        let project_config_path = project_dir.join("config.toml");
        let content = generate_config_with_comments(&config);
        fs::write(&project_config_path, &content).unwrap();

        let raw_content = fs::read_to_string(&project_config_path).unwrap();

        assert!(
            raw_content.contains("#"),
            "Saved config should contain comments"
        );
        assert!(
            raw_content.contains("# Autom8 Configuration"),
            "Saved config should have header comment"
        );
    }

    #[test]
    fn test_us003_get_effective_config_returns_project_if_exists() {
        // Use temp directory to avoid race conditions
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        fs::create_dir_all(&config_dir).unwrap();

        // Create global config first
        let global_config = Config::default();
        let global_path = config_dir.join("config.toml");
        fs::write(&global_path, generate_config_with_comments(&global_config)).unwrap();

        // Create project config with distinct values
        let project_config = Config {
            review: false,
            commit: false,
            pull_request: false,
            ..Default::default()
        };
        let project_dir = config_dir.join("test-project");
        fs::create_dir_all(&project_dir).unwrap();
        let project_path = project_dir.join("config.toml");
        fs::write(
            &project_path,
            generate_config_with_comments(&project_config),
        )
        .unwrap();

        // Simulate get_effective_config logic
        let effective_path = if project_path.exists() {
            &project_path
        } else {
            &global_path
        };

        let effective: Config =
            toml::from_str(&fs::read_to_string(effective_path).unwrap()).unwrap();
        assert_eq!(
            effective, project_config,
            "Should return project config when it exists"
        );
    }

    #[test]
    fn test_us003_get_effective_config_returns_global_when_project_missing() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        fs::create_dir_all(&config_dir).unwrap();

        // Create global config
        let global_config = Config {
            review: true,
            commit: true,
            pull_request: false,
            ..Default::default()
        };
        let global_path = config_dir.join("config.toml");
        let content = generate_config_with_comments(&global_config);
        fs::write(&global_path, content).unwrap();

        // Create project dir but NOT project config
        let project_dir = config_dir.join("test-project");
        fs::create_dir_all(&project_dir).unwrap();

        // We can't directly test get_effective_config with temp dirs,
        // but we can verify the logic by checking path existence
        let project_config_path = project_dir.join("config.toml");
        assert!(
            !project_config_path.exists(),
            "Project config should not exist"
        );
        assert!(global_path.exists(), "Global config should exist");

        // Load global config to verify
        let loaded: Config = toml::from_str(&fs::read_to_string(&global_path).unwrap()).unwrap();
        assert_eq!(loaded, global_config);
    }

    #[test]
    fn test_us003_project_config_takes_precedence_over_global() {
        // Simulate project config overriding global with temp directories
        // to avoid race conditions with other tests
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        fs::create_dir_all(&config_dir).unwrap();

        // Create global config
        let global_config = Config {
            review: true,
            commit: true,
            pull_request: true,
            ..Default::default()
        };
        let global_path = config_dir.join("config.toml");
        fs::write(&global_path, generate_config_with_comments(&global_config)).unwrap();

        // Create project config with different values
        let project_config = Config {
            review: false,
            commit: true,
            pull_request: false,
            ..Default::default()
        };
        let project_dir = config_dir.join("my-project");
        fs::create_dir_all(&project_dir).unwrap();
        let project_path = project_dir.join("config.toml");
        fs::write(
            &project_path,
            generate_config_with_comments(&project_config),
        )
        .unwrap();

        // Simulate get_effective_config logic: prefer project if exists
        let effective_path = if project_path.exists() {
            &project_path
        } else {
            &global_path
        };

        let effective: Config =
            toml::from_str(&fs::read_to_string(effective_path).unwrap()).unwrap();
        assert_eq!(
            effective, project_config,
            "Project config should take precedence over global"
        );
        assert_ne!(
            effective, global_config,
            "Should not return global config when project config exists"
        );
    }

    #[test]
    fn test_us003_get_effective_config_does_not_create_project_config() {
        // Use temp directory to test the logic
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        fs::create_dir_all(&config_dir).unwrap();

        // Create global config
        let global_config = Config::default();
        let global_path = config_dir.join("config.toml");
        fs::write(&global_path, generate_config_with_comments(&global_config)).unwrap();

        // Create project dir but NOT project config
        let project_dir = config_dir.join("test-project");
        fs::create_dir_all(&project_dir).unwrap();
        let project_config_path = project_dir.join("config.toml");

        // Simulate get_effective_config: it should NOT create project config
        assert!(
            !project_config_path.exists(),
            "Project config should not exist before"
        );

        // Simulate reading effective config (prefer project if exists, else global)
        let effective_path = if project_config_path.exists() {
            &project_config_path
        } else {
            &global_path
        };
        let _effective: Config =
            toml::from_str(&fs::read_to_string(effective_path).unwrap()).unwrap();

        // get_effective_config should NOT have created the project config
        assert!(
            !project_config_path.exists(),
            "get_effective_config should NOT create project config"
        );
    }

    #[test]
    fn test_us003_project_config_roundtrip() {
        // Use temp directory to avoid race conditions
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        let project_dir = config_dir.join("test-project");
        fs::create_dir_all(&project_dir).unwrap();

        let original = Config {
            review: false,
            commit: true,
            pull_request: false,
            ..Default::default()
        };

        // Save
        let project_config_path = project_dir.join("config.toml");
        let content = generate_config_with_comments(&original);
        fs::write(&project_config_path, &content).unwrap();

        // Load
        let loaded: Config =
            toml::from_str(&fs::read_to_string(&project_config_path).unwrap()).unwrap();

        assert_eq!(original, loaded, "Config should survive save/load cycle");
    }

    #[test]
    fn test_us003_project_config_handles_partial_config() {
        // Use temp directory to avoid race conditions
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        let project_dir = config_dir.join("test-project");
        fs::create_dir_all(&project_dir).unwrap();

        let project_config_path = project_dir.join("config.toml");

        // Write a partial config (missing some fields)
        let partial_content = r#"
# Partial project config
review = false
"#;
        fs::write(&project_config_path, partial_content).unwrap();

        // Load should fill in defaults for missing fields
        let loaded: Config =
            toml::from_str(&fs::read_to_string(&project_config_path).unwrap()).unwrap();

        assert!(!loaded.review, "review should be false as specified");
        assert!(loaded.commit, "missing commit should default to true");
        assert!(
            loaded.pull_request,
            "missing pull_request should default to true"
        );
    }

    #[test]
    fn test_us003_inheritance_simulation_with_temp_dirs() {
        // Simulate the full inheritance flow with temp directories
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        fs::create_dir_all(&config_dir).unwrap();

        // Create global config
        let global_config = Config {
            review: true,
            commit: false,
            pull_request: false,
            ..Default::default()
        };
        let global_content = generate_config_with_comments(&global_config);
        let global_path = config_dir.join("config.toml");
        fs::write(&global_path, &global_content).unwrap();

        // Create project directory
        let project_dir = config_dir.join("test-project");
        fs::create_dir_all(project_dir.join("spec")).unwrap();
        fs::create_dir_all(project_dir.join("runs")).unwrap();

        // Simulate load_project_config behavior: copy global to project
        let project_config_path = project_dir.join("config.toml");
        assert!(!project_config_path.exists());

        // Copy global config content to project config
        fs::write(&project_config_path, &global_content).unwrap();

        // Verify project config exists and matches global
        assert!(project_config_path.exists());
        let loaded: Config =
            toml::from_str(&fs::read_to_string(&project_config_path).unwrap()).unwrap();
        assert_eq!(
            loaded, global_config,
            "Project config should inherit from global"
        );

        // Verify comments were preserved
        let project_content = fs::read_to_string(&project_config_path).unwrap();
        assert!(project_content.contains("# Autom8 Configuration"));
        assert!(project_content.contains("# Review state"));
    }

    #[test]
    fn test_us003_project_config_override_simulation() {
        // Simulate project config overriding global with different values
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().join(".config").join("autom8");
        fs::create_dir_all(&config_dir).unwrap();

        // Create global config
        let global_config = Config {
            review: true,
            commit: true,
            pull_request: true,
            ..Default::default()
        };
        let global_path = config_dir.join("config.toml");
        fs::write(&global_path, generate_config_with_comments(&global_config)).unwrap();

        // Create project config with different values
        let project_config = Config {
            review: false,
            commit: true,
            pull_request: false,
            ..Default::default()
        };
        let project_dir = config_dir.join("my-project");
        fs::create_dir_all(&project_dir).unwrap();
        let project_path = project_dir.join("config.toml");
        fs::write(
            &project_path,
            generate_config_with_comments(&project_config),
        )
        .unwrap();

        // Simulate get_effective_config logic: prefer project if exists
        let effective_path = if project_path.exists() {
            &project_path
        } else {
            &global_path
        };

        let effective: Config =
            toml::from_str(&fs::read_to_string(effective_path).unwrap()).unwrap();
        assert_eq!(
            effective, project_config,
            "Project config should take precedence"
        );
        assert_ne!(effective.review, global_config.review);
        assert_ne!(effective.pull_request, global_config.pull_request);
    }

    // =========================================================================
    // US-004: Config Validation Tests
    // =========================================================================

    #[test]
    fn test_us004_validate_config_accepts_default_config() {
        let config = Config::default();
        assert!(validate_config(&config).is_ok());
    }

    #[test]
    fn test_us004_validate_config_accepts_all_true() {
        let config = Config {
            review: true,
            commit: true,
            pull_request: true,
            ..Default::default()
        };
        assert!(validate_config(&config).is_ok());
    }

    #[test]
    fn test_us004_validate_config_accepts_all_false() {
        let config = Config {
            review: false,
            commit: false,
            pull_request: false,
            ..Default::default()
        };
        assert!(validate_config(&config).is_ok());
    }

    #[test]
    fn test_us004_validate_config_accepts_commit_true_pr_false() {
        let config = Config {
            review: true,
            commit: true,
            pull_request: false,
            ..Default::default()
        };
        assert!(validate_config(&config).is_ok());
    }

    #[test]
    fn test_us004_validate_config_accepts_commit_false_pr_false() {
        let config = Config {
            review: true,
            commit: false,
            pull_request: false,
            ..Default::default()
        };
        assert!(validate_config(&config).is_ok());
    }

    #[test]
    fn test_us004_validate_config_rejects_pr_true_commit_false() {
        let config = Config {
            review: true,
            commit: false,
            pull_request: true,
            ..Default::default()
        };
        let result = validate_config(&config);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), ConfigError::PullRequestWithoutCommit);
    }

    #[test]
    fn test_us004_config_error_message_is_actionable() {
        let error = ConfigError::PullRequestWithoutCommit;
        let message = error.to_string();

        // Verify the error message contains the exact required text
        assert_eq!(
            message,
            "Cannot create pull request without commits. \
            Either set `commit = true` or set `pull_request = false`"
        );
    }

    #[test]
    fn test_us004_config_error_implements_error_trait() {
        let error = ConfigError::PullRequestWithoutCommit;
        // Verify it implements std::error::Error
        let _: &dyn std::error::Error = &error;
    }

    #[test]
    fn test_us004_config_error_debug_format() {
        let error = ConfigError::PullRequestWithoutCommit;
        let debug_str = format!("{:?}", error);
        assert!(debug_str.contains("PullRequestWithoutCommit"));
    }

    #[test]
    fn test_us004_config_error_clone() {
        let error = ConfigError::PullRequestWithoutCommit;
        let cloned = error.clone();
        assert_eq!(error, cloned);
    }

    #[test]
    fn test_us004_validate_config_accepts_review_false_with_valid_pr_commit() {
        // Review state doesn't affect PR/commit validation
        let config = Config {
            review: false,
            commit: true,
            pull_request: true,
            ..Default::default()
        };
        assert!(validate_config(&config).is_ok());
    }

    #[test]
    fn test_us004_validate_config_all_combinations() {
        // Test all 8 possible boolean combinations (for review, commit, pull_request)
        let combinations = [
            (false, false, false, true), // all false - valid
            (false, false, true, false), // pr=true, commit=false - invalid
            (false, true, false, true),  // commit=true, pr=false - valid
            (false, true, true, true),   // commit=true, pr=true - valid
            (true, false, false, true),  // review=true, commit=false, pr=false - valid
            (true, false, true, false),  // review=true, pr=true, commit=false - invalid
            (true, true, false, true),   // review=true, commit=true, pr=false - valid
            (true, true, true, true),    // all true - valid
        ];

        for (review, commit, pull_request, should_be_valid) in combinations {
            let config = Config {
                review,
                commit,
                pull_request,
                ..Default::default()
            };
            let result = validate_config(&config);
            assert_eq!(
                result.is_ok(),
                should_be_valid,
                "Config (review={}, commit={}, pull_request={}) expected valid={}, got valid={}",
                review,
                commit,
                pull_request,
                should_be_valid,
                result.is_ok()
            );
        }
    }

    #[test]
    fn test_us004_get_effective_config_validates_before_returning() {
        // This test verifies that get_effective_config validates the loaded config
        // We can't easily test this with real files in a unit test, but we can
        // verify the validation function is called by testing with a simulated scenario

        // Create an invalid config directly and validate it
        let invalid_config = Config {
            review: true,
            commit: false,
            pull_request: true,
            ..Default::default()
        };
        let validation_result = validate_config(&invalid_config);
        assert!(validation_result.is_err());

        // Verify the error message contains actionable information
        let error = validation_result.unwrap_err();
        let message = error.to_string();
        assert!(message.contains("commit = true"));
        assert!(message.contains("pull_request = false"));
    }

    #[test]
    fn test_us004_validation_integration_with_autom8_error() {
        // Verify ConfigError can be converted to Autom8Error::Config
        let config_error = ConfigError::PullRequestWithoutCommit;
        let autom8_error = Autom8Error::Config(config_error.to_string());

        // The error message should be preserved
        let error_string = format!("{}", autom8_error);
        assert!(error_string.contains("Cannot create pull request without commits"));
    }

    // =========================================================================
    // Test: config files with use_tui should still parse (backwards compat)
    // =========================================================================

    #[test]
    fn test_config_with_use_tui_field_still_parses() {
        // Old config files may still have use_tui field - ensure they parse without error
        let toml_str = r#"
            review = true
            commit = true
            pull_request = true
            use_tui = true
        "#;
        // This should parse successfully (use_tui is ignored)
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(config.review);
        assert!(config.commit);
        assert!(config.pull_request);
    }

    // ========================================================================
    // US-005: Worktree Configuration Option tests
    // ========================================================================

    #[test]
    fn test_worktree_config_defaults_to_true() {
        let config = Config::default();
        assert!(config.worktree, "worktree should default to true");
    }

    #[test]
    fn test_worktree_config_can_be_enabled() {
        let toml_str = r#"
            worktree = true
        "#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(
            config.worktree,
            "worktree should be true when set in config"
        );
    }

    #[test]
    fn test_worktree_config_missing_defaults_to_true() {
        // Config files without worktree field should default to true
        let toml_str = r#"
            review = true
            commit = true
            pull_request = true
        "#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(
            config.worktree,
            "missing worktree field should default to true"
        );
    }

    #[test]
    fn test_worktree_config_explicit_false() {
        let toml_str = r#"
            worktree = false
        "#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(
            !config.worktree,
            "explicit worktree = false should be respected"
        );
    }

    #[test]
    fn test_worktree_config_with_all_other_fields() {
        let toml_str = r#"
            review = false
            commit = true
            pull_request = false
            worktree = true
        "#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(!config.review);
        assert!(config.commit);
        assert!(!config.pull_request);
        assert!(config.worktree);
    }

    #[test]
    fn test_worktree_config_documentation_note_in_generated_comments() {
        let config = Config::default();
        let content = generate_config_with_comments(&config);

        // Verify the git repository requirement note is documented
        assert!(
            content.contains("Requires a git repository"),
            "config comments should document git repo requirement"
        );
    }

    // ========================================================================
    // US-008: worktree_cleanup configuration tests
    // ========================================================================

    #[test]
    fn test_worktree_cleanup_config_defaults_to_false() {
        let config = Config::default();
        assert!(
            !config.worktree_cleanup,
            "worktree_cleanup should default to false for backward compatibility"
        );
    }

    #[test]
    fn test_worktree_cleanup_config_can_be_enabled() {
        let toml_str = r#"
            worktree_cleanup = true
        "#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(
            config.worktree_cleanup,
            "worktree_cleanup should be true when set in config"
        );
    }

    #[test]
    fn test_worktree_cleanup_config_missing_defaults_to_false() {
        // Old config files without worktree_cleanup field should still work
        let toml_str = r#"
            review = true
            commit = true
            worktree = true
        "#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(
            !config.worktree_cleanup,
            "missing worktree_cleanup field should default to false"
        );
    }

    #[test]
    fn test_worktree_cleanup_config_explicit_false() {
        let toml_str = r#"
            worktree_cleanup = false
        "#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(
            !config.worktree_cleanup,
            "explicit worktree_cleanup = false should be respected"
        );
    }

    #[test]
    fn test_worktree_cleanup_config_with_all_worktree_fields() {
        let toml_str = r#"
            worktree = true
            worktree_path_pattern = "{repo}-test-{branch}"
            worktree_cleanup = true
        "#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(config.worktree);
        assert_eq!(config.worktree_path_pattern, "{repo}-test-{branch}");
        assert!(config.worktree_cleanup);
    }

    #[test]
    fn test_worktree_cleanup_in_generated_comments() {
        let config = Config {
            worktree_cleanup: true,
            ..Default::default()
        };
        let content = generate_config_with_comments(&config);

        // Verify worktree_cleanup is documented
        assert!(
            content.contains("worktree_cleanup = true"),
            "generated config should include worktree_cleanup setting"
        );
        assert!(
            content.contains("successful completion"),
            "config comments should document cleanup behavior"
        );
    }

    #[test]
    fn test_worktree_cleanup_in_default_config_with_comments() {
        // Verify DEFAULT_CONFIG_WITH_COMMENTS includes worktree_cleanup
        assert!(
            DEFAULT_CONFIG_WITH_COMMENTS.contains("worktree_cleanup"),
            "DEFAULT_CONFIG_WITH_COMMENTS should include worktree_cleanup"
        );
        assert!(
            DEFAULT_CONFIG_WITH_COMMENTS.contains("worktree_cleanup = false"),
            "DEFAULT_CONFIG_WITH_COMMENTS should have worktree_cleanup = false"
        );
    }

    #[test]
    fn test_worktree_cleanup_serialization_roundtrip() {
        let config = Config {
            worktree: true,
            worktree_cleanup: true,
            ..Default::default()
        };

        // Serialize to TOML
        let toml_str = toml::to_string(&config).unwrap();
        assert!(toml_str.contains("worktree_cleanup = true"));

        // Deserialize back
        let parsed: Config = toml::from_str(&toml_str).unwrap();
        assert_eq!(parsed.worktree_cleanup, config.worktree_cleanup);
    }

    // ========================================================================
    // US-001 (draft-pr-config): pull_request_draft configuration tests
    // ========================================================================

    #[test]
    fn test_pull_request_draft_config_defaults_to_false() {
        let config = Config::default();
        assert!(
            !config.pull_request_draft,
            "pull_request_draft should default to false for backward compatibility"
        );
    }

    #[test]
    fn test_pull_request_draft_config_can_be_enabled() {
        let toml_str = r#"
            pull_request_draft = true
        "#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(
            config.pull_request_draft,
            "pull_request_draft should be true when set in config"
        );
    }

    #[test]
    fn test_pull_request_draft_config_missing_defaults_to_false() {
        // Old config files without pull_request_draft field should still work
        let toml_str = r#"
            review = true
            commit = true
            pull_request = true
        "#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(
            !config.pull_request_draft,
            "missing pull_request_draft field should default to false"
        );
    }

    #[test]
    fn test_pull_request_draft_config_explicit_false() {
        let toml_str = r#"
            pull_request_draft = false
        "#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(
            !config.pull_request_draft,
            "explicit pull_request_draft = false should be respected"
        );
    }

    #[test]
    fn test_pull_request_draft_config_with_all_pr_fields() {
        let toml_str = r#"
            pull_request = true
            pull_request_draft = true
        "#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(config.pull_request);
        assert!(config.pull_request_draft);
    }

    #[test]
    fn test_pull_request_draft_in_generated_comments() {
        let config = Config {
            pull_request_draft: true,
            ..Default::default()
        };
        let content = generate_config_with_comments(&config);

        // Verify pull_request_draft is documented
        assert!(
            content.contains("pull_request_draft = true"),
            "generated config should include pull_request_draft setting"
        );
        assert!(
            content.contains("draft mode"),
            "config comments should document draft mode behavior"
        );
    }

    #[test]
    fn test_pull_request_draft_in_default_config_with_comments() {
        // Verify DEFAULT_CONFIG_WITH_COMMENTS includes pull_request_draft
        assert!(
            DEFAULT_CONFIG_WITH_COMMENTS.contains("pull_request_draft"),
            "DEFAULT_CONFIG_WITH_COMMENTS should include pull_request_draft"
        );
        assert!(
            DEFAULT_CONFIG_WITH_COMMENTS.contains("pull_request_draft = false"),
            "DEFAULT_CONFIG_WITH_COMMENTS should have pull_request_draft = false"
        );
    }

    #[test]
    fn test_pull_request_draft_serialization_roundtrip() {
        let config = Config {
            pull_request: true,
            pull_request_draft: true,
            ..Default::default()
        };

        // Serialize to TOML
        let toml_str = toml::to_string(&config).unwrap();
        assert!(toml_str.contains("pull_request_draft = true"));

        // Deserialize back
        let parsed: Config = toml::from_str(&toml_str).unwrap();
        assert_eq!(parsed.pull_request_draft, config.pull_request_draft);
    }

    // US-001: Conditional Story Display in Describe View

    #[test]
    fn test_us001_spec_summary_is_active_field() {
        // Verify SpecSummary has is_active field
        let spec_active = SpecSummary {
            filename: "spec-active.json".to_string(),
            path: PathBuf::from("/test/spec-active.json"),
            project_name: "test".to_string(),
            branch_name: "feature/active".to_string(),
            description: "Active spec".to_string(),
            stories: vec![],
            completed_count: 0,
            total_count: 0,
            is_active: true,
        };

        let spec_inactive = SpecSummary {
            filename: "spec-inactive.json".to_string(),
            path: PathBuf::from("/test/spec-inactive.json"),
            project_name: "test".to_string(),
            branch_name: "feature/inactive".to_string(),
            description: "Inactive spec".to_string(),
            stories: vec![],
            completed_count: 0,
            total_count: 0,
            is_active: false,
        };

        assert!(spec_active.is_active);
        assert!(!spec_inactive.is_active);
    }

    // ========================================================================
    // US-004: Last Run Time Accuracy Tests
    // ========================================================================

    /// Helper function to compute the most meaningful timestamp for a run.
    /// This mirrors the logic in `list_projects_tree()` for testability.
    fn compute_last_run_timestamp(
        has_active_run: bool,
        run_started_at: Option<chrono::DateTime<chrono::Utc>>,
        run_finished_at: Option<chrono::DateTime<chrono::Utc>>,
        archived_started_at: Option<chrono::DateTime<chrono::Utc>>,
        archived_finished_at: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Option<chrono::DateTime<chrono::Utc>> {
        if has_active_run {
            // Active run: show when it started
            run_started_at
        } else {
            // No active run: prefer finished_at over started_at
            run_finished_at
                .or(run_started_at)
                .or(archived_finished_at)
                .or(archived_started_at)
        }
    }

    #[test]
    fn test_us004_last_run_date_active_run_uses_started_at() {
        use chrono::{Duration, Utc};

        let started_at = Utc::now() - Duration::minutes(30);
        let finished_at = None; // Active runs don't have finished_at

        let result = compute_last_run_timestamp(
            true,             // has_active_run
            Some(started_at), // run_started_at
            finished_at,      // run_finished_at
            None,             // archived_started_at
            None,             // archived_finished_at
        );

        assert_eq!(result, Some(started_at));
    }

    #[test]
    fn test_us004_last_run_date_completed_run_uses_finished_at() {
        use chrono::{Duration, Utc};

        let started_at = Utc::now() - Duration::hours(2);
        let finished_at = Utc::now() - Duration::minutes(30);

        let result = compute_last_run_timestamp(
            false,             // has_active_run (completed)
            Some(started_at),  // run_started_at
            Some(finished_at), // run_finished_at
            None,              // archived_started_at
            None,              // archived_finished_at
        );

        // Should use finished_at, not started_at
        assert_eq!(result, Some(finished_at));
    }

    #[test]
    fn test_us004_last_run_date_completed_run_fallback_to_started_at() {
        use chrono::{Duration, Utc};

        let started_at = Utc::now() - Duration::hours(2);
        // finished_at is None (run may have been interrupted before completion)

        let result = compute_last_run_timestamp(
            false,            // has_active_run (completed)
            Some(started_at), // run_started_at
            None,             // run_finished_at (missing)
            None,             // archived_started_at
            None,             // archived_finished_at
        );

        // Should fall back to started_at when finished_at is missing
        assert_eq!(result, Some(started_at));
    }

    #[test]
    fn test_us004_last_run_date_archived_run_uses_finished_at() {
        use chrono::{Duration, Utc};

        let archived_started_at = Utc::now() - Duration::days(1);
        let archived_finished_at = Utc::now() - Duration::hours(23);

        let result = compute_last_run_timestamp(
            false,                      // has_active_run
            None,                       // run_started_at (no current run)
            None,                       // run_finished_at
            Some(archived_started_at),  // archived_started_at
            Some(archived_finished_at), // archived_finished_at
        );

        // Should use archived finished_at
        assert_eq!(result, Some(archived_finished_at));
    }

    #[test]
    fn test_us004_last_run_date_no_runs_returns_none() {
        let result = compute_last_run_timestamp(
            false, // has_active_run
            None,  // run_started_at
            None,  // run_finished_at
            None,  // archived_started_at
            None,  // archived_finished_at
        );

        assert_eq!(result, None);
    }

    #[test]
    fn test_us004_last_run_date_prefers_current_over_archived() {
        use chrono::{Duration, Utc};

        // Current run is more recent but completed
        let current_started_at = Utc::now() - Duration::hours(1);
        let current_finished_at = Utc::now() - Duration::minutes(30);

        // Older archived run
        let archived_started_at = Utc::now() - Duration::days(7);
        let archived_finished_at = Utc::now() - Duration::days(7) + Duration::hours(2);

        let result = compute_last_run_timestamp(
            false,                      // has_active_run
            Some(current_started_at),   // run_started_at
            Some(current_finished_at),  // run_finished_at
            Some(archived_started_at),  // archived_started_at
            Some(archived_finished_at), // archived_finished_at
        );

        // Should use current run's finished_at, not archived
        assert_eq!(result, Some(current_finished_at));
    }
}