shipper-cli 0.3.0-rc.2

CLI adapter for Shipper. Install with `cargo install shipper --locked`; this crate is for embedders who want the exact CLI surface programmatically.
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
//! BDD (Behavior-Driven Development) tests for cross-cutting workflow scenarios.
//!
//! These tests correspond to `features/workflow.feature` and exercise the
//! resume, parallel publish, status, and doctor commands in representative
//! end-to-end situations inside temporary workspaces.

use std::fs;
use std::path::{Path, PathBuf};
use std::thread;
use std::time::Duration;

use assert_cmd::Command;
use predicates::str::contains;
use serial_test::serial;
use tempfile::tempdir;
use tiny_http::{Header, Response, Server, StatusCode};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn write_file(path: &Path, content: &str) {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("mkdir");
    }
    fs::write(path, content).expect("write");
}

fn shipper_cmd() -> Command {
    Command::new(assert_cmd::cargo::cargo_bin!("shipper-cli"))
}

struct TestRegistry {
    base_url: String,
    handle: thread::JoinHandle<()>,
}

impl TestRegistry {
    fn join(self) {
        self.handle.join().expect("join server");
    }
}

fn spawn_registry(statuses: Vec<u16>, expected_requests: usize) -> TestRegistry {
    let server = Server::http("127.0.0.1:0").expect("server");
    let base_url = format!("http://{}", server.server_addr());
    let handle = thread::spawn(move || {
        for idx in 0..expected_requests {
            let req = match server.recv_timeout(Duration::from_secs(30)) {
                Ok(Some(r)) => r,
                _ => break,
            };
            let status = statuses
                .get(idx)
                .copied()
                .or_else(|| statuses.last().copied())
                .unwrap_or(404);
            let resp = Response::from_string("{}")
                .with_status_code(StatusCode(status))
                .with_header(
                    Header::from_bytes("Content-Type", "application/json").expect("header"),
                );
            req.respond(resp).expect("respond");
        }
    });
    TestRegistry { base_url, handle }
}

fn spawn_doctor_registry(expected_requests: usize) -> TestRegistry {
    let server = Server::http("127.0.0.1:0").expect("server");
    let base_url = format!("http://{}", server.server_addr());
    let handle = thread::spawn(move || {
        for _ in 0..expected_requests {
            let req = match server.recv_timeout(Duration::from_secs(30)) {
                Ok(Some(r)) => r,
                _ => break,
            };
            let resp = Response::from_string(r#"{"crate":{"id":"serde"}}"#)
                .with_status_code(StatusCode(200))
                .with_header(
                    Header::from_bytes("Content-Type", "application/json").expect("header"),
                );
            req.respond(resp).expect("respond");
        }
    });
    TestRegistry { base_url, handle }
}

fn path_sep() -> &'static str {
    if cfg!(windows) { ";" } else { ":" }
}

fn create_fake_cargo_proxy(bin_dir: &Path) {
    #[cfg(windows)]
    {
        fs::write(
            bin_dir.join("cargo.cmd"),
            "@echo off\r\nif \"%1\"==\"publish\" (\r\n  if \"%SHIPPER_FAKE_PUBLISH_EXIT%\"==\"\" (exit /b 0) else (exit /b %SHIPPER_FAKE_PUBLISH_EXIT%)\r\n)\r\n\"%REAL_CARGO%\" %*\r\nexit /b %ERRORLEVEL%\r\n",
        )
        .expect("write fake cargo");
    }

    #[cfg(not(windows))]
    {
        use std::os::unix::fs::PermissionsExt;

        let path = bin_dir.join("cargo");
        fs::write(
            &path,
            "#!/usr/bin/env sh\nif [ \"$1\" = \"publish\" ]; then\n  exit \"${SHIPPER_FAKE_PUBLISH_EXIT:-0}\"\nfi\n\"$REAL_CARGO\" \"$@\"\n",
        )
        .expect("write fake cargo");
        let mut perms = fs::metadata(&path).expect("meta").permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&path, perms).expect("chmod");
    }
}

fn fake_cargo_bin_path(bin_dir: &Path) -> String {
    #[cfg(windows)]
    {
        bin_dir.join("cargo.cmd").display().to_string()
    }
    #[cfg(not(windows))]
    {
        bin_dir.join("cargo").display().to_string()
    }
}

fn setup_fake_cargo(td: &Path) -> (String, String, String) {
    let bin_dir = td.join("fake-bin");
    fs::create_dir_all(&bin_dir).expect("mkdir");
    create_fake_cargo_proxy(&bin_dir);
    let old_path = std::env::var("PATH").unwrap_or_default();
    let mut new_path = bin_dir.display().to_string();
    if !old_path.is_empty() {
        new_path.push_str(path_sep());
        new_path.push_str(&old_path);
    }
    let real_cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string());
    let fake_cargo = fake_cargo_bin_path(&bin_dir);
    (new_path, real_cargo, fake_cargo)
}

fn find_executable_on_path(program: &str) -> Option<PathBuf> {
    let path_var = std::env::var_os("PATH")?;

    #[cfg(windows)]
    let candidates = [
        format!("{program}.exe"),
        format!("{program}.cmd"),
        format!("{program}.bat"),
        program.to_string(),
    ];
    #[cfg(not(windows))]
    let candidates = [program.to_string()];

    std::env::split_paths(&path_var)
        .flat_map(|dir| candidates.iter().map(move |candidate| dir.join(candidate)))
        .find(|candidate| candidate.is_file())
}

fn resolve_tool_path(env_var: &str, program: &str) -> PathBuf {
    if let Some(configured) = std::env::var_os(env_var) {
        let configured = PathBuf::from(configured);
        if configured.is_file() {
            return configured;
        }
        if let Some(resolved) = find_executable_on_path(&configured.to_string_lossy()) {
            return resolved;
        }
    }

    find_executable_on_path(program).unwrap_or_else(|| panic!("failed to resolve {program}"))
}

fn create_tool_proxy(bin_dir: &Path, tool: &str, env_var: &str) {
    #[cfg(windows)]
    {
        fs::write(
            bin_dir.join(format!("{tool}.cmd")),
            format!("@echo off\r\n\"%{env_var}%\" %*\r\nexit /b %ERRORLEVEL%\r\n"),
        )
        .expect("write tool proxy");
    }

    #[cfg(not(windows))]
    {
        use std::os::unix::fs::PermissionsExt;

        let path = bin_dir.join(tool);
        fs::write(
            &path,
            format!("#!/usr/bin/env sh\n\"${{{env_var}}}\" \"$@\"\n"),
        )
        .expect("write tool proxy");
        let mut perms = fs::metadata(&path).expect("meta").permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&path, perms).expect("chmod");
    }
}

fn create_failing_tool_proxy(bin_dir: &Path, tool: &str, message: &str) {
    #[cfg(windows)]
    {
        fs::write(
            bin_dir.join(format!("{tool}.cmd")),
            format!("@echo off\r\necho {message} 1>&2\r\nexit /b 1\r\n"),
        )
        .expect("write failing tool proxy");
    }

    #[cfg(not(windows))]
    {
        use std::os::unix::fs::PermissionsExt;

        let path = bin_dir.join(tool);
        fs::write(
            &path,
            format!("#!/usr/bin/env sh\necho '{message}' >&2\nexit 1\n"),
        )
        .expect("write failing tool proxy");
        let mut perms = fs::metadata(&path).expect("meta").permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&path, perms).expect("chmod");
    }
}

fn path_entry_has_cargo(path: &Path) -> bool {
    #[cfg(windows)]
    {
        path.join("cargo.exe").exists()
            || path.join("cargo.cmd").exists()
            || path.join("cargo.bat").exists()
            || path.join("cargo.com").exists()
    }

    #[cfg(not(windows))]
    {
        path.join("cargo").exists()
    }
}

fn setup_doctor_tool_path(td: &Path) -> (String, String, String, Option<String>) {
    let bin_dir = td.join("doctor-bin");
    fs::create_dir_all(&bin_dir).expect("mkdir");

    create_failing_tool_proxy(&bin_dir, "cargo", "simulated missing cargo");
    create_tool_proxy(&bin_dir, "rustc", "REAL_RUSTC");
    let real_cargo = resolve_tool_path("CARGO", "cargo");
    let real_rustc = resolve_tool_path("RUSTC", "rustc");

    let real_git = find_executable_on_path("git");
    if real_git.is_some() {
        create_tool_proxy(&bin_dir, "git", "REAL_GIT");
    }

    let filtered_path = std::env::var_os("PATH")
        .map(|path| {
            std::env::split_paths(&path)
                .filter(|entry| !path_entry_has_cargo(entry))
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();

    let mut tool_path = bin_dir.display().to_string();
    if !filtered_path.is_empty() {
        tool_path.push_str(path_sep());
        tool_path.push_str(
            &std::env::join_paths(filtered_path)
                .expect("join PATH")
                .to_string_lossy(),
        );
    }

    (
        tool_path,
        real_cargo.display().to_string(),
        real_rustc.display().to_string(),
        real_git.map(|path| path.display().to_string()),
    )
}

fn fast_args(cmd: &mut Command, manifest: &Path, api_base: &str, state_dir: &Path) {
    cmd.arg("--manifest-path")
        .arg(manifest)
        .arg("--api-base")
        .arg(api_base)
        .arg("--allow-dirty")
        .arg("--verify-timeout")
        .arg("0ms")
        .arg("--verify-poll")
        .arg("0ms")
        .arg("--no-readiness")
        .arg("--max-attempts")
        .arg("2")
        .arg("--base-delay")
        .arg("0ms")
        .arg("--state-dir")
        .arg(state_dir);
}

// ---------------------------------------------------------------------------
// Workspace builders
// ---------------------------------------------------------------------------

fn create_single_crate_workspace(root: &Path) {
    write_file(
        &root.join("Cargo.toml"),
        r#"
[workspace]
members = ["demo"]
resolver = "2"
"#,
    );
    write_file(
        &root.join("demo/Cargo.toml"),
        r#"
[package]
name = "demo"
version = "0.1.0"
edition = "2021"
"#,
    );
    write_file(&root.join("demo/src/lib.rs"), "pub fn demo() {}\n");
}

fn create_two_crate_workspace(root: &Path) {
    write_file(
        &root.join("Cargo.toml"),
        r#"
[workspace]
members = ["core", "app"]
resolver = "2"
"#,
    );
    write_file(
        &root.join("core/Cargo.toml"),
        r#"
[package]
name = "core"
version = "0.1.0"
edition = "2021"
"#,
    );
    write_file(&root.join("core/src/lib.rs"), "pub fn core() {}\n");
    write_file(
        &root.join("app/Cargo.toml"),
        r#"
[package]
name = "app"
version = "0.1.0"
edition = "2021"

[dependencies]
core = { path = "../core" }
"#,
    );
    write_file(&root.join("app/src/lib.rs"), "pub fn app() {}\n");
}

fn create_independent_workspace(root: &Path) {
    write_file(
        &root.join("Cargo.toml"),
        r#"
[workspace]
members = ["alpha", "beta", "gamma"]
resolver = "2"
"#,
    );
    for name in &["alpha", "beta", "gamma"] {
        write_file(
            &root.join(format!("{name}/Cargo.toml")),
            &format!(
                r#"
[package]
name = "{name}"
version = "0.1.0"
edition = "2021"
"#
            ),
        );
        write_file(
            &root.join(format!("{name}/src/lib.rs")),
            &format!("pub fn {name}() {{}}\n"),
        );
    }
}

fn create_parallel_workspace(root: &Path) {
    write_file(
        &root.join("Cargo.toml"),
        r#"
[workspace]
members = ["core", "api", "cli", "app"]
resolver = "2"
"#,
    );
    write_file(
        &root.join("core/Cargo.toml"),
        r#"
[package]
name = "core"
version = "0.1.0"
edition = "2021"
"#,
    );
    write_file(&root.join("core/src/lib.rs"), "pub fn core() {}\n");

    write_file(
        &root.join("api/Cargo.toml"),
        r#"
[package]
name = "api"
version = "0.1.0"
edition = "2021"

[dependencies]
core = { path = "../core" }
"#,
    );
    write_file(&root.join("api/src/lib.rs"), "pub fn api() {}\n");

    write_file(
        &root.join("cli/Cargo.toml"),
        r#"
[package]
name = "cli"
version = "0.1.0"
edition = "2021"

[dependencies]
core = { path = "../core" }
"#,
    );
    write_file(&root.join("cli/src/lib.rs"), "pub fn cli() {}\n");

    write_file(
        &root.join("app/Cargo.toml"),
        r#"
[package]
name = "app"
version = "0.1.0"
edition = "2021"

[dependencies]
api = { path = "../api" }
cli = { path = "../cli" }
"#,
    );
    write_file(&root.join("app/src/lib.rs"), "pub fn app() {}\n");
}

fn create_multi_crate_workspace(root: &Path) {
    write_file(
        &root.join("Cargo.toml"),
        r#"
[workspace]
members = ["core-lib", "utils-lib", "top-app"]
resolver = "2"
"#,
    );
    write_file(
        &root.join("core-lib/Cargo.toml"),
        r#"
[package]
name = "core-lib"
version = "0.1.0"
edition = "2021"
"#,
    );
    write_file(&root.join("core-lib/src/lib.rs"), "pub fn core() {}\n");

    write_file(
        &root.join("utils-lib/Cargo.toml"),
        r#"
[package]
name = "utils-lib"
version = "0.1.0"
edition = "2021"

[dependencies]
core-lib = { path = "../core-lib" }
"#,
    );
    write_file(
        &root.join("utils-lib/src/lib.rs"),
        "pub fn utils() { core_lib::core(); }\n",
    );

    write_file(
        &root.join("top-app/Cargo.toml"),
        r#"
[package]
name = "top-app"
version = "0.1.0"
edition = "2021"

[dependencies]
core-lib = { path = "../core-lib" }
utils-lib = { path = "../utils-lib" }
"#,
    );
    write_file(
        &root.join("top-app/src/lib.rs"),
        "pub fn app() { utils_lib::utils(); }\n",
    );
}

fn create_solo_workspace(root: &Path) {
    write_file(
        &root.join("Cargo.toml"),
        r#"
[workspace]
members = ["solo"]
resolver = "2"
"#,
    );
    write_file(
        &root.join("solo/Cargo.toml"),
        r#"
[package]
name = "solo"
version = "0.3.0"
edition = "2021"
"#,
    );
    write_file(&root.join("solo/src/lib.rs"), "pub fn solo() {}\n");
}

// ============================================================================
// Feature: Resume workflow
// ============================================================================

mod resume_continues_after_interruption {
    use super::*;

    // Scenario: Resume after interrupted publish completes remaining crates
    //
    // Given: a workspace with "core" and "app" where "app" depends on "core"
    // And: a prior publish run failed while publishing "app"
    // And: the state file marks core as Skipped and app as Failed
    // When: I run "shipper resume"
    // Then: exit code is 0, receipt shows app as Published, core was not re-published
    #[test]
    #[serial]
    fn given_interrupted_publish_when_resume_then_completes_remaining_crates() {
        // Given: create workspace and fail the initial publish
        let td = tempdir().expect("tempdir");
        create_two_crate_workspace(td.path());
        let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());
        let state_dir = td.path().join(".shipper");

        // Initial publish: core 200 (skip), app 404 cargo-fail 404 404 → ~4 reqs.
        // Resume: app 404, cargo ok, readiness 200 → ~2 reqs.
        let registry = spawn_registry(vec![200, 404, 404, 404, 404, 200], 7);

        // Initial publish that fails on app
        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("--allow-dirty")
            .arg("--verify-timeout")
            .arg("0ms")
            .arg("--verify-poll")
            .arg("0ms")
            .arg("--no-readiness")
            .arg("--max-attempts")
            .arg("1")
            .arg("--base-delay")
            .arg("0ms")
            .arg("--state-dir")
            .arg(&state_dir)
            .arg("publish")
            .env("PATH", &new_path)
            .env("REAL_CARGO", &real_cargo)
            .env("SHIPPER_CARGO_BIN", &fake_cargo)
            .env("SHIPPER_FAKE_PUBLISH_EXIT", "1")
            .assert()
            .failure();

        // Verify pre-condition: app is failed
        let state: serde_json::Value = serde_json::from_str(
            &fs::read_to_string(state_dir.join("state.json")).expect("read state"),
        )
        .expect("parse state");
        let app_state = state["packages"]["app@0.1.0"]["state"]["state"]
            .as_str()
            .expect("app state");
        assert_eq!(app_state, "failed", "app should be failed before resume");

        // When: resume with cargo publish succeeding
        let mut cmd = shipper_cmd();
        fast_args(
            &mut cmd,
            &td.path().join("Cargo.toml"),
            &registry.base_url,
            &state_dir,
        );
        cmd.arg("resume")
            .env("PATH", &new_path)
            .env("REAL_CARGO", &real_cargo)
            .env("SHIPPER_CARGO_BIN", &fake_cargo)
            .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
            .assert()
            .success();

        // Then: receipt shows app as published
        let receipt: serde_json::Value = serde_json::from_str(
            &fs::read_to_string(state_dir.join("receipt.json")).expect("read receipt"),
        )
        .expect("parse receipt");
        let packages = receipt["packages"].as_array().expect("packages array");
        let app_pkg = packages.iter().find(|p| p["name"].as_str() == Some("app"));
        assert!(app_pkg.is_some(), "receipt should contain app");
        assert_eq!(
            app_pkg.unwrap()["state"]["state"].as_str(),
            Some("published"),
            "app should be published after resume"
        );

        registry.join();
    }
}

mod resume_noop_when_complete {
    use super::*;

    // Scenario: Resume with all packages already published is a no-op
    //
    // Given: a workspace with a single crate that was already published
    // When: I run "shipper resume"
    // Then: exit code is 0, cargo publish is not invoked, output says "already complete"
    #[test]
    #[serial]
    fn given_all_published_when_resume_then_noop() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());
        let state_dir = td.path().join(".shipper");

        // First publish successfully: version-check 404, readiness 200 → 2 reqs.
        let registry = spawn_registry(vec![404, 200], 3);

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("--allow-dirty")
            .arg("--verify-timeout")
            .arg("0ms")
            .arg("--verify-poll")
            .arg("0ms")
            .arg("--no-readiness")
            .arg("--max-attempts")
            .arg("1")
            .arg("--state-dir")
            .arg(&state_dir)
            .arg("publish")
            .env("PATH", &new_path)
            .env("REAL_CARGO", &real_cargo)
            .env("SHIPPER_CARGO_BIN", &fake_cargo)
            .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
            .assert()
            .success();

        // Verify demo is published in state
        let state: serde_json::Value = serde_json::from_str(
            &fs::read_to_string(state_dir.join("state.json")).expect("read state"),
        )
        .expect("parse state");
        assert_eq!(
            state["packages"]["demo@0.1.0"]["state"]["state"].as_str(),
            Some("published")
        );

        // When: resume on already-completed state
        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("--allow-dirty")
            .arg("--verify-timeout")
            .arg("0ms")
            .arg("--verify-poll")
            .arg("0ms")
            .arg("--no-readiness")
            .arg("--max-attempts")
            .arg("1")
            .arg("--state-dir")
            .arg(&state_dir)
            .arg("resume")
            .env("PATH", &new_path)
            .env("REAL_CARGO", &real_cargo)
            .env("SHIPPER_CARGO_BIN", &fake_cargo)
            .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
            .assert()
            .success()
            .get_output()
            .stderr
            .clone();

        // Then: output says already complete
        let stderr = String::from_utf8(output).expect("utf8");
        assert!(
            stderr.contains("already complete"),
            "expected 'already complete' in stderr, got: {stderr}"
        );

        registry.join();
    }
}

// ============================================================================
// Feature: Parallel publish
// ============================================================================

mod parallel_independent_skipped {
    use super::*;

    // Scenario: Parallel publish groups independent crates into one level
    //
    // Given: a workspace with independent crates alpha, beta, gamma
    // And: registry reports all versions as already published (200)
    // When: I run "shipper publish --parallel --max-concurrent 2"
    // Then: exit code is 0, all three appear in receipt as Skipped
    #[test]
    #[serial]
    fn given_independent_crates_when_parallel_publish_then_all_skipped() {
        let td = tempdir().expect("tempdir");
        create_independent_workspace(td.path());
        let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());
        let state_dir = td.path().join(".shipper");

        // All 200: every version_exists → "already published" → skip
        let registry = spawn_registry(vec![200, 200, 200], 3);

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("--allow-dirty")
            .arg("--max-attempts")
            .arg("1")
            .arg("--state-dir")
            .arg(&state_dir)
            .arg("--max-concurrent")
            .arg("2")
            .arg("--parallel")
            .arg("publish")
            .env("PATH", &new_path)
            .env("REAL_CARGO", &real_cargo)
            .env("SHIPPER_CARGO_BIN", &fake_cargo)
            .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
            .assert()
            .success();

        // Then: receipt contains all 3 as skipped
        let receipt: serde_json::Value = serde_json::from_str(
            &fs::read_to_string(state_dir.join("receipt.json")).expect("read receipt"),
        )
        .expect("parse receipt");
        let packages = receipt["packages"].as_array().expect("packages array");
        assert_eq!(packages.len(), 3, "receipt should have 3 packages");

        for pkg in packages {
            let pkg_state = pkg["state"]["state"].as_str().unwrap_or("unknown");
            assert!(
                pkg_state == "skipped" || pkg_state == "published",
                "expected skipped or published, got: {pkg_state}"
            );
        }

        registry.join();
    }
}

mod parallel_respects_dependency_ordering {
    use super::*;

    // Scenario: Parallel publish respects dependency ordering across levels
    //
    // Given: a workspace with core → {api, cli} → app
    // And: registry reports all versions as already published
    // When: I run "shipper publish --parallel"
    // Then: exit code is 0, all four crates appear in the receipt
    #[test]
    #[serial]
    fn given_dependencies_when_parallel_publish_then_all_in_receipt() {
        let td = tempdir().expect("tempdir");
        create_parallel_workspace(td.path());
        let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());
        let state_dir = td.path().join(".shipper");

        // All 200: version_exists → skip for 4 crates
        let registry = spawn_registry(vec![200, 200, 200, 200], 4);

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("--allow-dirty")
            .arg("--max-attempts")
            .arg("1")
            .arg("--state-dir")
            .arg(&state_dir)
            .arg("--max-concurrent")
            .arg("1")
            .arg("--parallel")
            .arg("publish")
            .env("PATH", &new_path)
            .env("REAL_CARGO", &real_cargo)
            .env("SHIPPER_CARGO_BIN", &fake_cargo)
            .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
            .assert()
            .success();

        // Then: receipt has all 4 packages
        let receipt: serde_json::Value = serde_json::from_str(
            &fs::read_to_string(state_dir.join("receipt.json")).expect("read receipt"),
        )
        .expect("parse receipt");
        let packages = receipt["packages"].as_array().expect("packages array");
        assert_eq!(packages.len(), 4, "receipt should have 4 packages");

        let names: Vec<&str> = packages.iter().filter_map(|p| p["name"].as_str()).collect();
        assert!(names.contains(&"core"), "receipt should contain core");
        assert!(names.contains(&"api"), "receipt should contain api");
        assert!(names.contains(&"cli"), "receipt should contain cli");
        assert!(names.contains(&"app"), "receipt should contain app");

        registry.join();
    }
}

// ============================================================================
// Feature: Status command
// ============================================================================

mod status_mixed_published_and_missing {
    use super::*;

    // Scenario: Status reports mixed published and missing crates
    //
    // Given: a workspace with core-lib, utils-lib, and top-app
    // And: registry returns 200 for core-lib, 404 for utils-lib and top-app
    // When: I run "shipper status"
    // Then: exit code is 0, output contains published for core-lib and missing for others
    #[test]
    fn given_mixed_versions_when_status_then_reports_each_correctly() {
        let td = tempdir().expect("tempdir");
        create_multi_crate_workspace(td.path());

        // core-lib → 200 (published), utils-lib → 404 (missing), top-app → 404 (missing)
        let registry = spawn_registry(vec![200, 404, 404], 3);

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("status")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");

        // Then: at least one published, at least one missing
        assert!(
            stdout.contains("published"),
            "expected at least one published crate in: {stdout}"
        );
        assert!(
            stdout.contains("missing"),
            "expected at least one missing crate in: {stdout}"
        );

        registry.join();
    }
}

mod status_single_crate_shows_version {
    use super::*;

    // Scenario: Status for a single-crate workspace shows version
    //
    // Given: a workspace with solo@0.3.0
    // And: registry returns 404 (not found)
    // When: I run "shipper status"
    // Then: exit code is 0, output contains "solo@0.3.0"
    #[test]
    fn given_single_crate_when_status_then_shows_version() {
        let td = tempdir().expect("tempdir");
        create_solo_workspace(td.path());

        let registry = spawn_registry(vec![404], 1);

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("status")
            .assert()
            .success()
            .stdout(contains("solo@0.3.0"));

        registry.join();
    }
}

// ============================================================================
// Feature: Doctor diagnostics
// ============================================================================

mod doctor_reports_header_and_workspace {
    use super::*;

    // Scenario: Doctor reports diagnostics header and workspace root
    //
    // Given: a valid workspace with crate "demo" and a reachable mock registry
    // When: I run "shipper doctor"
    // Then: exit code is 0, output contains header and workspace_root
    #[test]
    fn given_valid_workspace_when_doctor_then_reports_header_and_root() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        fs::create_dir_all(td.path().join("cargo-home")).expect("mkdir");

        let registry = spawn_doctor_registry(1);

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("doctor")
            .env("CARGO_HOME", td.path().join("cargo-home"))
            .env_remove("CARGO_REGISTRY_TOKEN")
            .env_remove("CARGO_REGISTRIES_CRATES_IO_TOKEN")
            .assert()
            .success()
            .stdout(contains("Shipper Doctor - Diagnostics Report"))
            .stdout(contains("workspace_root:"));

        registry.join();
    }
}

mod doctor_warns_missing_token {
    use super::*;

    // Scenario: Doctor warns when no registry token is configured
    //
    // Given: a valid workspace, no CARGO_REGISTRY_TOKEN
    // When: I run "shipper doctor"
    // Then: exit code is 0, output contains "NONE FOUND"
    #[test]
    fn given_no_token_when_doctor_then_warns_none_found() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        let cargo_home = td.path().join("cargo-home");
        fs::create_dir_all(&cargo_home).expect("mkdir");

        let registry = spawn_doctor_registry(1);

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("doctor")
            .env("CARGO_HOME", &cargo_home)
            .env_remove("CARGO_REGISTRY_TOKEN")
            .env_remove("CARGO_REGISTRIES_CRATES_IO_TOKEN")
            .assert()
            .success()
            .stdout(contains("NONE FOUND"));

        registry.join();
    }
}

mod doctor_detects_cargo {
    use super::*;

    // Scenario: Doctor detects cargo version
    //
    // Given: a valid workspace (cargo is on PATH)
    // When: I run "shipper doctor"
    // Then: exit code is 0, output contains cargo version line
    #[test]
    fn given_cargo_installed_when_doctor_then_shows_version() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        fs::create_dir_all(td.path().join("cargo-home")).expect("mkdir");

        let registry = spawn_doctor_registry(1);

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("doctor")
            .env("CARGO_HOME", td.path().join("cargo-home"))
            .env_remove("CARGO_REGISTRY_TOKEN")
            .env_remove("CARGO_REGISTRIES_CRATES_IO_TOKEN")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");
        assert!(
            stdout.contains("cargo: cargo"),
            "expected cargo version line, got: {stdout}"
        );

        registry.join();
    }
}

mod doctor_reports_registry_reachability {
    use super::*;

    // Scenario: Doctor reports registry reachability
    //
    // Given: a valid workspace with a reachable mock registry
    // When: I run "shipper doctor"
    // Then: exit code is 0, output contains "registry_reachable: true"
    #[test]
    fn given_reachable_registry_when_doctor_then_reports_reachable() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        fs::create_dir_all(td.path().join("cargo-home")).expect("mkdir");

        let registry = spawn_doctor_registry(1);

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("doctor")
            .env("CARGO_HOME", td.path().join("cargo-home"))
            .env_remove("CARGO_REGISTRY_TOKEN")
            .env_remove("CARGO_REGISTRIES_CRATES_IO_TOKEN")
            .assert()
            .success()
            .stdout(contains("registry_reachable: true"));

        registry.join();
    }
}

// ============================================================================
// Feature: Config validation workflow
// ============================================================================

mod config_validate_rejects_zero_max_attempts {
    use super::*;

    // Scenario: Config validate rejects zero retry max_attempts
    //
    // Given: a .shipper.toml with retry.max_attempts = 0
    // When: I run "shipper config validate"
    // Then: exit code is non-zero, error mentions "max_attempts"
    #[test]
    fn given_zero_max_attempts_when_config_validate_then_error() {
        let td = tempdir().expect("tempdir");
        write_file(
            &td.path().join(".shipper.toml"),
            r#"
schema_version = "shipper.config.v1"

[retry]
max_attempts = 0
"#,
        );

        shipper_cmd()
            .arg("config")
            .arg("validate")
            .arg("-p")
            .arg(td.path().join(".shipper.toml"))
            .assert()
            .failure()
            .stderr(contains("max_attempts"));
    }
}

mod config_validate_rejects_invalid_jitter {
    use super::*;

    // Scenario: Config validate rejects jitter outside valid range
    //
    // Given: a .shipper.toml with retry.jitter = 1.5
    // When: I run "shipper config validate"
    // Then: exit code is non-zero, error mentions "jitter"
    #[test]
    fn given_invalid_jitter_when_config_validate_then_error() {
        let td = tempdir().expect("tempdir");
        write_file(
            &td.path().join(".shipper.toml"),
            r#"
schema_version = "shipper.config.v1"

[retry]
jitter = 1.5
"#,
        );

        shipper_cmd()
            .arg("config")
            .arg("validate")
            .arg("-p")
            .arg(td.path().join(".shipper.toml"))
            .assert()
            .failure()
            .stderr(contains("jitter"));
    }
}

// ============================================================================
// Feature: Doctor token warning
// ============================================================================

mod doctor_reports_token_source_when_missing {
    use super::*;

    // Scenario: Doctor reports token source when no token is configured
    //
    // Given: a valid workspace, no CARGO_REGISTRY_TOKEN, no credentials file
    // When: I run "shipper doctor"
    // Then: exit code is 0, output contains "auth_type:" and "NONE FOUND"
    #[test]
    fn given_no_token_no_credentials_when_doctor_then_reports_none_found() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        let cargo_home = td.path().join("cargo-home");
        fs::create_dir_all(&cargo_home).expect("mkdir");

        let registry = spawn_doctor_registry(1);

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("doctor")
            .env("CARGO_HOME", &cargo_home)
            .env_remove("CARGO_REGISTRY_TOKEN")
            .env_remove("CARGO_REGISTRIES_CRATES_IO_TOKEN")
            .assert()
            .success()
            .stdout(contains("auth_type:"))
            .stdout(contains("NONE FOUND"));

        registry.join();
    }
}

// ============================================================================
// Feature: Clean command
// ============================================================================

mod clean_removes_state_files {
    use super::*;

    // Scenario: Clean removes state files from .shipper directory
    //
    // Given: a workspace with "demo" and a state directory containing state.json and events.jsonl
    // When: I run "shipper clean"
    // Then: exit code is 0, output contains "Clean complete", state.json is removed
    #[test]
    #[serial]
    fn given_state_files_when_clean_then_removes_them() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        let state_dir = td.path().join(".shipper");
        fs::create_dir_all(&state_dir).expect("mkdir");

        // Pre-populate state files
        write_file(&state_dir.join("state.json"), r#"{"plan_id":"test"}"#);
        write_file(&state_dir.join("events.jsonl"), "{}\n");
        assert!(state_dir.join("state.json").exists());

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--state-dir")
            .arg(&state_dir)
            .arg("clean")
            .assert()
            .success()
            .stdout(contains("Clean complete"));

        // Then: state.json should be removed
        assert!(
            !state_dir.join("state.json").exists(),
            "state.json should be removed after clean"
        );
        assert!(
            !state_dir.join("events.jsonl").exists(),
            "events.jsonl should be removed after clean"
        );
    }
}

mod clean_keep_receipt {
    use super::*;

    // Scenario: Clean with --keep-receipt preserves receipt.json
    //
    // Given: a workspace with state.json, events.jsonl, and receipt.json in state dir
    // When: I run "shipper clean --keep-receipt"
    // Then: exit code is 0, receipt.json still exists, state.json is removed
    #[test]
    #[serial]
    fn given_receipt_when_clean_keep_receipt_then_preserves_it() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        let state_dir = td.path().join(".shipper");
        fs::create_dir_all(&state_dir).expect("mkdir");

        // Pre-populate state files including receipt
        write_file(&state_dir.join("state.json"), r#"{"plan_id":"test"}"#);
        write_file(&state_dir.join("events.jsonl"), "{}\n");
        write_file(&state_dir.join("receipt.json"), r#"{"packages":[]}"#);

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--state-dir")
            .arg(&state_dir)
            .arg("clean")
            .arg("--keep-receipt")
            .assert()
            .success()
            .stdout(contains("Clean complete"));

        // Then: receipt.json should be preserved
        assert!(
            state_dir.join("receipt.json").exists(),
            "receipt.json should be preserved with --keep-receipt"
        );
        // And: state.json should be removed
        assert!(
            !state_dir.join("state.json").exists(),
            "state.json should be removed"
        );
    }
}

// ============================================================================
// Feature: Plan with package filter
// ============================================================================

mod plan_with_package_filter {
    use super::*;

    // Scenario: Plan with --package filter shows only selected package and its deps
    //
    // Given: a workspace with "core", "utils", and "app" where "app" depends on both
    // When: I run "shipper plan --package app"
    // Then: exit code is 0, output contains "app@0.1.0"
    #[test]
    fn given_multi_crate_when_plan_with_package_then_shows_filtered() {
        let td = tempdir().expect("tempdir");
        create_multi_crate_workspace(td.path());

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--package")
            .arg("top-app")
            .arg("plan")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");

        // Then: output should contain the filtered package
        assert!(
            stdout.contains("top-app@0.1.0"),
            "expected top-app@0.1.0 in plan output, got: {stdout}"
        );
        // And: total packages should reflect filtered set (app + its deps)
        assert!(
            stdout.contains("Total packages to publish:"),
            "expected total packages line in output, got: {stdout}"
        );
    }
}

// ============================================================================
// Feature: Dry run publish (preflight)
// ============================================================================

mod preflight_checks_without_publishing {
    use super::*;

    // Scenario: Preflight checks workspace without publishing
    //
    // Given: a workspace with "demo" and registry reports version as already published
    // When: I run "shipper preflight --allow-dirty"
    // Then: exit code is 0, no state.json created
    #[test]
    fn given_workspace_when_preflight_then_no_state_file() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        let state_dir = td.path().join(".shipper");

        // Registry returns 200 for version-exists checks; preflight may issue multiple requests
        let registry = spawn_registry(vec![200, 200, 200], 3);

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("--allow-dirty")
            .arg("--state-dir")
            .arg(&state_dir)
            .arg("--skip-ownership-check")
            .arg("--no-verify")
            .arg("preflight")
            .assert()
            .success();

        // Then: no state.json should be created (preflight doesn't persist state)
        assert!(
            !state_dir.join("state.json").exists(),
            "preflight should not create state.json"
        );

        registry.join();
    }
}

// ============================================================================
// Feature: Edge-case scenarios
// ============================================================================

fn create_dev_dependency_workspace(root: &Path) {
    write_file(
        &root.join("Cargo.toml"),
        r#"
[workspace]
members = ["lib-a", "lib-b"]
resolver = "2"
"#,
    );
    write_file(
        &root.join("lib-a/Cargo.toml"),
        r#"
[package]
name = "lib-a"
version = "0.1.0"
edition = "2021"
"#,
    );
    write_file(&root.join("lib-a/src/lib.rs"), "pub fn a() {}\n");
    write_file(
        &root.join("lib-b/Cargo.toml"),
        r#"
[package]
name = "lib-b"
version = "0.1.0"
edition = "2021"

[dev-dependencies]
lib-a = { path = "../lib-a" }
"#,
    );
    write_file(
        &root.join("lib-b/src/lib.rs"),
        "pub fn b() {}\n#[cfg(test)] mod tests { use lib_a::a; #[test] fn it() { a(); } }\n",
    );
}

mod publish_all_already_published_sequential {
    use super::*;

    // Scenario: Sequential publish when all crates are already published skips everything
    //
    // Given: a workspace with "core" and "app" where "app" depends on "core"
    // And: registry reports both versions as already published (200)
    // When: I run "shipper publish" (sequential, no --parallel)
    // Then: exit code is 0, receipt shows both crates as skipped
    #[test]
    #[serial]
    fn given_all_published_when_sequential_publish_then_all_skipped() {
        let td = tempdir().expect("tempdir");
        create_two_crate_workspace(td.path());
        let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());
        let state_dir = td.path().join(".shipper");

        // Both return 200 → already published → skip
        let registry = spawn_registry(vec![200, 200], 2);

        let mut cmd = shipper_cmd();
        fast_args(
            &mut cmd,
            &td.path().join("Cargo.toml"),
            &registry.base_url,
            &state_dir,
        );
        cmd.arg("publish")
            .env("PATH", &new_path)
            .env("REAL_CARGO", &real_cargo)
            .env("SHIPPER_CARGO_BIN", &fake_cargo)
            .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
            .assert()
            .success();

        // Then: receipt shows all crates as skipped
        let receipt: serde_json::Value = serde_json::from_str(
            &fs::read_to_string(state_dir.join("receipt.json")).expect("read receipt"),
        )
        .expect("parse receipt");
        let packages = receipt["packages"].as_array().expect("packages array");
        assert_eq!(packages.len(), 2, "receipt should have 2 packages");

        for pkg in packages {
            let pkg_state = pkg["state"]["state"].as_str().unwrap_or("unknown");
            assert_eq!(
                pkg_state, "skipped",
                "expected skipped for {}, got: {pkg_state}",
                pkg["name"]
            );
        }

        registry.join();
    }
}

mod clean_with_no_state_directory {
    use super::*;

    // Scenario: Clean when .shipper directory does not exist exits gracefully
    //
    // Given: a workspace with "demo" and no .shipper directory
    // When: I run "shipper clean"
    // Then: exit code is 0, output says "State directory does not exist"
    #[test]
    fn given_no_state_dir_when_clean_then_reports_not_exist() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        let state_dir = td.path().join(".shipper");

        // Ensure .shipper does not exist
        assert!(!state_dir.exists());

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--state-dir")
            .arg(&state_dir)
            .arg("clean")
            .assert()
            .success()
            .stdout(contains("State directory does not exist"));
    }
}

mod doctor_reports_unreachable_registry {
    use super::*;

    // Scenario: Doctor reports registry unreachable when mock server is not running
    //
    // Given: a valid workspace with an unreachable registry API base
    // When: I run "shipper doctor"
    // Then: exit code is 0, output contains "registry_reachable: false"
    #[test]
    fn given_unreachable_registry_when_doctor_then_reports_unreachable() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        fs::create_dir_all(td.path().join("cargo-home")).expect("mkdir");

        // Use a port that is guaranteed not to be listening
        let bad_url = "http://127.0.0.1:1";

        let assert = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(bad_url)
            .arg("doctor")
            .env("CARGO_HOME", td.path().join("cargo-home"))
            .env_remove("CARGO_REGISTRY_TOKEN")
            .env_remove("CARGO_REGISTRIES_CRATES_IO_TOKEN")
            .assert()
            .success();

        // registry_reachable: false is emitted via reporter.warn() → stderr
        let stderr = String::from_utf8(assert.get_output().stderr.clone()).expect("utf8");
        assert!(
            stderr.contains("registry_reachable: false"),
            "expected 'registry_reachable: false' in stderr, got: {stderr}"
        );
    }
}

mod plan_with_dev_dependencies_only {
    use super::*;

    // Scenario: Plan on a workspace where crates have only dev-dependencies
    //
    // Given: a workspace with "lib-a" and "lib-b" where "lib-b" dev-depends on "lib-a"
    // When: I run "shipper plan"
    // Then: exit code is 0, output lists both crates, total is 2
    #[test]
    fn given_dev_deps_only_when_plan_then_both_crates_listed() {
        let td = tempdir().expect("tempdir");
        create_dev_dependency_workspace(td.path());

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("plan")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");

        assert!(
            stdout.contains("lib-a@0.1.0"),
            "expected lib-a@0.1.0 in plan output, got: {stdout}"
        );
        assert!(
            stdout.contains("lib-b@0.1.0"),
            "expected lib-b@0.1.0 in plan output, got: {stdout}"
        );
        assert!(
            stdout.contains("Total packages to publish:"),
            "expected total packages line in output, got: {stdout}"
        );
    }
}

mod preflight_fails_on_non_git_directory {
    use super::*;

    // Scenario: Preflight fails when run in a non-git directory without --allow-dirty
    //
    // Given: a workspace with "demo" that is NOT inside a git repository
    // When: I run "shipper preflight" (without --allow-dirty)
    // Then: exit code is non-zero (git cleanliness check fails)
    #[test]
    fn given_non_git_dir_when_preflight_without_allow_dirty_then_fails() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());

        let registry = spawn_registry(vec![200, 200, 200], 3);

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("--skip-ownership-check")
            .arg("--no-verify")
            .arg("preflight")
            .assert()
            .failure();

        registry.join();
    }
}

mod resume_with_corrupted_state_file {
    use super::*;

    // Scenario: Resume with a corrupted (non-JSON) state file fails gracefully
    //
    // Given: a workspace with "demo" and a state file containing garbage data
    // When: I run "shipper resume"
    // Then: exit code is non-zero, error output mentions parse/state issue
    #[test]
    #[serial]
    fn given_corrupted_state_when_resume_then_fails_with_error() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        let state_dir = td.path().join(".shipper");
        fs::create_dir_all(&state_dir).expect("mkdir");

        // Write corrupted state
        write_file(&state_dir.join("state.json"), "NOT VALID JSON {{{{");

        let registry = spawn_registry(vec![200], 1);

        let mut cmd = shipper_cmd();
        fast_args(
            &mut cmd,
            &td.path().join("Cargo.toml"),
            &registry.base_url,
            &state_dir,
        );
        cmd.arg("resume").assert().failure();

        registry.join();
    }
}

mod status_all_published {
    use super::*;

    // Scenario: Status shows all crates as published when registry reports all exist
    //
    // Given: a workspace with "core" and "app"
    // And: registry returns 200 for both versions
    // When: I run "shipper status"
    // Then: exit code is 0, output contains "published" for both, no "missing"
    #[test]
    fn given_all_published_when_status_then_no_missing() {
        let td = tempdir().expect("tempdir");
        create_two_crate_workspace(td.path());

        // Both return 200 → published
        let registry = spawn_registry(vec![200, 200], 2);

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("status")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");

        assert!(
            stdout.contains("published"),
            "expected published in output, got: {stdout}"
        );
        assert!(
            !stdout.contains("missing"),
            "expected no missing in output, got: {stdout}"
        );

        registry.join();
    }
}

// ============================================================================
// Feature: Real-world workflow scenarios (bdd_ prefix)
// ============================================================================

mod bdd_preflight_dry_run_no_state {
    use super::*;

    // Scenario: User runs preflight (dry-run equivalent) — no state/receipts written
    //
    // Given: a multi-crate workspace with "core-lib", "utils-lib", and "top-app"
    // And: registry reports all versions as already published (200)
    // When: I run "shipper preflight --allow-dirty --skip-ownership-check --no-verify"
    // Then: exit code is 0
    // And: no state.json is created in the state directory
    // And: no receipt.json is created in the state directory
    // And: no events.jsonl is created in the state directory
    #[test]
    fn bdd_preflight_dry_run_writes_no_state_or_receipts() {
        let td = tempdir().expect("tempdir");
        create_multi_crate_workspace(td.path());
        let state_dir = td.path().join(".shipper");

        // Registry returns 200 for version-exists checks; preflight may issue multiple requests
        let registry = spawn_registry(vec![200, 200, 200, 200, 200, 200], 6);

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("--allow-dirty")
            .arg("--skip-ownership-check")
            .arg("--no-verify")
            .arg("--state-dir")
            .arg(&state_dir)
            .arg("preflight")
            .assert()
            .success();

        // Then: no state or receipt artifacts should be created
        assert!(
            !state_dir.join("state.json").exists(),
            "preflight (dry-run) should not create state.json"
        );
        assert!(
            !state_dir.join("receipt.json").exists(),
            "preflight (dry-run) should not create receipt.json"
        );

        registry.join();
    }
}

mod bdd_preflight_skip_ownership {
    use super::*;

    // Scenario: User runs preflight with --skip-ownership-check
    //
    // Given: a workspace with "demo"
    // And: registry reports the version as not published (404)
    // When: I run "shipper preflight --allow-dirty --skip-ownership-check --no-verify"
    // Then: exit code is 0
    // And: the Preflight Report is printed
    // And: ownership column shows "✗" (skipped, not verified)
    #[test]
    fn bdd_preflight_with_skip_ownership_check_succeeds() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());

        // Registry: 404 for version check (not published); preflight may issue multiple requests
        let registry = spawn_registry(vec![404, 404, 404], 3);

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("--allow-dirty")
            .arg("--skip-ownership-check")
            .arg("--no-verify")
            .arg("preflight")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");

        // Then: preflight report is generated
        assert!(
            stdout.contains("Preflight Report"),
            "expected Preflight Report header, got: {stdout}"
        );
        // And: ownership is not verified (shows ✗ because check was skipped)
        assert!(
            stdout.contains("Ownership verified: 0"),
            "expected 'Ownership verified: 0' when ownership check is skipped, got: {stdout}"
        );

        registry.join();
    }
}

mod bdd_resume_after_network_failure {
    use super::*;

    // Scenario: User resumes publish after a network failure
    //
    // Given: a three-crate workspace (core-lib, utils-lib, top-app)
    // And: an initial publish skipped core-lib and utils-lib (already published)
    //      but failed on top-app (simulating network failure during cargo publish)
    // And: the state file marks core-lib and utils-lib as Skipped and top-app as Failed
    // When: I run "shipper resume" with the network now recovered
    // Then: exit code is 0
    // And: receipt shows top-app as published
    // And: already-published crates were not re-published
    #[test]
    #[serial]
    fn bdd_resume_continues_from_last_published_after_failure() {
        let td = tempdir().expect("tempdir");
        create_multi_crate_workspace(td.path());
        let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());
        let state_dir = td.path().join(".shipper");

        // Initial publish: core-lib 200 (skip), utils-lib 200 (skip),
        // top-app 404 (needs publish), cargo fails → marked failed
        // Resume: top-app 404 (needs publish), cargo ok, verify 200
        let registry = spawn_registry(vec![200, 200, 404, 404, 404, 404, 200], 8);

        // Initial publish that fails on top-app (simulated network failure)
        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("--allow-dirty")
            .arg("--verify-timeout")
            .arg("0ms")
            .arg("--verify-poll")
            .arg("0ms")
            .arg("--no-readiness")
            .arg("--max-attempts")
            .arg("1")
            .arg("--base-delay")
            .arg("0ms")
            .arg("--state-dir")
            .arg(&state_dir)
            .arg("publish")
            .env("PATH", &new_path)
            .env("REAL_CARGO", &real_cargo)
            .env("SHIPPER_CARGO_BIN", &fake_cargo)
            .env("SHIPPER_FAKE_PUBLISH_EXIT", "1")
            .assert()
            .failure();

        // Verify: state file exists with failed package(s)
        assert!(
            state_dir.join("state.json").exists(),
            "state.json should exist after failed publish"
        );

        // When: resume with cargo publish now succeeding (network recovered)
        let mut cmd = shipper_cmd();
        fast_args(
            &mut cmd,
            &td.path().join("Cargo.toml"),
            &registry.base_url,
            &state_dir,
        );
        cmd.arg("resume")
            .env("PATH", &new_path)
            .env("REAL_CARGO", &real_cargo)
            .env("SHIPPER_CARGO_BIN", &fake_cargo)
            .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
            .assert()
            .success();

        // Then: receipt should exist with the resumed package(s)
        let receipt: serde_json::Value = serde_json::from_str(
            &fs::read_to_string(state_dir.join("receipt.json")).expect("read receipt"),
        )
        .expect("parse receipt");
        let packages = receipt["packages"].as_array().expect("packages array");
        assert!(
            !packages.is_empty(),
            "receipt should have at least one package after resume"
        );

        // All packages in receipt should be in a terminal state (published or skipped)
        for pkg in packages {
            let state = pkg["state"]["state"].as_str().unwrap_or("unknown");
            assert!(
                state == "published" || state == "skipped",
                "expected published or skipped for {}, got: {state}",
                pkg["name"]
            );
        }

        // Verify the failed package (top-app) was resolved
        let top_app = packages
            .iter()
            .find(|p| p["name"].as_str() == Some("top-app"));
        assert!(
            top_app.is_some(),
            "receipt should contain top-app after resume"
        );
        assert_eq!(
            top_app.unwrap()["state"]["state"].as_str(),
            Some("published"),
            "top-app should be published after resume"
        );

        registry.join();
    }
}

mod bdd_status_mixed_published_unpublished {
    use super::*;

    // Scenario: User runs status on workspace with mixed published/unpublished crates
    //
    // Given: a workspace with "core", "app" where "app" depends on "core"
    // And: registry returns 200 for "core" (published) and 404 for "app" (not published)
    // When: I run "shipper status"
    // Then: exit code is 0
    // And: output contains "published" (for core)
    // And: output contains "missing" (for app)
    // And: output contains both crate names
    #[test]
    fn bdd_status_shows_mixed_published_and_unpublished() {
        let td = tempdir().expect("tempdir");
        create_two_crate_workspace(td.path());

        // core → 200 (published), app → 404 (missing)
        let registry = spawn_registry(vec![200, 404], 2);

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("status")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");

        // Then: mixed status
        assert!(
            stdout.contains("published"),
            "expected at least one published crate, got: {stdout}"
        );
        assert!(
            stdout.contains("missing"),
            "expected at least one missing crate, got: {stdout}"
        );
        // And: both crate names appear
        assert!(
            stdout.contains("core"),
            "expected 'core' in status output, got: {stdout}"
        );
        assert!(
            stdout.contains("app"),
            "expected 'app' in status output, got: {stdout}"
        );

        registry.join();
    }
}

mod bdd_doctor_missing_cargo {
    use super::*;

    // Scenario: User runs doctor with cargo not on PATH
    //
    // Given: a valid workspace with "demo"
    // And: PATH only exposes the toolchain binaries needed for metadata
    // When: I run "shipper doctor"
    // Then: exit code is 0 (doctor is diagnostic, not a hard failure)
    // And: stderr contains a warning about being unable to run cargo
    #[test]
    fn bdd_doctor_warns_when_cargo_not_found() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        let cargo_home = td.path().join("cargo-home");
        fs::create_dir_all(&cargo_home).expect("mkdir");
        let (tool_path, real_cargo, real_rustc, real_git) = setup_doctor_tool_path(td.path());

        let registry = spawn_doctor_registry(1);

        let mut cmd = shipper_cmd();
        cmd.arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("doctor")
            .env("PATH", &tool_path)
            .env("CARGO", &real_cargo)
            .env("REAL_RUSTC", &real_rustc)
            .env("CARGO_HOME", &cargo_home)
            .env_remove("CARGO_REGISTRY_TOKEN")
            .env_remove("CARGO_REGISTRIES_CRATES_IO_TOKEN");
        if let Some(ref real_git) = real_git {
            cmd.env("REAL_GIT", real_git);
        }

        let assert = cmd.assert().success();

        // Then: stderr warns about cargo not being available
        let stderr = String::from_utf8(assert.get_output().stderr.clone()).expect("utf8");
        assert!(
            stderr.contains("unable to run cargo") || stderr.contains("cargo"),
            "expected warning about cargo not found, got stderr: {stderr}"
        );

        registry.join();
    }
}

mod bdd_publish_single_package {
    use super::*;

    // Scenario: User publishes single package from multi-crate workspace
    //
    // Given: a workspace with "core-lib", "utils-lib", and "top-app"
    // And: registry reports all versions as already published (200)
    // When: I run "shipper publish --package core-lib"
    // Then: exit code is 0
    // And: receipt contains only "core-lib" (filtered by --package)
    #[test]
    #[serial]
    fn bdd_publish_single_package_filters_correctly() {
        let td = tempdir().expect("tempdir");
        create_multi_crate_workspace(td.path());
        let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());
        let state_dir = td.path().join(".shipper");

        // 200 for core-lib version check → already published → skip
        let registry = spawn_registry(vec![200], 1);

        let mut cmd = shipper_cmd();
        fast_args(
            &mut cmd,
            &td.path().join("Cargo.toml"),
            &registry.base_url,
            &state_dir,
        );
        cmd.arg("--package")
            .arg("core-lib")
            .arg("publish")
            .env("PATH", &new_path)
            .env("REAL_CARGO", &real_cargo)
            .env("SHIPPER_CARGO_BIN", &fake_cargo)
            .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
            .assert()
            .success();

        // Then: receipt should contain only core-lib
        let receipt: serde_json::Value = serde_json::from_str(
            &fs::read_to_string(state_dir.join("receipt.json")).expect("read receipt"),
        )
        .expect("parse receipt");
        let packages = receipt["packages"].as_array().expect("packages array");
        assert_eq!(
            packages.len(),
            1,
            "receipt should have exactly 1 package when --package filters"
        );
        assert_eq!(
            packages[0]["name"].as_str(),
            Some("core-lib"),
            "the single package should be core-lib"
        );

        registry.join();
    }
}

mod bdd_plan_manifest_path_subcrate {
    use super::*;

    // Scenario: User runs plan with --manifest-path pointing to subcrate
    //
    // Given: a workspace with "core-lib", "utils-lib", and "top-app"
    // When: I run "shipper plan --manifest-path <workspace>/Cargo.toml --package utils-lib"
    // Then: exit code is 0
    // And: output contains "utils-lib@0.1.0"
    // And: plan is scoped to include utils-lib and its dependency core-lib
    #[test]
    fn bdd_plan_with_manifest_path_scoped_correctly() {
        let td = tempdir().expect("tempdir");
        create_multi_crate_workspace(td.path());

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--package")
            .arg("utils-lib")
            .arg("plan")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");

        // Then: utils-lib should be in the plan
        assert!(
            stdout.contains("utils-lib@0.1.0"),
            "expected utils-lib@0.1.0 in plan output, got: {stdout}"
        );
        // And: top-app should NOT be in the filtered plan
        assert!(
            !stdout.contains("top-app@0.1.0"),
            "expected top-app to be excluded from filtered plan, got: {stdout}"
        );
    }
}

mod bdd_config_conflicting_settings {
    use super::*;

    // Scenario: Config validation catches conflicting settings
    //
    // Given: a .shipper.toml with retry.base_delay > retry.max_delay (conflicting)
    // When: I run "shipper config validate"
    // Then: exit code is non-zero
    // And: error message mentions the conflict (max_delay must be >= base_delay)
    #[test]
    fn bdd_config_validation_catches_base_delay_exceeding_max_delay() {
        let td = tempdir().expect("tempdir");
        write_file(
            &td.path().join(".shipper.toml"),
            r#"
schema_version = "shipper.config.v1"

[retry]
base_delay = "30s"
max_delay = "5s"
"#,
        );

        shipper_cmd()
            .arg("config")
            .arg("validate")
            .arg("-p")
            .arg(td.path().join(".shipper.toml"))
            .assert()
            .failure()
            .stderr(contains("max_delay"));
    }
}

mod bdd_ci_github_actions_output {
    use super::*;

    // Scenario: CI template output matches expected format
    //
    // Given: a valid workspace with "demo"
    // When: I run "shipper ci github-actions"
    // Then: exit code is 0
    // And: output contains GitHub Actions step markers ("- name:", "uses:")
    // And: output references shipper publish
    // And: output references CARGO_REGISTRY_TOKEN
    #[test]
    fn bdd_ci_github_actions_produces_valid_yaml_steps() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("ci")
            .arg("github-actions")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");

        // Then: output contains GitHub Actions YAML structure
        assert!(
            stdout.contains("- name:"),
            "expected '- name:' YAML step marker, got: {stdout}"
        );
        assert!(
            stdout.contains("uses:"),
            "expected 'uses:' action reference, got: {stdout}"
        );
        assert!(
            stdout.contains("shipper publish"),
            "expected 'shipper publish' command reference, got: {stdout}"
        );
        assert!(
            stdout.contains("CARGO_REGISTRY_TOKEN"),
            "expected CARGO_REGISTRY_TOKEN env var reference, got: {stdout}"
        );
        // And: output starts with a comment header
        assert!(
            stdout.starts_with("# GitHub Actions"),
            "expected output to start with '# GitHub Actions' comment, got: {stdout}"
        );
    }
}

mod bdd_clean_preserves_workspace {
    use super::*;

    // Scenario: Clean command removes state files but preserves workspace
    //
    // Given: a workspace with "demo" and state files (state.json, events.jsonl, receipt.json)
    // When: I run "shipper clean"
    // Then: exit code is 0
    // And: state.json, events.jsonl, and receipt.json are removed
    // And: Cargo.toml still exists
    // And: demo/src/lib.rs still exists
    // And: demo/Cargo.toml still exists
    #[test]
    #[serial]
    fn bdd_clean_removes_state_but_preserves_source_files() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        let state_dir = td.path().join(".shipper");
        fs::create_dir_all(&state_dir).expect("mkdir");

        // Pre-populate state files
        write_file(&state_dir.join("state.json"), r#"{"plan_id":"test"}"#);
        write_file(&state_dir.join("events.jsonl"), "{}\n");
        write_file(&state_dir.join("receipt.json"), r#"{"packages":[]}"#);

        // Verify preconditions
        assert!(state_dir.join("state.json").exists());
        assert!(state_dir.join("events.jsonl").exists());
        assert!(state_dir.join("receipt.json").exists());
        assert!(td.path().join("Cargo.toml").exists());
        assert!(td.path().join("demo/Cargo.toml").exists());
        assert!(td.path().join("demo/src/lib.rs").exists());

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--state-dir")
            .arg(&state_dir)
            .arg("clean")
            .assert()
            .success()
            .stdout(contains("Clean complete"));

        // Then: state files should be removed
        assert!(
            !state_dir.join("state.json").exists(),
            "state.json should be removed after clean"
        );
        assert!(
            !state_dir.join("events.jsonl").exists(),
            "events.jsonl should be removed after clean"
        );
        assert!(
            !state_dir.join("receipt.json").exists(),
            "receipt.json should be removed after clean"
        );

        // And: workspace source files should be preserved
        assert!(
            td.path().join("Cargo.toml").exists(),
            "workspace Cargo.toml should be preserved after clean"
        );
        assert!(
            td.path().join("demo/Cargo.toml").exists(),
            "demo/Cargo.toml should be preserved after clean"
        );
        assert!(
            td.path().join("demo/src/lib.rs").exists(),
            "demo/src/lib.rs should be preserved after clean"
        );
    }
}

// ============================================================================
// Feature: Config validation workflow — malformed configs
// ============================================================================

mod config_validate_rejects_missing_schema_version {
    use super::*;

    // Scenario: Config validate rejects a TOML file that is not valid TOML at all
    //
    // Given: a file containing garbage text that is not valid TOML
    // When: I run "shipper config validate -p <path>"
    // Then: exit code is non-zero, stderr mentions a parsing or load failure
    #[test]
    fn given_garbage_content_when_config_validate_then_fails_with_parse_error() {
        let td = tempdir().expect("tempdir");
        write_file(
            &td.path().join(".shipper.toml"),
            "this is {{not}} valid TOML !!@#$",
        );

        shipper_cmd()
            .arg("config")
            .arg("validate")
            .arg("-p")
            .arg(td.path().join(".shipper.toml"))
            .assert()
            .failure();
    }
}

mod config_validate_rejects_unknown_schema_version {
    use super::*;

    // Scenario: Config validate rejects an unknown schema_version
    //
    // Given: a .shipper.toml with schema_version = "unknown.version.v99"
    // When: I run "shipper config validate"
    // Then: exit code is non-zero
    #[test]
    fn given_unknown_schema_version_when_config_validate_then_fails() {
        let td = tempdir().expect("tempdir");
        write_file(
            &td.path().join(".shipper.toml"),
            r#"
schema_version = "unknown.version.v99"
"#,
        );

        shipper_cmd()
            .arg("config")
            .arg("validate")
            .arg("-p")
            .arg(td.path().join(".shipper.toml"))
            .assert()
            .failure();
    }
}

mod config_validate_nonexistent_file {
    use super::*;

    // Scenario: Config validate for a nonexistent file fails with clear error
    //
    // Given: no config file at the specified path
    // When: I run "shipper config validate -p /nonexistent/.shipper.toml"
    // Then: exit code is non-zero, stderr mentions "not found"
    #[test]
    fn given_nonexistent_path_when_config_validate_then_fails_with_not_found() {
        let td = tempdir().expect("tempdir");
        let missing_path = td.path().join("does-not-exist.toml");

        shipper_cmd()
            .arg("config")
            .arg("validate")
            .arg("-p")
            .arg(&missing_path)
            .assert()
            .failure()
            .stderr(contains("not found"));
    }
}

// ============================================================================
// Feature: Multi-crate publishing — dependency ordering
// ============================================================================

mod plan_multi_crate_correct_ordering {
    use super::*;

    // Scenario: Plan for a workspace with chained dependencies shows correct order
    //
    // Given: a workspace with core-lib → utils-lib → top-app (transitive chain)
    // When: I run "shipper plan"
    // Then: exit code is 0
    // And: core-lib appears before utils-lib in the output
    // And: utils-lib appears before top-app in the output
    #[test]
    fn given_chain_deps_when_plan_then_core_before_utils_before_top() {
        let td = tempdir().expect("tempdir");
        create_multi_crate_workspace(td.path());

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("plan")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");

        // All three should be present
        assert!(stdout.contains("core-lib@0.1.0"), "missing core-lib");
        assert!(stdout.contains("utils-lib@0.1.0"), "missing utils-lib");
        assert!(stdout.contains("top-app@0.1.0"), "missing top-app");

        // Verify ordering: core-lib before utils-lib before top-app
        let pos_core = stdout.find("core-lib@0.1.0").expect("core-lib position");
        let pos_utils = stdout.find("utils-lib@0.1.0").expect("utils-lib position");
        let pos_top = stdout.find("top-app@0.1.0").expect("top-app position");
        assert!(
            pos_core < pos_utils,
            "core-lib should appear before utils-lib in plan"
        );
        assert!(
            pos_utils < pos_top,
            "utils-lib should appear before top-app in plan"
        );
    }
}

mod plan_independent_crates_all_listed {
    use super::*;

    // Scenario: Plan for workspace with independent crates lists all of them
    //
    // Given: a workspace with alpha, beta, gamma (no inter-dependencies)
    // When: I run "shipper plan"
    // Then: exit code is 0
    // And: all three crates appear in the output
    // And: total packages is 3
    #[test]
    fn given_independent_crates_when_plan_then_all_listed() {
        let td = tempdir().expect("tempdir");
        create_independent_workspace(td.path());

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("plan")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");

        assert!(stdout.contains("alpha@0.1.0"), "missing alpha");
        assert!(stdout.contains("beta@0.1.0"), "missing beta");
        assert!(stdout.contains("gamma@0.1.0"), "missing gamma");
        assert!(
            stdout.contains("Total packages to publish: 3"),
            "expected total 3 packages, got: {stdout}"
        );
    }
}

// ============================================================================
// Feature: Preflight failure handling
// ============================================================================

mod preflight_reports_git_check_failure {
    use super::*;

    // Scenario: Preflight without --allow-dirty in non-git dir gives clear error
    //
    // Given: a workspace with core-lib, utils-lib, top-app NOT in a git repo
    // When: I run "shipper preflight --skip-ownership-check --no-verify"
    // Then: exit code is non-zero (git cleanliness check fails)
    // And: stderr mentions git-related error
    #[test]
    fn given_multi_crate_non_git_when_preflight_then_fails_with_git_error() {
        let td = tempdir().expect("tempdir");
        create_multi_crate_workspace(td.path());

        let registry = spawn_registry(vec![200, 200, 200], 3);

        let assert = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("--skip-ownership-check")
            .arg("--no-verify")
            .arg("preflight")
            .assert()
            .failure();

        let stderr = String::from_utf8(assert.get_output().stderr.clone()).expect("utf8");
        assert!(
            stderr.to_lowercase().contains("git"),
            "expected git-related error in stderr, got: {stderr}"
        );

        registry.join();
    }
}

// ============================================================================
// Feature: Resume workflow — edge cases
// ============================================================================

mod resume_with_no_state_file {
    use super::*;

    // Scenario: Resume when no state file exists fails gracefully
    //
    // Given: a workspace with "demo" and an empty state directory
    // When: I run "shipper resume"
    // Then: exit code is non-zero, error mentions missing state
    #[test]
    #[serial]
    fn given_empty_state_dir_when_resume_then_fails_with_missing_state() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        let state_dir = td.path().join(".shipper");
        fs::create_dir_all(&state_dir).expect("mkdir");

        let registry = spawn_registry(vec![200], 1);

        let mut cmd = shipper_cmd();
        fast_args(
            &mut cmd,
            &td.path().join("Cargo.toml"),
            &registry.base_url,
            &state_dir,
        );
        cmd.arg("resume").assert().failure();

        registry.join();
    }
}

mod resume_with_nonexistent_state_dir {
    use super::*;

    // Scenario: Resume when state directory does not exist fails gracefully
    //
    // Given: a workspace with "demo" and no .shipper directory at all
    // When: I run "shipper resume"
    // Then: exit code is non-zero
    #[test]
    #[serial]
    fn given_no_state_dir_when_resume_then_fails() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        let state_dir = td.path().join("nonexistent-state");

        let registry = spawn_registry(vec![200], 1);

        let mut cmd = shipper_cmd();
        fast_args(
            &mut cmd,
            &td.path().join("Cargo.toml"),
            &registry.base_url,
            &state_dir,
        );
        cmd.arg("resume").assert().failure();

        registry.join();
    }
}

// ============================================================================
// Feature: Doctor diagnostics — additional checks
// ============================================================================

mod doctor_reports_package_count {
    use super::*;

    // Scenario: Doctor reports workspace package information
    //
    // Given: a multi-crate workspace with core-lib, utils-lib, top-app
    // When: I run "shipper doctor"
    // Then: exit code is 0
    // And: output contains the diagnostics header
    // And: output contains workspace_root
    #[test]
    fn given_multi_crate_workspace_when_doctor_then_reports_workspace_info() {
        let td = tempdir().expect("tempdir");
        create_multi_crate_workspace(td.path());
        fs::create_dir_all(td.path().join("cargo-home")).expect("mkdir");

        let registry = spawn_doctor_registry(1);

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("doctor")
            .env("CARGO_HOME", td.path().join("cargo-home"))
            .env_remove("CARGO_REGISTRY_TOKEN")
            .env_remove("CARGO_REGISTRIES_CRATES_IO_TOKEN")
            .assert()
            .success()
            .stdout(contains("Shipper Doctor - Diagnostics Report"))
            .stdout(contains("workspace_root:"));

        registry.join();
    }
}

mod doctor_with_token_env_var {
    use super::*;

    // Scenario: Doctor detects token when CARGO_REGISTRY_TOKEN is set
    //
    // Given: a workspace with "demo" and CARGO_REGISTRY_TOKEN is set
    // When: I run "shipper doctor"
    // Then: exit code is 0
    // And: output contains "token (detected)" (not "NONE FOUND")
    #[test]
    fn given_token_set_when_doctor_then_reports_token_detected() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        fs::create_dir_all(td.path().join("cargo-home")).expect("mkdir");

        let registry = spawn_doctor_registry(1);

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("doctor")
            .env("CARGO_HOME", td.path().join("cargo-home"))
            .env("CARGO_REGISTRY_TOKEN", "test-token-value")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");
        assert!(
            stdout.contains("token (detected)"),
            "expected 'token (detected)' when token is set, got: {stdout}"
        );
        assert!(
            !stdout.contains("NONE FOUND"),
            "should not report NONE FOUND when token is set, got: {stdout}"
        );

        registry.join();
    }
}

// ============================================================================
// Feature: Clean workflow — additional scenarios
// ============================================================================

mod clean_only_state_files_not_lock {
    use super::*;

    // Scenario: Clean removes state/events/receipt but not other files in state dir
    //
    // Given: a workspace with state.json, events.jsonl, and a custom file "notes.txt"
    //        in the state directory
    // When: I run "shipper clean"
    // Then: exit code is 0
    // And: state.json and events.jsonl are removed
    // And: notes.txt still exists (clean only removes known state files)
    #[test]
    #[serial]
    fn given_extra_files_in_state_dir_when_clean_then_only_state_files_removed() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        let state_dir = td.path().join(".shipper");
        fs::create_dir_all(&state_dir).expect("mkdir");

        write_file(&state_dir.join("state.json"), r#"{"plan_id":"test"}"#);
        write_file(&state_dir.join("events.jsonl"), "{}\n");
        write_file(&state_dir.join("notes.txt"), "user notes\n");

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--state-dir")
            .arg(&state_dir)
            .arg("clean")
            .assert()
            .success()
            .stdout(contains("Clean complete"));

        assert!(
            !state_dir.join("state.json").exists(),
            "state.json should be removed"
        );
        assert!(
            !state_dir.join("events.jsonl").exists(),
            "events.jsonl should be removed"
        );
        // Custom files should be preserved
        assert!(
            state_dir.join("notes.txt").exists(),
            "notes.txt should be preserved — clean only removes known state files"
        );
    }
}

// ============================================================================
// Feature: Status reporting — additional scenarios
// ============================================================================

mod status_all_missing {
    use super::*;

    // Scenario: Status reports all crates as missing when none are published
    //
    // Given: a workspace with core-lib, utils-lib, top-app
    // And: registry returns 404 for all versions
    // When: I run "shipper status"
    // Then: exit code is 0
    // And: output contains "missing" for all three
    // And: output does NOT contain "published"
    #[test]
    fn given_all_unpublished_when_status_then_all_missing() {
        let td = tempdir().expect("tempdir");
        create_multi_crate_workspace(td.path());

        let registry = spawn_registry(vec![404, 404, 404], 3);

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("status")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");

        assert!(
            stdout.contains("missing"),
            "expected 'missing' in status output, got: {stdout}"
        );
        assert!(
            !stdout.contains("published"),
            "expected no 'published' when all crates are unpublished, got: {stdout}"
        );
    }
}

mod status_shows_plan_id {
    use super::*;

    // Scenario: Status output includes the plan_id
    //
    // Given: a workspace with "demo"
    // And: registry returns 404 (not published)
    // When: I run "shipper status"
    // Then: exit code is 0
    // And: output contains "plan_id:"
    #[test]
    fn given_workspace_when_status_then_shows_plan_id() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());

        let registry = spawn_registry(vec![404], 1);

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("status")
            .assert()
            .success()
            .stdout(contains("plan_id:"));

        registry.join();
    }
}

// ============================================================================
// Feature: Parallel publish configuration
// ============================================================================

mod parallel_plan_with_max_concurrent_flag {
    use super::*;

    // Scenario: Plan accepts --parallel and --max-concurrent flags
    //
    // Given: a workspace with core → {api, cli} → app
    // When: I run "shipper plan --parallel --max-concurrent 3"
    // Then: exit code is 0
    // And: output contains all four crates
    #[test]
    fn given_parallel_workspace_when_plan_with_max_concurrent_then_succeeds() {
        let td = tempdir().expect("tempdir");
        create_parallel_workspace(td.path());

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--parallel")
            .arg("--max-concurrent")
            .arg("3")
            .arg("plan")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");

        assert!(stdout.contains("core@0.1.0"), "missing core in plan");
        assert!(stdout.contains("api@0.1.0"), "missing api in plan");
        assert!(stdout.contains("cli@0.1.0"), "missing cli in plan");
        assert!(stdout.contains("app@0.1.0"), "missing app in plan");
    }
}

mod parallel_publish_with_config_file {
    use super::*;

    // Scenario: Parallel publish respects settings from .shipper.toml config
    //
    // Given: a workspace with independent crates alpha, beta, gamma
    // And: a .shipper.toml with [parallel] max_concurrent = 1
    // And: registry reports all as already published
    // When: I run "shipper publish --parallel"
    // Then: exit code is 0, all crates appear in receipt
    #[test]
    #[serial]
    fn given_parallel_config_when_publish_then_respects_settings() {
        let td = tempdir().expect("tempdir");
        create_independent_workspace(td.path());
        write_file(
            &td.path().join(".shipper.toml"),
            r#"
schema_version = "shipper.config.v1"

[parallel]
max_concurrent = 1
"#,
        );
        let (new_path, real_cargo, fake_cargo) = setup_fake_cargo(td.path());
        let state_dir = td.path().join(".shipper");

        let registry = spawn_registry(vec![200, 200, 200], 3);

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--config")
            .arg(td.path().join(".shipper.toml"))
            .arg("--api-base")
            .arg(&registry.base_url)
            .arg("--allow-dirty")
            .arg("--max-attempts")
            .arg("1")
            .arg("--state-dir")
            .arg(&state_dir)
            .arg("--parallel")
            .arg("publish")
            .env("PATH", &new_path)
            .env("REAL_CARGO", &real_cargo)
            .env("SHIPPER_CARGO_BIN", &fake_cargo)
            .env("SHIPPER_FAKE_PUBLISH_EXIT", "0")
            .assert()
            .success();

        let receipt: serde_json::Value = serde_json::from_str(
            &fs::read_to_string(state_dir.join("receipt.json")).expect("read receipt"),
        )
        .expect("parse receipt");
        let packages = receipt["packages"].as_array().expect("packages array");
        assert_eq!(packages.len(), 3, "receipt should have 3 packages");

        registry.join();
    }
}

// ============================================================================
// Feature: Inspect commands
// ============================================================================

mod inspect_events_without_events_file {
    use super::*;

    // Scenario: inspect-events with no events file shows empty log path
    //
    // Given: a workspace with "demo" and no events.jsonl in the state directory
    // When: I run "shipper inspect-events"
    // Then: exit code is 0 (empty event log is valid)
    // And: output contains "Event log:" header
    #[test]
    fn given_no_events_file_when_inspect_events_then_shows_empty_log() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        let state_dir = td.path().join(".shipper");
        fs::create_dir_all(&state_dir).expect("mkdir");

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--state-dir")
            .arg(&state_dir)
            .arg("inspect-events")
            .assert()
            .success()
            .stdout(contains("Event log:"));
    }
}

mod inspect_receipt_without_receipt_file {
    use super::*;

    // Scenario: inspect-receipt fails gracefully when no receipt file exists
    //
    // Given: a workspace with "demo" and no receipt.json in the state directory
    // When: I run "shipper inspect-receipt"
    // Then: exit code is non-zero
    #[test]
    fn given_no_receipt_file_when_inspect_receipt_then_fails() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());
        let state_dir = td.path().join(".shipper");
        fs::create_dir_all(&state_dir).expect("mkdir");

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--state-dir")
            .arg(&state_dir)
            .arg("inspect-receipt")
            .assert()
            .failure();
    }
}

// ============================================================================
// Feature: CI template generation — additional platforms
// ============================================================================

mod ci_gitlab_output {
    use super::*;

    // Scenario: CI gitlab template produces valid GitLab CI YAML
    //
    // Given: a valid workspace with "demo"
    // When: I run "shipper ci gitlab"
    // Then: exit code is 0
    // And: output contains "stage:" or "script:" (GitLab CI keywords)
    // And: output references shipper publish
    #[test]
    fn given_workspace_when_ci_gitlab_then_produces_valid_yaml() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("ci")
            .arg("gitlab")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");

        assert!(
            stdout.contains("script:") || stdout.contains("stage:"),
            "expected GitLab CI keywords, got: {stdout}"
        );
        assert!(
            stdout.contains("shipper publish"),
            "expected 'shipper publish' in GitLab CI template, got: {stdout}"
        );
    }
}

mod ci_circleci_output {
    use super::*;

    // Scenario: CI circleci template produces valid CircleCI YAML
    //
    // Given: a valid workspace with "demo"
    // When: I run "shipper ci circleci"
    // Then: exit code is 0
    // And: output references shipper publish
    #[test]
    fn given_workspace_when_ci_circleci_then_produces_valid_yaml() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("ci")
            .arg("circleci")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");

        assert!(
            stdout.contains("shipper publish"),
            "expected 'shipper publish' in CircleCI template, got: {stdout}"
        );
    }
}

// ============================================================================
// Feature: Config init workflow
// ============================================================================

mod config_init_creates_valid_file {
    use super::*;

    // Scenario: Config init creates a .shipper.toml that passes validation
    //
    // Given: an empty directory
    // When: I run "shipper config init -o <path>"
    // And: I run "shipper config validate -p <path>"
    // Then: both commands succeed
    // And: the generated file contains schema_version
    #[test]
    fn given_empty_dir_when_config_init_then_file_validates() {
        let td = tempdir().expect("tempdir");
        let config_path = td.path().join("test-config.toml");

        // When: init
        shipper_cmd()
            .arg("config")
            .arg("init")
            .arg("-o")
            .arg(&config_path)
            .assert()
            .success()
            .stdout(contains("Created configuration file"));

        assert!(config_path.exists(), "config file should be created");

        // And: validate
        shipper_cmd()
            .arg("config")
            .arg("validate")
            .arg("-p")
            .arg(&config_path)
            .assert()
            .success()
            .stdout(contains("valid"));

        // And: file contains schema_version
        let content = fs::read_to_string(&config_path).expect("read config");
        assert!(
            content.contains("schema_version"),
            "generated config should contain schema_version, got: {content}"
        );
    }
}

// ============================================================================
// Feature: Quiet mode
// ============================================================================

mod plan_quiet_mode {
    use super::*;

    // Scenario: Plan with --quiet suppresses informational output
    //
    // Given: a workspace with "demo"
    // When: I run "shipper plan --quiet"
    // Then: exit code is 0
    // And: stdout still contains the plan data
    #[test]
    fn given_workspace_when_plan_quiet_then_succeeds_with_minimal_output() {
        let td = tempdir().expect("tempdir");
        create_single_crate_workspace(td.path());

        shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--quiet")
            .arg("plan")
            .assert()
            .success()
            .stdout(contains("demo@0.1.0"));
    }
}

// ============================================================================
// Feature: JSON output format
// ============================================================================

mod plan_json_format {
    use super::*;

    // Scenario: Plan with --format json still succeeds (plan uses text output)
    //
    // Given: a workspace with core-lib, utils-lib, top-app
    // When: I run "shipper plan --format json"
    // Then: exit code is 0
    // And: stdout contains the plan data (plan always uses text format)
    #[test]
    fn given_multi_crate_when_plan_json_then_valid_json_output() {
        let td = tempdir().expect("tempdir");
        create_multi_crate_workspace(td.path());

        let output = shipper_cmd()
            .arg("--manifest-path")
            .arg(td.path().join("Cargo.toml"))
            .arg("--format")
            .arg("json")
            .arg("plan")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let stdout = String::from_utf8(output).expect("utf8");
        // Plan command outputs text format regardless of --format flag
        assert!(
            stdout.contains("core-lib@0.1.0"),
            "plan output should contain core-lib, got: {stdout}"
        );
        assert!(
            stdout.contains("Total packages to publish:"),
            "plan output should contain package count, got: {stdout}"
        );
    }
}