zccache-cli 1.4.5

Command-line interface for the zccache compiler cache
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
//! zccache CLI -- command-line interface for the compiler cache.
//!
//! Usage modes:
//!
//! 1. Subcommand mode:
//!    zccache session-start --compiler /path/to/clang++
//!    zccache session-end `<id>`
//!    zccache status
//!
//! 2. Compiler wrapper mode (auto-detected):
//!    ZCCACHE_SESSION_ID=42 zccache clang++ -c foo.cpp -o foo.o
//!
//!    If the first arg isn't a known subcommand, zccache treats
//!    the entire command line as a compiler invocation and forwards
//!    it to the daemon via the session from ZCCACHE_SESSION_ID.

#[cfg(unix)]
#[global_allocator]
static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;

#[cfg(windows)]
#[global_allocator]
static GLOBAL_WIN: mimalloc::MiMalloc = mimalloc::MiMalloc;

use clap::{Parser, Subcommand, ValueEnum};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use zccache_artifact::{
    restore_rust_plan_local, rust_plan_bundle_dir, rust_plan_cache_key, save_rust_plan_local,
    RustArtifactPlanV1, RustPlanError, RustPlanOperation, RustPlanSummary,
};
use zccache_cli::{
    client_download, run_ino_convert_cached, session_end_idempotent, ArchiveFormat, DownloadParams,
    DownloadSource, InoConvertOptions, WaitMode,
};
use zccache_compiler::strict_paths::StrictPathsMode;
use zccache_core::NormalizedPath;
use zccache_gha::{GhaCache, GhaError};

/// zccache -- fast local compiler cache.
#[derive(Debug, Parser)]
#[command(name = "zccache", version, about)]
struct Cli {
    /// Clear the entire artifact cache (same as `zccache clear`).
    #[arg(long)]
    clear: bool,

    /// Show daemon and cache statistics (same as `zccache status`).
    #[arg(long)]
    show_stats: bool,

    /// Validate compiler path flag spelling: off, consistent, or absolute.
    #[arg(
        long,
        value_name = "MODE",
        num_args = 0..=1,
        default_missing_value = "absolute",
        require_equals = true
    )]
    strict_paths: Option<String>,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Debug, Subcommand)]
enum Commands {
    /// Start the daemon (if not already running).
    Start,
    /// Stop the daemon.
    #[command(visible_alias = "kill")]
    Stop,
    /// Show daemon and cache status.
    Status,
    /// Clear the artifact cache.
    Clear,
    /// Start a build session. Prints session ID to stdout.
    #[command(name = "session-start")]
    SessionStart {
        /// Working directory (defaults to current dir).
        #[arg(long)]
        cwd: Option<String>,
        /// Path to a log file for this session.
        #[arg(long)]
        log: Option<String>,
        /// IPC endpoint (default: platform-specific).
        #[arg(long)]
        endpoint: Option<String>,
        /// Enable per-session hit/miss statistics tracking.
        #[arg(long)]
        stats: bool,
        /// Write a per-session JSONL compile journal to this path (must end in .jsonl).
        #[arg(long)]
        journal: Option<String>,
    },
    /// End a build session.
    #[command(name = "session-end")]
    SessionEnd {
        /// Session ID to end.
        session_id: String,
        /// IPC endpoint (default: platform-specific).
        #[arg(long)]
        endpoint: Option<String>,
    },
    /// Query stats for an active session (without ending it).
    #[command(name = "session-stats")]
    SessionStatsCmd {
        /// Session ID to query.
        session_id: String,
        /// IPC endpoint (default: platform-specific).
        #[arg(long)]
        endpoint: Option<String>,
    },
    /// Wrap a compiler invocation (explicit mode).
    Wrap {
        /// Validate compiler path flag spelling: off, consistent, or absolute.
        #[arg(
            long,
            value_name = "MODE",
            num_args = 0..=1,
            default_missing_value = "absolute",
            require_equals = true
        )]
        strict_paths: Option<String>,
        /// The compiler and its arguments.
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// Show detailed information about a cache entry.
    Inspect {
        /// Cache key (hex).
        key: String,
    },
    /// Show or clear crash dumps from previous daemon crashes.
    Crashes {
        /// Delete all crash dumps.
        #[arg(long)]
        clear: bool,
    },
    /// Fingerprint-based file change detection.
    ///
    /// Answers "have files changed since the last successful operation?" by
    /// querying the daemon's in-memory watch state (<1ms on cache hit).
    #[command(name = "fp")]
    Fp {
        /// Path to the cache file (e.g., .cache/lint.json).
        #[arg(long)]
        cache_file: String,

        /// Cache algorithm: hash or two-layer.
        #[arg(long, default_value = "two-layer")]
        cache_type: String,

        /// IPC endpoint (default: platform-specific).
        #[arg(long)]
        endpoint: Option<String>,

        #[command(subcommand)]
        fp_command: FpCommands,
    },
    /// Convert an Arduino `.ino` sketch into a generated `.ino.cpp`.
    #[command(name = "ino")]
    Ino {
        /// Input `.ino` file.
        #[arg(long)]
        input: String,
        /// Output `.ino.cpp` file.
        #[arg(long)]
        output: String,
        /// Extra clang arguments used when parsing the `.ino`.
        #[arg(long = "clang-arg")]
        clang_args: Vec<String>,
        /// Do not inject `#include <Arduino.h>`.
        #[arg(long)]
        no_arduino_include: bool,
    },
    /// GitHub Actions cache operations.
    #[command(name = "gha-cache")]
    GhaCache {
        #[command(subcommand)]
        action: GhaCacheCommands,
    },
    /// Execute versioned Rust artifact cache plans.
    #[command(name = "rust-plan")]
    RustPlan {
        #[command(subcommand)]
        action: RustPlanCommands,
    },
    /// Download and optionally unarchive an artifact using the dedicated download daemon.
    Download {
        /// Source URL for a normal single-file download.
        #[arg(long)]
        url: Option<String>,
        /// One explicit URL per multipart segment, in concatenation order.
        #[arg(long = "part-url")]
        part_urls: Vec<String>,
        /// Optional archive/cache path. If omitted, zccache chooses a deterministic cache path.
        archive_path: Option<String>,
        /// Optional destination to expand or unarchive into.
        #[arg(long = "unarchive")]
        unarchive_path: Option<String>,
        /// Optional expected SHA-256 of the downloaded artifact.
        #[arg(long = "sha256")]
        expected_sha256: Option<String>,
        /// Number of parallel range connections to use for single-URL downloads.
        #[arg(long)]
        max_connections: Option<usize>,
        /// Minimum segment size before single-URL downloads switch to ranged fetching.
        #[arg(long)]
        min_segment_size: Option<u64>,
        /// Return immediately with `locked` if another client owns the artifact lock.
        #[arg(long)]
        no_wait: bool,
        /// Report what would happen without mutating the filesystem.
        #[arg(long)]
        dry_run: bool,
        /// Force re-download and re-expand even if cached state is already valid.
        #[arg(long)]
        force: bool,
    },
    /// Manage cargo registry cache (save/restore/hash/clean).
    #[command(name = "cargo-registry")]
    CargoRegistry {
        #[command(subcommand)]
        action: CargoRegistryCommands,
    },
    /// Namespaced blake3-keyed key/value store.
    ///
    /// Backed by `~/.zccache/index.redb` (separate redb table) and spilled
    /// payloads under `~/.zccache/kv/<namespace>/<hex>.bin`. See issue #130.
    Kv {
        #[command(subcommand)]
        action: KvCommands,
    },
    /// Pre-populate target/ with cached artifacts for near-instant builds.
    Warm {
        /// Cargo target directory (default: ./target).
        #[arg(long, default_value = "target")]
        target_dir: String,
        /// Build profile (default: debug).
        #[arg(long, default_value = "debug")]
        profile: String,
        /// IPC endpoint (default: platform-specific).
        #[arg(long)]
        endpoint: Option<String>,
    },
    /// Sum byte size of regular files under a target directory, with optional
    /// pruning. Used by `action/cleanup/prepare-target-snapshot.sh` instead of
    /// Python `os.walk` because jwalk parallelizes readdir+stat across cores —
    /// big win on Windows where per-file Defender callbacks dominate the walk.
    /// Prints total bytes as a decimal integer on stdout. See zccache#189.
    #[command(name = "snapshot-bytes")]
    SnapshotBytes {
        /// Directory to walk.
        #[arg(long)]
        target: PathBuf,
        /// Skip `incremental/` directories during the walk.
        #[arg(long)]
        prune_incremental: bool,
        /// Skip `*/build/*/out/` directories during the walk.
        #[arg(long)]
        prune_build_script_out: bool,
    },
}

#[derive(Debug, Subcommand)]
enum CargoRegistryCommands {
    /// Save cargo registry to a compressed archive.
    Save {
        /// Cache key (used as filename).
        #[arg(long)]
        key: String,
        /// Cargo home directory (default: ~/.cargo or $CARGO_HOME).
        #[arg(long)]
        cargo_home: Option<String>,
    },
    /// Restore cargo registry from a compressed archive.
    Restore {
        /// Cache key to restore.
        #[arg(long)]
        key: String,
        /// Cargo home directory (default: ~/.cargo or $CARGO_HOME).
        #[arg(long)]
        cargo_home: Option<String>,
    },
    /// Print hash of Cargo.lock for use as cache key.
    Hash {
        /// Path to Cargo.lock (default: ./Cargo.lock).
        #[arg(long, default_value = "Cargo.lock")]
        lockfile: String,
    },
    /// Remove cached registry archives.
    Clean,
}

/// `zccache kv` subcommands.
#[derive(Debug, Subcommand)]
enum KvCommands {
    /// Read a value to stdout. Exit 2 if missing.
    Get {
        /// Namespace (`[a-z0-9-]{1,64}`).
        namespace: String,
        /// 64-char hex key.
        hex_key: String,
    },
    /// Write a value. Source is either `--value-from <file>` or stdin.
    Put {
        /// Namespace (`[a-z0-9-]{1,64}`).
        namespace: String,
        /// 64-char hex key.
        hex_key: String,
        /// Read value bytes from this file.
        #[arg(long, conflicts_with = "value_from_stdin")]
        value_from: Option<String>,
        /// Read value bytes from stdin.
        #[arg(long, conflicts_with = "value_from")]
        value_from_stdin: bool,
    },
    /// Remove an entry. Idempotent — missing keys exit 0.
    Rm {
        /// Namespace.
        namespace: String,
        /// 64-char hex key.
        hex_key: String,
    },
    /// List entries under a namespace, sorted by hex key. One row per entry:
    /// `<hex>  <bytes>`.
    Ls {
        /// Namespace.
        namespace: String,
    },
    /// Drop every entry under a namespace.
    Clear {
        /// Namespace.
        namespace: String,
    },
    /// Print total bytes and per-namespace bytes.
    Stats,
}

/// Fingerprint subcommands.
#[derive(Debug, Subcommand)]
enum FpCommands {
    /// Check if files have changed since last success.
    ///
    /// Exit 0 = operation should run (files changed).
    /// Exit 1 = skip (no changes detected).
    Check {
        /// Root directory to scan (default: current directory).
        #[arg(long, default_value = ".")]
        root: String,

        /// File extensions to include (without dot, e.g., "rs", "cpp").
        /// Cannot be used with --include.
        #[arg(long, conflicts_with = "include")]
        ext: Vec<String>,

        /// Glob patterns for files to include (e.g., "**/*.rs").
        /// Cannot be used with --ext.
        #[arg(long, conflicts_with = "ext")]
        include: Vec<String>,

        /// Patterns or directory names to exclude.
        #[arg(long)]
        exclude: Vec<String>,
    },
    /// Mark the previous check as successful.
    #[command(name = "mark-success")]
    MarkSuccess,
    /// Mark the previous check as failed.
    #[command(name = "mark-failure")]
    MarkFailure,
    /// Invalidate the cache (delete all state).
    Invalidate,
}

/// GitHub Actions cache subcommands.
#[derive(Debug, Subcommand)]
enum GhaCacheCommands {
    /// Check if GHA cache API is available (env vars set).
    Status,
    /// Save a directory to the GHA cache (tar+gzip, then upload).
    Save {
        /// Cache key (must be unique per content).
        #[arg(long)]
        key: String,
        /// Path to the directory to cache.
        #[arg(long)]
        path: String,
    },
    /// Restore a directory from the GHA cache.
    Restore {
        /// Cache key to look up.
        #[arg(long)]
        key: String,
        /// Path to restore the directory into.
        #[arg(long)]
        path: String,
    },
}

/// Rust artifact plan subcommands.
#[derive(Debug, Subcommand)]
enum RustPlanCommands {
    /// Validate a soldr-generated Rust artifact plan.
    Validate {
        /// Path to the plan JSON file.
        #[arg(long)]
        plan: String,
        /// Print a machine-readable JSON summary.
        #[arg(long)]
        json: bool,
        /// Active zccache session ID whose compile-cache stats should be included.
        #[arg(long = "session-id")]
        session_id: Option<String>,
        /// IPC endpoint for session stats lookup.
        #[arg(long)]
        endpoint: Option<String>,
        /// Journal/log path to report in the summary, overriding the plan path.
        #[arg(long)]
        journal: Option<String>,
        /// Local cache directory for bundle path/key reporting.
        #[arg(long = "cache-dir")]
        cache_dir: Option<String>,
    },
    /// Restore Rust target artifacts from a saved plan bundle.
    Restore {
        /// Path to the plan JSON file.
        #[arg(long)]
        plan: String,
        /// Print a machine-readable JSON summary.
        #[arg(long)]
        json: bool,
        /// Active zccache session ID whose compile-cache stats should be included.
        #[arg(long = "session-id")]
        session_id: Option<String>,
        /// IPC endpoint for session stats lookup.
        #[arg(long)]
        endpoint: Option<String>,
        /// Journal/log path to report in the summary, overriding the plan path.
        #[arg(long)]
        journal: Option<String>,
        /// Cache backend to use.
        #[arg(long, default_value = "auto")]
        backend: RustPlanBackendArg,
        /// Local cache directory used for bundle storage.
        #[arg(long = "cache-dir")]
        cache_dir: Option<String>,
    },
    /// Save Rust target artifacts selected by a plan.
    Save {
        /// Path to the plan JSON file.
        #[arg(long)]
        plan: String,
        /// Print a machine-readable JSON summary.
        #[arg(long)]
        json: bool,
        /// Active zccache session ID whose compile-cache stats should be included.
        #[arg(long = "session-id")]
        session_id: Option<String>,
        /// IPC endpoint for session stats lookup.
        #[arg(long)]
        endpoint: Option<String>,
        /// Journal/log path to report in the summary, overriding the plan path.
        #[arg(long)]
        journal: Option<String>,
        /// Cache backend to use.
        #[arg(long, default_value = "auto")]
        backend: RustPlanBackendArg,
        /// Local cache directory used for bundle storage.
        #[arg(long = "cache-dir")]
        cache_dir: Option<String>,
    },
}

/// Rust artifact plan backend selection.
#[derive(Debug, Clone, Copy, ValueEnum)]
enum RustPlanBackendArg {
    Auto,
    Local,
    Gha,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RustPlanRuntimeErrorKind {
    Unavailable,
    Failure,
}

#[derive(Debug)]
enum RustPlanRuntimeError {
    Backend {
        backend: RustPlanBackendArg,
        kind: RustPlanRuntimeErrorKind,
        message: String,
    },
}

impl RustPlanRuntimeError {
    fn backend(&self) -> RustPlanBackendArg {
        match self {
            Self::Backend { backend, .. } => *backend,
        }
    }

    fn kind(&self) -> RustPlanRuntimeErrorKind {
        match self {
            Self::Backend { kind, .. } => *kind,
        }
    }

    fn message(&self) -> &str {
        match self {
            Self::Backend { message, .. } => message,
        }
    }

    fn with_kind(self, kind: RustPlanRuntimeErrorKind) -> Self {
        match self {
            Self::Backend {
                backend, message, ..
            } => Self::Backend {
                backend,
                kind,
                message,
            },
        }
    }
}

/// Known subcommand names for auto-detect.
const KNOWN_SUBCOMMANDS: &[&str] = &[
    "start",
    "stop",
    "status",
    "clear",
    "wrap",
    "inspect",
    "session-start",
    "session-end",
    "session-stats",
    "crashes",
    "fp",
    "ino",
    "download",
    "cargo-registry",
    "gha-cache",
    "rust-plan",
    "warm",
    "help",
    "--help",
    "-h",
    "--version",
    "-V",
];

fn absolute_path(path: &str) -> NormalizedPath {
    let path = Path::new(path);
    if path.is_absolute() {
        path.into()
    } else {
        std::env::current_dir()
            .unwrap_or_default()
            .join(path)
            .into()
    }
}

/// Convert an i32 exit code to ExitCode without silent truncation.
/// A bare `exit_code as u8` wraps: 256 → 0 (success), masking failures.
/// This preserves success/failure semantics: non-zero stays non-zero.
fn exit_code_from_i32(code: i32) -> ExitCode {
    let truncated = (code & 0xFF) as u8;
    if code != 0 && truncated == 0 {
        ExitCode::from(1)
    } else {
        ExitCode::from(truncated)
    }
}

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().collect();

    // Auto-detect: if first arg isn't a known subcommand or a --flag, enter wrap mode.
    // e.g., `zccache clang++ -c foo.cpp -o foo.o`
    match strip_leading_strict_paths_flags(&args[1..]) {
        Ok((strict_paths, wrapper_args))
            if !wrapper_args.is_empty()
                && !KNOWN_SUBCOMMANDS.contains(&wrapper_args[0].as_str())
                && !wrapper_args[0].starts_with("--") =>
        {
            return run_wrap(&wrapper_args, strict_paths);
        }
        Err(err) => {
            eprintln!("zccache: {err}");
            return ExitCode::FAILURE;
        }
        _ => {}
    }

    let cli = Cli::parse();
    let global_strict_paths = cli.strict_paths.clone();

    init_tracing();

    // Handle top-level flags (sccache-compatible)
    if cli.clear {
        let endpoint = resolve_endpoint(None);
        return run_async(cmd_clear(&endpoint));
    }
    if cli.show_stats {
        let endpoint = resolve_endpoint(None);
        return run_async(cmd_status(&endpoint));
    }

    let command = match cli.command {
        Some(cmd) => cmd,
        None => {
            // No subcommand and no flag — show help.
            use clap::CommandFactory;
            Cli::command().print_help().ok();
            return ExitCode::FAILURE;
        }
    };

    match command {
        Commands::Start => {
            let endpoint = resolve_endpoint(None);
            run_async(cmd_start(&endpoint))
        }
        Commands::Stop => {
            let endpoint = resolve_endpoint(None);
            run_async(cmd_stop(&endpoint))
        }
        Commands::Status => {
            let endpoint = resolve_endpoint(None);
            run_async(cmd_status(&endpoint))
        }
        Commands::Clear => {
            let endpoint = resolve_endpoint(None);
            run_async(cmd_clear(&endpoint))
        }
        Commands::Ino {
            input,
            output,
            clang_args,
            no_arduino_include,
        } => match run_ino_convert_cached(
            Path::new(&input),
            Path::new(&output),
            &InoConvertOptions {
                clang_args,
                inject_arduino_include: !no_arduino_include,
            },
        ) {
            Ok(_) => ExitCode::SUCCESS,
            Err(err) => {
                eprintln!("zccache: {err}");
                ExitCode::FAILURE
            }
        },
        Commands::GhaCache { action } => match action {
            GhaCacheCommands::Status => cmd_gha_status(),
            GhaCacheCommands::Save { key, path } => run_async(cmd_gha_save(&key, &path)),
            GhaCacheCommands::Restore { key, path } => run_async(cmd_gha_restore(&key, &path)),
        },
        Commands::RustPlan { action } => run_async(cmd_rust_plan(action)),
        Commands::Download {
            url,
            part_urls,
            archive_path,
            unarchive_path,
            expected_sha256,
            max_connections,
            min_segment_size,
            no_wait,
            dry_run,
            force,
        } => cmd_download(DownloadParams {
            source: match resolve_download_source(url, part_urls) {
                Ok(source) => source,
                Err(err) => {
                    eprintln!("zccache download: {err}");
                    return ExitCode::FAILURE;
                }
            },
            archive_path: archive_path.map(Into::into),
            unarchive_path: unarchive_path.map(Into::into),
            expected_sha256,
            archive_format: ArchiveFormat::Auto,
            max_connections,
            min_segment_size,
            wait_mode: if no_wait {
                WaitMode::NoWait
            } else {
                WaitMode::Block
            },
            dry_run,
            force,
        }),
        Commands::SessionStart {
            cwd,
            log,
            endpoint,
            stats,
            journal,
        } => {
            let endpoint = resolve_endpoint(endpoint.as_deref());
            let cwd = cwd
                .map(NormalizedPath::from)
                .unwrap_or_else(|| std::env::current_dir().unwrap_or_default().into());
            let log = log.map(|p| absolute_path(&p));
            let journal = journal.map(|p| {
                if !p.ends_with(".jsonl") {
                    eprintln!("error: --journal path must end in .jsonl");
                    std::process::exit(1);
                }
                absolute_path(&p)
            });
            run_async(cmd_session_start(
                &endpoint,
                cwd.as_path(),
                log.as_deref(),
                stats,
                journal,
            ))
        }
        Commands::SessionEnd {
            session_id,
            endpoint,
        } => {
            let endpoint = resolve_endpoint(endpoint.as_deref());
            cmd_session_end(&endpoint, session_id)
        }
        Commands::SessionStatsCmd {
            session_id,
            endpoint,
        } => {
            let endpoint = resolve_endpoint(endpoint.as_deref());
            run_async(cmd_session_stats(&endpoint, session_id))
        }
        Commands::Wrap { strict_paths, args } => {
            let strict_paths = match parse_optional_strict_paths(
                strict_paths.as_deref().or(global_strict_paths.as_deref()),
            ) {
                Ok(mode) => mode,
                Err(err) => {
                    eprintln!("zccache: {err}");
                    return ExitCode::FAILURE;
                }
            };
            run_wrap(&args, strict_paths)
        }
        Commands::Inspect { key } => {
            eprintln!("zccache inspect {key}: not yet implemented");
            ExitCode::FAILURE
        }
        Commands::Crashes { clear } => cmd_crashes(clear),
        Commands::Fp {
            cache_file,
            cache_type,
            endpoint,
            fp_command,
        } => {
            let endpoint = resolve_endpoint(endpoint.as_deref());
            let cache_file = absolute_path(&cache_file);
            match fp_command {
                FpCommands::Check {
                    root,
                    ext,
                    include,
                    exclude,
                } => {
                    let root = absolute_path(&root);
                    run_async(cmd_fp_check(
                        &endpoint,
                        cache_file.as_path(),
                        &cache_type,
                        root.as_path(),
                        &ext,
                        &include,
                        &exclude,
                    ))
                }
                FpCommands::MarkSuccess => {
                    run_async(cmd_fp_mark(&endpoint, cache_file.as_path(), true))
                }
                FpCommands::MarkFailure => {
                    run_async(cmd_fp_mark(&endpoint, cache_file.as_path(), false))
                }
                FpCommands::Invalidate => {
                    run_async(cmd_fp_invalidate(&endpoint, cache_file.as_path()))
                }
            }
        }
        Commands::CargoRegistry { action } => match action {
            CargoRegistryCommands::Save { key, cargo_home } => {
                cmd_cargo_registry_save(&key, cargo_home.as_deref())
            }
            CargoRegistryCommands::Restore { key, cargo_home } => {
                cmd_cargo_registry_restore(&key, cargo_home.as_deref())
            }
            CargoRegistryCommands::Hash { lockfile } => cmd_cargo_registry_hash(&lockfile),
            CargoRegistryCommands::Clean => cmd_cargo_registry_clean(),
        },
        Commands::Kv { action } => cmd_kv(action),
        Commands::Warm {
            target_dir,
            profile,
            ..
        } => {
            let target_dir = absolute_path(&target_dir);
            cmd_warm(&target_dir, &profile)
        }
        Commands::SnapshotBytes {
            target,
            prune_incremental,
            prune_build_script_out,
        } => cmd_snapshot_bytes(&target, prune_incremental, prune_build_script_out),
    }
}

// ─── Subcommand implementations ────────────────────────────────────────────

fn cmd_download(params: DownloadParams) -> ExitCode {
    match client_download(None, params) {
        Ok(result) => {
            println!("status={:?}", result.status);
            println!("archive_path={}", result.cache_path.display());
            println!("sha256={}", result.sha256);
            if let Some(unarchive_path) = &result.expanded_path {
                println!("unarchive_path={}", unarchive_path.display());
            }
            if let Some(bytes) = result.bytes {
                println!("bytes={bytes}");
            }
            ExitCode::SUCCESS
        }
        Err(err) => {
            eprintln!("zccache download: {err}");
            ExitCode::FAILURE
        }
    }
}

fn resolve_download_source(
    url: Option<String>,
    part_urls: Vec<String>,
) -> Result<DownloadSource, String> {
    match (url, part_urls.is_empty()) {
        (Some(url), true) => Ok(DownloadSource::Url(url)),
        (None, false) => Ok(DownloadSource::MultipartUrls(part_urls)),
        (Some(_), false) => Err("use either --url or --part-url, not both".to_string()),
        (None, true) => Err("provide either --url or at least one --part-url".to_string()),
    }
}

async fn cmd_start(endpoint: &str) -> ExitCode {
    match ensure_daemon(endpoint).await {
        Ok(()) => {
            eprintln!("daemon running at {endpoint}");
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("failed to start daemon: {e}");
            ExitCode::FAILURE
        }
    }
}

async fn cmd_stop(endpoint: &str) -> ExitCode {
    let mut conn = match connect(endpoint).await {
        Ok(c) => c,
        Err(_) => {
            let Some(pid) = zccache_ipc::check_running_daemon() else {
                eprintln!("daemon not running at {endpoint}");
                // No daemon — but the index file might still be there from a
                // crashed prior run. Probe once so callers (CI tar) can rely
                // on the lock being gone after `zccache stop` returns.
                wait_for_redb_release(endpoint).await;
                return ExitCode::SUCCESS;
            };

            match zccache_ipc::force_kill_process(pid) {
                Ok(()) => {
                    for _ in 0..50 {
                        if !zccache_ipc::is_process_alive(pid) {
                            zccache_ipc::remove_lock_file();
                            eprintln!(
                                "daemon process {pid} terminated after IPC connection failed"
                            );
                            wait_for_redb_release(endpoint).await;
                            return ExitCode::SUCCESS;
                        }
                        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
                    }
                    eprintln!(
                        "zccache: sent termination to daemon process {pid}, but it did not exit"
                    );
                    return ExitCode::FAILURE;
                }
                Err(e) => {
                    eprintln!(
                        "zccache: cannot connect to daemon at {endpoint}, and failed to kill \
                         locked process {pid}: {e}"
                    );
                    return ExitCode::FAILURE;
                }
            }
        }
    };

    if let Err(e) = conn.send(&zccache_protocol::Request::Shutdown).await {
        eprintln!("zccache: failed to send to daemon: {e}");
        return ExitCode::FAILURE;
    }
    let recv_result = match conn.recv().await {
        Ok(r) => r,
        Err(e) => {
            eprintln!("zccache: broken connection to daemon: {e}");
            return ExitCode::FAILURE;
        }
    };
    match recv_result {
        Some(zccache_protocol::Response::ShuttingDown) => {
            // The daemon acknowledges `Shutdown` immediately and continues
            // teardown asynchronously. On Windows the redb index lock is held
            // until the daemon process actually exits and `Drop` fires. Wait
            // for the IPC endpoint to drop and for `index.redb` to be
            // openable (i.e. no exclusive share lock) so callers like the CI
            // post-step tar do not race the daemon. See issue #182.
            wait_for_redb_release(endpoint).await;
            eprintln!("daemon stopped");
            ExitCode::SUCCESS
        }
        None => {
            eprintln!("zccache: lost connection to daemon (no response received)");
            ExitCode::FAILURE
        }
        Some(other) => {
            eprintln!("zccache: unexpected response from daemon: {other:?}");
            ExitCode::FAILURE
        }
    }
}

/// Default cap on how long `zccache stop` will wait after the daemon ACKs
/// `Shutdown` for the IPC endpoint to disappear and `index.redb` to become
/// openable. Overridable with `ZCCACHE_STOP_TIMEOUT_SECS`.
const STOP_WAIT_DEFAULT_SECS: u64 = 10;
/// Poll cadence inside the bounded wait loop.
const STOP_WAIT_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(100);

/// Returns the bounded total wait duration for `zccache stop`, honoring
/// `ZCCACHE_STOP_TIMEOUT_SECS` if it parses as a non-negative `u64`.
fn stop_wait_timeout() -> std::time::Duration {
    let secs = std::env::var("ZCCACHE_STOP_TIMEOUT_SECS")
        .ok()
        .and_then(|s| s.trim().parse::<u64>().ok())
        .unwrap_or(STOP_WAIT_DEFAULT_SECS);
    std::time::Duration::from_secs(secs)
}

/// Poll until both the IPC endpoint is unreachable and `index.redb` can be
/// opened (or does not exist). Emits a warning on timeout but never fails the
/// caller — the worst case is that the caller (e.g. CI cache tar) sees the
/// same error it would have seen without this wait.
async fn wait_for_redb_release(endpoint: &str) {
    let index_path = zccache_core::config::index_path();
    let deadline = std::time::Instant::now() + stop_wait_timeout();
    loop {
        let endpoint_gone = !is_ipc_endpoint_reachable(endpoint).await;
        let index_free = is_index_openable(index_path.as_path());
        if endpoint_gone && index_free {
            return;
        }
        if std::time::Instant::now() >= deadline {
            eprintln!(
                "zccache: timed out waiting for daemon teardown after stop \
                 (endpoint_gone={endpoint_gone}, index_free={index_free}); \
                 continuing anyway. set ZCCACHE_STOP_TIMEOUT_SECS to override."
            );
            return;
        }
        tokio::time::sleep(STOP_WAIT_POLL_INTERVAL).await;
    }
}

/// True if a fresh `connect()` to the daemon IPC endpoint succeeds.
async fn is_ipc_endpoint_reachable(endpoint: &str) -> bool {
    connect(endpoint).await.is_ok()
}

/// True if `index.redb` is either absent or openable for read. On Windows,
/// redb opens the index with exclusive share mode; any other handle opening
/// it returns `ERROR_SHARING_VIOLATION` (raw OS error 32, surfaced as
/// `ErrorKind::PermissionDenied` in current stable). On Unix this almost
/// always succeeds, which is also "lock released".
fn is_index_openable(path: &std::path::Path) -> bool {
    match std::fs::OpenOptions::new().read(true).open(path) {
        Ok(_) => true,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => true,
        Err(err) => {
            // ERROR_SHARING_VIOLATION (32) is the case we want to keep
            // polling on. Anything else (PermissionDenied for ACL reasons,
            // etc.) we also treat as "not ready" so we don't falsely report
            // success while the daemon still holds the file.
            if err.raw_os_error() == Some(32) || err.kind() == std::io::ErrorKind::PermissionDenied
            {
                return false;
            }
            // Any other unexpected error: treat as "ready" so we don't spin
            // forever on a fundamentally broken cache dir.
            true
        }
    }
}

async fn cmd_status(endpoint: &str) -> ExitCode {
    let mut conn = match connect(endpoint).await {
        Ok(c) => c,
        Err(e) => {
            eprintln!("daemon not running at {endpoint}: {e}");
            return ExitCode::FAILURE;
        }
    };

    if let Err(e) = conn.send(&zccache_protocol::Request::Status).await {
        eprintln!("zccache: failed to send to daemon: {e}");
        return ExitCode::FAILURE;
    }
    let recv_result = match conn.recv().await {
        Ok(r) => r,
        Err(e) => {
            eprintln!("zccache: broken connection to daemon: {e}");
            return ExitCode::FAILURE;
        }
    };
    match recv_result {
        Some(zccache_protocol::Response::Status(s)) => {
            let total = s.cache_hits + s.cache_misses;
            let hit_rate = if total > 0 {
                format!("{:.1}%", s.cache_hits as f64 / total as f64 * 100.0)
            } else {
                "n/a".to_string()
            };

            println!(
                "zccache daemon v{} (protocol v{}) ({}) — uptime {}",
                if s.version.is_empty() {
                    "unknown"
                } else {
                    &s.version
                },
                zccache_protocol::PROTOCOL_VERSION,
                endpoint,
                format_uptime(s.uptime_secs)
            );
            if !s.cache_dir.as_os_str().is_empty() {
                println!("cache dir: {}", s.cache_dir.display());
            }
            println!();
            println!(
                "  Compilations:  {} total ({} cached, {} cold, {} non-cacheable)",
                s.total_compilations, s.cache_hits, s.cache_misses, s.non_cacheable
            );
            println!("  Hit rate:      {hit_rate}");
            if s.time_saved_ms > 0 {
                println!("  Time saved:    ~{}", format_duration_ms(s.time_saved_ms));
            }
            if s.compile_errors > 0 {
                println!("  Errors:        {}", s.compile_errors);
            }
            println!();
            println!(
                "  Artifacts:     {} ({})",
                s.artifact_count,
                format_bytes(s.cache_size_bytes)
            );
            {
                let disk_info = if s.dep_graph_disk_size > 0 {
                    format!(
                        "v{}, {} on disk",
                        s.dep_graph_version,
                        format_bytes(s.dep_graph_disk_size)
                    )
                } else {
                    format!("v{}, not persisted", s.dep_graph_version)
                };
                println!(
                    "  Dep graph:     {} contexts, {} files ({})",
                    s.dep_graph_contexts, s.dep_graph_files, disk_info
                );
            }
            println!("  Metadata:      {} entries", s.metadata_entries);
            println!();
            if s.total_links > 0 {
                println!();
                let link_total = s.link_hits + s.link_misses;
                let link_hit_rate = if link_total > 0 {
                    format!("{:.1}%", s.link_hits as f64 / link_total as f64 * 100.0)
                } else {
                    "n/a".to_string()
                };
                println!(
                    "  Links:         {} total ({} cached, {} cold, {} non-cacheable)",
                    s.total_links, s.link_hits, s.link_misses, s.link_non_cacheable
                );
                println!("  Link hit rate: {link_hit_rate}");
            }
            println!();
            println!(
                "  Sessions:      {} active / {} total",
                s.sessions_active, s.sessions_total
            );
            ExitCode::SUCCESS
        }
        None => {
            eprintln!("zccache: lost connection to daemon (no response received)");
            ExitCode::FAILURE
        }
        Some(other) => {
            eprintln!("zccache: unexpected response from daemon: {other:?}");
            ExitCode::FAILURE
        }
    }
}

async fn cmd_clear(endpoint: &str) -> ExitCode {
    let mut conn = match connect(endpoint).await {
        Ok(c) => c,
        Err(_) => {
            eprintln!("daemon not running at {endpoint} — nothing to clear");
            return ExitCode::SUCCESS;
        }
    };

    if let Err(e) = conn.send(&zccache_protocol::Request::Clear).await {
        eprintln!("zccache: failed to send to daemon: {e}");
        return ExitCode::FAILURE;
    }
    let recv_result = match conn.recv().await {
        Ok(r) => r,
        Err(e) => {
            eprintln!("zccache: broken connection to daemon: {e}");
            return ExitCode::FAILURE;
        }
    };
    match recv_result {
        Some(zccache_protocol::Response::Cleared {
            artifacts_removed,
            metadata_cleared,
            dep_graph_contexts_cleared,
            on_disk_bytes_freed,
        }) => {
            println!("Cache cleared:");
            println!("  Artifacts removed:  {artifacts_removed}");
            println!("  Metadata cleared:   {metadata_cleared}");
            println!("  Dep graph contexts: {dep_graph_contexts_cleared}");
            if on_disk_bytes_freed > 0 {
                println!(
                    "  Disk freed:         {}",
                    format_bytes(on_disk_bytes_freed)
                );
            }
            ExitCode::SUCCESS
        }
        None => {
            eprintln!("zccache: lost connection to daemon (no response received)");
            ExitCode::FAILURE
        }
        Some(other) => {
            eprintln!("zccache: unexpected response from daemon: {other:?}");
            ExitCode::FAILURE
        }
    }
}

fn cmd_kv(action: KvCommands) -> ExitCode {
    use std::io::{Read, Write};
    use zccache_artifact::{Key, KvError, KvStore};

    fn open_store() -> Result<KvStore, ExitCode> {
        match KvStore::open_default() {
            Ok(s) => Ok(s),
            Err(e) => {
                eprintln!("zccache kv: open: {e}");
                Err(ExitCode::FAILURE)
            }
        }
    }

    fn parse_key(hex: &str) -> Result<Key, ExitCode> {
        Key::from_hex(hex).map_err(|e| {
            eprintln!("zccache kv: bad key: {e}");
            ExitCode::FAILURE
        })
    }

    match action {
        KvCommands::Get { namespace, hex_key } => {
            let store = match open_store() {
                Ok(s) => s,
                Err(c) => return c,
            };
            let key = match parse_key(&hex_key) {
                Ok(k) => k,
                Err(c) => return c,
            };
            match store.get(&namespace, &key) {
                Ok(Some(bytes)) => {
                    let stdout = std::io::stdout();
                    let mut handle = stdout.lock();
                    if let Err(e) = handle.write_all(&bytes) {
                        eprintln!("zccache kv get: write stdout: {e}");
                        return ExitCode::FAILURE;
                    }
                    ExitCode::SUCCESS
                }
                Ok(None) => ExitCode::from(2),
                Err(e) => {
                    eprintln!("zccache kv get: {e}");
                    ExitCode::FAILURE
                }
            }
        }
        KvCommands::Put {
            namespace,
            hex_key,
            value_from,
            value_from_stdin,
        } => {
            let store = match open_store() {
                Ok(s) => s,
                Err(c) => return c,
            };
            let key = match parse_key(&hex_key) {
                Ok(k) => k,
                Err(c) => return c,
            };
            let bytes = if let Some(path) = value_from {
                match std::fs::read(&path) {
                    Ok(b) => b,
                    Err(e) => {
                        eprintln!("zccache kv put: read {path}: {e}");
                        return ExitCode::FAILURE;
                    }
                }
            } else if value_from_stdin {
                let mut buf = Vec::new();
                if let Err(e) = std::io::stdin().read_to_end(&mut buf) {
                    eprintln!("zccache kv put: read stdin: {e}");
                    return ExitCode::FAILURE;
                }
                buf
            } else {
                eprintln!("zccache kv put: must specify --value-from <file> or --value-from-stdin");
                return ExitCode::FAILURE;
            };
            match store.put(&namespace, &key, &bytes) {
                Ok(_) => ExitCode::SUCCESS,
                Err(KvError::TooLarge(n, m)) => {
                    eprintln!("zccache kv put: value too large: {n} bytes (max {m})");
                    ExitCode::FAILURE
                }
                Err(e) => {
                    eprintln!("zccache kv put: {e}");
                    ExitCode::FAILURE
                }
            }
        }
        KvCommands::Rm { namespace, hex_key } => {
            let store = match open_store() {
                Ok(s) => s,
                Err(c) => return c,
            };
            let key = match parse_key(&hex_key) {
                Ok(k) => k,
                Err(c) => return c,
            };
            match store.remove(&namespace, &key) {
                Ok(()) => ExitCode::SUCCESS,
                Err(e) => {
                    eprintln!("zccache kv rm: {e}");
                    ExitCode::FAILURE
                }
            }
        }
        KvCommands::Ls { namespace } => {
            let store = match open_store() {
                Ok(s) => s,
                Err(c) => return c,
            };
            match store.list_namespace(&namespace) {
                Ok(entries) => {
                    for (k, len) in entries {
                        println!("{}  {}", k.to_hex(), len);
                    }
                    ExitCode::SUCCESS
                }
                Err(e) => {
                    eprintln!("zccache kv ls: {e}");
                    ExitCode::FAILURE
                }
            }
        }
        KvCommands::Clear { namespace } => {
            let store = match open_store() {
                Ok(s) => s,
                Err(c) => return c,
            };
            match store.clear_namespace(&namespace) {
                Ok(()) => ExitCode::SUCCESS,
                Err(e) => {
                    eprintln!("zccache kv clear: {e}");
                    ExitCode::FAILURE
                }
            }
        }
        KvCommands::Stats => {
            let store = match open_store() {
                Ok(s) => s,
                Err(c) => return c,
            };
            let total = match store.total_bytes() {
                Ok(n) => n,
                Err(e) => {
                    eprintln!("zccache kv stats: {e}");
                    return ExitCode::FAILURE;
                }
            };
            let by_ns = match store.stats() {
                Ok(v) => v,
                Err(e) => {
                    eprintln!("zccache kv stats: {e}");
                    return ExitCode::FAILURE;
                }
            };
            println!("total_bytes  {total}");
            for (ns, bytes) in by_ns {
                println!("{ns}  {bytes}");
            }
            ExitCode::SUCCESS
        }
    }
}

fn cmd_warm(target_dir: &Path, profile: &str) -> ExitCode {
    let cache_dir = zccache_core::config::default_cache_dir();
    let index_path = cache_dir.join("index.redb");
    let artifact_dir = cache_dir.join("artifacts");
    // Look for Cargo.lock in cwd or next to target_dir
    let lockfile = {
        let cwd = Path::new("Cargo.lock");
        let parent = target_dir.parent().map(|p| p.join("Cargo.lock"));
        if cwd.exists() {
            Some(cwd.to_path_buf())
        } else if let Some(ref p) = parent {
            if p.exists() {
                Some(p.clone())
            } else {
                None
            }
        } else {
            None
        }
    };
    match warm_target(
        index_path.as_ref(),
        artifact_dir.as_ref(),
        target_dir,
        profile,
        lockfile.as_deref(),
    ) {
        Ok((restored, skipped, errors)) => {
            println!("zccache warm: restored {restored} files, skipped {skipped}, errors {errors}");
            if errors > 0 {
                ExitCode::FAILURE
            } else {
                ExitCode::SUCCESS
            }
        }
        Err(e) => {
            eprintln!("zccache warm: {e}");
            ExitCode::FAILURE
        }
    }
}

/// Parse crate names from a Cargo.lock file.
/// Returns a set of crate names with hyphens converted to underscores
/// (matching how cargo names output files).
fn parse_lockfile_crates(lockfile: &Path) -> Result<std::collections::HashSet<String>, String> {
    let content = std::fs::read_to_string(lockfile)
        .map_err(|e| format!("failed to read {}: {e}", lockfile.display()))?;
    let mut crates = std::collections::HashSet::new();
    for line in content.lines() {
        // Cargo.lock format: name = "crate-name"
        if let Some(name) = line.strip_prefix("name = \"") {
            if let Some(name) = name.strip_suffix('"') {
                // Cargo converts hyphens to underscores in output filenames
                crates.insert(name.replace('-', "_"));
            }
        }
    }
    Ok(crates)
}

/// Check if an output filename matches any crate in the allowed set.
/// Output filenames look like: libserde-abc123.rlib, serde-abc123.d,
/// libproc_macro2-def456.so, etc.
fn artifact_matches_lockfile(
    filename: &str,
    allowed_crates: &std::collections::HashSet<String>,
) -> bool {
    // Strip lib prefix if present
    let name = filename.strip_prefix("lib").unwrap_or(filename);
    // Find the hash separator: last hyphen followed by hex chars
    // e.g., "serde-abc123.rlib" → crate name is "serde"
    // e.g., "proc_macro2-def456.rmeta" → crate name is "proc_macro2"
    // Walk from the end to find the hash suffix
    if let Some(pos) = name.rfind('-') {
        let crate_name = &name[..pos];
        allowed_crates.contains(crate_name)
    } else {
        // No hash separator — might be a build script or other file, allow it
        true
    }
}

/// Core logic for `zccache warm` — testable with custom paths.
/// If lockfile is Some, only restores artifacts matching crates in the lockfile.
fn warm_target(
    index_path: &Path,
    artifact_dir: &Path,
    target_dir: &Path,
    profile: &str,
    lockfile: Option<&Path>,
) -> Result<(u64, u64, u64), String> {
    if !index_path.exists() {
        return Err(format!("no artifact index at {}", index_path.display()));
    }

    let store = zccache_artifact::ArtifactStore::open(index_path)
        .map_err(|e| format!("failed to open artifact index: {e}"))?;

    let all_entries = store
        .load_all()
        .map_err(|e| format!("failed to read artifact index: {e}"))?;

    if all_entries.is_empty() {
        return Err("no cached artifacts found in index".to_string());
    }

    // If we have a lockfile, only restore artifacts matching its crates
    let allowed_crates = match lockfile {
        Some(lf) => Some(parse_lockfile_crates(lf)?),
        None => None,
    };

    let artifacts = all_entries;

    let deps_dir = target_dir.join(profile).join("deps");
    std::fs::create_dir_all(&deps_dir)
        .map_err(|e| format!("failed to create {}: {e}", deps_dir.display()))?;
    let now = std::time::SystemTime::now();
    let file_times = std::fs::FileTimes::new()
        .set_accessed(now)
        .set_modified(now);

    let mut restored = 0u64;
    let mut skipped = 0u64;
    let mut errors = 0u64;

    for (key_hex, idx) in &artifacts {
        for (i, name) in idx.output_names.iter().enumerate() {
            let src = artifact_dir.join(format!("{key_hex}_{i}"));
            let dst = deps_dir.join(name.as_str());

            // Skip if artifact doesn't match any crate in the lockfile
            if let Some(ref allowed) = allowed_crates {
                if !artifact_matches_lockfile(name, allowed) {
                    skipped += 1;
                    continue;
                }
            }

            // Skip if source payload does not exist on disk.
            if !src.exists() {
                skipped += 1;
                continue;
            }

            // Remove existing file at destination (hardlink will fail if it exists).
            if dst.exists() {
                if let Err(e) = std::fs::remove_file(&dst) {
                    eprintln!(
                        "zccache warm: failed to remove existing {}: {e}",
                        dst.display()
                    );
                    errors += 1;
                    continue;
                }
            }

            // Try hardlink first, fall back to copy.
            let linked = std::fs::hard_link(&src, &dst).is_ok();
            if !linked {
                if let Err(e) = std::fs::copy(&src, &dst) {
                    eprintln!(
                        "zccache warm: failed to copy {} -> {}: {e}",
                        src.display(),
                        dst.display()
                    );
                    errors += 1;
                    continue;
                }
            }

            // Touch mtime to current time so cargo sees the file as fresh.
            if let Ok(f) = std::fs::File::open(&dst) {
                let _ = f.set_times(file_times);
            }

            restored += 1;
        }
    }

    Ok((restored, skipped, errors))
}

async fn cmd_session_start(
    endpoint: &str,
    cwd: &Path,
    log: Option<&Path>,
    track_stats: bool,
    journal: Option<NormalizedPath>,
) -> ExitCode {
    if let Err(e) = ensure_daemon(endpoint).await {
        eprintln!("cannot start daemon at {endpoint}: {e}");
        return ExitCode::FAILURE;
    }

    let mut conn = match connect(endpoint).await {
        Ok(c) => c,
        Err(e) => {
            eprintln!("cannot connect to daemon at {endpoint}: {e}");
            return ExitCode::FAILURE;
        }
    };

    if let Err(e) = conn
        .send(&zccache_protocol::Request::SessionStart {
            client_pid: std::process::id(),
            working_dir: cwd.into(),
            log_file: log.map(NormalizedPath::from),
            track_stats,
            journal_path: journal,
        })
        .await
    {
        eprintln!("zccache: failed to send to daemon: {e}");
        return ExitCode::FAILURE;
    }

    let recv_result = match conn.recv().await {
        Ok(r) => r,
        Err(e) => {
            eprintln!("zccache: broken connection to daemon: {e}");
            return ExitCode::FAILURE;
        }
    };
    match recv_result {
        Some(zccache_protocol::Response::SessionStarted {
            session_id,
            journal_path,
        }) => {
            // One-line JSON so scripts can parse both the session ID and start time:
            //   result=$(zccache session-start)
            let started_at = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();
            if let Some(ref jp) = journal_path {
                // Escape backslashes for valid JSON (Windows paths contain `\`)
                let jp_escaped = jp.display().to_string().replace('\\', "\\\\");
                println!(
                    r#"{{"session_id":"{}","started_at":{},"journal_path":"{}"}}"#,
                    session_id, started_at, jp_escaped
                );
            } else {
                println!(
                    r#"{{"session_id":"{}","started_at":{}}}"#,
                    session_id, started_at
                );
            }
            ExitCode::SUCCESS
        }
        Some(zccache_protocol::Response::Error { message }) => {
            eprintln!("session-start failed: {message}");
            ExitCode::FAILURE
        }
        None => {
            eprintln!("zccache: lost connection to daemon (no response received)");
            ExitCode::FAILURE
        }
        Some(other) => {
            eprintln!("zccache: unexpected response from daemon: {other:?}");
            ExitCode::FAILURE
        }
    }
}

fn cmd_session_end(endpoint: &str, session_id: String) -> ExitCode {
    // Thin wrapper around the shared library entry point. All daemon
    // callers (CLI, soldr, future tools) must agree on what "the daemon
    // is gone" means — see `session_end_idempotent` for the contract
    // and issue #159 for why this lives in the library.
    match session_end_idempotent(endpoint, &session_id) {
        Ok(Some(s)) => {
            let total = s.hits + s.misses;
            let hit_rate = if total > 0 {
                format!("{:.1}%", s.hits as f64 / total as f64 * 100.0)
            } else {
                "n/a".to_string()
            };
            eprintln!(
                "Session {session_id} complete ({})",
                format_duration_ms(s.duration_ms)
            );
            eprintln!(
                "  {} compilations: {} hits, {} misses, {} non-cacheable",
                s.compilations, s.hits, s.misses, s.non_cacheable
            );
            eprintln!("  Hit rate: {hit_rate}");
            if s.time_saved_ms > 0 {
                eprintln!("  Time saved: ~{}", format_duration_ms(s.time_saved_ms));
            }
            ExitCode::SUCCESS
        }
        // `Ok(None)` covers both:
        //   - daemon was unreachable (already logged by the library), and
        //   - daemon was reached but had no stats for this session.
        // Both are no-op successes.
        Ok(None) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("zccache: session-end failed: {e}");
            ExitCode::FAILURE
        }
    }
}

async fn cmd_session_stats(endpoint: &str, session_id: String) -> ExitCode {
    let mut conn = match connect(endpoint).await {
        Ok(c) => c,
        Err(e) => {
            eprintln!("cannot connect to daemon at {endpoint}: {e}");
            return ExitCode::FAILURE;
        }
    };

    if let Err(e) = conn
        .send(&zccache_protocol::Request::SessionStats {
            session_id: session_id.clone(),
        })
        .await
    {
        eprintln!("zccache: failed to send to daemon: {e}");
        return ExitCode::FAILURE;
    }

    let recv_result = match conn.recv().await {
        Ok(r) => r,
        Err(e) => {
            eprintln!("zccache: broken connection to daemon: {e}");
            return ExitCode::FAILURE;
        }
    };
    match recv_result {
        Some(zccache_protocol::Response::SessionStatsResult { stats }) => {
            if let Some(s) = stats {
                let total = s.hits + s.misses;
                let hit_rate = if total > 0 {
                    format!("{:.1}%", s.hits as f64 / total as f64 * 100.0)
                } else {
                    "n/a".to_string()
                };
                eprintln!(
                    "Session {session_id} (active, {})",
                    format_duration_ms(s.duration_ms)
                );
                eprintln!(
                    "  {} compilations: {} hits, {} misses, {} non-cacheable",
                    s.compilations, s.hits, s.misses, s.non_cacheable
                );
                eprintln!("  Hit rate: {hit_rate}");
                if s.time_saved_ms > 0 {
                    eprintln!("  Time saved: ~{}", format_duration_ms(s.time_saved_ms));
                }
            } else {
                eprintln!("Session {session_id}: stats tracking not enabled");
            }
            ExitCode::SUCCESS
        }
        Some(zccache_protocol::Response::Error { message }) => {
            eprintln!("session-stats failed: {message}");
            ExitCode::FAILURE
        }
        None => {
            eprintln!("zccache: lost connection to daemon (no response received)");
            ExitCode::FAILURE
        }
        Some(other) => {
            eprintln!("zccache: unexpected response from daemon: {other:?}");
            ExitCode::FAILURE
        }
    }
}

fn cmd_crashes(clear: bool) -> ExitCode {
    let crash_dir = zccache_core::config::crash_dump_dir();

    if clear {
        let count = match std::fs::read_dir(&crash_dir) {
            Ok(entries) => {
                let mut n = 0u64;
                for entry in entries.flatten() {
                    if std::fs::remove_file(entry.path()).is_ok() {
                        n += 1;
                    }
                }
                n
            }
            Err(_) => 0,
        };
        println!("Deleted {count} crash dump(s).");
        return ExitCode::SUCCESS;
    }

    let mut dumps: Vec<_> = match std::fs::read_dir(&crash_dir) {
        Ok(entries) => entries
            .flatten()
            .filter(|e| e.path().extension().is_some_and(|ext| ext == "txt"))
            .collect(),
        Err(_) => {
            println!("No crash dumps found.");
            return ExitCode::SUCCESS;
        }
    };

    if dumps.is_empty() {
        println!("No crash dumps found.");
        return ExitCode::SUCCESS;
    }

    dumps.sort_by_key(|e| e.file_name());

    println!("Crash dumps ({}):", dumps.len());
    println!();
    for entry in &dumps {
        let path = entry.path();
        println!("  {}", path.display());
        if let Ok(content) = std::fs::read_to_string(&path) {
            for (i, line) in content.lines().enumerate() {
                if i >= 5 {
                    println!("    ...");
                    break;
                }
                println!("    {line}");
            }
            println!();
        }
    }

    ExitCode::SUCCESS
}

// ─── Cargo registry subcommands ──────────────────────────────────────────

/// Resolve the cargo home directory from an explicit argument, the `CARGO_HOME`
/// env var, or the default `~/.cargo`.
fn resolve_cargo_home(explicit: Option<&str>) -> Result<NormalizedPath, String> {
    if let Some(p) = explicit {
        return Ok(NormalizedPath::from(p));
    }
    if let Ok(ch) = std::env::var("CARGO_HOME") {
        if !ch.is_empty() {
            return Ok(NormalizedPath::from(ch));
        }
    }
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .map_err(|_| "cannot determine home directory (set HOME or CARGO_HOME)".to_string())?;
    Ok(NormalizedPath::from(home).join(".cargo"))
}

/// Directory where cargo-registry archives are stored.
fn cargo_registry_cache_dir() -> Result<NormalizedPath, String> {
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .map_err(|_| "cannot determine home directory (set HOME)".to_string())?;
    Ok(NormalizedPath::from(home)
        .join(".zccache")
        .join("cargo-registry"))
}

/// Matches setup-soldr's boolean env-var normalization: `1`, `true`, `yes`,
/// `on` (case-insensitive) are truthy; anything else (including `None`,
/// empty, `0`, `false`, `no`, `off`) is falsy. See zccache#184.
fn flag_truthy(value: Option<&str>) -> bool {
    let Some(raw) = value else { return false };
    let trimmed = raw.trim();
    matches!(trimmed, "1")
        || trimmed.eq_ignore_ascii_case("true")
        || trimmed.eq_ignore_ascii_case("yes")
        || trimmed.eq_ignore_ascii_case("on")
}

fn env_flag_truthy(name: &str) -> bool {
    flag_truthy(std::env::var(name).ok().as_deref())
}

/// Parallel walk of `target` summing the bytes of every regular file, with
/// optional pruning. Uses jwalk for parallel readdir + stat (rayon under the
/// hood) — on Windows this hides per-file Defender callback latency that
/// dominates the single-threaded `os.walk` baseline. See zccache#189.
fn cmd_snapshot_bytes(
    target: &Path,
    prune_incremental: bool,
    prune_build_script_out: bool,
) -> ExitCode {
    match snapshot_bytes_walk(target, prune_incremental, prune_build_script_out) {
        Ok(total) => {
            println!("{total}");
            ExitCode::SUCCESS
        }
        Err(err) => {
            eprintln!("zccache snapshot-bytes: {err}");
            ExitCode::FAILURE
        }
    }
}

fn snapshot_bytes_walk(
    target: &Path,
    prune_incremental: bool,
    prune_build_script_out: bool,
) -> std::io::Result<u64> {
    use jwalk::WalkDirGeneric;
    use std::sync::Mutex;

    if !target.exists() {
        return Ok(0);
    }

    // Dedup by (dev, inode) so hardlinked files don't double-count.
    let seen: Mutex<std::collections::HashSet<(u64, u64)>> = Mutex::new(Default::default());

    let walker = WalkDirGeneric::<((), Option<u64>)>::new(target).process_read_dir(
        move |_depth, parent_path, _read_dir_state, children| {
            for child in children.iter_mut() {
                let Ok(entry) = child.as_mut() else { continue };
                if !entry.file_type().is_dir() {
                    continue;
                }
                let name = entry.file_name().to_string_lossy().into_owned();
                if prune_incremental && name == "incremental" {
                    entry.read_children_path = None;
                    continue;
                }
                if prune_build_script_out && name == "out" {
                    // `*/build/*/out` — only prune if grandparent is `build`.
                    if let Some(grandparent) = parent_path.parent() {
                        if grandparent.file_name().and_then(|s| s.to_str()) == Some("build") {
                            entry.read_children_path = None;
                        }
                    }
                }
            }
        },
    );

    let mut total: u64 = 0;
    for entry in walker {
        let entry = match entry {
            Ok(e) => e,
            Err(err) => {
                // Tolerate per-entry stat failures the same way `os.walk` does
                // in the bash fallback: skip and continue. We only bail on
                // catastrophic root-level failure (handled by walker init).
                eprintln!("zccache snapshot-bytes: skip entry: {err}");
                continue;
            }
        };
        if !entry.file_type().is_file() {
            continue;
        }
        let meta = match entry.metadata() {
            Ok(m) => m,
            Err(_) => continue,
        };
        if let Some(key) = file_identity(&meta) {
            let mut seen_guard = seen.lock().expect("seen mutex poisoned");
            if !seen_guard.insert(key) {
                continue;
            }
        }
        total = total.saturating_add(meta.len());
    }
    Ok(total)
}

#[cfg(unix)]
fn file_identity(meta: &std::fs::Metadata) -> Option<(u64, u64)> {
    use std::os::unix::fs::MetadataExt;
    Some((meta.dev(), meta.ino()))
}

#[cfg(windows)]
fn file_identity(_meta: &std::fs::Metadata) -> Option<(u64, u64)> {
    // Windows file IDs require a separate Win32 call; not worth the cost just
    // for hardlink dedup in a target/ tree. Cargo doesn't hardlink within
    // `target/` in practice, so the dedup is a no-op here.
    None
}

#[cfg(not(any(unix, windows)))]
fn file_identity(_meta: &std::fs::Metadata) -> Option<(u64, u64)> {
    None
}

fn cmd_cargo_registry_save(key: &str, cargo_home: Option<&str>) -> ExitCode {
    // setup-soldr#70's payload C migration: when setup-soldr owns
    // `~/.cargo/registry` caching with fast-zstd, double-saving here just
    // burns CPU on the same bytes. Caller signals takeover via env var.
    if env_flag_truthy("SOLDR_SKIP_CARGO_REGISTRY_SAVE") {
        println!(
            "cargo-registry save: skipping (SOLDR_SKIP_CARGO_REGISTRY_SAVE=1) \
             — caller owns the cache layer"
        );
        return ExitCode::SUCCESS;
    }
    let cargo_home = match resolve_cargo_home(cargo_home) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("zccache cargo-registry save: {e}");
            return ExitCode::FAILURE;
        }
    };
    let cache_dir = match cargo_registry_cache_dir() {
        Ok(d) => d,
        Err(e) => {
            eprintln!("zccache cargo-registry save: {e}");
            return ExitCode::FAILURE;
        }
    };
    if let Err(e) = std::fs::create_dir_all(&cache_dir) {
        eprintln!(
            "zccache cargo-registry save: failed to create {}: {e}",
            cache_dir.display()
        );
        return ExitCode::FAILURE;
    }
    let archive_path = cache_dir.join(format!("{key}.tar.gz"));

    // Collect paths to archive.
    let subdirs: &[&str] = &["registry/index", "registry/cache", "git/db"];
    let mut paths: Vec<(NormalizedPath, String)> = Vec::new();
    for subdir in subdirs {
        let p = cargo_home.join(subdir);
        if p.exists() {
            paths.push((p, subdir.to_string()));
        }
    }

    if paths.is_empty() {
        eprintln!(
            "no cargo registry directories found in {}",
            cargo_home.display()
        );
        return ExitCode::SUCCESS;
    }

    // Create tar.gz archive.
    let file = match std::fs::File::create(&archive_path) {
        Ok(f) => f,
        Err(e) => {
            eprintln!(
                "zccache cargo-registry save: failed to create {}: {e}",
                archive_path.display()
            );
            return ExitCode::FAILURE;
        }
    };
    let gz = flate2::write::GzEncoder::new(file, flate2::Compression::fast());
    let mut tar = tar::Builder::new(gz);

    for (path, name) in &paths {
        if let Err(e) = tar.append_dir_all(name, path) {
            eprintln!("zccache cargo-registry save: failed to add {name}: {e}");
            return ExitCode::FAILURE;
        }
    }
    if let Err(e) = tar.finish() {
        eprintln!("zccache cargo-registry save: failed to finalize archive: {e}");
        return ExitCode::FAILURE;
    }

    let size = std::fs::metadata(&archive_path)
        .map(|m| m.len())
        .unwrap_or(0);
    println!(
        "saved cargo registry to {} ({})",
        archive_path.display(),
        format_bytes(size)
    );
    ExitCode::SUCCESS
}

fn cmd_cargo_registry_restore(key: &str, cargo_home: Option<&str>) -> ExitCode {
    let cargo_home = match resolve_cargo_home(cargo_home) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("zccache cargo-registry restore: {e}");
            return ExitCode::FAILURE;
        }
    };
    let cache_dir = match cargo_registry_cache_dir() {
        Ok(d) => d,
        Err(e) => {
            eprintln!("zccache cargo-registry restore: {e}");
            return ExitCode::FAILURE;
        }
    };
    let archive_path = cache_dir.join(format!("{key}.tar.gz"));

    if !archive_path.exists() {
        eprintln!("no cached registry found for key: {key}");
        return ExitCode::FAILURE;
    }

    let file = match std::fs::File::open(&archive_path) {
        Ok(f) => f,
        Err(e) => {
            eprintln!(
                "zccache cargo-registry restore: failed to open {}: {e}",
                archive_path.display()
            );
            return ExitCode::FAILURE;
        }
    };
    let gz = flate2::read::GzDecoder::new(file);
    let mut tar = tar::Archive::new(gz);
    if let Err(e) = tar.unpack(&cargo_home) {
        eprintln!("zccache cargo-registry restore: failed to unpack archive: {e}");
        return ExitCode::FAILURE;
    }

    println!("restored cargo registry from {}", archive_path.display());
    ExitCode::SUCCESS
}

fn cmd_cargo_registry_hash(lockfile: &str) -> ExitCode {
    let path = Path::new(lockfile);
    if !path.exists() {
        eprintln!("lockfile not found: {lockfile}");
        return ExitCode::FAILURE;
    }
    let hash = match zccache_hash::hash_file(path) {
        Ok(h) => h,
        Err(e) => {
            eprintln!("zccache cargo-registry hash: failed to hash {lockfile}: {e}");
            return ExitCode::FAILURE;
        }
    };
    // Print first 16 hex chars (matches action's cache key format).
    let hex = hash.to_hex();
    println!("{}", &hex[..16]);
    ExitCode::SUCCESS
}

fn cmd_cargo_registry_clean() -> ExitCode {
    let cache_dir = match cargo_registry_cache_dir() {
        Ok(d) => d,
        Err(e) => {
            eprintln!("zccache cargo-registry clean: {e}");
            return ExitCode::FAILURE;
        }
    };
    if cache_dir.exists() {
        let count = match std::fs::read_dir(&cache_dir) {
            Ok(entries) => entries.count(),
            Err(e) => {
                eprintln!(
                    "zccache cargo-registry clean: failed to read {}: {e}",
                    cache_dir.display()
                );
                return ExitCode::FAILURE;
            }
        };
        if let Err(e) = std::fs::remove_dir_all(&cache_dir) {
            eprintln!(
                "zccache cargo-registry clean: failed to remove {}: {e}",
                cache_dir.display()
            );
            return ExitCode::FAILURE;
        }
        println!("removed {count} cached registry archive(s)");
    } else {
        println!("no cached archives to clean");
    }
    ExitCode::SUCCESS
}

// ─── GHA cache subcommands ────────────────────────────────────────────────

fn cmd_gha_status() -> ExitCode {
    if GhaCache::is_available() {
        let url = std::env::var("ACTIONS_CACHE_URL").unwrap_or_default();
        println!("GHA cache: available");
        println!("  ACTIONS_CACHE_URL = {url}");
        ExitCode::SUCCESS
    } else {
        println!("GHA cache: not available (ACTIONS_CACHE_URL or ACTIONS_RUNTIME_TOKEN not set)");
        ExitCode::SUCCESS
    }
}

async fn cmd_gha_save(key: &str, path: &str) -> ExitCode {
    let cache = match GhaCache::from_env() {
        Ok(c) => c,
        Err(GhaError::NotAvailable) => {
            eprintln!("zccache gha-cache: not running in GitHub Actions");
            return ExitCode::FAILURE;
        }
        Err(e) => {
            eprintln!("zccache gha-cache: {e}");
            return ExitCode::FAILURE;
        }
    };

    let src = Path::new(path);
    if !src.exists() {
        eprintln!("zccache gha-cache save: path does not exist: {path}");
        return ExitCode::FAILURE;
    }

    // Create a tar.gz archive in memory.
    let data = match tar_gz_encode(src) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("zccache gha-cache save: failed to create archive: {e}");
            return ExitCode::FAILURE;
        }
    };

    let version = GhaCache::version_hash(&[path]);
    match cache.save(key, &version, &data).await {
        Ok(()) => {
            eprintln!(
                "zccache gha-cache save: uploaded {} bytes for key '{key}'",
                data.len()
            );
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("zccache gha-cache save: {e}");
            ExitCode::FAILURE
        }
    }
}

async fn cmd_gha_restore(key: &str, path: &str) -> ExitCode {
    let cache = match GhaCache::from_env() {
        Ok(c) => c,
        Err(GhaError::NotAvailable) => {
            eprintln!("zccache gha-cache: not running in GitHub Actions");
            return ExitCode::FAILURE;
        }
        Err(e) => {
            eprintln!("zccache gha-cache: {e}");
            return ExitCode::FAILURE;
        }
    };

    let version = GhaCache::version_hash(&[path]);
    let data = match cache.restore(key, &version).await {
        Ok(Some(d)) => d,
        Ok(None) => {
            eprintln!("zccache gha-cache restore: cache miss for key '{key}'");
            return ExitCode::FAILURE;
        }
        Err(e) => {
            eprintln!("zccache gha-cache restore: {e}");
            return ExitCode::FAILURE;
        }
    };

    let dest = Path::new(path);
    if let Err(e) = std::fs::create_dir_all(dest) {
        eprintln!("zccache gha-cache restore: failed to create directory: {e}");
        return ExitCode::FAILURE;
    }

    match tar_gz_decode(&data, dest) {
        Ok(()) => {
            eprintln!(
                "zccache gha-cache restore: restored {} bytes for key '{key}' to {path}",
                data.len()
            );
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("zccache gha-cache restore: failed to extract archive: {e}");
            ExitCode::FAILURE
        }
    }
}

// ─── Rust artifact plan subcommands ─────────────────────────────────────────

async fn cmd_rust_plan(action: RustPlanCommands) -> ExitCode {
    match action {
        RustPlanCommands::Validate {
            plan,
            json,
            session_id,
            endpoint,
            journal,
            cache_dir,
        } => {
            let cache_dir = resolve_rust_plan_cache_dir(cache_dir.as_deref());
            match load_rust_plan_for_cli(&plan, RustPlanOperation::Validate, json) {
                Ok(plan) => {
                    let mut summary =
                        RustPlanSummary::validation_success(&plan, cache_dir.as_path());
                    enrich_rust_plan_summary(
                        &mut summary,
                        session_id.as_deref(),
                        endpoint.as_deref(),
                        journal.as_deref(),
                    )
                    .await;
                    print_rust_plan_summary(&summary, json);
                    ExitCode::SUCCESS
                }
                Err(code) => code,
            }
        }
        RustPlanCommands::Restore {
            plan,
            json,
            session_id,
            endpoint,
            journal,
            backend,
            cache_dir,
        } => {
            let cache_dir = resolve_rust_plan_cache_dir(cache_dir.as_deref());
            let plan = match load_rust_plan_for_cli(&plan, RustPlanOperation::Restore, json) {
                Ok(plan) => plan,
                Err(code) => return code,
            };
            let backend = resolve_rust_plan_backend(backend);
            match run_rust_plan_restore(&plan, cache_dir.as_path(), backend).await {
                Ok(mut summary) => {
                    enrich_rust_plan_summary(
                        &mut summary,
                        session_id.as_deref(),
                        endpoint.as_deref(),
                        journal.as_deref(),
                    )
                    .await;
                    print_rust_plan_summary(&summary, json);
                    ExitCode::SUCCESS
                }
                Err(err) => {
                    print_rust_plan_runtime_error(
                        RustPlanOperation::Restore,
                        &plan,
                        cache_dir.as_path(),
                        backend,
                        &err,
                        json,
                    );
                    ExitCode::FAILURE
                }
            }
        }
        RustPlanCommands::Save {
            plan,
            json,
            session_id,
            endpoint,
            journal,
            backend,
            cache_dir,
        } => {
            let cache_dir = resolve_rust_plan_cache_dir(cache_dir.as_deref());
            let plan = match load_rust_plan_for_cli(&plan, RustPlanOperation::Save, json) {
                Ok(plan) => plan,
                Err(code) => return code,
            };
            let backend = resolve_rust_plan_backend(backend);
            match run_rust_plan_save(&plan, cache_dir.as_path(), backend).await {
                Ok(mut summary) => {
                    enrich_rust_plan_summary(
                        &mut summary,
                        session_id.as_deref(),
                        endpoint.as_deref(),
                        journal.as_deref(),
                    )
                    .await;
                    print_rust_plan_summary(&summary, json);
                    ExitCode::SUCCESS
                }
                Err(err) => {
                    print_rust_plan_runtime_error(
                        RustPlanOperation::Save,
                        &plan,
                        cache_dir.as_path(),
                        backend,
                        &err,
                        json,
                    );
                    ExitCode::FAILURE
                }
            }
        }
    }
}

fn resolve_rust_plan_cache_dir(explicit: Option<&str>) -> NormalizedPath {
    explicit
        .map(NormalizedPath::from)
        .unwrap_or_else(|| zccache_core::config::default_cache_dir().join("rust-artifacts"))
}

fn load_rust_plan_for_cli(
    path: &str,
    operation: RustPlanOperation,
    json: bool,
) -> Result<RustArtifactPlanV1, ExitCode> {
    match RustArtifactPlanV1::load(Path::new(path)) {
        Ok(plan) => Ok(plan),
        Err(err) => {
            print_rust_plan_error(operation, &err, json);
            Err(ExitCode::FAILURE)
        }
    }
}

async fn run_rust_plan_restore(
    plan: &RustArtifactPlanV1,
    cache_dir: &Path,
    backend: RustPlanBackendArg,
) -> Result<RustPlanSummary, RustPlanRuntimeError> {
    match backend {
        RustPlanBackendArg::Local => restore_rust_plan_local(plan, cache_dir)
            .map_err(|err| rust_plan_backend_failure(backend, err.to_string())),
        RustPlanBackendArg::Gha => restore_rust_plan_gha(plan, cache_dir).await,
        RustPlanBackendArg::Auto => unreachable!("auto backend is resolved before execution"),
    }
}

async fn run_rust_plan_save(
    plan: &RustArtifactPlanV1,
    cache_dir: &Path,
    backend: RustPlanBackendArg,
) -> Result<RustPlanSummary, RustPlanRuntimeError> {
    match backend {
        RustPlanBackendArg::Local => save_rust_plan_local(plan, cache_dir)
            .map_err(|err| rust_plan_backend_failure(backend, err.to_string())),
        RustPlanBackendArg::Gha => save_rust_plan_gha(plan, cache_dir).await,
        RustPlanBackendArg::Auto => unreachable!("auto backend is resolved before execution"),
    }
}

fn resolve_rust_plan_backend(backend: RustPlanBackendArg) -> RustPlanBackendArg {
    match backend {
        RustPlanBackendArg::Auto if GhaCache::is_available() => RustPlanBackendArg::Gha,
        RustPlanBackendArg::Auto => RustPlanBackendArg::Local,
        other => other,
    }
}

fn rust_plan_gha_version(cache_key: &str) -> String {
    GhaCache::version_hash(&["zccache-rust-plan-v1", cache_key])
}

async fn restore_rust_plan_gha(
    plan: &RustArtifactPlanV1,
    cache_dir: &Path,
) -> Result<RustPlanSummary, RustPlanRuntimeError> {
    let cache_key = rust_plan_cache_key(plan);
    let version = rust_plan_gha_version(&cache_key);
    let cache = GhaCache::from_env().map_err(rust_plan_gha_error)?;
    let Some(data) = cache
        .restore(&cache_key, &version)
        .await
        .map_err(rust_plan_gha_error)?
    else {
        let mut summary = restore_rust_plan_local(plan, cache_dir)
            .map_err(|err| rust_plan_backend_failure(RustPlanBackendArg::Gha, err.to_string()))?;
        summary.set_backend("gha", Some(cache_key), Some(version));
        summary.record_skip("<gha-cache>", "backend_cache_miss");
        return Ok(summary);
    };

    let bundle_dir = rust_plan_bundle_dir(cache_dir, &cache_key);
    if bundle_dir.exists() {
        std::fs::remove_dir_all(&bundle_dir)
            .map_err(|err| rust_plan_backend_failure(RustPlanBackendArg::Gha, err.to_string()))?;
    }
    let bundle_parent = bundle_dir.parent().ok_or_else(|| {
        rust_plan_backend_failure(
            RustPlanBackendArg::Gha,
            "invalid rust-plan bundle path".to_string(),
        )
    })?;
    std::fs::create_dir_all(bundle_parent)
        .map_err(|err| rust_plan_backend_failure(RustPlanBackendArg::Gha, err.to_string()))?;
    tar_gz_decode(&data, bundle_parent)
        .map_err(|err| rust_plan_backend_failure(RustPlanBackendArg::Gha, err.to_string()))?;
    let mut summary = restore_rust_plan_local(plan, cache_dir)
        .map_err(|err| rust_plan_backend_failure(RustPlanBackendArg::Gha, err.to_string()))?;
    summary.set_backend("gha", Some(cache_key), Some(version));
    Ok(summary)
}

async fn save_rust_plan_gha(
    plan: &RustArtifactPlanV1,
    cache_dir: &Path,
) -> Result<RustPlanSummary, RustPlanRuntimeError> {
    let summary = save_rust_plan_local(plan, cache_dir)
        .map_err(|err| rust_plan_backend_failure(RustPlanBackendArg::Gha, err.to_string()))?;
    let cache_key = summary.cache_key.clone();
    let bundle_dir = rust_plan_bundle_dir(cache_dir, &cache_key);
    let data = tar_gz_encode(&bundle_dir)
        .map_err(|err| rust_plan_backend_failure(RustPlanBackendArg::Gha, err.to_string()))?;
    let version = rust_plan_gha_version(&cache_key);
    let cache = GhaCache::from_env().map_err(rust_plan_gha_error)?;
    cache
        .save(&cache_key, &version, &data)
        .await
        .map_err(rust_plan_gha_error)?;
    let mut summary = summary;
    summary.set_backend("gha", Some(cache_key), Some(version));
    Ok(summary)
}

fn rust_plan_gha_error(err: GhaError) -> RustPlanRuntimeError {
    let kind = if matches!(&err, GhaError::NotAvailable) {
        RustPlanRuntimeErrorKind::Unavailable
    } else {
        RustPlanRuntimeErrorKind::Failure
    };
    rust_plan_backend_failure(RustPlanBackendArg::Gha, err.to_string()).with_kind(kind)
}

fn rust_plan_backend_failure(backend: RustPlanBackendArg, message: String) -> RustPlanRuntimeError {
    RustPlanRuntimeError::Backend {
        backend,
        kind: RustPlanRuntimeErrorKind::Failure,
        message,
    }
}

fn rust_plan_runtime_error_message(err: &RustPlanRuntimeError) -> String {
    let backend = match err.backend() {
        RustPlanBackendArg::Local => "local",
        RustPlanBackendArg::Gha => "GHA",
        RustPlanBackendArg::Auto => unreachable!("auto backend is resolved before execution"),
    };
    let kind = match err.kind() {
        RustPlanRuntimeErrorKind::Unavailable => "unavailable",
        RustPlanRuntimeErrorKind::Failure => "failure",
    };
    format!("{backend} cache backend {kind}: {}", err.message())
}

fn rust_plan_runtime_failure_summary(
    operation: RustPlanOperation,
    plan: &RustArtifactPlanV1,
    cache_dir: &Path,
    backend: RustPlanBackendArg,
    err: &RustPlanRuntimeError,
) -> RustPlanSummary {
    let mut summary = RustPlanSummary::validation_success(plan, cache_dir);
    summary.operation = operation;
    summary.backend = match backend {
        RustPlanBackendArg::Local => "local".to_string(),
        RustPlanBackendArg::Gha => "gha".to_string(),
        RustPlanBackendArg::Auto => unreachable!("auto backend is resolved before execution"),
    };
    if matches!(backend, RustPlanBackendArg::Gha) {
        let cache_key = summary.cache_key.clone();
        summary.backend_cache_key = Some(cache_key.clone());
        summary.backend_cache_version = Some(rust_plan_gha_version(&cache_key));
    }
    summary.compatibility.status = "error".to_string();
    summary.compatibility.errors = vec![rust_plan_runtime_error_message(err)];
    summary
}

fn print_rust_plan_runtime_error(
    operation: RustPlanOperation,
    plan: &RustArtifactPlanV1,
    cache_dir: &Path,
    backend: RustPlanBackendArg,
    err: &RustPlanRuntimeError,
    json: bool,
) {
    if json {
        let summary = rust_plan_runtime_failure_summary(operation, plan, cache_dir, backend, err);
        print_rust_plan_summary(&summary, true);
    } else {
        eprintln!(
            "zccache rust-plan: {}",
            rust_plan_runtime_error_message(err)
        );
    }
}

async fn enrich_rust_plan_summary(
    summary: &mut RustPlanSummary,
    session_id: Option<&str>,
    endpoint: Option<&str>,
    journal: Option<&str>,
) {
    if let Some(journal) = journal {
        summary.journal_log_path = Some(absolute_path(journal));
    }

    if let Some(session_id) = session_id {
        let endpoint = resolve_endpoint(endpoint);
        summary.compile_cache_stats = Some(query_session_stats_json(&endpoint, session_id).await);
    }
}

async fn query_session_stats_json(endpoint: &str, session_id: &str) -> serde_json::Value {
    match query_session_stats(endpoint, session_id).await {
        Ok(Some(stats)) => session_stats_json(session_id, &stats),
        Ok(None) => serde_json::json!({
            "status": "not_tracked",
            "session_id": session_id,
            "message": "session exists but stats tracking is not enabled"
        }),
        Err(err) => serde_json::json!({
            "status": "error",
            "session_id": session_id,
            "error": err
        }),
    }
}

async fn query_session_stats(
    endpoint: &str,
    session_id: &str,
) -> Result<Option<zccache_protocol::SessionStats>, String> {
    let mut conn = connect(endpoint)
        .await
        .map_err(|err| format!("cannot connect to daemon at {endpoint}: {err}"))?;

    conn.send(&zccache_protocol::Request::SessionStats {
        session_id: session_id.to_string(),
    })
    .await
    .map_err(|err| format!("failed to send session stats request: {err}"))?;

    let recv_result = conn
        .recv()
        .await
        .map_err(|err| format!("broken daemon connection: {err}"))?;
    match recv_result {
        Some(zccache_protocol::Response::SessionStatsResult { stats }) => Ok(stats),
        Some(zccache_protocol::Response::Error { message }) => Err(message),
        Some(other) => Err(format!("unexpected daemon response: {other:?}")),
        None => Err("lost connection to daemon (no response received)".to_string()),
    }
}

fn session_stats_json(
    session_id: &str,
    stats: &zccache_protocol::SessionStats,
) -> serde_json::Value {
    let total = stats.hits + stats.misses;
    let hit_rate = if total > 0 {
        Some(stats.hits as f64 / total as f64)
    } else {
        None
    };
    serde_json::json!({
        "status": "ok",
        "session_id": session_id,
        "duration_ms": stats.duration_ms,
        "compilations": stats.compilations,
        "hits": stats.hits,
        "misses": stats.misses,
        "non_cacheable": stats.non_cacheable,
        "errors": stats.errors,
        "time_saved_ms": stats.time_saved_ms,
        "unique_sources": stats.unique_sources,
        "bytes_read": stats.bytes_read,
        "bytes_written": stats.bytes_written,
        "hit_rate": hit_rate,
    })
}

fn print_rust_plan_summary(summary: &RustPlanSummary, json: bool) {
    if json {
        match serde_json::to_string_pretty(summary) {
            Ok(s) => println!("{s}"),
            Err(err) => eprintln!("zccache rust-plan: failed to encode JSON summary: {err}"),
        }
        return;
    }

    println!(
        "zccache rust-plan {}: {}",
        match summary.operation {
            RustPlanOperation::Validate => "validate",
            RustPlanOperation::Restore => "restore",
            RustPlanOperation::Save => "save",
        },
        summary.compatibility.status
    );
    println!("  mode: {}", summary.mode);
    println!("  backend: {}", summary.backend);
    println!("  cache key: {}", summary.cache_key);
    if let Some(key) = &summary.backend_cache_key {
        println!("  backend cache key: {key}");
    }
    if let Some(version) = &summary.backend_cache_version {
        println!("  backend cache version: {version}");
    }
    if let Some(path) = &summary.archive_path {
        println!("  bundle: {}", path.display());
    }
    if summary.saved_file_count > 0 || summary.saved_bytes > 0 {
        println!(
            "  saved: {} files ({})",
            summary.saved_file_count,
            format_bytes(summary.saved_bytes)
        );
    }
    if summary.restored_file_count > 0 || summary.restored_bytes > 0 {
        println!(
            "  restored: {} files ({})",
            summary.restored_file_count,
            format_bytes(summary.restored_bytes)
        );
    }
    if summary.skipped_count > 0 {
        println!("  skipped: {}", summary.skipped_count);
        for (reason, count) in &summary.skipped_reasons {
            println!("    {reason}: {count}");
        }
    }
    for mismatch in &summary.key_input_mismatches {
        println!("  mismatch: {mismatch}");
    }
    if let Some(stats) = &summary.compile_cache_stats {
        println!("  compile cache stats: {stats}");
    }
}

fn print_rust_plan_error(operation: RustPlanOperation, err: &RustPlanError, json: bool) {
    if json {
        let summary = RustPlanSummary::compatibility_failure(operation, err);
        print_rust_plan_summary(&summary, true);
    } else {
        eprintln!("zccache rust-plan: {err}");
    }
}

/// Create a tar.gz archive from a directory path.
fn tar_gz_encode(src: &Path) -> Result<Vec<u8>, std::io::Error> {
    use flate2::write::GzEncoder;
    use flate2::Compression;

    let buf = Vec::new();
    let enc = GzEncoder::new(buf, Compression::fast());
    let mut tar = tar::Builder::new(enc);
    // Use the last component of the path as the archive prefix so that
    // extraction recreates the directory structure relative to the target.
    let prefix = src
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| ".".to_string());
    tar.append_dir_all(&prefix, src)?;
    let enc = tar.into_inner()?;
    enc.finish()
}

/// Extract a tar.gz archive into a destination directory.
fn tar_gz_decode(data: &[u8], dest: &Path) -> Result<(), std::io::Error> {
    use flate2::read::GzDecoder;

    let dec = GzDecoder::new(data);
    let mut archive = tar::Archive::new(dec);
    archive.unpack(dest)
}

// ─── Fingerprint subcommands ──────────────────────────────────────────────

async fn cmd_fp_check(
    endpoint: &str,
    cache_file: &Path,
    cache_type: &str,
    root: &Path,
    ext: &[String],
    include: &[String],
    exclude: &[String],
) -> ExitCode {
    if let Err(e) = ensure_daemon(endpoint).await {
        eprintln!("zccache fp: failed to start daemon: {e}");
        return ExitCode::from(2);
    }

    let mut conn = match connect(endpoint).await {
        Ok(c) => c,
        Err(e) => {
            eprintln!("zccache fp: cannot connect to daemon: {e}");
            return ExitCode::from(2);
        }
    };

    let request = zccache_protocol::Request::FingerprintCheck {
        cache_file: cache_file.into(),
        cache_type: cache_type.to_string(),
        root: root.into(),
        extensions: ext.to_vec(),
        include_globs: include.to_vec(),
        exclude: exclude.to_vec(),
    };

    if let Err(e) = conn.send(&request).await {
        eprintln!("zccache fp: send error: {e}");
        return ExitCode::from(2);
    }

    match conn.recv::<zccache_protocol::Response>().await {
        Ok(Some(zccache_protocol::Response::FingerprintCheckResult {
            decision,
            reason,
            changed_files,
        })) => {
            if decision == "skip" {
                eprintln!("zccache fp: skip (no changes)");
                ExitCode::from(1)
            } else {
                let reason_str = reason.as_deref().unwrap_or("unknown");
                if changed_files.is_empty() {
                    eprintln!("zccache fp: run ({reason_str})");
                } else {
                    eprintln!(
                        "zccache fp: run ({reason_str}, {} file(s) changed)",
                        changed_files.len()
                    );
                }
                ExitCode::SUCCESS
            }
        }
        Ok(Some(zccache_protocol::Response::Error { message })) => {
            eprintln!("zccache fp: daemon error: {message}");
            ExitCode::from(2)
        }
        Ok(other) => {
            eprintln!("zccache fp: unexpected response: {other:?}");
            ExitCode::from(2)
        }
        Err(e) => {
            eprintln!("zccache fp: recv error: {e}");
            ExitCode::from(2)
        }
    }
}

async fn cmd_fp_mark(endpoint: &str, cache_file: &Path, success: bool) -> ExitCode {
    if let Err(e) = ensure_daemon(endpoint).await {
        eprintln!("zccache fp: failed to start daemon: {e}");
        return ExitCode::from(2);
    }

    let mut conn = match connect(endpoint).await {
        Ok(c) => c,
        Err(e) => {
            eprintln!("zccache fp: cannot connect to daemon: {e}");
            return ExitCode::from(2);
        }
    };

    let request = if success {
        zccache_protocol::Request::FingerprintMarkSuccess {
            cache_file: cache_file.into(),
        }
    } else {
        zccache_protocol::Request::FingerprintMarkFailure {
            cache_file: cache_file.into(),
        }
    };

    if let Err(e) = conn.send(&request).await {
        eprintln!("zccache fp: send error: {e}");
        return ExitCode::from(2);
    }

    match conn.recv::<zccache_protocol::Response>().await {
        Ok(Some(zccache_protocol::Response::FingerprintAck)) => {
            let label = if success {
                "mark-success"
            } else {
                "mark-failure"
            };
            eprintln!("zccache fp: {label}");
            ExitCode::SUCCESS
        }
        Ok(Some(zccache_protocol::Response::Error { message })) => {
            eprintln!("zccache fp: daemon error: {message}");
            ExitCode::from(2)
        }
        Ok(other) => {
            eprintln!("zccache fp: unexpected response: {other:?}");
            ExitCode::from(2)
        }
        Err(e) => {
            eprintln!("zccache fp: recv error: {e}");
            ExitCode::from(2)
        }
    }
}

async fn cmd_fp_invalidate(endpoint: &str, cache_file: &Path) -> ExitCode {
    if let Err(e) = ensure_daemon(endpoint).await {
        eprintln!("zccache fp: failed to start daemon: {e}");
        return ExitCode::from(2);
    }

    let mut conn = match connect(endpoint).await {
        Ok(c) => c,
        Err(e) => {
            eprintln!("zccache fp: cannot connect to daemon: {e}");
            return ExitCode::from(2);
        }
    };

    let request = zccache_protocol::Request::FingerprintInvalidate {
        cache_file: cache_file.into(),
    };

    if let Err(e) = conn.send(&request).await {
        eprintln!("zccache fp: send error: {e}");
        return ExitCode::from(2);
    }

    match conn.recv::<zccache_protocol::Response>().await {
        Ok(Some(zccache_protocol::Response::FingerprintAck)) => {
            eprintln!("zccache fp: invalidated");
            ExitCode::SUCCESS
        }
        Ok(Some(zccache_protocol::Response::Error { message })) => {
            eprintln!("zccache fp: daemon error: {message}");
            ExitCode::from(2)
        }
        Ok(other) => {
            eprintln!("zccache fp: unexpected response: {other:?}");
            ExitCode::from(2)
        }
        Err(e) => {
            eprintln!("zccache fp: recv error: {e}");
            ExitCode::from(2)
        }
    }
}

// ─── Wrap (compiler wrapper) ───────────────────────────────────────────────

/// Run the compiler/tool directly without caching (ZCCACHE_DISABLE mode).
fn run_passthrough(args: &[String]) -> ExitCode {
    let tool = &args[0];
    let tool_args = if args.len() > 1 { &args[1..] } else { &[] };

    // Resolve the tool path (normalize MSYS paths, search PATH)
    let resolved = resolve_compiler_path(tool);

    match std::process::Command::new(&resolved)
        .args(tool_args)
        .status()
    {
        Ok(status) => exit_code_from_i32(status.code().unwrap_or(1)),
        Err(e) => {
            eprintln!("zccache: failed to run {}: {e}", resolved.display());
            ExitCode::FAILURE
        }
    }
}

// ─── Rustfmt caching ───────────────────────────────────────────────────────

/// Run rustfmt with format caching.
///
/// Files whose content hash is already in the format cache are skipped entirely,
/// preserving their mtime and avoiding unnecessary downstream rebuilds.
/// After formatting, the new content hash of each file is stored in the cache.
fn run_rustfmt_cached(rustfmt_path: &Path, args: &[String], cwd: &Path) -> ExitCode {
    use zccache_compiler::parse_rustfmt::{find_rustfmt_config, parse_rustfmt_invocation};

    let parsed = match parse_rustfmt_invocation(args) {
        Some(p) => p,
        None => {
            // --help, --version, or stdin mode: pass through
            return run_tool_direct(rustfmt_path, args);
        }
    };

    // Build format context: rustfmt binary identity + config + flags.
    // Changes to any of these invalidate the entire format cache scope.
    let context_hash = {
        let mut hasher = zccache_hash::StreamHasher::new();
        hasher.update(b"zccache-fmt-v1");

        // Hash rustfmt binary content for version identity
        if let Ok(bin_hash) = zccache_hash::hash_file(rustfmt_path) {
            hasher.update(bin_hash.as_bytes());
        } else {
            hasher.update(b"unknown-binary");
        }

        // Hash config file content (if found)
        let config_path = parsed
            .config_path
            .clone()
            .or_else(|| find_rustfmt_config(cwd));
        if let Some(ref cfg) = config_path {
            if let Ok(cfg_hash) = zccache_hash::hash_file(cfg) {
                hasher.update(cfg_hash.as_bytes());
            }
        }

        // Hash flags (edition, --check, etc.)
        for flag in &parsed.flags {
            hasher.update(flag.as_bytes());
            hasher.update(b"\0");
        }

        hasher.finalize().to_hex()
    };

    // Format cache directory: {cache_dir}/fmt/{context_hash}/
    let cache_dir = zccache_core::config::default_cache_dir()
        .join("fmt")
        .join(&context_hash);

    // Ensure cache dir exists
    let _ = std::fs::create_dir_all(&cache_dir);

    // Resolve source files to absolute paths and check cache (parallel)
    use rayon::prelude::*;

    let results: Vec<(NormalizedPath, bool, Option<zccache_hash::ContentHash>)> = parsed
        .source_files
        .par_iter()
        .map(|src| {
            let abs = if src.is_absolute() {
                src.clone()
            } else {
                cwd.join(src).into()
            };
            let (is_hit, hash) = match zccache_hash::hash_file(&abs) {
                Ok(content_hash) => {
                    let marker = cache_dir.join(content_hash.to_hex());
                    (marker.exists(), Some(content_hash))
                }
                Err(_) => (false, None),
            };
            (abs, is_hit, hash)
        })
        .collect();

    let mut miss_files: Vec<NormalizedPath> = Vec::new();
    let mut all_files: Vec<(NormalizedPath, bool, Option<zccache_hash::ContentHash>)> = Vec::new();
    for (abs, is_hit, hash) in results {
        if !is_hit {
            miss_files.push(abs.clone());
        }
        all_files.push((abs, is_hit, hash));
    }

    // All files are cache hits — skip rustfmt entirely (mtime preserved!)
    if miss_files.is_empty() {
        if parsed.check_mode {
            // --check: all files are known-formatted → exit 0
            return ExitCode::SUCCESS;
        }
        // Normal mode: all files already formatted → nothing to do
        return ExitCode::SUCCESS;
    }

    // Run rustfmt on miss files only (normal mode) or all files (--check mode)
    let exit_code = if parsed.check_mode {
        // --check mode: run on miss files only; if all would pass, we
        // already returned above. For misses, we must run to determine
        // if they're formatted.
        run_rustfmt_on_files(rustfmt_path, args, &miss_files, &parsed)
    } else {
        // Normal mode: run on miss files only
        run_rustfmt_on_files(rustfmt_path, args, &miss_files, &parsed)
    };

    let exit_i32 = match exit_code {
        Ok(code) => code,
        Err(e) => {
            eprintln!("zccache: failed to run rustfmt: {e}");
            return ExitCode::FAILURE;
        }
    };

    // On success (exit 0), store new content hashes in format cache
    if exit_i32 == 0 {
        // For --check mode with exit 0: the miss files were already formatted
        // (we just didn't know it). Reuse the hash from the lookup phase.
        // For normal mode with exit 0: files were reformatted. Must re-hash.
        for (abs, was_hit, cached_hash) in &all_files {
            if *was_hit {
                continue; // Already in cache
            }
            let new_hash = if parsed.check_mode {
                *cached_hash
            } else {
                zccache_hash::hash_file(abs).ok()
            };
            if let Some(h) = new_hash {
                let marker = cache_dir.join(h.to_hex());
                let _ = std::fs::write(&marker, b"");
            }
        }
    }

    exit_code_from_i32(exit_i32)
}

/// Run rustfmt on a specific set of files, reconstructing the argument list.
fn run_rustfmt_on_files(
    rustfmt_path: &Path,
    original_args: &[String],
    files: &[NormalizedPath],
    parsed: &zccache_compiler::parse_rustfmt::ParsedRustfmt,
) -> Result<i32, std::io::Error> {
    // Reconstruct args: flags + the miss files (not the original file list)
    let mut cmd = std::process::Command::new(rustfmt_path);
    cmd.args(&parsed.flags);
    for f in files {
        cmd.arg(f);
    }

    // Suppress original args' source files — we pass our filtered list above.
    // But we need to preserve any non-file, non-flag args. In practice,
    // flags + files covers everything.
    let _ = original_args; // intentionally unused — we reconstruct from parsed

    let status = cmd.status()?;
    Ok(status.code().unwrap_or(1))
}

/// Run a tool directly and return its exit code.
fn run_tool_direct(tool: &Path, args: &[String]) -> ExitCode {
    match std::process::Command::new(tool).args(args).status() {
        Ok(status) => exit_code_from_i32(status.code().unwrap_or(1)),
        Err(e) => {
            eprintln!("zccache: failed to run {}: {e}", tool.display());
            ExitCode::FAILURE
        }
    }
}

// ─── Wrap (compiler wrapper) ───────────────────────────────────────────────

fn strip_leading_strict_paths_flags(
    args: &[String],
) -> Result<(Option<StrictPathsMode>, Vec<String>), String> {
    let mut strict_paths = None;
    let mut index = 0;

    while let Some(arg) = args.get(index) {
        if arg == "--strict-paths" {
            strict_paths = Some(StrictPathsMode::Absolute);
            index += 1;
        } else if let Some(value) = arg.strip_prefix("--strict-paths=") {
            strict_paths = Some(StrictPathsMode::parse(value).map_err(|err| err.to_string())?);
            index += 1;
        } else {
            break;
        }
    }

    Ok((strict_paths, args[index..].to_vec()))
}

fn parse_optional_strict_paths(value: Option<&str>) -> Result<Option<StrictPathsMode>, String> {
    value
        .map(|value| StrictPathsMode::parse(value).map_err(|err| err.to_string()))
        .transpose()
}

fn effective_strict_paths_mode(
    strict_paths_override: Option<StrictPathsMode>,
) -> Result<StrictPathsMode, String> {
    if let Some(mode) = strict_paths_override {
        return Ok(mode);
    }

    match std::env::var("ZCCACHE_STRICT_PATHS") {
        Ok(value) => StrictPathsMode::parse(&value).map_err(|err| err.to_string()),
        Err(std::env::VarError::NotPresent) => Ok(StrictPathsMode::Off),
        Err(std::env::VarError::NotUnicode(_)) => {
            Err("ZCCACHE_STRICT_PATHS is not valid Unicode".to_string())
        }
    }
}

fn set_client_env(env: &mut Vec<(String, String)>, key: &str, value: String) {
    if let Some((_, existing)) = env.iter_mut().find(|(env_key, _)| env_key == key) {
        *existing = value;
    } else {
        env.push((key.to_string(), value));
    }
}

/// Wrap a compiler or tool invocation.
///
/// `args` is the full command: ["clang++", "-c", "foo.cpp", "-o", "foo.o"]
/// or ["ar", "rcs", "libfoo.a", "a.o", "b.o"]
///
/// If the first arg is a known archiver (ar, llvm-ar, lib.exe), routes to
/// the link/archive path. Otherwise, routes to the compile path.
///
/// If ZCCACHE_SESSION_ID is set, uses that session and sends the tool
/// as a per-request override. If unset, auto-creates an ephemeral session.
fn run_wrap(args: &[String], strict_paths_override: Option<StrictPathsMode>) -> ExitCode {
    if args.is_empty() {
        eprintln!("usage: zccache <compiler|tool> <args...>");
        return ExitCode::FAILURE;
    }

    // ZCCACHE_DISABLE=1 — passthrough to compiler/tool without caching.
    if std::env::var("ZCCACHE_DISABLE").is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true")) {
        return run_passthrough(args);
    }

    let strict_paths_mode = match effective_strict_paths_mode(strict_paths_override) {
        Ok(mode) => mode,
        Err(err) => {
            eprintln!("zccache: {err}");
            return ExitCode::FAILURE;
        }
    };

    // Normalize MSYS paths (e.g. /c/Users/... → C:\Users\...) on Windows,
    // then resolve to an absolute path so the daemon can find it.
    let wrapped_tool = resolve_compiler_path(&args[0]);
    let tool_args: Vec<String> = if args.len() > 1 {
        args[1..].to_vec()
    } else {
        Vec::new()
    };

    let cwd = std::env::current_dir().unwrap_or_default();

    let mut client_env: Vec<(String, String)> = std::env::vars().collect();
    if let Some(mode) = strict_paths_override {
        set_client_env(
            &mut client_env,
            "ZCCACHE_STRICT_PATHS",
            mode.as_str().to_string(),
        );
    }
    let endpoint = resolve_endpoint(None);

    // Release the CWD handle on the build directory. On Windows, a process's
    // CWD holds an implicit kernel handle that prevents the directory from
    // being deleted. We've captured everything we need into local variables.
    let _ = std::env::set_current_dir(std::env::temp_dir());

    // Check if this is a rustfmt invocation — handle via format cache path
    if zccache_compiler::detect_family(&args[0]).is_formatter() {
        return run_rustfmt_cached(&wrapped_tool, &tool_args, &cwd);
    }

    // Check if this is an archiver or linker tool (including gcc -shared)
    if zccache_compiler::parse_archiver::is_archiver(&args[0])
        || zccache_compiler::parse_linker::is_link_invocation(&args[0], &tool_args)
    {
        return run_async(cmd_link_ephemeral(
            &endpoint,
            &wrapped_tool,
            tool_args,
            cwd.into(),
            client_env,
        ));
    }

    if let Err(err) = zccache_compiler::strict_paths::validate_args(&tool_args, strict_paths_mode) {
        eprintln!("{}", err.diagnostic(&args[0], &tool_args));
        return ExitCode::FAILURE;
    }

    // Otherwise, treat as a compiler invocation
    match std::env::var("ZCCACHE_SESSION_ID") {
        Ok(session_id) => {
            if session_id.is_empty() {
                eprintln!("ZCCACHE_SESSION_ID is empty");
                return ExitCode::FAILURE;
            }
            run_async(cmd_compile(
                &endpoint,
                &session_id,
                tool_args,
                cwd.into(),
                wrapped_tool,
                client_env,
            ))
        }
        Err(_) => {
            // No session — auto-create an ephemeral one for this compilation.
            run_async(cmd_compile_ephemeral(
                &endpoint,
                &wrapped_tool,
                tool_args,
                cwd.into(),
                client_env,
            ))
        }
    }
}

/// Resolve a compiler name/path to an absolute path.
/// Normalizes MSYS paths on Windows, then searches PATH if not already absolute.
fn resolve_compiler_path(compiler: &str) -> NormalizedPath {
    let normalized = zccache_core::path::normalize_msys_path(compiler);
    let path = Path::new(&normalized);

    // Already absolute — return as-is.
    if path.is_absolute() {
        return normalized.into();
    }

    // Search PATH for the compiler.
    match which_on_path(&normalized) {
        Some(abs) => abs,
        None => normalized.into(), // Let the daemon report the error.
    }
}

async fn cmd_compile(
    endpoint: &str,
    session_id: &str,
    args: Vec<String>,
    cwd: NormalizedPath,
    compiler: NormalizedPath,
    client_env: Vec<(String, String)>,
) -> ExitCode {
    let mut conn = match connect(endpoint).await {
        Ok(c) => c,
        Err(e) => {
            eprintln!("cannot connect to daemon at {endpoint}: {e}");
            return ExitCode::FAILURE;
        }
    };

    if let Err(e) = conn
        .send(&zccache_protocol::Request::Compile {
            session_id: session_id.to_string(),
            args,
            cwd,
            compiler,
            env: Some(client_env),
        })
        .await
    {
        eprintln!("zccache: failed to send to daemon: {e}");
        return ExitCode::FAILURE;
    }

    let recv_result = match conn.recv().await {
        Ok(r) => r,
        Err(e) => {
            eprintln!("zccache: broken connection to daemon: {e}");
            return ExitCode::FAILURE;
        }
    };
    match recv_result {
        Some(zccache_protocol::Response::CompileResult {
            exit_code,
            stdout,
            stderr,
            ..
        }) => {
            // Relay compiler output
            use std::io::Write;
            let _ = std::io::stdout().write_all(&stdout);
            let _ = std::io::stderr().write_all(&stderr);
            exit_code_from_i32(exit_code)
        }
        Some(zccache_protocol::Response::Error { message }) => {
            eprintln!("zccache error: {message}");
            ExitCode::FAILURE
        }
        None => {
            eprintln!("zccache: lost connection to daemon (no response received)");
            ExitCode::FAILURE
        }
        Some(other) => {
            eprintln!("zccache: unexpected response from daemon: {other:?}");
            ExitCode::FAILURE
        }
    }
}

/// Ephemeral session: single-roundtrip compile (session start + compile + session end
/// in one IPC message). Used when ZCCACHE_SESSION_ID is not set (drop-in mode).
async fn cmd_compile_ephemeral(
    endpoint: &str,
    compiler: &Path,
    args: Vec<String>,
    cwd: NormalizedPath,
    client_env: Vec<(String, String)>,
) -> ExitCode {
    // Ensure daemon is running and version-compatible.
    if let Err(e) = ensure_daemon(endpoint).await {
        eprintln!("cannot start daemon at {endpoint}: {e}");
        return ExitCode::FAILURE;
    }
    let mut conn = match connect(endpoint).await {
        Ok(c) => c,
        Err(e) => {
            eprintln!("cannot connect to daemon at {endpoint}: {e}");
            return ExitCode::FAILURE;
        }
    };

    if let Err(e) = conn
        .send(&zccache_protocol::Request::CompileEphemeral {
            client_pid: std::process::id(),
            working_dir: cwd.clone(),
            compiler: compiler.into(),
            args,
            cwd,
            env: Some(client_env),
        })
        .await
    {
        eprintln!("zccache: failed to send to daemon: {e}");
        return ExitCode::FAILURE;
    }

    let recv_result = match conn.recv().await {
        Ok(r) => r,
        Err(e) => {
            eprintln!("zccache: broken connection to daemon: {e}");
            return ExitCode::FAILURE;
        }
    };
    match recv_result {
        Some(zccache_protocol::Response::CompileResult {
            exit_code,
            stdout,
            stderr,
            ..
        }) => {
            use std::io::Write;
            let _ = std::io::stdout().write_all(&stdout);
            let _ = std::io::stderr().write_all(&stderr);
            exit_code_from_i32(exit_code)
        }
        Some(zccache_protocol::Response::Error { message }) => {
            eprintln!("zccache error: {message}");
            ExitCode::FAILURE
        }
        None => {
            eprintln!("zccache: lost connection to daemon (no response received)");
            ExitCode::FAILURE
        }
        Some(other) => {
            eprintln!("zccache: unexpected response from daemon: {other:?}");
            ExitCode::FAILURE
        }
    }
}

/// Ephemeral link/archive: single-roundtrip for `zccache ar ...` etc.
async fn cmd_link_ephemeral(
    endpoint: &str,
    tool: &Path,
    args: Vec<String>,
    cwd: NormalizedPath,
    client_env: Vec<(String, String)>,
) -> ExitCode {
    if let Err(e) = ensure_daemon(endpoint).await {
        eprintln!("cannot start daemon at {endpoint}: {e}");
        return ExitCode::FAILURE;
    }
    let mut conn = match connect(endpoint).await {
        Ok(c) => c,
        Err(e) => {
            eprintln!("cannot connect to daemon at {endpoint}: {e}");
            return ExitCode::FAILURE;
        }
    };

    if let Err(e) = conn
        .send(&zccache_protocol::Request::LinkEphemeral {
            client_pid: std::process::id(),
            tool: tool.into(),
            args,
            cwd,
            env: Some(client_env),
        })
        .await
    {
        eprintln!("zccache: failed to send to daemon: {e}");
        return ExitCode::FAILURE;
    }

    let recv_result = match conn.recv().await {
        Ok(r) => r,
        Err(e) => {
            eprintln!("zccache: broken connection to daemon: {e}");
            return ExitCode::FAILURE;
        }
    };
    match recv_result {
        Some(zccache_protocol::Response::LinkResult {
            exit_code,
            stdout,
            stderr,
            warning,
            ..
        }) => {
            use std::io::Write;
            let _ = std::io::stdout().write_all(&stdout);
            let _ = std::io::stderr().write_all(&stderr);
            if let Some(w) = warning {
                eprintln!("zccache warning: {w}");
            }
            exit_code_from_i32(exit_code)
        }
        Some(zccache_protocol::Response::Error { message }) => {
            eprintln!("zccache error: {message}");
            ExitCode::FAILURE
        }
        None => {
            eprintln!("zccache: lost connection to daemon (no response received)");
            ExitCode::FAILURE
        }
        Some(other) => {
            eprintln!("zccache: unexpected response from daemon: {other:?}");
            ExitCode::FAILURE
        }
    }
}

// ─── Daemon auto-start ─────────────────────────────────────────────────────

enum VersionCheck {
    Ok,
    /// Daemon is newer than client — safe to proceed.
    DaemonNewer {
        daemon_ver: String,
    },
    /// Daemon is older than client — must restart.
    DaemonOlder {
        daemon_ver: String,
    },
    /// Could not connect to the daemon at all.
    Unreachable,
    /// Connected but could not complete the version exchange (protocol mismatch, etc.).
    CommError,
}

/// Connect to the daemon and compare its version to ours.
async fn check_daemon_version(endpoint: &str) -> VersionCheck {
    let mut conn = match connect(endpoint).await {
        Ok(c) => c,
        Err(_) => return VersionCheck::Unreachable,
    };
    if conn.send(&zccache_protocol::Request::Status).await.is_err() {
        return VersionCheck::CommError;
    }
    match conn.recv::<zccache_protocol::Response>().await {
        Ok(Some(zccache_protocol::Response::Status(s))) => {
            if s.version == zccache_core::VERSION {
                return VersionCheck::Ok;
            }
            let client_ver = zccache_core::version::current();
            match zccache_core::version::Version::parse(&s.version) {
                Some(daemon_ver) => match daemon_ver.cmp(&client_ver) {
                    std::cmp::Ordering::Equal => VersionCheck::Ok,
                    std::cmp::Ordering::Greater => VersionCheck::DaemonNewer {
                        daemon_ver: s.version,
                    },
                    std::cmp::Ordering::Less => VersionCheck::DaemonOlder {
                        daemon_ver: s.version,
                    },
                },
                // Unparseable daemon version → treat as older (safe default)
                None => VersionCheck::DaemonOlder {
                    daemon_ver: s.version,
                },
            }
        }
        _ => VersionCheck::CommError,
    }
}

/// Spawn a new daemon and wait for it to become ready.
async fn spawn_and_wait(endpoint: &str) -> Result<(), String> {
    let daemon_bin = find_daemon_binary().ok_or("cannot find zccache-daemon binary")?;
    tracing::debug!(?daemon_bin, %endpoint, "spawning daemon");
    spawn_daemon(&daemon_bin, endpoint)?;

    for _ in 0..100 {
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        if connect(endpoint).await.is_ok() {
            return Ok(());
        }
    }
    Err("daemon started but not accepting connections after 10s".to_string())
}

/// Ensure the daemon is running **and version-compatible**.
///
/// Version checking is asymmetric: a newer daemon is accepted (it's
/// backward-compatible), but an older daemon triggers a hard error
/// telling the user to run `zccache stop` first.
///
/// Handles concurrent calls gracefully: when multiple processes race to start
/// the daemon, only one wins the bind. The losers detect this and connect to
/// the winning daemon instead of failing.
/// Stop a stale daemon that is unreachable or version-incompatible.
///
/// Attempts graceful shutdown via IPC first, then falls back to force-killing
/// the process via the lock file PID. Waits for the endpoint to be released.
async fn stop_stale_daemon(endpoint: &str) {
    // Try graceful shutdown via IPC
    if let Ok(mut conn) = connect(endpoint).await {
        let _ = conn.send(&zccache_protocol::Request::Shutdown).await;
        // Give it a moment to process the shutdown
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
    }

    // Force-kill via lock file PID if the daemon is still alive
    if let Some(pid) = zccache_ipc::check_running_daemon() {
        tracing::debug!(pid, "force-killing stale daemon process");
        if zccache_ipc::force_kill_process(pid).is_ok() {
            for _ in 0..50 {
                if !zccache_ipc::is_process_alive(pid) {
                    break;
                }
                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            }
        }
        zccache_ipc::remove_lock_file();
    }

    // Wait briefly for the endpoint (named pipe / socket) to be fully released
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}

async fn ensure_daemon(endpoint: &str) -> Result<(), String> {
    // Fast path: connect + version check
    match check_daemon_version(endpoint).await {
        VersionCheck::Ok => return Ok(()),
        VersionCheck::DaemonNewer { daemon_ver } => {
            tracing::debug!(
                daemon_ver,
                client_ver = zccache_core::VERSION,
                "daemon is newer than client, proceeding"
            );
            return Ok(());
        }
        VersionCheck::DaemonOlder { daemon_ver } => {
            tracing::info!(
                daemon_ver,
                client_ver = zccache_core::VERSION,
                "daemon is older than client, auto-recovering"
            );
            stop_stale_daemon(endpoint).await;
            return spawn_and_wait(endpoint).await;
        }
        VersionCheck::CommError => {
            tracing::info!("cannot communicate with daemon, auto-recovering");
            stop_stale_daemon(endpoint).await;
            return spawn_and_wait(endpoint).await;
        }
        VersionCheck::Unreachable => {
            // Fall through to lock-file check / spawn
        }
    }

    // Check lock file for a running daemon we just can't reach yet
    if let Some(pid) = zccache_ipc::check_running_daemon() {
        for _ in 0..20 {
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            match check_daemon_version(endpoint).await {
                VersionCheck::Ok => return Ok(()),
                VersionCheck::DaemonNewer { daemon_ver } => {
                    tracing::debug!(
                        daemon_ver,
                        client_ver = zccache_core::VERSION,
                        "daemon is newer than client, proceeding"
                    );
                    return Ok(());
                }
                VersionCheck::DaemonOlder { daemon_ver } => {
                    tracing::info!(
                        daemon_ver,
                        client_ver = zccache_core::VERSION,
                        "daemon is older than client during startup, auto-recovering"
                    );
                    stop_stale_daemon(endpoint).await;
                    return spawn_and_wait(endpoint).await;
                }
                VersionCheck::CommError => {
                    tracing::info!(
                        "cannot communicate with daemon during startup, auto-recovering"
                    );
                    stop_stale_daemon(endpoint).await;
                    return spawn_and_wait(endpoint).await;
                }
                VersionCheck::Unreachable => continue,
            }
        }
        return Err(format!(
            "daemon process {pid} exists but not accepting connections"
        ));
    }

    // No daemon running — spawn one
    spawn_and_wait(endpoint).await
}

/// Find the daemon binary. Looks next to the CLI binary first, then on PATH.
fn find_daemon_binary() -> Option<NormalizedPath> {
    let name = if cfg!(windows) {
        "zccache-daemon.exe"
    } else {
        "zccache-daemon"
    };

    // Look next to the CLI binary
    if let Ok(exe) = std::env::current_exe() {
        if let Some(dir) = exe.parent() {
            let candidate = dir.join(name);
            if candidate.exists() {
                return Some(candidate.into());
            }
        }
    }

    // Fall back to PATH
    which_on_path(name)
}

/// Simple PATH lookup (no external crate needed).
/// On Windows, also tries appending `.exe` if the name has no extension.
fn which_on_path(name: &str) -> Option<NormalizedPath> {
    let path_var = std::env::var_os("PATH")?;
    for dir in std::env::split_paths(&path_var) {
        let candidate = dir.join(name);
        if candidate.is_file() {
            return Some(candidate.into());
        }
        // On Windows, try with .exe suffix
        #[cfg(windows)]
        if std::path::Path::new(name).extension().is_none() {
            let with_exe = dir.join(format!("{name}.exe"));
            if with_exe.is_file() {
                return Some(with_exe.into());
            }
        }
    }
    None
}

/// Spawn the daemon as a detached background process.
///
/// On Windows, we must prevent the daemon from inheriting pipe handles.
/// When the CLI is invoked via `subprocess.run(capture_output=True)` (e.g. from
/// Python/meson), the parent creates pipes for stdout/stderr. If the daemon
/// inherits these handles, the parent hangs forever waiting for pipe closure
/// because the daemon never exits.
fn spawn_daemon(bin: &std::path::Path, endpoint: &str) -> Result<(), String> {
    // Best-effort: GC stale copies, then spawn from a fresh copy in the
    // zccache global runtime-binaries dir so the install path stays
    // overwritable. See issue #134.
    zccache_cli::gc_runtime_binaries();
    let bin_owned: std::path::PathBuf;
    let spawn_bin: &std::path::Path = match zccache_cli::prepare_daemon_exe(bin) {
        Ok(p) => {
            bin_owned = p;
            &bin_owned
        }
        Err(_) => bin,
    };

    let mut cmd = std::process::Command::new(spawn_bin);
    cmd.args(["--foreground", "--endpoint", endpoint]);

    // Detach stdio so the daemon doesn't hold our console
    cmd.stdin(std::process::Stdio::null());
    cmd.stdout(std::process::Stdio::null());
    cmd.stderr(std::process::Stdio::null());

    apply_cli_spawn_lineage(&mut cmd);

    // Platform-specific: prevent console window on Windows and avoid
    // inheriting parent pipe handles (which cause subprocess hangs).
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
        cmd.creation_flags(CREATE_NO_WINDOW);

        // Mark our stdout/stderr as non-inheritable before spawning the daemon.
        // This prevents the daemon from inheriting pipe handles that a grandparent
        // process (e.g. Python subprocess.run) may have created for capture.
        // Without this, the daemon keeps the pipe open indefinitely, causing the
        // grandparent to hang waiting for EOF on the pipe.
        disable_handle_inheritance();
    }

    cmd.spawn()
        .map_err(|e| format!("failed to spawn daemon: {e}"))?;

    // Re-enable inheritance for our own handles (in case we do further spawns)
    #[cfg(windows)]
    restore_handle_inheritance();

    Ok(())
}

/// Initialize spawn-lineage env vars on a command the CLI is about to spawn.
///
/// Mirrors the daemon-side propagation in `zccache_daemon::lineage` so process
/// attribution (orphan tracking, running-process scanners) sees a consistent
/// chain across CLI -> daemon -> compiler hops. The chain is initialized with
/// the CLI's PID, and the originator marker is set to `zccache-cli:<pid>`
/// unless an outer tool has already claimed it.
fn apply_cli_spawn_lineage(cmd: &mut std::process::Command) {
    const ENV_ORIGINATOR: &str = "RUNNING_PROCESS_ORIGINATOR";
    const ENV_LINEAGE: &str = "ZCCACHE_LINEAGE";
    const ENV_PARENT_PID: &str = "ZCCACHE_PARENT_PID";
    const ENV_CLIENT_PID: &str = "ZCCACHE_CLIENT_PID";

    let cli_pid = std::process::id();

    if std::env::var(ENV_ORIGINATOR).is_err() {
        cmd.env(ENV_ORIGINATOR, format!("zccache-cli:{cli_pid}"));
    }

    let chain = match std::env::var(ENV_LINEAGE) {
        Ok(existing)
            if existing
                .rsplit_once('>')
                .map_or(existing.as_str(), |(_, last)| last)
                != cli_pid.to_string() =>
        {
            format!("{existing}>{cli_pid}")
        }
        Ok(existing) => existing,
        Err(_) => cli_pid.to_string(),
    };
    cmd.env(ENV_LINEAGE, chain);
    cmd.env(ENV_PARENT_PID, cli_pid.to_string());
    cmd.env(ENV_CLIENT_PID, cli_pid.to_string());
}

/// On Windows, mark stdout/stderr handles as non-inheritable so that child
/// processes (the daemon) do not inherit pipe handles from grandparent processes.
#[cfg(windows)]
fn disable_handle_inheritance() {
    use std::os::windows::io::AsRawHandle;

    extern "system" {
        fn SetHandleInformation(handle: *mut std::ffi::c_void, mask: u32, flags: u32) -> i32;
    }
    const HANDLE_FLAG_INHERIT: u32 = 1;

    // Safety: we're calling a standard Win32 API with valid handle values.
    // The handles come from Rust's stdout/stderr which are always valid.
    unsafe {
        let stdout = std::io::stdout();
        let stderr = std::io::stderr();
        SetHandleInformation(stdout.as_raw_handle() as *mut _, HANDLE_FLAG_INHERIT, 0);
        SetHandleInformation(stderr.as_raw_handle() as *mut _, HANDLE_FLAG_INHERIT, 0);
    }
}

/// Restore stdout/stderr handles as inheritable (undo `disable_handle_inheritance`).
#[cfg(windows)]
fn restore_handle_inheritance() {
    use std::os::windows::io::AsRawHandle;

    extern "system" {
        fn SetHandleInformation(handle: *mut std::ffi::c_void, mask: u32, flags: u32) -> i32;
    }
    const HANDLE_FLAG_INHERIT: u32 = 1;

    unsafe {
        let stdout = std::io::stdout();
        let stderr = std::io::stderr();
        SetHandleInformation(
            stdout.as_raw_handle() as *mut _,
            HANDLE_FLAG_INHERIT,
            HANDLE_FLAG_INHERIT,
        );
        SetHandleInformation(
            stderr.as_raw_handle() as *mut _,
            HANDLE_FLAG_INHERIT,
            HANDLE_FLAG_INHERIT,
        );
    }
}

// ─── Helpers ───────────────────────────────────────────────────────────────

/// Platform-correct connect (returns different types on Unix vs Windows).
#[cfg(unix)]
async fn connect(endpoint: &str) -> Result<zccache_ipc::IpcConnection, zccache_ipc::IpcError> {
    zccache_ipc::connect(endpoint).await
}

#[cfg(windows)]
async fn connect(
    endpoint: &str,
) -> Result<zccache_ipc::IpcClientConnection, zccache_ipc::IpcError> {
    zccache_ipc::connect(endpoint).await
}

fn resolve_endpoint(explicit: Option<&str>) -> String {
    if let Some(ep) = explicit {
        return ep.to_string();
    }
    if let Ok(ep) = std::env::var("ZCCACHE_ENDPOINT") {
        return ep;
    }
    zccache_ipc::default_endpoint()
}

fn run_async(future: impl std::future::Future<Output = ExitCode>) -> ExitCode {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("failed to create tokio runtime")
        .block_on(future)
}

fn format_uptime(secs: u64) -> String {
    if secs < 60 {
        format!("{secs}s")
    } else if secs < 3600 {
        format!("{}m {}s", secs / 60, secs % 60)
    } else {
        let h = secs / 3600;
        let m = (secs % 3600) / 60;
        format!("{h}h {m}m")
    }
}

fn format_duration_ms(ms: u64) -> String {
    if ms < 1000 {
        format!("{ms}ms")
    } else if ms < 60_000 {
        format!("{:.1}s", ms as f64 / 1000.0)
    } else {
        let secs = ms / 1000;
        format!("{}m {}s", secs / 60, secs % 60)
    }
}

fn format_bytes(bytes: u64) -> String {
    if bytes == 0 {
        "0 B".to_string()
    } else if bytes < 1024 {
        format!("{bytes} B")
    } else if bytes < 1024 * 1024 {
        format!("{:.1} KB", bytes as f64 / 1024.0)
    } else if bytes < 1024 * 1024 * 1024 {
        format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
    } else {
        format!("{:.1} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
    }
}

fn init_tracing() {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn")),
        )
        .init();
}

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

    #[test]
    fn exit_code_zero_stays_zero() {
        assert_eq!(exit_code_from_i32(0), ExitCode::from(0));
    }

    #[test]
    fn exit_code_one_stays_one() {
        assert_eq!(exit_code_from_i32(1), ExitCode::from(1));
    }

    #[test]
    fn exit_code_255_stays_255() {
        assert_eq!(exit_code_from_i32(255), ExitCode::from(255));
    }

    #[test]
    fn exit_code_256_becomes_one_not_zero() {
        // Without the fix, 256 as u8 == 0, masking the failure.
        assert_ne!(exit_code_from_i32(256), ExitCode::from(0));
        assert_eq!(exit_code_from_i32(256), ExitCode::from(1));
    }

    #[test]
    fn exit_code_512_becomes_one_not_zero() {
        assert_eq!(exit_code_from_i32(512), ExitCode::from(1));
    }

    #[test]
    fn exit_code_negative_preserves_failure() {
        // -1 & 0xFF == 255
        assert_ne!(exit_code_from_i32(-1), ExitCode::from(0));
        assert_eq!(exit_code_from_i32(-1), ExitCode::from(255));
    }

    #[test]
    fn exit_code_257_keeps_low_byte() {
        // 257 & 0xFF == 1, non-zero, so kept as-is.
        assert_eq!(exit_code_from_i32(257), ExitCode::from(1));
    }

    #[test]
    fn rust_plan_cli_parses_validate_restore_save() {
        let validate = Cli::try_parse_from([
            "zccache",
            "rust-plan",
            "validate",
            "--plan",
            "plan.json",
            "--json",
        ])
        .unwrap();
        assert!(matches!(
            validate.command,
            Some(Commands::RustPlan {
                action: RustPlanCommands::Validate { json: true, .. }
            })
        ));

        let restore = Cli::try_parse_from([
            "zccache",
            "rust-plan",
            "restore",
            "--plan",
            "plan.json",
            "--backend",
            "local",
            "--session-id",
            "session-123",
            "--endpoint",
            "tcp:127.0.0.1:9",
            "--journal",
            "session.jsonl",
            "--cache-dir",
            ".cache/rust-plan",
        ])
        .unwrap();
        assert!(matches!(
            restore.command,
            Some(Commands::RustPlan {
                action: RustPlanCommands::Restore {
                    backend: RustPlanBackendArg::Local,
                    session_id: Some(_),
                    endpoint: Some(_),
                    journal: Some(_),
                    ..
                }
            })
        ));

        let save = Cli::try_parse_from([
            "zccache",
            "rust-plan",
            "save",
            "--plan",
            "plan.json",
            "--backend",
            "gha",
        ])
        .unwrap();
        assert!(matches!(
            save.command,
            Some(Commands::RustPlan {
                action: RustPlanCommands::Save {
                    backend: RustPlanBackendArg::Gha,
                    ..
                }
            })
        ));
    }

    #[test]
    fn rust_plan_session_stats_json_separates_compile_cache_stats() {
        let stats = zccache_protocol::SessionStats {
            duration_ms: 1000,
            compilations: 10,
            hits: 7,
            misses: 3,
            non_cacheable: 2,
            errors: 1,
            time_saved_ms: 250,
            unique_sources: 8,
            bytes_read: 1024,
            bytes_written: 2048,
        };
        let json = session_stats_json("session-123", &stats);
        assert_eq!(json["status"], "ok");
        assert_eq!(json["session_id"], "session-123");
        assert_eq!(json["compilations"], 10);
        assert_eq!(json["hits"], 7);
        assert_eq!(json["misses"], 3);
        assert_eq!(json["hit_rate"].as_f64().unwrap(), 0.7);
    }

    #[test]
    fn rust_plan_gha_version_is_stable_for_backend_diagnostics() {
        let key = "rust-plan-v1-test";
        assert_eq!(rust_plan_gha_version(key), rust_plan_gha_version(key));
        assert_ne!(rust_plan_gha_version(key), rust_plan_gha_version("other"));
    }

    #[test]
    fn warm_restores_rust_artifacts_to_correct_paths() {
        let dir = tempfile::tempdir().unwrap();
        let cache_dir = dir.path().join("cache");
        let artifact_dir = cache_dir.join("artifacts");
        let index_path = cache_dir.join("index.redb");
        let target_dir = dir.path().join("target");

        std::fs::create_dir_all(&artifact_dir).unwrap();

        // Create a fake artifact store with two Rust crates
        let store = zccache_artifact::ArtifactStore::open(&index_path).unwrap();

        // Artifact 1: libserde-abc123.rlib + libserde-abc123.rmeta + serde-abc123.d
        let key1 = "aaaaaaaabbbbbbbb";
        let idx1 = zccache_artifact::ArtifactIndex::new(
            vec![
                "libserde-abc123.rlib".to_string(),
                "libserde-abc123.rmeta".to_string(),
                "serde-abc123.d".to_string(),
            ],
            vec![100, 50, 10],
            vec![],
            vec![],
            0,
        );
        store.insert(key1, &idx1).unwrap();
        // Write payload files on disk
        std::fs::write(artifact_dir.join(format!("{key1}_0")), b"rlib-content").unwrap();
        std::fs::write(artifact_dir.join(format!("{key1}_1")), b"rmeta-content").unwrap();
        std::fs::write(artifact_dir.join(format!("{key1}_2")), b"dep-info").unwrap();

        // Artifact 2: libproc_macro2-def456.rlib
        let key2 = "ccccccccdddddddd";
        let idx2 = zccache_artifact::ArtifactIndex::new(
            vec!["libproc_macro2-def456.rlib".to_string()],
            vec![200],
            vec![],
            vec![],
            0,
        );
        store.insert(key2, &idx2).unwrap();
        std::fs::write(artifact_dir.join(format!("{key2}_0")), b"proc-macro2-rlib").unwrap();

        // Artifact 3: NOT Rust (C++ object file) — should be filtered out
        let key3 = "eeeeeeeeffffffff";
        let idx3 = zccache_artifact::ArtifactIndex::new(
            vec!["foo.o".to_string()],
            vec![300],
            vec![],
            vec![],
            0,
        );
        store.insert(key3, &idx3).unwrap();
        std::fs::write(artifact_dir.join(format!("{key3}_0")), b"object-file").unwrap();

        drop(store); // Release redb lock

        // Run warm
        let (restored, skipped, errors) =
            warm_target(&index_path, &artifact_dir, &target_dir, "debug", None).unwrap();

        // Verify counts
        assert_eq!(errors, 0, "should have 0 errors");
        assert_eq!(
            restored, 5,
            "should restore all 5 files (3 serde + 1 proc_macro2 + 1 C++ .o)"
        );
        assert_eq!(skipped, 0, "all payloads exist on disk");

        // Verify files exist at correct paths
        let deps = target_dir.join("debug").join("deps");
        assert!(
            deps.join("libserde-abc123.rlib").exists(),
            "serde rlib missing"
        );
        assert!(
            deps.join("libserde-abc123.rmeta").exists(),
            "serde rmeta missing"
        );
        assert!(
            deps.join("serde-abc123.d").exists(),
            "serde dep-info missing"
        );
        assert!(
            deps.join("libproc_macro2-def456.rlib").exists(),
            "proc_macro2 rlib missing"
        );

        // Verify content is correct
        assert_eq!(
            std::fs::read(deps.join("libserde-abc123.rlib")).unwrap(),
            b"rlib-content"
        );
        assert_eq!(
            std::fs::read(deps.join("libproc_macro2-def456.rlib")).unwrap(),
            b"proc-macro2-rlib"
        );

        // Verify C++ artifact IS restored (warm restores everything, not just Rust)
        assert!(
            deps.join("foo.o").exists(),
            "C++ .o file should also be in deps/"
        );
        assert_eq!(std::fs::read(deps.join("foo.o")).unwrap(), b"object-file");

        // Verify mtime is recent (within 5 seconds)
        let meta = std::fs::metadata(deps.join("libserde-abc123.rlib")).unwrap();
        let age = meta.modified().unwrap().elapsed().unwrap();
        assert!(age.as_secs() < 5, "mtime should be fresh, got {age:?}");
    }

    #[test]
    fn warm_skips_missing_payloads() {
        let dir = tempfile::tempdir().unwrap();
        let cache_dir = dir.path().join("cache");
        let artifact_dir = cache_dir.join("artifacts");
        let index_path = cache_dir.join("index.redb");
        let target_dir = dir.path().join("target");

        std::fs::create_dir_all(&artifact_dir).unwrap();

        let store = zccache_artifact::ArtifactStore::open(&index_path).unwrap();
        let key = "1111111122222222";
        let idx = zccache_artifact::ArtifactIndex::new(
            vec!["libfoo-xyz.rlib".to_string()],
            vec![100],
            vec![],
            vec![],
            0,
        );
        store.insert(key, &idx).unwrap();
        // DON'T write the payload file — simulate missing artifact on disk
        drop(store);

        let (restored, skipped, errors) =
            warm_target(&index_path, &artifact_dir, &target_dir, "debug", None).unwrap();

        assert_eq!(restored, 0);
        assert_eq!(skipped, 1, "should skip 1 missing payload");
        assert_eq!(errors, 0);
    }

    #[test]
    fn warm_returns_error_on_missing_index() {
        let dir = tempfile::tempdir().unwrap();
        let result = warm_target(
            &dir.path().join("nonexistent.redb"),
            &dir.path().join("artifacts"),
            &dir.path().join("target"),
            "debug",
            None,
        );
        assert!(result.is_err());
    }

    // ── Helper: create a fake artifact store with test data ──────

    fn make_test_store(dir: &Path) -> (PathBuf, PathBuf) {
        let cache_dir = dir.join("cache");
        let artifact_dir = cache_dir.join("artifacts");
        let index_path = cache_dir.join("index.redb");
        std::fs::create_dir_all(&artifact_dir).unwrap();

        let store = zccache_artifact::ArtifactStore::open(&index_path).unwrap();

        // serde (in a typical Cargo.lock)
        let k1 = "aaaa0001";
        store
            .insert(
                k1,
                &zccache_artifact::ArtifactIndex::new(
                    vec![
                        "libserde-abc123.rlib".into(),
                        "libserde-abc123.rmeta".into(),
                        "serde-abc123.d".into(),
                    ],
                    vec![100, 50, 10],
                    vec![],
                    vec![],
                    0,
                ),
            )
            .unwrap();
        std::fs::write(artifact_dir.join(format!("{k1}_0")), b"serde-rlib").unwrap();
        std::fs::write(artifact_dir.join(format!("{k1}_1")), b"serde-rmeta").unwrap();
        std::fs::write(artifact_dir.join(format!("{k1}_2")), b"serde-d").unwrap();

        // proc-macro2 (hyphen → underscore in filename)
        let k2 = "aaaa0002";
        store
            .insert(
                k2,
                &zccache_artifact::ArtifactIndex::new(
                    vec!["libproc_macro2-def456.rlib".into()],
                    vec![200],
                    vec![],
                    vec![],
                    0,
                ),
            )
            .unwrap();
        std::fs::write(artifact_dir.join(format!("{k2}_0")), b"proc-macro2-rlib").unwrap();

        // tokio (NOT in our test lockfile)
        let k3 = "aaaa0003";
        store
            .insert(
                k3,
                &zccache_artifact::ArtifactIndex::new(
                    vec!["libtokio-ghi789.rlib".into()],
                    vec![300],
                    vec![],
                    vec![],
                    0,
                ),
            )
            .unwrap();
        std::fs::write(artifact_dir.join(format!("{k3}_0")), b"tokio-rlib").unwrap();

        // C++ object file (no crate name pattern)
        let k4 = "aaaa0004";
        store
            .insert(
                k4,
                &zccache_artifact::ArtifactIndex::new(
                    vec!["foo.o".into()],
                    vec![50],
                    vec![],
                    vec![],
                    0,
                ),
            )
            .unwrap();
        std::fs::write(artifact_dir.join(format!("{k4}_0")), b"cpp-object").unwrap();

        drop(store);
        (index_path, artifact_dir)
    }

    fn write_lockfile(dir: &Path, crates: &[&str]) -> PathBuf {
        let lockfile = dir.join("Cargo.lock");
        let mut content = String::from("# This file is automatically @generated\nversion = 3\n\n");
        for name in crates {
            content.push_str(&format!(
                "[[package]]\nname = \"{name}\"\nversion = \"1.0.0\"\n\n"
            ));
        }
        std::fs::write(&lockfile, &content).unwrap();
        lockfile
    }

    // ── Lockfile parsing tests ───────────────────────────────────

    #[test]
    fn parse_lockfile_extracts_crate_names() {
        let dir = tempfile::tempdir().unwrap();
        let lf = write_lockfile(dir.path(), &["serde", "proc-macro2", "unicode-ident"]);
        let crates = parse_lockfile_crates(&lf).unwrap();
        assert!(crates.contains("serde"));
        assert!(
            crates.contains("proc_macro2"),
            "hyphens should be underscores"
        );
        assert!(crates.contains("unicode_ident"));
        assert!(!crates.contains("tokio"), "tokio not in lockfile");
    }

    #[test]
    fn artifact_matches_lockfile_basic() {
        let mut allowed = std::collections::HashSet::new();
        allowed.insert("serde".to_string());
        allowed.insert("proc_macro2".to_string());

        assert!(artifact_matches_lockfile("libserde-abc123.rlib", &allowed));
        assert!(artifact_matches_lockfile("libserde-abc123.rmeta", &allowed));
        assert!(artifact_matches_lockfile("serde-abc123.d", &allowed));
        assert!(artifact_matches_lockfile(
            "libproc_macro2-def456.rlib",
            &allowed
        ));
        assert!(!artifact_matches_lockfile("libtokio-ghi789.rlib", &allowed));
        // No hash separator → allowed (could be build script output)
        assert!(artifact_matches_lockfile("build_script_build", &allowed));
    }

    // ── Strategy tests ───────────────────────────────────────────

    #[test]
    fn warm_without_lockfile_restores_everything() {
        let dir = tempfile::tempdir().unwrap();
        let (index_path, artifact_dir) = make_test_store(dir.path());
        let target_dir = dir.path().join("target");

        let (restored, _, _) =
            warm_target(&index_path, &artifact_dir, &target_dir, "debug", None).unwrap();

        let deps = target_dir.join("debug").join("deps");
        assert_eq!(restored, 6, "without lockfile: restore all 6 files");
        assert!(deps.join("libserde-abc123.rlib").exists());
        assert!(
            deps.join("libtokio-ghi789.rlib").exists(),
            "tokio restored without filter"
        );
        assert!(
            deps.join("foo.o").exists(),
            "C++ file restored without filter"
        );
    }

    #[test]
    fn warm_with_lockfile_filters_to_matching_crates() {
        let dir = tempfile::tempdir().unwrap();
        let (index_path, artifact_dir) = make_test_store(dir.path());
        let target_dir = dir.path().join("target");
        let lockfile = write_lockfile(dir.path(), &["serde", "proc-macro2"]);

        let (restored, skipped, _) = warm_target(
            &index_path,
            &artifact_dir,
            &target_dir,
            "debug",
            Some(&lockfile),
        )
        .unwrap();

        let deps = target_dir.join("debug").join("deps");
        // serde (3) + proc-macro2 (1) + foo.o (1, no hash separator = allowed)
        assert_eq!(restored, 5);
        assert!(deps.join("libserde-abc123.rlib").exists());
        assert!(deps.join("libproc_macro2-def456.rlib").exists());
        assert!(
            !deps.join("libtokio-ghi789.rlib").exists(),
            "tokio NOT in lockfile"
        );
        assert!(
            deps.join("foo.o").exists(),
            "no hash separator = allowed through"
        );
        assert!(skipped > 0, "tokio should be skipped");
    }

    // ── Adversarial tests ────────────────────────────────────────

    #[test]
    fn adversarial_crate_removed_from_lockfile() {
        // Scenario: tokio was in the cache from a previous build,
        // but was removed from Cargo.toml/Cargo.lock.
        // Warm should NOT restore it.
        let dir = tempfile::tempdir().unwrap();
        let (index_path, artifact_dir) = make_test_store(dir.path());
        let target_dir = dir.path().join("target");
        // Lockfile has serde but NOT tokio
        let lockfile = write_lockfile(dir.path(), &["serde"]);

        let (restored, _, _) = warm_target(
            &index_path,
            &artifact_dir,
            &target_dir,
            "debug",
            Some(&lockfile),
        )
        .unwrap();

        let deps = target_dir.join("debug").join("deps");
        assert!(deps.join("libserde-abc123.rlib").exists());
        assert!(
            !deps.join("libtokio-ghi789.rlib").exists(),
            "removed crate must NOT be restored"
        );
        // serde (3) + foo.o (1, no hash separator = allowed)
        assert_eq!(restored, 4);
    }

    #[test]
    fn adversarial_stale_file_in_target_from_previous_warm() {
        // Scenario: previous warm restored tokio. Then tokio was removed
        // from Cargo.lock. New warm runs — does it leave the stale file?
        // Answer: yes, warm doesn't delete. But cargo ignores unknown files.
        let dir = tempfile::tempdir().unwrap();
        let (index_path, artifact_dir) = make_test_store(dir.path());
        let target_dir = dir.path().join("target");
        let deps = target_dir.join("debug").join("deps");
        std::fs::create_dir_all(&deps).unwrap();

        // Simulate stale file from previous warm
        std::fs::write(deps.join("libtokio-ghi789.rlib"), b"stale").unwrap();

        // Now warm with lockfile that excludes tokio
        let lockfile = write_lockfile(dir.path(), &["serde"]);
        warm_target(
            &index_path,
            &artifact_dir,
            &target_dir,
            "debug",
            Some(&lockfile),
        )
        .unwrap();

        // Stale file still there (warm doesn't delete)
        assert!(
            deps.join("libtokio-ghi789.rlib").exists(),
            "warm doesn't clean up stale files — cargo ignores them"
        );
        // But it wasn't overwritten with fresh content
        assert_eq!(
            std::fs::read(deps.join("libtokio-ghi789.rlib")).unwrap(),
            b"stale",
            "stale file content unchanged"
        );
    }

    #[test]
    fn adversarial_version_bump_old_artifact_in_cache() {
        // Scenario: cache has serde 1.0.227 artifacts, but Cargo.lock
        // now requires serde 1.0.228. The old artifacts have different
        // hashes in the filename so they won't conflict.
        let dir = tempfile::tempdir().unwrap();
        let cache_dir = dir.path().join("cache");
        let artifact_dir = cache_dir.join("artifacts");
        let index_path = cache_dir.join("index.redb");
        std::fs::create_dir_all(&artifact_dir).unwrap();

        let store = zccache_artifact::ArtifactStore::open(&index_path).unwrap();

        // Old version's artifact (different hash suffix)
        let k_old = "bbbb0001";
        store
            .insert(
                k_old,
                &zccache_artifact::ArtifactIndex::new(
                    vec!["libserde-old111.rlib".into()],
                    vec![100],
                    vec![],
                    vec![],
                    0,
                ),
            )
            .unwrap();
        std::fs::write(artifact_dir.join(format!("{k_old}_0")), b"old-serde").unwrap();

        // New version's artifact (different hash suffix)
        let k_new = "bbbb0002";
        store
            .insert(
                k_new,
                &zccache_artifact::ArtifactIndex::new(
                    vec!["libserde-new222.rlib".into()],
                    vec![100],
                    vec![],
                    vec![],
                    0,
                ),
            )
            .unwrap();
        std::fs::write(artifact_dir.join(format!("{k_new}_0")), b"new-serde").unwrap();

        drop(store);

        let target_dir = dir.path().join("target");
        let lockfile = write_lockfile(dir.path(), &["serde"]);

        let (restored, _, _) = warm_target(
            &index_path,
            &artifact_dir,
            &target_dir,
            "debug",
            Some(&lockfile),
        )
        .unwrap();

        let deps = target_dir.join("debug").join("deps");
        // Both old and new are restored — cargo will use the one matching
        // its own fingerprint and ignore the other
        assert_eq!(restored, 2);
        assert!(deps.join("libserde-old111.rlib").exists());
        assert!(deps.join("libserde-new222.rlib").exists());
        // This is safe: cargo only links the artifact matching its
        // fingerprint hash. The extra file wastes ~100 bytes of disk.
    }

    #[test]
    fn adversarial_corrupted_cache_file() {
        // Scenario: artifact payload on disk is corrupted (truncated).
        // Warm restores it, cargo tries to use it, gets an error,
        // and recompiles from scratch. Verify warm doesn't crash.
        let dir = tempfile::tempdir().unwrap();
        let cache_dir = dir.path().join("cache");
        let artifact_dir = cache_dir.join("artifacts");
        let index_path = cache_dir.join("index.redb");
        std::fs::create_dir_all(&artifact_dir).unwrap();

        let store = zccache_artifact::ArtifactStore::open(&index_path).unwrap();
        let key = "cccc0001";
        store
            .insert(
                key,
                &zccache_artifact::ArtifactIndex::new(
                    vec!["libserde-abc123.rlib".into()],
                    vec![1000], // Claims 1000 bytes
                    vec![],
                    vec![],
                    0,
                ),
            )
            .unwrap();
        // But payload is only 5 bytes (corrupted/truncated)
        std::fs::write(artifact_dir.join(format!("{key}_0")), b"short").unwrap();
        drop(store);

        let target_dir = dir.path().join("target");
        let (restored, _, errors) =
            warm_target(&index_path, &artifact_dir, &target_dir, "debug", None).unwrap();

        // Warm restores it without error (it doesn't validate content)
        assert_eq!(restored, 1);
        assert_eq!(errors, 0);
        // Cargo will detect the corruption via its own hash check and rebuild
        let deps = target_dir.join("debug").join("deps");
        assert_eq!(
            std::fs::read(deps.join("libserde-abc123.rlib")).unwrap(),
            b"short"
        );
    }

    #[test]
    fn adversarial_empty_lockfile() {
        // Edge case: Cargo.lock exists but has no packages
        let dir = tempfile::tempdir().unwrap();
        let (index_path, artifact_dir) = make_test_store(dir.path());
        let target_dir = dir.path().join("target");
        let lockfile = write_lockfile(dir.path(), &[]);

        let (restored, skipped, _) = warm_target(
            &index_path,
            &artifact_dir,
            &target_dir,
            "debug",
            Some(&lockfile),
        )
        .unwrap();

        // foo.o has no hash separator → allowed through. Everything else skipped.
        assert_eq!(restored, 1, "only foo.o (no hash separator) passes");
        assert!(skipped > 0);
    }

    // ── Protocol mismatch recovery (issue #27) ──────────────────

    /// Regression test for <https://github.com/zackees/zccache/issues/27>.
    ///
    /// When a stale daemon is running but can't communicate (protocol mismatch
    /// or corrupt pipe), `ensure_daemon` should auto-recover instead of telling
    /// the user to manually run `zccache stop`.
    ///
    /// This test creates a fake "stale daemon" — an IPC listener that accepts
    /// connections and immediately drops them, causing `check_daemon_version`
    /// to return `CommError`. We then verify that `ensure_daemon` does NOT
    /// return the "Run `zccache stop` first" error.
    #[tokio::test]
    #[ignore] // Integration test — needs daemon binary. Run with `test --full`.
    async fn ensure_daemon_auto_recovers_on_comm_error() {
        let endpoint = zccache_ipc::unique_test_endpoint();

        // Spawn a fake stale daemon: accepts one connection, drops it (CommError),
        // then shuts down so the endpoint is released for the real daemon.
        let ep = endpoint.clone();
        let mut listener = zccache_ipc::IpcListener::bind(&ep).unwrap();
        let server = tokio::spawn(async move {
            // Accept the connection from check_daemon_version, drop it immediately
            let _ = listener.accept().await;
            // Listener drops here, releasing the endpoint
        });

        // Give the listener time to be ready
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        let result = ensure_daemon(&endpoint).await;

        // Ensure server task has completed
        let _ = server.await;

        // The OLD behavior (bug): returns Err("...Run `zccache stop` first.")
        // The NEW behavior (fix): auto-recovers — either succeeds or fails
        // for a different reason (e.g., daemon binary not found).
        if let Err(msg) = &result {
            assert!(
                !msg.contains("zccache stop"),
                "Bug #27: ensure_daemon requires manual `zccache stop` instead of \
                 auto-recovering on protocol mismatch: {msg}"
            );
        }
    }

    /// `wait_for_redb_release` keys on `is_index_openable`. A missing index
    /// file is the common case in CI when no daemon ever started — it must
    /// report "ready" so the wait does not stall.
    #[test]
    fn index_openable_treats_missing_file_as_ready() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let missing = tmp.path().join("does-not-exist.redb");
        assert!(is_index_openable(&missing));
    }

    /// An ordinary index file with no exclusive lock should be reported as
    /// openable. This is the path Unix always takes and the path Windows
    /// takes after the daemon's `Drop` fires.
    #[test]
    fn index_openable_succeeds_for_unlocked_file() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("index.redb");
        std::fs::write(&path, b"fake redb body").expect("write");
        assert!(is_index_openable(&path));
    }

    /// Simulate a daemon holding the file with Windows exclusive share mode.
    /// The probe must return false so the poll loop keeps waiting; on Unix
    /// this open succeeds (no exclusive share semantics), so the assertion
    /// flips. Either way we exercise the branch that gates the poll loop.
    #[cfg(windows)]
    #[test]
    fn index_openable_returns_false_for_exclusive_share_lock() {
        use std::os::windows::fs::OpenOptionsExt;
        // FILE_SHARE_NONE = 0, matching redb's exclusive open on Windows.
        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("index.redb");
        std::fs::write(&path, b"fake redb body").expect("write");
        let _holder = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .share_mode(0)
            .open(&path)
            .expect("hold exclusive");
        assert!(!is_index_openable(&path));
        drop(_holder);
        assert!(is_index_openable(&path));
    }

    /// The bounded wait loop must return promptly once both conditions are
    /// true. Use an endpoint we know is unreachable plus a missing index
    /// file so the very first poll satisfies the predicate.
    #[test]
    fn wait_for_redb_release_returns_when_both_conditions_satisfied() {
        let tmp = tempfile::tempdir().expect("tempdir");
        // Point the index probe at a non-existent file.
        std::env::set_var("ZCCACHE_CACHE_DIR", tmp.path());
        std::env::set_var("ZCCACHE_STOP_TIMEOUT_SECS", "2");

        // An obviously-bad endpoint so `connect()` fails fast and
        // `is_ipc_endpoint_reachable` returns false on the first probe.
        let unreachable_endpoint = if cfg!(windows) {
            r"\\.\pipe\zccache-test-does-not-exist-182".to_string()
        } else {
            tmp.path()
                .join("does-not-exist.sock")
                .to_string_lossy()
                .into_owned()
        };

        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("runtime");
        let started = std::time::Instant::now();
        rt.block_on(wait_for_redb_release(&unreachable_endpoint));
        let elapsed = started.elapsed();
        std::env::remove_var("ZCCACHE_STOP_TIMEOUT_SECS");
        std::env::remove_var("ZCCACHE_CACHE_DIR");

        // The first iteration of the loop should satisfy both predicates and
        // return immediately — well under the 2s timeout we configured.
        assert!(
            elapsed < std::time::Duration::from_secs(2),
            "wait_for_redb_release blocked for {elapsed:?} despite both conditions \
             being satisfied at t=0"
        );
    }

    /// Verify the env-var override is honored and the timeout fires when the
    /// index file is held by a locker we never release within the budget.
    #[cfg(windows)]
    #[test]
    fn wait_for_redb_release_times_out_when_index_stays_locked() {
        use std::os::windows::fs::OpenOptionsExt;

        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("index.redb");
        std::fs::write(&path, b"fake redb body").expect("write");
        let _holder = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .share_mode(0)
            .open(&path)
            .expect("hold exclusive");

        std::env::set_var("ZCCACHE_CACHE_DIR", tmp.path());
        // 1 second timeout so the test stays fast.
        std::env::set_var("ZCCACHE_STOP_TIMEOUT_SECS", "1");

        let unreachable_endpoint = r"\\.\pipe\zccache-test-does-not-exist-182-timeout".to_string();
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("runtime");
        let started = std::time::Instant::now();
        rt.block_on(wait_for_redb_release(&unreachable_endpoint));
        let elapsed = started.elapsed();

        std::env::remove_var("ZCCACHE_STOP_TIMEOUT_SECS");
        std::env::remove_var("ZCCACHE_CACHE_DIR");
        drop(_holder);

        // We expect roughly the configured 1s budget — allow generous slack
        // for CI variance. The point is: it returned, it did not hang
        // forever, and it took at least the configured timeout.
        assert!(
            elapsed >= std::time::Duration::from_millis(900),
            "wait returned in {elapsed:?}, before the 1s timeout"
        );
        assert!(
            elapsed < std::time::Duration::from_secs(5),
            "wait took {elapsed:?}, exceeding reasonable slack on 1s timeout"
        );
    }

    /// Exercises both branches of the setup-soldr-compatible bool grammar.
    /// Tests the pure function so we don't have to mutate process env vars
    /// — that's a documented foot-gun in cargo's parallel test runner.
    #[test]
    fn flag_truthy_matches_setup_soldr_normalization() {
        // Truthy variants
        for v in ["1", "true", "True", "TRUE", "yes", "YES", "on", "On"] {
            assert!(flag_truthy(Some(v)), "expected truthy: {v:?}");
        }
        // Whitespace tolerated
        assert!(flag_truthy(Some("  true  ")));

        // Falsy / "leave behavior unchanged" variants
        assert!(!flag_truthy(None));
        for v in [
            "", "0", "false", "False", "no", "off", "OFF", "garbage", "2",
        ] {
            assert!(!flag_truthy(Some(v)), "expected falsy: {v:?}");
        }
    }

    // ─── snapshot-bytes parallel walk (issue #189) ──────────────────────

    fn write_file(path: &Path, bytes: &[u8]) {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).expect("mkdir -p");
        }
        std::fs::write(path, bytes).expect("write file");
    }

    /// Empty / missing target dir returns 0 bytes (mirrors os.walk behavior).
    #[test]
    fn snapshot_bytes_missing_target_is_zero() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let missing = tmp.path().join("nope");
        assert_eq!(snapshot_bytes_walk(&missing, true, false).unwrap(), 0);
    }

    /// Sums regular files. `--prune-incremental` removes `incremental/`
    /// directories from the walk entirely.
    #[test]
    fn snapshot_bytes_prunes_incremental() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let target = tmp.path();
        write_file(&target.join("debug/deps/libfoo.rlib"), &[0u8; 100]);
        write_file(&target.join("debug/incremental/foo/state.bin"), &[0u8; 999]);
        write_file(
            &target.join("release/incremental/bar/state.bin"),
            &[0u8; 999],
        );

        let with_prune = snapshot_bytes_walk(target, true, false).unwrap();
        assert_eq!(with_prune, 100, "incremental should be excluded");

        let without_prune = snapshot_bytes_walk(target, false, false).unwrap();
        assert_eq!(
            without_prune,
            100 + 999 + 999,
            "without prune, all files counted"
        );
    }

    /// `--prune-build-script-out` removes `*/build/*/out/` only. A bare `out/`
    /// outside that pattern stays in the count.
    #[test]
    fn snapshot_bytes_prunes_build_script_out_only_under_build() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let target = tmp.path();
        write_file(
            &target.join("debug/build/libz-sys-abc/out/native/libz.a"),
            &[0u8; 500],
        );
        write_file(
            &target.join("debug/build/libz-sys-abc/build-script-build"),
            &[0u8; 50],
        );
        // `out/` that is NOT under `build/<pkg>/` should not be pruned.
        write_file(&target.join("debug/deps/some/out/data.bin"), &[0u8; 7]);

        let pruned = snapshot_bytes_walk(target, true, true).unwrap();
        assert_eq!(
            pruned,
            50 + 7,
            "only build/<pkg>/out should be pruned; deps/some/out kept"
        );

        let kept = snapshot_bytes_walk(target, true, false).unwrap();
        assert_eq!(kept, 500 + 50 + 7);
    }

    /// Walker tolerates an entirely empty tree — returns 0, doesn't error.
    #[test]
    fn snapshot_bytes_empty_target_is_zero() {
        let tmp = tempfile::tempdir().expect("tempdir");
        assert_eq!(snapshot_bytes_walk(tmp.path(), true, false).unwrap(), 0);
    }
}