zlayer-registry 0.11.3

OCI container registry client with blob caching
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
//! OCI distribution client for pulling and pushing images

use crate::cache::BlobCacheBackend;
use crate::error::{RegistryError, Result};
use crate::image_config::{ImageConfig, OciImageConfigRoot};
use crate::wasm::{detect_artifact_type, extract_wasm_info, ArtifactType, WasmArtifactInfo};
use oci_client::{
    client::{ClientConfig, ClientProtocol},
    manifest::{ImageIndexEntry, OciImageIndex, OciImageManifest, OciManifest},
    secrets::RegistryAuth,
    Reference, RegistryOperation,
};
use std::sync::Arc;
use thiserror::Error;
use tokio::sync::Semaphore;
use tracing::instrument;

#[cfg(feature = "local")]
use crate::wasm_export::WasmExportResult;

/// Errors that can occur during push operations
#[derive(Debug, Error)]
pub enum PushError {
    /// Authentication failed for the registry
    #[error("authentication failed for registry {registry}: {reason}")]
    AuthenticationFailed {
        /// Registry hostname
        registry: String,
        /// Reason for failure
        reason: String,
    },

    /// Failed to upload a blob
    #[error("failed to upload blob {digest}: {reason}")]
    BlobUploadFailed {
        /// Digest of the blob that failed to upload
        digest: String,
        /// Reason for failure
        reason: String,
    },

    /// Failed to upload a manifest
    #[error("failed to upload manifest: {reason}")]
    ManifestUploadFailed {
        /// Reason for failure
        reason: String,
    },

    /// Network error during push
    #[error("network error: {0}")]
    NetworkError(String),

    /// Invalid image reference
    #[error("invalid image reference: {reference}")]
    InvalidReference {
        /// The invalid reference string
        reference: String,
    },

    /// OCI distribution error
    #[error("OCI distribution error: {0}")]
    OciError(#[from] oci_client::errors::OciDistributionError),
}

/// Result of a successful push operation
#[derive(Debug, Clone)]
pub struct PushResult {
    /// Digest of the pushed manifest (sha256:...)
    pub manifest_digest: String,
    /// List of blob digests that were pushed
    pub blobs_pushed: Vec<String>,
    /// Full reference to the pushed image
    pub reference: String,
}

/// Map Rust architecture names to Go/OCI architecture names.
fn go_arch_name() -> &'static str {
    match std::env::consts::ARCH {
        "x86_64" => "amd64",
        "x86" => "amd",
        "aarch64" => "arm64",
        "powerpc64" => "ppc64le",
        other => other,
    }
}

/// Map Rust OS names to Go/OCI OS names.
fn go_os_name() -> &'static str {
    match std::env::consts::OS {
        "macos" => "darwin",
        other => other,
    }
}

/// Returns true when the image reference uses a "mutable" tag whose meaning
/// can change over time (e.g. `:latest`, `:dev`), so cached manifests for it
/// must be revalidated against the registry rather than trusted forever.
///
/// Returns false for pinned tags (`:v1.2.3`), digest references
/// (`image@sha256:...`), and anything else not in the known-mutable set.
fn is_mutable_tag(image: &str) -> bool {
    // Digest references are always immutable — strip anything from `@` onward
    // and, if a digest was present, the reference is content-addressed.
    let (without_digest, had_digest) = match image.find('@') {
        Some(idx) => (&image[..idx], true),
        None => (image, false),
    };
    if had_digest {
        return false;
    }

    // Find the tag by looking at the LAST `:`. If everything after it contains
    // a `/`, that colon was part of a registry host:port, not a tag separator.
    let tag = match without_digest.rfind(':') {
        Some(idx) => {
            let candidate = &without_digest[idx + 1..];
            if candidate.contains('/') {
                // Colon belonged to a host:port, so there is no explicit tag.
                None
            } else {
                Some(candidate)
            }
        }
        None => None,
    };

    match tag {
        // No tag at all — Docker defaults to `latest`, which is mutable.
        // Empty tag (e.g. `nginx:`) is treated the same as a missing tag.
        None | Some("") => true,
        Some(t) => matches!(t, "latest" | "dev" | "edge" | "main" | "master"),
    }
}

/// Parse an image reference into (name, tag/reference) for local registry lookup.
#[cfg(feature = "local")]
#[allow(clippy::unnecessary_wraps)]
fn parse_local_image_ref(image: &str) -> Option<(String, String)> {
    if let Some(at_pos) = image.find('@') {
        let name = &image[..at_pos];
        let digest = &image[at_pos + 1..];
        return Some((name.to_string(), digest.to_string()));
    }
    if let Some(colon_pos) = image.rfind(':') {
        let potential_tag = &image[colon_pos + 1..];
        if !potential_tag.contains('/') && !potential_tag.is_empty() {
            let name = &image[..colon_pos];
            return Some((name.to_string(), potential_tag.to_string()));
        }
    }
    Some((image.to_string(), "latest".to_string()))
}

/// Build a `platform_resolver` closure that picks manifests matching `target`.
///
/// When `target` is `Some`, the closure looks for the exact `{os}/{arch}` in
/// the image index and ignores any host-specific fallback (the caller has
/// asked for a specific platform, so respect that intent).
///
/// When `target` is `None`, the closure falls back to the process's runtime
/// platform (via `go_os_name()` / `go_arch_name()`), preserving the previous
/// hardcoded resolver's behavior — including the macOS-specific two-pass
/// search that first tries `darwin/{arch}` (native zlayer sandbox images)
/// and then `linux/{arch}` (standard Docker Hub images which run inside a
/// Linux VM via Docker Desktop or similar).
fn build_platform_resolver(
    target: Option<zlayer_spec::TargetPlatform>,
) -> impl Fn(&[ImageIndexEntry]) -> Option<String> + Send + Sync + 'static {
    // Resolve once at construction time so env isn't read on every invocation.
    //
    // Windows multi-platform indexes distinguish Server/Desktop build families
    // via `platform.os.version` (e.g. `10.0.26100.*` for Server 2025 / Win11
    // 24H2, `10.0.20348.*` for Server 2022). When the caller pinned a target
    // os_version, prefer manifest entries whose os.version equals the
    // constraint OR shares the same `major.minor.build` prefix.
    //
    // Macos-fallback only applies when we're using the host's default
    // (no explicit override) AND the host is macOS — an explicit
    // `darwin/...` override from a caller should NOT silently match linux.
    let has_target = target.is_some();
    let (target_os, target_arch, target_os_version): (String, String, Option<String>) = match target
    {
        Some(tp) => (
            tp.os.as_oci_str().to_string(),
            tp.arch.as_oci_str().to_string(),
            tp.os_version,
        ),
        None => (go_os_name().to_string(), go_arch_name().to_string(), None),
    };
    let use_macos_fallback = !has_target && cfg!(target_os = "macos");

    move |manifests: &[ImageIndexEntry]| -> Option<String> {
        // Pass 1a: Windows + pinned os_version — prefer an entry whose
        // `os.version` matches exactly or shares the requested prefix.
        if target_os == "windows" {
            if let Some(want_version) = target_os_version.as_deref() {
                if let Some(entry) = manifests.iter().find(|entry| {
                    entry.platform.as_ref().is_some_and(|p| {
                        p.os == target_os
                            && p.architecture == target_arch
                            && p.os_version
                                .as_deref()
                                .is_some_and(|v| v == want_version || v.starts_with(want_version))
                    })
                }) {
                    return Some(entry.digest.clone());
                }
            }
        }

        // Pass 1: exact {os}/{arch} match (os.version ignored — back-compat,
        // and used as the fallback when no Windows os.version match was found).
        if let Some(entry) = manifests.iter().find(|entry| {
            entry
                .platform
                .as_ref()
                .is_some_and(|p| p.os == target_os && p.architecture == target_arch)
        }) {
            return Some(entry.digest.clone());
        }

        // Pass 2: macOS-only fallback to linux/{arch} (for Docker Hub images
        // run inside a Linux VM). Only runs when we're using host defaults.
        if use_macos_fallback {
            return manifests
                .iter()
                .find(|entry| {
                    entry
                        .platform
                        .as_ref()
                        .is_some_and(|p| p.os == "linux" && p.architecture == target_arch)
                })
                .map(|entry| entry.digest.clone());
        }

        None
    }
}

/// Build a [`ClientConfig`] with the zlayer platform resolver and sensible
/// defaults for timeouts and protocol.
///
/// `target` overrides the platform used by the resolver; `None` preserves the
/// historical behavior of matching the process's runtime platform (with the
/// macOS `darwin → linux` fallback).
fn build_client_config(target: Option<zlayer_spec::TargetPlatform>) -> ClientConfig {
    ClientConfig {
        protocol: ClientProtocol::Https,
        connect_timeout: Some(std::time::Duration::from_secs(30)),
        read_timeout: Some(std::time::Duration::from_secs(300)), // 5 minutes for large layers
        platform_resolver: Some(Box::new(build_platform_resolver(target))),
        ..Default::default()
    }
}

/// OCI image puller with caching
pub struct ImagePuller {
    client: oci_client::Client,
    cache: Arc<Box<dyn BlobCacheBackend>>,
    concurrency_limit: Arc<Semaphore>,
    #[cfg(feature = "local")]
    local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
}

impl ImagePuller {
    /// Create a new image puller with any cache backend.
    ///
    /// Pulls will target the process's runtime platform (with the historical
    /// macOS `darwin → linux` fallback). To pull a specific platform, use
    /// [`ImagePuller::with_platform`].
    pub fn new<C: BlobCacheBackend + 'static>(cache: C) -> Self {
        let client = oci_client::Client::new(build_client_config(None));

        Self {
            client,
            cache: Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>),
            concurrency_limit: Arc::new(Semaphore::new(3)),
            #[cfg(feature = "local")]
            local_registry: None,
        }
    }

    /// Create a new image puller with boxed cache backend.
    ///
    /// Pulls will target the process's runtime platform (with the historical
    /// macOS `darwin → linux` fallback). To pull a specific platform, use
    /// [`ImagePuller::with_platform`].
    #[must_use]
    pub fn with_cache(cache: Arc<Box<dyn BlobCacheBackend>>) -> Self {
        let client = oci_client::Client::new(build_client_config(None));

        Self {
            client,
            cache,
            concurrency_limit: Arc::new(Semaphore::new(3)),
            #[cfg(feature = "local")]
            local_registry: None,
        }
    }

    /// Create a new image puller targeting a specific OCI platform.
    ///
    /// The puller's internal `oci-client` will select the manifest whose
    /// `{os}/{arch}` matches `target` from a multi-platform image index.
    /// Unlike [`ImagePuller::new`], no macOS `darwin → linux` fallback is
    /// applied — an explicit target is respected exactly.
    #[must_use]
    pub fn with_platform(
        cache: Arc<Box<dyn BlobCacheBackend>>,
        target: zlayer_spec::TargetPlatform,
    ) -> Self {
        let client = oci_client::Client::new(build_client_config(Some(target)));

        Self {
            client,
            cache,
            concurrency_limit: Arc::new(Semaphore::new(3)),
            #[cfg(feature = "local")]
            local_registry: None,
        }
    }

    /// Store authentication for a registry
    ///
    /// This ensures the client has auth credentials before attempting pulls.
    async fn store_auth(&self, image: &str, auth: &RegistryAuth) -> Result<()> {
        let reference: Reference = image.parse().map_err(|_| RegistryError::NotFound {
            registry: "unknown".to_string(),
            image: image.to_string(),
        })?;

        // Store auth in the client's internal cache
        // This is called by pull_image_manifest, but we call it explicitly here
        // to ensure auth is available for blob pulls
        self.client
            .store_auth_if_needed(reference.resolve_registry(), auth)
            .await;

        Ok(())
    }

    /// Set concurrency limit for blob downloads
    #[must_use]
    pub fn with_concurrency_limit(mut self, limit: usize) -> Self {
        self.concurrency_limit = Arc::new(Semaphore::new(limit));
        self
    }

    /// Set a local OCI registry for image resolution.
    #[cfg(feature = "local")]
    #[must_use]
    pub fn with_local_registry(
        mut self,
        registry: std::sync::Arc<crate::local_registry::LocalRegistry>,
    ) -> Self {
        self.local_registry = Some(registry);
        self
    }

    /// Pull a single blob and cache it
    ///
    /// Uses the provided authentication credentials to pull blobs from the registry.
    ///
    /// # Errors
    ///
    /// Returns an error if the blob cannot be pulled from the registry or cached.
    ///
    /// # Panics
    ///
    /// Panics if the concurrency semaphore is closed.
    pub async fn pull_blob(
        &self,
        image: &str,
        digest: &str,
        auth: &RegistryAuth,
    ) -> Result<Vec<u8>> {
        self.pull_blob_with_urls(image, digest, auth, &[], None)
            .await
    }

    /// Pull a blob, with foreign-layer `urls[]` redirect fallback on 404.
    ///
    /// Behaviour matches [`pull_blob`] for ordinary layers. For descriptors that
    /// carry a non-empty `urls` list (typically Windows base layers with media
    /// type `application/vnd.docker.image.rootfs.foreign.diff.tar.gzip` or the
    /// OCI nondistributable layer types served by Microsoft Container Registry),
    /// a primary-registry 404 triggers sequential `GET`s against each URL.
    /// Each redirect response is digest-verified (and size-verified when
    /// `expected_size` is provided); the first successful match is cached and
    /// returned.
    ///
    /// At most the first `MAX_FOREIGN_LAYER_REDIRECTS` URLs are attempted; any
    /// additional URLs are ignored to guard against circular redirect spam.
    ///
    /// # Errors
    ///
    /// Returns an error if the blob cannot be pulled from the primary registry
    /// and every `urls[]` fallback also fails.
    ///
    /// # Panics
    ///
    /// Panics if the concurrency semaphore is closed.
    pub async fn pull_blob_with_urls(
        &self,
        image: &str,
        digest: &str,
        auth: &RegistryAuth,
        urls: &[String],
        expected_size: Option<i64>,
    ) -> Result<Vec<u8>> {
        // Check cache first (now async)
        if let Some(data) = self.cache.get(digest).await? {
            tracing::debug!(digest = %digest, "blob found in cache");
            return Ok(data);
        }

        // Store auth before pulling blob
        self.store_auth(image, auth).await?;

        let reference: Reference = image.parse().map_err(|_| RegistryError::NotFound {
            registry: "unknown".to_string(),
            image: image.to_string(),
        })?;

        let _permit = self.concurrency_limit.acquire().await.unwrap();

        tracing::debug!(digest = %digest, image = %image, "pulling blob from registry");

        // Pull from registry into memory
        // Note: We pass &mut buffer directly, not wrapped in BufWriter.
        // Vec<u8> implements AsyncWrite and oci_client's pull_blob writes directly to it.
        // Using BufWriter was causing data to not be flushed properly.
        let mut buffer = Vec::new();
        let primary_result = self.client.pull_blob(&reference, digest, &mut buffer).await;

        let buffer = match primary_result {
            Ok(()) => buffer,
            Err(err) if is_blob_not_found(&err) && !urls.is_empty() => {
                tracing::info!(
                    digest = %digest,
                    urls_count = urls.len(),
                    "primary registry missed foreign layer; attempting urls[] redirects"
                );
                let mut last_err: Option<RegistryError> = None;
                let mut recovered: Option<Vec<u8>> = None;
                for url in urls.iter().take(MAX_FOREIGN_LAYER_REDIRECTS) {
                    match fetch_blob_from_url(url, digest, expected_size).await {
                        Ok(bytes) => {
                            tracing::info!(url = %url, "foreign layer recovered via redirect");
                            recovered = Some(bytes);
                            break;
                        }
                        Err(e) => {
                            tracing::warn!(url = %url, error = %e, "redirect attempt failed");
                            last_err = Some(e);
                        }
                    }
                }
                if let Some(bytes) = recovered {
                    bytes
                } else {
                    tracing::error!(
                        digest = %digest,
                        image = %image,
                        "foreign layer redirect fallback exhausted"
                    );
                    return Err(last_err.unwrap_or(RegistryError::Oci(err)));
                }
            }
            Err(err) => {
                tracing::error!(error = %err, digest = %digest, image = %image, "failed to pull blob from registry");
                return Err(RegistryError::Oci(err));
            }
        };

        // Validate blob data is not empty
        if buffer.is_empty() {
            return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
                format!("blob {digest} was empty after pulling from registry"),
            )));
        }

        // Cache the blob (now async)
        self.cache.put(digest, &buffer).await?;

        tracing::debug!(digest = %digest, size = buffer.len(), "blob cached successfully");

        Ok(buffer)
    }

    /// Fetch the current upstream manifest digest for `image` from the registry
    /// without pulling the manifest body. Uses `HEAD /v2/{repo}/manifests/{tag}`.
    ///
    /// Returns `Ok(Some(digest))` when the registry reports a current digest,
    /// `Ok(None)` when the image or tag is not found on the registry, and `Err`
    /// on transport / auth / protocol failures.
    ///
    /// This exists so [`pull_manifest`] can revalidate its cache entry against
    /// the live registry state for mutable tags (`:latest`, `:dev`, ...) without
    /// paying for a full manifest download on every pull.
    ///
    /// # Errors
    ///
    /// Returns an error if the image reference is invalid or the registry
    /// returns a transport, auth, or protocol-level failure.
    pub async fn remote_manifest_digest(
        &self,
        image: &str,
        auth: &RegistryAuth,
    ) -> Result<Option<String>> {
        let reference: Reference = image.parse().map_err(|_| RegistryError::NotFound {
            registry: "unknown".to_string(),
            image: image.to_string(),
        })?;

        match self.client.fetch_manifest_digest(&reference, auth).await {
            Ok(digest) => Ok(Some(digest)),
            Err(oci_client::errors::OciDistributionError::ImageManifestNotFoundError(_)) => {
                tracing::debug!(image = %image, "remote manifest not found");
                Ok(None)
            }
            Err(e) => {
                tracing::warn!(error = %e, image = %image, "failed to fetch remote manifest digest");
                Err(RegistryError::Oci(e))
            }
        }
    }

    /// Try to satisfy a manifest request from the persistent cache.
    ///
    /// Returns `Some((manifest, digest))` when the cached entry is usable
    /// (either because the image ref is pinned, or because a HEAD revalidation
    /// against the registry confirmed the cached digest is still current, or
    /// because the registry was unreachable and we're falling back to stale).
    /// Returns `None` when the caller should proceed to fetch the manifest
    /// fresh from the registry — i.e. there is no cached entry, the cached
    /// bytes could not be deserialized, or revalidation detected a newer
    /// digest and already invalidated the cache entries.
    async fn try_cached_manifest(
        &self,
        image: &str,
        auth: &RegistryAuth,
        cache_key: &str,
        digest_key: &str,
    ) -> Option<(OciImageManifest, String)> {
        let data = self.cache.get(cache_key).await.ok().flatten()?;
        let manifest = serde_json::from_slice::<OciImageManifest>(&data).ok()?;

        let cached_digest = self
            .cache
            .get(digest_key)
            .await
            .ok()
            .flatten()
            .and_then(|bytes| String::from_utf8(bytes).ok());

        // Pinned refs: trust the cache without revalidation.
        if !is_mutable_tag(image) {
            let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
            tracing::debug!(image = %image, "manifest cache hit (pinned ref)");
            return Some((manifest, digest));
        }

        // Mutable tag: revalidate against the registry.
        match self.remote_manifest_digest(image, auth).await {
            Ok(Some(remote_digest)) => {
                if let Some(cached) = cached_digest.as_deref() {
                    if cached == remote_digest {
                        tracing::debug!(image = %image, "manifest cache hit (revalidated)");
                        return Some((manifest, remote_digest));
                    }
                    tracing::info!(
                        image = %image,
                        cached = %cached,
                        remote = %remote_digest,
                        "cached manifest is stale, refetching"
                    );
                } else {
                    // Legacy pre-revalidation entry with no cached digest:
                    // treat as stale so we refetch once and populate both
                    // keys for future revalidations.
                    tracing::info!(
                        image = %image,
                        remote = %remote_digest,
                        "cached manifest has no stored digest, refetching"
                    );
                }
                if let Err(e) = self.cache.delete(cache_key).await {
                    tracing::warn!(
                        image = %image,
                        error = %e,
                        "failed to delete stale manifest cache entry"
                    );
                }
                if let Err(e) = self.cache.delete(digest_key).await {
                    tracing::warn!(
                        image = %image,
                        error = %e,
                        "failed to delete stale manifest digest cache entry"
                    );
                }
                None
            }
            Ok(None) => {
                tracing::warn!(image = %image, "remote manifest not found, using stale cache");
                let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
                Some((manifest, digest))
            }
            Err(e) => {
                tracing::warn!(
                    image = %image,
                    error = %e,
                    "manifest revalidation failed, using stale cache"
                );
                let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
                Some((manifest, digest))
            }
        }
    }

    /// Try to resolve a manifest from the local registry.
    #[cfg(feature = "local")]
    async fn try_local_registry(&self, image: &str) -> Option<(OciImageManifest, String)> {
        let registry = self.local_registry.as_ref()?;
        let (name, reference) = parse_local_image_ref(image)?;
        match registry.get_manifest(&name, &reference).await {
            Ok(data) => match serde_json::from_slice::<OciImageManifest>(&data) {
                Ok(manifest) => {
                    let digest = crate::cache::compute_digest(&data);
                    tracing::debug!(image = %image, digest = %digest, "manifest found in local registry");
                    Some((manifest, digest))
                }
                Err(e) => {
                    tracing::warn!(image = %image, error = %e, "local registry manifest parse failed");
                    None
                }
            },
            Err(_) => None,
        }
    }

    /// Pull an image manifest from the registry.
    ///
    /// Returns the manifest and its registry-reported digest. Manifests are
    /// cached to avoid repeated network requests for the same image reference.
    ///
    /// For mutable tags (`:latest`, `:dev`, `:edge`, `:main`, `:master`, or
    /// missing/empty tags), a cache hit triggers a `HEAD` revalidation against
    /// the upstream registry. If the cached digest still matches, the cached
    /// manifest is returned. If the remote digest differs, the cache entry is
    /// invalidated and the manifest is refetched. If the revalidation request
    /// itself fails (e.g. the registry is unreachable), the stale cached
    /// manifest is returned rather than failing the caller — serving stale
    /// beats crashing the deploy.
    ///
    /// Pinned tags (e.g. `:v1.2.3`) and digest references (`img@sha256:...`)
    /// are treated as immutable: a cache hit is returned without revalidation.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be pulled or the image reference is invalid.
    pub async fn pull_manifest(
        &self,
        image: &str,
        auth: &RegistryAuth,
    ) -> Result<(OciImageManifest, String)> {
        let cache_key = format!("manifest:{image}");
        let digest_key = format!("manifest-digest:{image}");

        // 1. Blob cache hit?
        if let Some(hit) = self
            .try_cached_manifest(image, auth, &cache_key, &digest_key)
            .await
        {
            return Ok(hit);
        }

        // 2. Local registry hit? Populate blob cache from it.
        #[cfg(feature = "local")]
        if let Some((manifest, digest)) = self.try_local_registry(image).await {
            if let Ok(bytes) = serde_json::to_vec(&manifest) {
                let _ = self.cache.put(&cache_key, &bytes).await;
                let _ = self.cache.put(&digest_key, digest.as_bytes()).await;
            }

            if is_mutable_tag(image) {
                match self.remote_manifest_digest(image, auth).await {
                    Ok(Some(remote_digest)) if remote_digest != digest => {
                        tracing::info!(
                            image = %image,
                            local = %digest,
                            remote = %remote_digest,
                            "remote has newer manifest, pulling fresh"
                        );
                        // Fall through to remote pull below
                    }
                    Ok(Some(_)) => {
                        tracing::debug!(image = %image, "local manifest matches remote, using local");
                        return Ok((manifest, digest));
                    }
                    Ok(None) => {
                        tracing::debug!(image = %image, "image not on remote registry, using local");
                        return Ok((manifest, digest));
                    }
                    Err(e) => {
                        tracing::warn!(image = %image, error = %e, "remote check failed, using local manifest");
                        return Ok((manifest, digest));
                    }
                }
            } else {
                return Ok((manifest, digest));
            }
        }

        // 3. Pull from remote registry
        let reference: Reference = image.parse().map_err(|_| RegistryError::NotFound {
            registry: "unknown".to_string(),
            image: image.to_string(),
        })?;

        tracing::info!(image = %image, "pulling manifest from registry");

        match self.client.pull_image_manifest(&reference, auth).await {
            Ok((manifest, digest)) => {
                tracing::debug!(
                    image = %image,
                    digest = %digest,
                    layers = manifest.layers.len(),
                    "manifest pulled successfully"
                );

                if let Ok(bytes) = serde_json::to_vec(&manifest) {
                    let _ = self.cache.put(&cache_key, &bytes).await;
                    let _ = self.cache.put(&digest_key, digest.as_bytes()).await;
                }

                Ok((manifest, digest))
            }
            Err(remote_err) => {
                // 4. Remote failed — try local registry as last resort
                #[cfg(feature = "local")]
                if let Some((manifest, digest)) = self.try_local_registry(image).await {
                    tracing::warn!(
                        image = %image,
                        error = %remote_err,
                        "remote pull failed, falling back to local registry"
                    );
                    return Ok((manifest, digest));
                }

                tracing::error!(error = %remote_err, image = %image, "failed to pull manifest");
                Err(RegistryError::Oci(remote_err))
            }
        }
    }

    /// Pull an image manifest, optionally forcing a cache bypass.
    ///
    /// When `force_refresh` is `true`, any cached entry for this image is
    /// deleted before the fetch, guaranteeing a round-trip to the registry.
    /// This is the implementation hook for `PullPolicy::Always` — higher-level
    /// runtimes translate their policy into this boolean.
    ///
    /// When `force_refresh` is `false`, this behaves identically to
    /// [`pull_manifest`], which already revalidates cached entries for mutable
    /// tags.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be pulled or the image
    /// reference is invalid.
    pub async fn pull_manifest_with_policy(
        &self,
        image: &str,
        auth: &RegistryAuth,
        force_refresh: bool,
    ) -> Result<(OciImageManifest, String)> {
        if force_refresh {
            let cache_key = format!("manifest:{image}");
            let digest_key = format!("manifest-digest:{image}");
            if let Err(e) = self.cache.delete(&cache_key).await {
                tracing::warn!(
                    image = %image,
                    error = %e,
                    "failed to invalidate manifest cache for force refresh"
                );
            }
            if let Err(e) = self.cache.delete(&digest_key).await {
                tracing::warn!(
                    image = %image,
                    error = %e,
                    "failed to invalidate manifest digest cache for force refresh"
                );
            }
        }
        self.pull_manifest(image, auth).await
    }

    /// Pull and parse the image configuration from the registry.
    ///
    /// This fetches the manifest, extracts the config blob digest, pulls the
    /// config blob, and parses it to extract container runtime defaults like
    /// `Entrypoint`, `Cmd`, `WorkingDir`, `Env`, and `User`.
    ///
    /// # Arguments
    ///
    /// * `image` - Image reference (e.g., "docker.io/library/nginx:latest")
    /// * `auth` - Registry authentication credentials
    ///
    /// # Returns
    ///
    /// Returns the parsed `ImageConfig` containing the container runtime defaults.
    /// If the image config blob has no `config` section, returns a default (empty)
    /// `ImageConfig`.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest or config blob cannot be fetched, or if
    /// the config blob cannot be parsed as valid JSON.
    pub async fn pull_image_config(&self, image: &str, auth: &RegistryAuth) -> Result<ImageConfig> {
        let (manifest, _digest) = self.pull_manifest(image, auth).await?;

        let config_digest = &manifest.config.digest;

        tracing::debug!(
            image = %image,
            config_digest = %config_digest,
            config_media_type = %manifest.config.media_type,
            "fetching image config blob"
        );

        let config_blob = self.pull_blob(image, config_digest, auth).await?;

        let config_root: OciImageConfigRoot =
            serde_json::from_slice(&config_blob).map_err(|e| {
                tracing::error!(
                    error = %e,
                    image = %image,
                    config_digest = %config_digest,
                    "failed to parse image config JSON"
                );
                RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
                    "failed to parse image config for {image}: {e}"
                )))
            })?;

        let config = config_root.config.unwrap_or_default();

        tracing::info!(
            image = %image,
            has_entrypoint = config.entrypoint.is_some(),
            has_cmd = config.cmd.is_some(),
            has_working_dir = config.working_dir.is_some(),
            has_user = config.user.is_some(),
            env_count = config.env.as_ref().map_or(0, std::vec::Vec::len),
            "image config parsed successfully"
        );

        Ok(config)
    }

    /// Pull and parse the image configuration, optionally forcing a cache
    /// bypass on the underlying manifest fetch.
    ///
    /// When `force_refresh` is `true`, the manifest cache entry for this image
    /// is invalidated before fetching. The config blob itself is
    /// content-addressed by digest, so it does not need explicit invalidation
    /// — once the refreshed manifest points at a new config digest, the
    /// existing blob-cache lookup will naturally miss and refetch.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest or config blob cannot be fetched, or
    /// if the config blob cannot be parsed as valid JSON.
    pub async fn pull_image_config_with_policy(
        &self,
        image: &str,
        auth: &RegistryAuth,
        force_refresh: bool,
    ) -> Result<ImageConfig> {
        if force_refresh {
            let cache_key = format!("manifest:{image}");
            let digest_key = format!("manifest-digest:{image}");
            if let Err(e) = self.cache.delete(&cache_key).await {
                tracing::warn!(
                    image = %image,
                    error = %e,
                    "failed to invalidate manifest cache for force refresh"
                );
            }
            if let Err(e) = self.cache.delete(&digest_key).await {
                tracing::warn!(
                    image = %image,
                    error = %e,
                    "failed to invalidate manifest digest cache for force refresh"
                );
            }
        }
        self.pull_image_config(image, auth).await
    }

    /// Fetch the operating system targeted by `image` from its OCI config blob.
    ///
    /// Reads the top-level `os` field (OCI-canonical lowercase, e.g.
    /// `"linux"` / `"windows"` / `"darwin"`) from the image config and
    /// converts it via [`zlayer_spec::OsKind::from_oci_str`]. Multi-platform
    /// indexes are resolved by the puller's configured `platform_resolver`
    /// (set at construction time), so the answer reflects the manifest that
    /// would actually be pulled for this host.
    ///
    /// Returns:
    /// * `Ok(Some(os))` when the config blob carries a recognized OS.
    /// * `Ok(None)` when the `os` field is absent or holds an unknown value —
    ///   the caller should treat this as "fall through to a platform-agnostic
    ///   default" rather than an error.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest or config blob cannot be fetched, or
    /// if the config blob cannot be parsed as valid JSON.
    pub async fn image_os(
        &self,
        image: &str,
        auth: &RegistryAuth,
    ) -> Result<Option<zlayer_spec::OsKind>> {
        let (manifest, _digest) = self.pull_manifest(image, auth).await?;

        let config_digest = &manifest.config.digest;
        let config_blob = self.pull_blob(image, config_digest, auth).await?;

        let config_root: OciImageConfigRoot =
            serde_json::from_slice(&config_blob).map_err(|e| {
                tracing::error!(
                    error = %e,
                    image = %image,
                    config_digest = %config_digest,
                    "failed to parse image config JSON for OS inspection"
                );
                RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
                    "failed to parse image config for {image}: {e}"
                )))
            })?;

        Ok(config_root
            .os
            .as_deref()
            .and_then(zlayer_spec::OsKind::from_oci_str))
    }

    /// Detect the artifact type of an image from its manifest
    ///
    /// This method pulls the manifest and determines whether the image is a
    /// traditional container image or a WASM artifact.
    ///
    /// # Arguments
    ///
    /// * `image` - Image reference (e.g., "ghcr.io/myorg/mymodule:v1.0")
    /// * `auth` - Registry authentication credentials
    ///
    /// # Returns
    ///
    /// Returns the detected `ArtifactType` along with the manifest and digest.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be pulled.
    pub async fn detect_artifact_type(
        &self,
        image: &str,
        auth: &RegistryAuth,
    ) -> Result<(ArtifactType, OciImageManifest, String)> {
        let (manifest, digest) = self.pull_manifest(image, auth).await?;
        let artifact_type = detect_artifact_type(&manifest);

        tracing::info!(
            image = %image,
            artifact_type = %artifact_type,
            "detected artifact type"
        );

        Ok((artifact_type, manifest, digest))
    }

    /// Extract WASM artifact information from an image
    ///
    /// This method pulls the manifest and extracts detailed information about
    /// a WASM artifact, including WASI version, layer digest, and module name.
    ///
    /// # Arguments
    ///
    /// * `image` - Image reference (e.g., "ghcr.io/myorg/mymodule:v1.0")
    /// * `auth` - Registry authentication credentials
    ///
    /// # Returns
    ///
    /// Returns `Some(WasmArtifactInfo)` if this is a WASM artifact, `None` otherwise.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be pulled.
    pub async fn get_wasm_info(
        &self,
        image: &str,
        auth: &RegistryAuth,
    ) -> Result<Option<WasmArtifactInfo>> {
        let (manifest, _digest) = self.pull_manifest(image, auth).await?;
        Ok(extract_wasm_info(&manifest))
    }

    /// Pull a WASM binary from an image
    ///
    /// This method pulls the manifest, verifies it's a WASM artifact, and
    /// returns the raw WASM binary bytes.
    ///
    /// # Arguments
    ///
    /// * `image` - Image reference (e.g., "ghcr.io/myorg/mymodule:v1.0")
    /// * `auth` - Registry authentication credentials
    ///
    /// # Returns
    ///
    /// Returns the WASM binary bytes if this is a WASM artifact.
    ///
    /// # Errors
    ///
    /// Returns an error if this is not a WASM artifact or if the WASM layer
    /// cannot be found.
    pub async fn pull_wasm(
        &self,
        image: &str,
        auth: &RegistryAuth,
    ) -> Result<(Vec<u8>, WasmArtifactInfo)> {
        let (manifest, _digest) = self.pull_manifest(image, auth).await?;

        let wasm_info = extract_wasm_info(&manifest).ok_or_else(|| RegistryError::NotFound {
            registry: "unknown".to_string(),
            image: format!("{image} (not a WASM artifact)"),
        })?;

        let wasm_digest =
            wasm_info
                .wasm_layer_digest
                .as_ref()
                .ok_or_else(|| RegistryError::NotFound {
                    registry: "unknown".to_string(),
                    image: format!("{image} (no WASM layer found)"),
                })?;

        tracing::info!(
            image = %image,
            wasi_version = %wasm_info.wasi_version,
            wasm_digest = %wasm_digest,
            "pulling WASM binary"
        );

        let wasm_bytes = self.pull_blob(image, wasm_digest, auth).await?;

        tracing::info!(
            image = %image,
            wasm_size = wasm_bytes.len(),
            "WASM binary pulled successfully"
        );

        Ok((wasm_bytes, wasm_info))
    }

    /// Pull a complete image (manifest + all layers)
    ///
    /// Returns a vector of (`layer_data`, `media_type`) tuples in order (base layer first).
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest or any layer cannot be pulled.
    pub async fn pull_image(
        &self,
        image: &str,
        auth: &RegistryAuth,
    ) -> Result<Vec<(Vec<u8>, String)>> {
        // Pull manifest first
        let (manifest, _digest) = self.pull_manifest(image, auth).await?;

        tracing::info!(
            image = %image,
            layer_count = manifest.layers.len(),
            "pulling image layers"
        );

        // Pull each layer in order
        let mut layers = Vec::with_capacity(manifest.layers.len());
        for (i, layer) in manifest.layers.iter().enumerate() {
            tracing::debug!(
                layer = i,
                digest = %layer.digest,
                media_type = %layer.media_type,
                size = layer.size,
                "pulling layer"
            );

            let layer_urls: &[String] = layer.urls.as_deref().unwrap_or(&[]);
            let data = self
                .pull_blob_with_urls(image, &layer.digest, auth, layer_urls, Some(layer.size))
                .await?;

            // Validate layer data is not empty
            if data.is_empty() {
                return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
                    format!("layer {i} ({}) is empty after pull", layer.digest),
                )));
            }

            layers.push((data, layer.media_type.clone()));
        }

        tracing::info!(
            image = %image,
            layers_pulled = layers.len(),
            "image pull complete"
        );

        Ok(layers)
    }

    /// Pull a complete image, optionally forcing a cache bypass on the
    /// underlying manifest fetch.
    ///
    /// When `force_refresh` is `true`, the manifest cache entry for this image
    /// is invalidated before fetching. Layer blobs are content-addressed by
    /// digest, so they do not need explicit invalidation — once the refreshed
    /// manifest points at new layer digests, the existing blob-cache lookups
    /// will naturally miss and refetch the new layers. Shared layer blobs
    /// remain valid cache hits.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest or any layer cannot be pulled.
    pub async fn pull_image_with_policy(
        &self,
        image: &str,
        auth: &RegistryAuth,
        force_refresh: bool,
    ) -> Result<Vec<(Vec<u8>, String)>> {
        if force_refresh {
            let cache_key = format!("manifest:{image}");
            let digest_key = format!("manifest-digest:{image}");
            if let Err(e) = self.cache.delete(&cache_key).await {
                tracing::warn!(
                    image = %image,
                    error = %e,
                    "failed to invalidate manifest cache for force refresh"
                );
            }
            if let Err(e) = self.cache.delete(&digest_key).await {
                tracing::warn!(
                    image = %image,
                    error = %e,
                    "failed to invalidate manifest digest cache for force refresh"
                );
            }
        }
        self.pull_image(image, auth).await
    }

    /// Push a blob to a remote registry
    ///
    /// Uploads a blob (layer or config) to the specified registry. The blob is
    /// identified by its digest and will be stored at the repository specified
    /// in the reference.
    ///
    /// # Arguments
    ///
    /// * `reference` - Image reference (e.g., "ghcr.io/myorg/mymodule:v1.0")
    /// * `digest` - Content digest of the blob (e.g., "sha256:abc123...")
    /// * `data` - Raw blob data to upload
    /// * `_media_type` - MIME type of the blob content (reserved for future use)
    /// * `auth` - Registry authentication credentials
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The reference is invalid
    /// - Authentication fails
    /// - The blob upload fails
    #[instrument(
        name = "push_blob",
        skip(self, data, auth, _media_type),
        fields(
            reference = %reference,
            digest = %digest,
            size = data.len(),
        )
    )]
    pub async fn push_blob(
        &self,
        reference: &str,
        digest: &str,
        data: &[u8],
        _media_type: &str,
        auth: &RegistryAuth,
    ) -> std::result::Result<(), PushError> {
        let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
            reference: reference.to_string(),
        })?;

        tracing::debug!(
            reference = %reference,
            digest = %digest,
            size = data.len(),
            "pushing blob to registry"
        );

        // Authenticate for push operation
        self.client
            .auth(&image_ref, auth, RegistryOperation::Push)
            .await
            .map_err(|e| PushError::AuthenticationFailed {
                registry: image_ref.resolve_registry().to_string(),
                reason: e.to_string(),
            })?;

        // Push the blob
        self.client
            .push_blob(&image_ref, data, digest)
            .await
            .map_err(|e| PushError::BlobUploadFailed {
                digest: digest.to_string(),
                reason: e.to_string(),
            })?;

        tracing::info!(
            reference = %reference,
            digest = %digest,
            size = data.len(),
            "blob pushed successfully"
        );

        Ok(())
    }

    /// Push a manifest to a remote registry
    ///
    /// Uploads an OCI image manifest to the specified registry. The manifest
    /// should reference blobs that have already been uploaded.
    ///
    /// # Arguments
    ///
    /// * `reference` - Image reference (e.g., "ghcr.io/myorg/mymodule:v1.0")
    /// * `manifest` - OCI image manifest to upload
    /// * `auth` - Registry authentication credentials
    ///
    /// # Returns
    ///
    /// Returns the manifest digest on success.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The reference is invalid
    /// - Authentication fails
    /// - The manifest upload fails
    #[instrument(
        name = "push_manifest_to_registry",
        skip(self, manifest, auth),
        fields(
            reference = %reference,
            layers = manifest.layers.len(),
        )
    )]
    pub async fn push_manifest_to_registry(
        &self,
        reference: &str,
        manifest: &OciImageManifest,
        auth: &RegistryAuth,
    ) -> std::result::Result<String, PushError> {
        let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
            reference: reference.to_string(),
        })?;

        tracing::debug!(
            reference = %reference,
            layers = manifest.layers.len(),
            config_digest = %manifest.config.digest,
            "pushing manifest to registry"
        );

        // Authenticate for push operation
        self.client
            .auth(&image_ref, auth, RegistryOperation::Push)
            .await
            .map_err(|e| PushError::AuthenticationFailed {
                registry: image_ref.resolve_registry().to_string(),
                reason: e.to_string(),
            })?;

        // Push the manifest
        let manifest_url = self
            .client
            .push_manifest(&image_ref, &OciManifest::Image(manifest.clone()))
            .await
            .map_err(|e| PushError::ManifestUploadFailed {
                reason: e.to_string(),
            })?;

        // Extract digest from the manifest URL or compute it
        // The manifest URL typically contains the digest after the @ symbol
        let digest = if let Some(digest_start) = manifest_url.rfind('@') {
            manifest_url[digest_start + 1..].to_string()
        } else {
            // Compute digest from manifest JSON
            let manifest_json =
                serde_json::to_vec(manifest).map_err(|e| PushError::ManifestUploadFailed {
                    reason: format!("failed to serialize manifest: {e}"),
                })?;
            crate::cache::compute_digest(&manifest_json)
        };

        tracing::info!(
            reference = %reference,
            digest = %digest,
            manifest_url = %manifest_url,
            "manifest pushed successfully"
        );

        Ok(digest)
    }

    /// Push an OCI image index (manifest list) to a remote registry.
    ///
    /// Used for multi-platform images where each platform has its own manifest
    /// and the index ties them together.
    ///
    /// # Errors
    ///
    /// Returns an error if the reference is invalid, authentication fails, or
    /// the index upload fails.
    #[instrument(
        name = "push_image_index_to_registry",
        skip(self, index, auth),
        fields(
            reference = %reference,
            manifests = index.manifests.len(),
        )
    )]
    pub async fn push_image_index_to_registry(
        &self,
        reference: &str,
        index: &OciImageIndex,
        auth: &RegistryAuth,
    ) -> std::result::Result<String, PushError> {
        let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
            reference: reference.to_string(),
        })?;

        tracing::debug!(
            reference = %reference,
            manifests = index.manifests.len(),
            "pushing image index to registry"
        );

        // Authenticate for push operation
        self.client
            .auth(&image_ref, auth, RegistryOperation::Push)
            .await
            .map_err(|e| PushError::AuthenticationFailed {
                registry: image_ref.resolve_registry().to_string(),
                reason: e.to_string(),
            })?;

        // Push the image index
        let manifest_url = self
            .client
            .push_manifest(&image_ref, &OciManifest::ImageIndex(index.clone()))
            .await
            .map_err(|e| PushError::ManifestUploadFailed {
                reason: e.to_string(),
            })?;

        let digest = if let Some(digest_start) = manifest_url.rfind('@') {
            manifest_url[digest_start + 1..].to_string()
        } else {
            let index_json =
                serde_json::to_vec(index).map_err(|e| PushError::ManifestUploadFailed {
                    reason: format!("failed to serialize image index: {e}"),
                })?;
            crate::cache::compute_digest(&index_json)
        };

        tracing::info!(
            reference = %reference,
            digest = %digest,
            "image index pushed successfully"
        );

        Ok(digest)
    }

    /// Push a WASM artifact to a remote registry
    ///
    /// This method pushes a complete WASM artifact including the config blob,
    /// WASM binary layer, and manifest. It uses the result from `export_wasm_as_oci`
    /// to obtain the properly formatted blobs.
    ///
    /// # Arguments
    ///
    /// * `reference` - Image reference (e.g., "ghcr.io/myorg/mymodule:v1.0")
    /// * `export_result` - Result from `export_wasm_as_oci` containing all blobs
    /// * `auth` - Registry authentication credentials
    ///
    /// # Returns
    ///
    /// Returns a `PushResult` containing the manifest digest and list of pushed blobs.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The reference is invalid
    /// - Authentication fails
    /// - Any blob or manifest upload fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zlayer_registry::{ImagePuller, BlobCache};
    /// use zlayer_registry::wasm_export::{WasmExportConfig, export_wasm_as_oci};
    /// use oci_client::secrets::RegistryAuth;
    /// use std::path::PathBuf;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let puller = ImagePuller::new(BlobCache::new()?);
    ///
    /// let export_config = WasmExportConfig {
    ///     wasm_path: PathBuf::from("./my_module.wasm"),
    ///     module_name: "my-module".to_string(),
    ///     wasi_version: None,
    ///     annotations: Default::default(),
    /// };
    ///
    /// let export_result = export_wasm_as_oci(&export_config).await?;
    ///
    /// let auth = RegistryAuth::Basic("user".to_string(), "token".to_string());
    /// let push_result = puller.push_wasm(
    ///     "ghcr.io/myorg/my-module:v1.0",
    ///     &export_result,
    ///     &auth,
    /// ).await?;
    ///
    /// println!("Pushed manifest: {}", push_result.manifest_digest);
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "local")]
    #[allow(clippy::too_many_lines)]
    #[instrument(
        name = "push_wasm",
        skip(self, export_result, auth),
        fields(
            reference = %reference,
            wasm_size = export_result.wasm_size,
            wasi_version = %export_result.wasi_version,
        )
    )]
    pub async fn push_wasm(
        &self,
        reference: &str,
        export_result: &WasmExportResult,
        auth: &RegistryAuth,
    ) -> std::result::Result<PushResult, PushError> {
        use crate::wasm::{WASM_CONFIG_MEDIA_TYPE_V0, WASM_LAYER_MEDIA_TYPE_GENERIC};

        let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
            reference: reference.to_string(),
        })?;

        tracing::info!(
            reference = %reference,
            wasm_size = export_result.wasm_size,
            wasi_version = %export_result.wasi_version,
            artifact_type = %export_result.artifact_type,
            "pushing WASM artifact to registry"
        );

        // Authenticate for push operation
        self.client
            .auth(&image_ref, auth, RegistryOperation::Push)
            .await
            .map_err(|e| PushError::AuthenticationFailed {
                registry: image_ref.resolve_registry().to_string(),
                reason: e.to_string(),
            })?;

        let mut blobs_pushed = Vec::new();

        // Push config blob
        tracing::debug!(
            digest = %export_result.config_digest,
            size = export_result.config_size,
            "pushing config blob"
        );
        self.client
            .push_blob(
                &image_ref,
                &export_result.config_blob,
                &export_result.config_digest,
            )
            .await
            .map_err(|e| PushError::BlobUploadFailed {
                digest: export_result.config_digest.clone(),
                reason: e.to_string(),
            })?;
        blobs_pushed.push(export_result.config_digest.clone());

        // Push WASM binary blob
        tracing::debug!(
            digest = %export_result.wasm_layer_digest,
            size = export_result.wasm_size,
            "pushing WASM layer blob"
        );
        self.client
            .push_blob(
                &image_ref,
                &export_result.wasm_binary,
                &export_result.wasm_layer_digest,
            )
            .await
            .map_err(|e| PushError::BlobUploadFailed {
                digest: export_result.wasm_layer_digest.clone(),
                reason: e.to_string(),
            })?;
        blobs_pushed.push(export_result.wasm_layer_digest.clone());

        // Build the manifest from the export result
        #[allow(clippy::cast_possible_wrap)]
        let manifest = OciImageManifest {
            schema_version: 2,
            media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
            artifact_type: Some(export_result.artifact_type.clone()),
            config: oci_client::manifest::OciDescriptor {
                media_type: WASM_CONFIG_MEDIA_TYPE_V0.to_string(),
                digest: export_result.config_digest.clone(),
                size: export_result.config_size as i64,
                urls: None,
                annotations: None,
            },
            layers: vec![oci_client::manifest::OciDescriptor {
                media_type: WASM_LAYER_MEDIA_TYPE_GENERIC.to_string(),
                digest: export_result.wasm_layer_digest.clone(),
                size: export_result.wasm_size as i64,
                urls: None,
                annotations: None,
            }],
            annotations: None,
            subject: None,
        };

        // Push manifest
        tracing::debug!(
            config_digest = %export_result.config_digest,
            wasm_digest = %export_result.wasm_layer_digest,
            "pushing manifest"
        );
        let manifest_url = self
            .client
            .push_manifest(&image_ref, &OciManifest::Image(manifest))
            .await
            .map_err(|e| PushError::ManifestUploadFailed {
                reason: e.to_string(),
            })?;

        // Extract digest from manifest URL or use the precomputed one
        let manifest_digest = if let Some(digest_start) = manifest_url.rfind('@') {
            manifest_url[digest_start + 1..].to_string()
        } else {
            export_result.manifest_digest.clone()
        };

        tracing::info!(
            reference = %reference,
            manifest_digest = %manifest_digest,
            blobs_pushed = blobs_pushed.len(),
            "WASM artifact pushed successfully"
        );

        Ok(PushResult {
            manifest_digest,
            blobs_pushed,
            reference: reference.to_string(),
        })
    }
}

/// Image reference information
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Image {
    /// Registry host (e.g., "docker.io", "ghcr.io")
    pub registry: String,
    /// Repository name (e.g., "library/nginx")
    pub repository: String,
    /// Tag (e.g., "latest", "v1.0.0")
    pub tag: String,
}

impl std::fmt::Display for Image {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}/{}:{}", self.registry, self.repository, self.tag)
    }
}

/// Maximum number of `urls[]` entries consulted when a foreign layer 404s on
/// the primary registry. Descriptors rarely carry more than one or two URLs;
/// the cap is a defence against circular / abusive redirect lists.
const MAX_FOREIGN_LAYER_REDIRECTS: usize = 5;

/// Return `true` when an `OciDistributionError` reports that the blob does not
/// exist on the primary registry — i.e. the conditions under which we should
/// fall back to the descriptor's `urls[]` list.
fn is_blob_not_found(err: &oci_client::errors::OciDistributionError) -> bool {
    use oci_client::errors::{OciDistributionError, OciErrorCode};
    match err {
        OciDistributionError::ImageManifestNotFoundError(_) => true,
        OciDistributionError::ServerError { code, .. } => *code == 404,
        OciDistributionError::RegistryError { envelope, .. } => envelope.errors.iter().any(|e| {
            matches!(
                e.code,
                OciErrorCode::BlobUnknown
                    | OciErrorCode::ManifestBlobUnknown
                    | OciErrorCode::ManifestUnknown
                    | OciErrorCode::NotFound
                    | OciErrorCode::NameUnknown
            )
        }),
        OciDistributionError::RequestError(req_err) => {
            req_err.status() == Some(reqwest::StatusCode::NOT_FOUND)
        }
        _ => false,
    }
}

/// Fetch raw bytes from an HTTP(S) URL with optional HTTP Basic authentication.
///
/// This is the low-level primitive used by all other `fetch_*_from_url` helpers
/// in this module — `fetch_blob_from_url` (with digest/size verification),
/// `fetch_archive_from_url` (non-empty archive assertion), and any future
/// content-type-specific fetcher. It performs no validation on the response
/// body beyond HTTP status; callers are responsible for any content-specific
/// checks. `context` is a short human-readable label used to prefix error
/// messages (e.g. `"foreign-layer redirect"`, `"archive fetch"`).
///
/// The caller is responsible for supplying an HTTPS URL when credentials are
/// involved — TLS is never bypassed.
///
/// # Errors
///
/// Returns [`RegistryError::Cache`] on HTTP client construction failure,
/// network error, non-2xx status code, or I/O error while reading the
/// response body. The URL and `context` are included in the error for
/// diagnostics.
pub async fn fetch_from_url(
    url: &str,
    auth: Option<(&str, &str)>,
    context: &str,
) -> Result<Vec<u8>> {
    let client = reqwest::Client::builder().build().map_err(|e| {
        RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
            "failed to build HTTP client for {context} {url}: {e}"
        )))
    })?;

    let mut req = client.get(url);
    if let Some((user, pw)) = auth {
        req = req.basic_auth(user, Some(pw));
    }

    let response = req.send().await.map_err(|e| {
        RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
            "{context} GET {url} failed: {e}"
        )))
    })?;

    if !response.status().is_success() {
        return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
            format!("{context} {url} returned HTTP {}", response.status()),
        )));
    }

    let bytes = response.bytes().await.map_err(|e| {
        RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
            "failed to read {context} body from {url}: {e}"
        )))
    })?;

    Ok(bytes.to_vec())
}

/// Fetch a foreign layer blob from an out-of-registry URL (e.g. MCR) and
/// verify that its SHA-256 digest matches `expected_digest`. Size is verified
/// against `expected_size` when the value is `Some(n)` and `n >= 0`.
async fn fetch_blob_from_url(
    url: &str,
    expected_digest: &str,
    expected_size: Option<i64>,
) -> Result<Vec<u8>> {
    use sha2::{Digest, Sha256};

    let bytes = fetch_from_url(url, None, "foreign-layer redirect").await?;

    if bytes.is_empty() {
        return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
            format!("foreign-layer redirect {url} returned empty body"),
        )));
    }

    if let Some(expected) = expected_size {
        if let Ok(expected_u) = u64::try_from(expected) {
            if bytes.len() as u64 != expected_u {
                return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
                    format!(
                        "foreign-layer redirect {url}: size mismatch (expected {expected}, got {})",
                        bytes.len()
                    ),
                )));
            }
        }
    }

    let mut hasher = Sha256::new();
    hasher.update(&bytes);
    let actual = hex::encode(hasher.finalize());
    let expected = expected_digest
        .strip_prefix("sha256:")
        .unwrap_or(expected_digest);
    if !actual.eq_ignore_ascii_case(expected) {
        return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
            format!(
                "foreign-layer redirect {url}: digest mismatch (expected {expected_digest}, got sha256:{actual})"
            ),
        )));
    }

    Ok(bytes)
}

/// Fetch an OCI tar archive (or tar.gz) from a remote HTTP(S) URL with optional
/// HTTP Basic authentication.
///
/// Unlike [`fetch_blob_from_url`], there is no digest verification — OCI
/// archives are not content-addressable blobs by URL. Validation happens
/// inside the importer via the embedded `oci-layout` + manifest digests.
/// Only asserts the response body is non-empty so callers get a clean error
/// message on accidental 200-with-empty-body responses from misconfigured
/// object stores.
///
/// Suitable for authenticating against Forgejo / Gitea generic-package APIs,
/// Nexus raw repositories, and similar file-blob endpoints.
///
/// # Errors
///
/// Returns [`RegistryError::Cache`] on any HTTP/network error (propagated
/// from [`fetch_from_url`]) or when the response body is empty.
pub async fn fetch_archive_from_url(url: &str, auth: Option<(&str, &str)>) -> Result<Vec<u8>> {
    let bytes = fetch_from_url(url, auth, "archive fetch").await?;

    if bytes.is_empty() {
        return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
            format!("archive fetch {url} returned empty body"),
        )));
    }

    Ok(bytes)
}

/// Convert a [`zlayer_spec::RegistryAuth`] into the [`RegistryAuth`] shape
/// that the OCI client speaks. Anonymous is returned when `auth` is `None`.
///
/// Basic and Token map onto the same `(username, password)` shape today —
/// the client's bearer-token path is a parsing detail handled by
/// `oci-client` itself. The explicit match keeps us honest when a future
/// [`zlayer_spec::RegistryAuthType`] variant lands with different semantics.
fn spec_auth_to_oci(auth: Option<&zlayer_spec::RegistryAuth>) -> RegistryAuth {
    let Some(a) = auth else {
        return RegistryAuth::Anonymous;
    };
    match a.auth_type {
        zlayer_spec::RegistryAuthType::Basic | zlayer_spec::RegistryAuthType::Token => {
            RegistryAuth::Basic(a.username.clone(), a.password.clone())
        }
    }
}

/// Fetch the OCI operating system of `image` without pulling any layers.
///
/// Convenience wrapper that constructs an ephemeral [`ImagePuller`] backed by
/// an in-memory [`BlobCache`] and calls [`ImagePuller::image_os`]. Intended
/// for callers that need a one-shot OS inspection and don't otherwise own a
/// long-lived puller — e.g. the agent's `CompositeRuntime` deciding which
/// child runtime should run a freshly-pulled image. The caller's own
/// long-lived puller has already pulled the blobs to its persistent cache;
/// this helper only touches the ~1–5 KB config blob, so the redundant fetch
/// is negligible.
///
/// Auth is the same [`zlayer_spec::RegistryAuth`] carried on the
/// [`Runtime::pull_image_with_policy`](crate) trait; `None` maps to
/// anonymous. The manifest is resolved for the process's runtime platform
/// (with the historical macOS `darwin → linux` fallback) — matching the
/// behavior of [`ImagePuller::new`].
///
/// # Errors
///
/// Returns an error if the in-memory cache cannot be initialized, or if the
/// manifest or config blob cannot be fetched or parsed. Callers in the hot
/// path (e.g. `CompositeRuntime::pull_image_with_policy`) should treat any
/// error as non-fatal: the safe fall-through is "dispatch to the primary
/// runtime" rather than failing the pull.
pub async fn fetch_image_os(
    image: &str,
    auth: Option<&zlayer_spec::RegistryAuth>,
) -> Result<Option<zlayer_spec::OsKind>> {
    let cache = crate::cache::BlobCache::new()?;
    let puller = ImagePuller::new(cache);

    let oci_auth = spec_auth_to_oci(auth);
    puller.image_os(image, &oci_auth).await
}

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

    // =========================================================================
    // Image Display Tests
    // =========================================================================

    #[test]
    fn test_image_display() {
        let image = Image {
            registry: "docker.io".to_string(),
            repository: "library/nginx".to_string(),
            tag: "latest".to_string(),
        };
        assert_eq!(image.to_string(), "docker.io/library/nginx:latest");
    }

    #[test]
    fn test_image_display_ghcr() {
        let image = Image {
            registry: "ghcr.io".to_string(),
            repository: "myorg/myrepo".to_string(),
            tag: "v1.2.3".to_string(),
        };
        assert_eq!(image.to_string(), "ghcr.io/myorg/myrepo:v1.2.3");
    }

    #[test]
    fn test_image_display_with_nested_repo() {
        let image = Image {
            registry: "gcr.io".to_string(),
            repository: "project/subdir/image".to_string(),
            tag: "sha-abc123".to_string(),
        };
        assert_eq!(image.to_string(), "gcr.io/project/subdir/image:sha-abc123");
    }

    #[test]
    fn test_image_clone() {
        let image = Image {
            registry: "docker.io".to_string(),
            repository: "library/nginx".to_string(),
            tag: "latest".to_string(),
        };
        let cloned = image.clone();
        assert_eq!(image, cloned);
        assert_eq!(cloned.registry, "docker.io");
        assert_eq!(cloned.repository, "library/nginx");
        assert_eq!(cloned.tag, "latest");
    }

    #[test]
    fn test_image_equality() {
        let image1 = Image {
            registry: "docker.io".to_string(),
            repository: "library/nginx".to_string(),
            tag: "latest".to_string(),
        };
        let image2 = Image {
            registry: "docker.io".to_string(),
            repository: "library/nginx".to_string(),
            tag: "latest".to_string(),
        };
        let image3 = Image {
            registry: "ghcr.io".to_string(),
            repository: "library/nginx".to_string(),
            tag: "latest".to_string(),
        };

        assert_eq!(image1, image2);
        assert_ne!(image1, image3);
    }

    #[test]
    fn test_image_debug() {
        let image = Image {
            registry: "docker.io".to_string(),
            repository: "test".to_string(),
            tag: "v1".to_string(),
        };
        let debug_str = format!("{image:?}");
        assert!(debug_str.contains("Image"));
        assert!(debug_str.contains("docker.io"));
        assert!(debug_str.contains("test"));
        assert!(debug_str.contains("v1"));
    }

    // =========================================================================
    // PushError Display Tests
    // =========================================================================

    #[test]
    fn test_push_error_display_authentication_failed() {
        let err = PushError::AuthenticationFailed {
            registry: "ghcr.io".to_string(),
            reason: "invalid token".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "authentication failed for registry ghcr.io: invalid token"
        );
    }

    #[test]
    fn test_push_error_display_authentication_failed_empty_reason() {
        let err = PushError::AuthenticationFailed {
            registry: "docker.io".to_string(),
            reason: String::new(),
        };
        assert_eq!(
            err.to_string(),
            "authentication failed for registry docker.io: "
        );
    }

    #[test]
    fn test_push_error_display_authentication_failed_long_reason() {
        let long_reason = "a]".repeat(100);
        let err = PushError::AuthenticationFailed {
            registry: "ghcr.io".to_string(),
            reason: long_reason.clone(),
        };
        assert!(err.to_string().contains(&long_reason));
    }

    #[test]
    fn test_push_error_display_blob_upload_failed() {
        let err = PushError::BlobUploadFailed {
            digest: "sha256:abc123".to_string(),
            reason: "connection reset".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "failed to upload blob sha256:abc123: connection reset"
        );
    }

    #[test]
    fn test_push_error_display_blob_upload_failed_with_full_digest() {
        let digest =
            "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855".to_string();
        let err = PushError::BlobUploadFailed {
            digest: digest.clone(),
            reason: "timeout".to_string(),
        };
        assert!(err.to_string().contains(&digest));
        assert!(err.to_string().contains("timeout"));
    }

    #[test]
    fn test_push_error_display_manifest_upload_failed() {
        let err = PushError::ManifestUploadFailed {
            reason: "invalid manifest".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "failed to upload manifest: invalid manifest"
        );
    }

    #[test]
    fn test_push_error_display_manifest_upload_failed_json_error() {
        let err = PushError::ManifestUploadFailed {
            reason: "invalid JSON: unexpected token at position 42".to_string(),
        };
        assert!(err.to_string().contains("invalid JSON"));
        assert!(err.to_string().contains("position 42"));
    }

    #[test]
    fn test_push_error_display_network_error() {
        let err = PushError::NetworkError("timeout".to_string());
        assert_eq!(err.to_string(), "network error: timeout");
    }

    #[test]
    fn test_push_error_display_network_error_connection_refused() {
        let err = PushError::NetworkError("connection refused: 127.0.0.1:5000".to_string());
        assert_eq!(
            err.to_string(),
            "network error: connection refused: 127.0.0.1:5000"
        );
    }

    #[test]
    fn test_push_error_display_network_error_dns() {
        let err =
            PushError::NetworkError("DNS resolution failed for registry.example.com".to_string());
        assert!(err.to_string().contains("DNS resolution failed"));
    }

    #[test]
    fn test_push_error_display_invalid_reference() {
        let err = PushError::InvalidReference {
            reference: "invalid::ref".to_string(),
        };
        assert_eq!(err.to_string(), "invalid image reference: invalid::ref");
    }

    #[test]
    fn test_push_error_display_invalid_reference_empty() {
        let err = PushError::InvalidReference {
            reference: String::new(),
        };
        assert_eq!(err.to_string(), "invalid image reference: ");
    }

    #[test]
    fn test_push_error_display_invalid_reference_special_chars() {
        let err = PushError::InvalidReference {
            reference: "ghcr.io/test/image:tag@sha256:abc".to_string(),
        };
        assert!(err
            .to_string()
            .contains("ghcr.io/test/image:tag@sha256:abc"));
    }

    // =========================================================================
    // PushError Debug Tests
    // =========================================================================

    #[test]
    fn test_push_error_debug_authentication_failed() {
        let err = PushError::AuthenticationFailed {
            registry: "ghcr.io".to_string(),
            reason: "invalid token".to_string(),
        };
        let debug_str = format!("{err:?}");
        assert!(debug_str.contains("AuthenticationFailed"));
        assert!(debug_str.contains("ghcr.io"));
        assert!(debug_str.contains("invalid token"));
    }

    #[test]
    fn test_push_error_debug_blob_upload_failed() {
        let err = PushError::BlobUploadFailed {
            digest: "sha256:abc123".to_string(),
            reason: "network error".to_string(),
        };
        let debug_str = format!("{err:?}");
        assert!(debug_str.contains("BlobUploadFailed"));
        assert!(debug_str.contains("sha256:abc123"));
        assert!(debug_str.contains("network error"));
    }

    #[test]
    fn test_push_error_debug_manifest_upload_failed() {
        let err = PushError::ManifestUploadFailed {
            reason: "schema validation failed".to_string(),
        };
        let debug_str = format!("{err:?}");
        assert!(debug_str.contains("ManifestUploadFailed"));
        assert!(debug_str.contains("schema validation failed"));
    }

    #[test]
    fn test_push_error_debug_network_error() {
        let err = PushError::NetworkError("connection timed out".to_string());
        let debug_str = format!("{err:?}");
        assert!(debug_str.contains("NetworkError"));
        assert!(debug_str.contains("connection timed out"));
    }

    #[test]
    fn test_push_error_debug_invalid_reference() {
        let err = PushError::InvalidReference {
            reference: "bad-ref".to_string(),
        };
        let debug_str = format!("{err:?}");
        assert!(debug_str.contains("InvalidReference"));
        assert!(debug_str.contains("bad-ref"));
    }

    #[test]
    fn test_push_error_debug_oci_error() {
        // Create an OCI error using a valid variant (GenericError)
        let oci_err =
            oci_client::errors::OciDistributionError::GenericError(Some("test error".to_string()));
        let err = PushError::OciError(oci_err);
        let debug_str = format!("{err:?}");
        assert!(debug_str.contains("OciError"));
    }

    // =========================================================================
    // PushError From OCI Error Tests
    // =========================================================================

    #[test]
    fn test_push_error_from_oci_generic_error() {
        let oci_err = oci_client::errors::OciDistributionError::GenericError(Some(
            "generic error message".to_string(),
        ));
        let push_err: PushError = oci_err.into();
        match push_err {
            PushError::OciError(inner) => {
                assert!(inner.to_string().contains("generic error message"));
            }
            _ => panic!("Expected OciError variant"),
        }
    }

    #[test]
    fn test_push_error_from_oci_config_conversion_error() {
        let oci_err = oci_client::errors::OciDistributionError::ConfigConversionError(
            "config conversion failed".to_string(),
        );
        let push_err: PushError = oci_err.into();
        match push_err {
            PushError::OciError(inner) => {
                assert!(inner.to_string().contains("config conversion"));
            }
            _ => panic!("Expected OciError variant"),
        }
    }

    #[test]
    fn test_push_error_from_oci_manifest_parsing_error() {
        let oci_err = oci_client::errors::OciDistributionError::ManifestParsingError(
            "invalid manifest JSON".to_string(),
        );
        let push_err: PushError = oci_err.into();
        match push_err {
            PushError::OciError(inner) => {
                assert!(
                    inner.to_string().contains("manifest") || inner.to_string().contains("JSON")
                );
            }
            _ => panic!("Expected OciError variant"),
        }
    }

    #[test]
    fn test_push_error_from_oci_image_manifest_not_found() {
        let oci_err = oci_client::errors::OciDistributionError::ImageManifestNotFoundError(
            "image:tag".to_string(),
        );
        let push_err: PushError = oci_err.into();
        match push_err {
            PushError::OciError(inner) => {
                assert!(inner.to_string().contains("image:tag"));
            }
            _ => panic!("Expected OciError variant"),
        }
    }

    #[test]
    fn test_push_error_from_oci_url_parse_error() {
        let oci_err =
            oci_client::errors::OciDistributionError::UrlParseError("invalid URL".to_string());
        let push_err: PushError = oci_err.into();
        match push_err {
            PushError::OciError(inner) => {
                assert!(inner.to_string().contains("URL"));
            }
            _ => panic!("Expected OciError variant"),
        }
    }

    #[test]
    fn test_push_error_from_oci_unsupported_schema_version() {
        let oci_err = oci_client::errors::OciDistributionError::UnsupportedSchemaVersionError(99);
        let push_err: PushError = oci_err.into();
        match push_err {
            PushError::OciError(inner) => {
                // The error should contain information about the version
                let _ = inner.to_string();
            }
            _ => panic!("Expected OciError variant"),
        }
    }

    #[test]
    fn test_push_error_from_oci_unsupported_media_type() {
        let oci_err = oci_client::errors::OciDistributionError::UnsupportedMediaTypeError(
            "application/unknown".to_string(),
        );
        let push_err: PushError = oci_err.into();
        match push_err {
            PushError::OciError(inner) => {
                assert!(inner.to_string().contains("application/unknown"));
            }
            _ => panic!("Expected OciError variant"),
        }
    }

    #[test]
    fn test_push_error_oci_error_display() {
        let oci_err = oci_client::errors::OciDistributionError::GenericError(Some(
            "version mismatch".to_string(),
        ));
        let push_err = PushError::OciError(oci_err);
        assert!(push_err.to_string().contains("OCI distribution error"));
    }

    #[test]
    fn test_push_error_from_oci_spec_violation() {
        let oci_err = oci_client::errors::OciDistributionError::SpecViolationError(
            "OCI spec violation".to_string(),
        );
        let push_err: PushError = oci_err.into();
        match push_err {
            PushError::OciError(inner) => {
                assert!(
                    inner.to_string().contains("spec") || inner.to_string().contains("violation")
                );
            }
            _ => panic!("Expected OciError variant"),
        }
    }

    #[test]
    fn test_push_error_from_oci_versioned_parsing_error() {
        let oci_err = oci_client::errors::OciDistributionError::VersionedParsingError(
            "failed to parse versioned content".to_string(),
        );
        let push_err: PushError = oci_err.into();
        match push_err {
            PushError::OciError(inner) => {
                let _ = inner.to_string();
            }
            _ => panic!("Expected OciError variant"),
        }
    }

    #[test]
    fn test_push_error_from_oci_registry_token_decode() {
        let oci_err = oci_client::errors::OciDistributionError::RegistryTokenDecodeError(
            "invalid token format".to_string(),
        );
        let push_err: PushError = oci_err.into();
        match push_err {
            PushError::OciError(inner) => {
                assert!(inner.to_string().contains("token"));
            }
            _ => panic!("Expected OciError variant"),
        }
    }

    #[test]
    fn test_push_error_from_oci_incompatible_layer_media_type() {
        let oci_err = oci_client::errors::OciDistributionError::IncompatibleLayerMediaTypeError(
            "application/vnd.incompatible".to_string(),
        );
        let push_err: PushError = oci_err.into();
        match push_err {
            PushError::OciError(inner) => {
                assert!(
                    inner.to_string().contains("incompatible")
                        || inner.to_string().contains("layer")
                );
            }
            _ => panic!("Expected OciError variant"),
        }
    }

    // =========================================================================
    // PushResult Tests
    // =========================================================================

    #[test]
    fn test_push_result_creation_all_fields() {
        let result = PushResult {
            manifest_digest: "sha256:abc123".to_string(),
            blobs_pushed: vec!["sha256:def456".to_string(), "sha256:ghi789".to_string()],
            reference: "ghcr.io/test/image:v1.0".to_string(),
        };
        assert_eq!(result.manifest_digest, "sha256:abc123");
        assert_eq!(result.blobs_pushed.len(), 2);
        assert_eq!(result.blobs_pushed[0], "sha256:def456");
        assert_eq!(result.blobs_pushed[1], "sha256:ghi789");
        assert_eq!(result.reference, "ghcr.io/test/image:v1.0");
    }

    #[test]
    fn test_push_result_creation_empty_blobs() {
        let result = PushResult {
            manifest_digest: "sha256:empty".to_string(),
            blobs_pushed: vec![],
            reference: "docker.io/test:latest".to_string(),
        };
        assert!(result.blobs_pushed.is_empty());
        assert_eq!(result.manifest_digest, "sha256:empty");
    }

    #[test]
    fn test_push_result_creation_single_blob() {
        let result = PushResult {
            manifest_digest: "sha256:single".to_string(),
            blobs_pushed: vec!["sha256:only_one".to_string()],
            reference: "registry.example.com/repo:tag".to_string(),
        };
        assert_eq!(result.blobs_pushed.len(), 1);
    }

    #[test]
    fn test_push_result_creation_many_blobs() {
        let blobs: Vec<String> = (0..100).map(|i| format!("sha256:blob{i:03}")).collect();
        let result = PushResult {
            manifest_digest: "sha256:many".to_string(),
            blobs_pushed: blobs,
            reference: "test/image:v1".to_string(),
        };
        assert_eq!(result.blobs_pushed.len(), 100);
        assert_eq!(result.blobs_pushed[0], "sha256:blob000");
        assert_eq!(result.blobs_pushed[99], "sha256:blob099");
    }

    #[test]
    fn test_push_result_clone() {
        let result = PushResult {
            manifest_digest: "sha256:abc".to_string(),
            blobs_pushed: vec!["sha256:def".to_string()],
            reference: "test:v1".to_string(),
        };
        let cloned = result.clone();
        assert_eq!(result.manifest_digest, cloned.manifest_digest);
        assert_eq!(result.blobs_pushed, cloned.blobs_pushed);
        assert_eq!(result.reference, cloned.reference);
    }

    #[test]
    fn test_push_result_clone_independence() {
        let result = PushResult {
            manifest_digest: "sha256:original".to_string(),
            blobs_pushed: vec!["sha256:blob1".to_string()],
            reference: "original:v1".to_string(),
        };
        let mut cloned = result.clone();
        cloned.manifest_digest = "sha256:modified".to_string();
        cloned.blobs_pushed.push("sha256:blob2".to_string());

        // Original should be unchanged
        assert_eq!(result.manifest_digest, "sha256:original");
        assert_eq!(result.blobs_pushed.len(), 1);

        // Cloned should have changes
        assert_eq!(cloned.manifest_digest, "sha256:modified");
        assert_eq!(cloned.blobs_pushed.len(), 2);
    }

    #[test]
    fn test_push_result_debug() {
        let result = PushResult {
            manifest_digest: "sha256:test".to_string(),
            blobs_pushed: vec!["sha256:blob1".to_string(), "sha256:blob2".to_string()],
            reference: "ghcr.io/org/repo:tag".to_string(),
        };
        let debug_str = format!("{result:?}");
        assert!(debug_str.contains("PushResult"));
        assert!(debug_str.contains("sha256:test"));
        assert!(debug_str.contains("sha256:blob1"));
        assert!(debug_str.contains("sha256:blob2"));
        assert!(debug_str.contains("ghcr.io/org/repo:tag"));
    }

    #[test]
    fn test_push_result_with_full_sha256_digest() {
        let full_digest = "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
        let result = PushResult {
            manifest_digest: full_digest.to_string(),
            blobs_pushed: vec![full_digest.to_string()],
            reference: "test:latest".to_string(),
        };
        assert_eq!(result.manifest_digest.len(), 71); // "sha256:" + 64 hex chars
    }

    // =========================================================================
    // Reference Parsing Tests (for push methods)
    // =========================================================================

    #[test]
    fn test_valid_reference_parsing_docker_hub() {
        let reference = "docker.io/library/nginx:latest";
        let parsed: Result<Reference, _> = reference.parse();
        assert!(parsed.is_ok());
    }

    #[test]
    fn test_valid_reference_parsing_ghcr() {
        let reference = "ghcr.io/myorg/myrepo:v1.0.0";
        let parsed: Result<Reference, _> = reference.parse();
        assert!(parsed.is_ok());
    }

    #[test]
    fn test_valid_reference_parsing_with_digest() {
        let reference = "ghcr.io/test/image@sha256:abc123def456789012345678901234567890123456789012345678901234";
        let parsed: Result<Reference, _> = reference.parse();
        // Note: The oci_client may or may not accept this format
        // This test documents the current behavior
        let _ = parsed;
    }

    #[test]
    fn test_valid_reference_parsing_nested_repo() {
        let reference = "gcr.io/project-id/subdir/image:tag";
        let parsed: Result<Reference, _> = reference.parse();
        assert!(parsed.is_ok());
    }

    #[test]
    fn test_invalid_reference_empty() {
        let reference = "";
        let parsed: Result<Reference, _> = reference.parse();
        assert!(parsed.is_err());
    }

    #[test]
    fn test_invalid_reference_double_colon() {
        let reference = "invalid::reference";
        let parsed: Result<Reference, _> = reference.parse();
        assert!(parsed.is_err());
    }

    // =========================================================================
    // PushError Construction Helper Tests
    // =========================================================================

    #[test]
    fn test_push_error_authentication_failed_construction() {
        let err = PushError::AuthenticationFailed {
            registry: "test.registry.io".to_string(),
            reason: "credentials expired".to_string(),
        };
        // Verify the error contains the expected information
        let display = err.to_string();
        assert!(display.contains("test.registry.io"));
        assert!(display.contains("credentials expired"));
    }

    #[test]
    fn test_push_error_blob_upload_failed_construction() {
        let digest = "sha256:1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
        let err = PushError::BlobUploadFailed {
            digest: digest.to_string(),
            reason: "server returned 500".to_string(),
        };
        let display = err.to_string();
        assert!(display.contains(digest));
        assert!(display.contains("server returned 500"));
    }

    #[test]
    fn test_push_error_manifest_upload_failed_construction() {
        let err = PushError::ManifestUploadFailed {
            reason: "manifest already exists with different content".to_string(),
        };
        let display = err.to_string();
        assert!(display.contains("manifest already exists"));
    }

    #[test]
    fn test_push_error_network_error_construction() {
        let err = PushError::NetworkError("TLS handshake failed".to_string());
        let display = err.to_string();
        assert!(display.contains("TLS handshake failed"));
    }

    #[test]
    fn test_push_error_invalid_reference_construction() {
        let err = PushError::InvalidReference {
            reference: "not/a/valid/reference!!!".to_string(),
        };
        let display = err.to_string();
        assert!(display.contains("not/a/valid/reference!!!"));
    }

    // =========================================================================
    // Error Variant Discrimination Tests
    // =========================================================================

    #[test]
    fn test_push_error_is_authentication_failed() {
        let err = PushError::AuthenticationFailed {
            registry: "test".to_string(),
            reason: "test".to_string(),
        };
        assert!(matches!(err, PushError::AuthenticationFailed { .. }));
        assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
        assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
        assert!(!matches!(err, PushError::NetworkError(_)));
        assert!(!matches!(err, PushError::InvalidReference { .. }));
        assert!(!matches!(err, PushError::OciError(_)));
    }

    #[test]
    fn test_push_error_is_blob_upload_failed() {
        let err = PushError::BlobUploadFailed {
            digest: "test".to_string(),
            reason: "test".to_string(),
        };
        assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
        assert!(matches!(err, PushError::BlobUploadFailed { .. }));
        assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
        assert!(!matches!(err, PushError::NetworkError(_)));
        assert!(!matches!(err, PushError::InvalidReference { .. }));
        assert!(!matches!(err, PushError::OciError(_)));
    }

    #[test]
    fn test_push_error_is_manifest_upload_failed() {
        let err = PushError::ManifestUploadFailed {
            reason: "test".to_string(),
        };
        assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
        assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
        assert!(matches!(err, PushError::ManifestUploadFailed { .. }));
        assert!(!matches!(err, PushError::NetworkError(_)));
        assert!(!matches!(err, PushError::InvalidReference { .. }));
        assert!(!matches!(err, PushError::OciError(_)));
    }

    #[test]
    fn test_push_error_is_network_error() {
        let err = PushError::NetworkError("test".to_string());
        assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
        assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
        assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
        assert!(matches!(err, PushError::NetworkError(_)));
        assert!(!matches!(err, PushError::InvalidReference { .. }));
        assert!(!matches!(err, PushError::OciError(_)));
    }

    #[test]
    fn test_push_error_is_invalid_reference() {
        let err = PushError::InvalidReference {
            reference: "test".to_string(),
        };
        assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
        assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
        assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
        assert!(!matches!(err, PushError::NetworkError(_)));
        assert!(matches!(err, PushError::InvalidReference { .. }));
        assert!(!matches!(err, PushError::OciError(_)));
    }

    #[test]
    fn test_push_error_is_oci_error() {
        let oci_err =
            oci_client::errors::OciDistributionError::GenericError(Some("test".to_string()));
        let err = PushError::OciError(oci_err);
        assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
        assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
        assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
        assert!(!matches!(err, PushError::NetworkError(_)));
        assert!(!matches!(err, PushError::InvalidReference { .. }));
        assert!(matches!(err, PushError::OciError(_)));
    }

    // =========================================================================
    // Error std::error::Error Trait Tests
    // =========================================================================

    #[test]
    fn test_push_error_implements_error_trait() {
        let err = PushError::NetworkError("test".to_string());
        // Verify it implements std::error::Error by using the Error trait
        let _: &dyn std::error::Error = &err;
    }

    #[test]
    fn test_push_error_source_for_oci_error() {
        use std::error::Error;
        let oci_err =
            oci_client::errors::OciDistributionError::GenericError(Some("test".to_string()));
        let err = PushError::OciError(oci_err);
        // OciError variant should have a source
        let source = err.source();
        assert!(source.is_some());
    }

    #[test]
    fn test_push_error_source_for_other_variants() {
        use std::error::Error;

        let err1 = PushError::AuthenticationFailed {
            registry: "test".to_string(),
            reason: "test".to_string(),
        };
        assert!(err1.source().is_none());

        let err2 = PushError::BlobUploadFailed {
            digest: "test".to_string(),
            reason: "test".to_string(),
        };
        assert!(err2.source().is_none());

        let err3 = PushError::ManifestUploadFailed {
            reason: "test".to_string(),
        };
        assert!(err3.source().is_none());

        let err4 = PushError::NetworkError("test".to_string());
        assert!(err4.source().is_none());

        let err5 = PushError::InvalidReference {
            reference: "test".to_string(),
        };
        assert!(err5.source().is_none());
    }

    // =========================================================================
    // ImagePuller Creation Tests (without network)
    // =========================================================================

    #[test]
    fn test_image_puller_creation_with_blob_cache() {
        let cache = crate::cache::BlobCache::new().unwrap();
        let puller = ImagePuller::new(cache);
        // Just verify it was created successfully
        let _ = puller;
    }

    #[test]
    fn test_image_puller_with_concurrency_limit() {
        let cache = crate::cache::BlobCache::new().unwrap();
        let puller = ImagePuller::new(cache).with_concurrency_limit(5);
        let _ = puller;
    }

    #[test]
    fn test_image_puller_with_concurrency_limit_one() {
        let cache = crate::cache::BlobCache::new().unwrap();
        let puller = ImagePuller::new(cache).with_concurrency_limit(1);
        let _ = puller;
    }

    #[test]
    fn test_image_puller_with_shared_cache() {
        let cache = crate::cache::BlobCache::new().unwrap();
        let shared: Arc<Box<dyn BlobCacheBackend>> = Arc::new(Box::new(cache));
        let puller = ImagePuller::with_cache(shared);
        let _ = puller;
    }

    // =========================================================================
    // Push Method Reference Validation Tests (async)
    // =========================================================================

    #[tokio::test]
    async fn test_push_blob_invalid_reference_returns_error() {
        let cache = crate::cache::BlobCache::new().unwrap();
        let puller = ImagePuller::new(cache);

        let result = puller
            .push_blob(
                "invalid::reference",
                "sha256:test",
                b"test data",
                "application/octet-stream",
                &RegistryAuth::Anonymous,
            )
            .await;

        assert!(result.is_err());
        match result {
            Err(PushError::InvalidReference { reference }) => {
                assert_eq!(reference, "invalid::reference");
            }
            other => panic!("Expected InvalidReference error, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_push_blob_empty_reference_returns_error() {
        let cache = crate::cache::BlobCache::new().unwrap();
        let puller = ImagePuller::new(cache);

        let result = puller
            .push_blob(
                "",
                "sha256:test",
                b"test data",
                "application/octet-stream",
                &RegistryAuth::Anonymous,
            )
            .await;

        assert!(result.is_err());
        match result {
            Err(PushError::InvalidReference { reference }) => {
                assert!(reference.is_empty());
            }
            other => panic!("Expected InvalidReference error, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_push_manifest_invalid_reference_returns_error() {
        let cache = crate::cache::BlobCache::new().unwrap();
        let puller = ImagePuller::new(cache);

        let manifest = oci_client::manifest::OciImageManifest::default();

        let result = puller
            .push_manifest_to_registry("invalid::reference", &manifest, &RegistryAuth::Anonymous)
            .await;

        assert!(result.is_err());
        match result {
            Err(PushError::InvalidReference { reference }) => {
                assert_eq!(reference, "invalid::reference");
            }
            other => panic!("Expected InvalidReference error, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_push_manifest_empty_reference_returns_error() {
        let cache = crate::cache::BlobCache::new().unwrap();
        let puller = ImagePuller::new(cache);

        let manifest = oci_client::manifest::OciImageManifest::default();

        let result = puller
            .push_manifest_to_registry("", &manifest, &RegistryAuth::Anonymous)
            .await;

        assert!(result.is_err());
        match result {
            Err(PushError::InvalidReference { reference }) => {
                assert!(reference.is_empty());
            }
            other => panic!("Expected InvalidReference error, got {other:?}"),
        }
    }

    // =========================================================================
    // Push WASM Reference Validation Tests (async, feature-gated)
    // =========================================================================

    #[cfg(feature = "local")]
    #[tokio::test]
    async fn test_push_wasm_invalid_reference_returns_error() {
        use crate::wasm::WasiVersion;
        use crate::wasm_export::WasmExportResult;

        let cache = crate::cache::BlobCache::new().unwrap();
        let puller = ImagePuller::new(cache);

        let export_result = WasmExportResult {
            manifest_digest: "sha256:test".to_string(),
            manifest_size: 100,
            wasm_layer_digest: "sha256:wasm".to_string(),
            wasm_size: 1000,
            config_digest: "sha256:config".to_string(),
            config_size: 2,
            wasi_version: WasiVersion::Preview1,
            artifact_type: "application/vnd.wasm.module.v1+wasm".to_string(),
            manifest_json: b"{}".to_vec(),
            config_blob: b"{}".to_vec(),
            wasm_binary: vec![0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00],
        };

        let result = puller
            .push_wasm(
                "invalid::reference",
                &export_result,
                &RegistryAuth::Anonymous,
            )
            .await;

        assert!(result.is_err());
        match result {
            Err(PushError::InvalidReference { reference }) => {
                assert_eq!(reference, "invalid::reference");
            }
            other => panic!("Expected InvalidReference error, got {other:?}"),
        }
    }

    #[cfg(feature = "local")]
    #[tokio::test]
    async fn test_push_wasm_empty_reference_returns_error() {
        use crate::wasm::WasiVersion;
        use crate::wasm_export::WasmExportResult;

        let cache = crate::cache::BlobCache::new().unwrap();
        let puller = ImagePuller::new(cache);

        let export_result = WasmExportResult {
            manifest_digest: "sha256:test".to_string(),
            manifest_size: 100,
            wasm_layer_digest: "sha256:wasm".to_string(),
            wasm_size: 1000,
            config_digest: "sha256:config".to_string(),
            config_size: 2,
            wasi_version: WasiVersion::Preview2,
            artifact_type: "application/vnd.wasm.component.v1+wasm".to_string(),
            manifest_json: b"{}".to_vec(),
            config_blob: b"{}".to_vec(),
            wasm_binary: vec![0x00, 0x61, 0x73, 0x6d, 0x0d, 0x00, 0x01, 0x00],
        };

        let result = puller
            .push_wasm("", &export_result, &RegistryAuth::Anonymous)
            .await;

        assert!(result.is_err());
        match result {
            Err(PushError::InvalidReference { reference }) => {
                assert!(reference.is_empty());
            }
            other => panic!("Expected InvalidReference error, got {other:?}"),
        }
    }

    // =========================================================================
    // WasmExportResult Field Verification Tests (feature-gated)
    // =========================================================================

    #[cfg(feature = "local")]
    #[test]
    fn test_wasm_export_result_debug_formatting() {
        use crate::wasm::WasiVersion;
        use crate::wasm_export::WasmExportResult;

        let result = WasmExportResult {
            manifest_digest: "sha256:manifest".to_string(),
            manifest_size: 500,
            wasm_layer_digest: "sha256:layer".to_string(),
            wasm_size: 10000,
            config_digest: "sha256:cfg".to_string(),
            config_size: 2,
            wasi_version: WasiVersion::Preview2,
            artifact_type: "application/vnd.wasm.component.v1+wasm".to_string(),
            manifest_json: vec![],
            config_blob: vec![],
            wasm_binary: vec![],
        };

        let debug_str = format!("{result:?}");
        assert!(debug_str.contains("WasmExportResult"));
        assert!(debug_str.contains("sha256:manifest"));
        assert!(debug_str.contains("sha256:layer"));
        assert!(debug_str.contains("Preview2"));
    }

    #[cfg(feature = "local")]
    #[test]
    fn test_wasm_export_result_clone_independence() {
        use crate::wasm::WasiVersion;
        use crate::wasm_export::WasmExportResult;

        let result = WasmExportResult {
            manifest_digest: "sha256:original".to_string(),
            manifest_size: 100,
            wasm_layer_digest: "sha256:wasm".to_string(),
            wasm_size: 1000,
            config_digest: "sha256:config".to_string(),
            config_size: 2,
            wasi_version: WasiVersion::Preview1,
            artifact_type: "application/vnd.wasm.module.v1+wasm".to_string(),
            manifest_json: b"{}".to_vec(),
            config_blob: b"{}".to_vec(),
            wasm_binary: vec![0x00, 0x61, 0x73, 0x6d],
        };

        let mut cloned = result.clone();
        cloned.manifest_digest = "sha256:modified".to_string();

        // Original should be unchanged
        assert_eq!(result.manifest_digest, "sha256:original");
        assert_eq!(cloned.manifest_digest, "sha256:modified");
    }

    #[cfg(feature = "local")]
    #[test]
    fn test_wasm_export_result_all_fields_populated() {
        use crate::wasm::WasiVersion;
        use crate::wasm_export::WasmExportResult;

        let wasm_binary = vec![0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
        let config_blob = b"{}".to_vec();
        let manifest_json = b"{\"schemaVersion\": 2}".to_vec();

        let result = WasmExportResult {
            manifest_digest: "sha256:abc".to_string(),
            manifest_size: manifest_json.len() as u64,
            wasm_layer_digest: "sha256:def".to_string(),
            wasm_size: wasm_binary.len() as u64,
            config_digest: "sha256:ghi".to_string(),
            config_size: config_blob.len() as u64,
            wasi_version: WasiVersion::Preview1,
            artifact_type: "application/vnd.wasm.module.v1+wasm".to_string(),
            manifest_json: manifest_json.clone(),
            config_blob: config_blob.clone(),
            wasm_binary: wasm_binary.clone(),
        };

        // Verify all fields
        assert!(result.manifest_digest.starts_with("sha256:"));
        assert_eq!(result.manifest_size, manifest_json.len() as u64);
        assert!(result.wasm_layer_digest.starts_with("sha256:"));
        assert_eq!(result.wasm_size, wasm_binary.len() as u64);
        assert!(result.config_digest.starts_with("sha256:"));
        assert_eq!(result.config_size, config_blob.len() as u64);
        assert_eq!(result.wasi_version, WasiVersion::Preview1);
        assert!(result.artifact_type.contains("wasm"));
        assert!(!result.manifest_json.is_empty());
        assert!(!result.config_blob.is_empty());
        assert!(!result.wasm_binary.is_empty());
    }

    // =========================================================================
    // Integration Tests for Push Flow (Documenting Expected Behavior)
    // =========================================================================
    // Note: These tests document the expected behavior of push operations.
    // Full integration tests would require a mock registry server.

    #[test]
    fn test_push_flow_documentation_blob_before_manifest() {
        // This test documents that blobs must be pushed before the manifest.
        // The manifest references blobs by digest, so blobs must exist first.
        //
        // Expected flow:
        // 1. Push config blob -> get config digest
        // 2. Push layer blob(s) -> get layer digest(s)
        // 3. Build manifest referencing the digests
        // 4. Push manifest
        //
        // This is enforced by the push_wasm method which pushes blobs first.
    }

    #[test]
    fn test_push_flow_documentation_authentication_order() {
        // This test documents that authentication happens before each push operation.
        // The client authenticates separately for blob and manifest pushes.
        //
        // Expected flow for push_blob:
        // 1. Parse reference
        // 2. Authenticate for push operation
        // 3. Push blob data
        //
        // Expected flow for push_manifest:
        // 1. Parse reference
        // 2. Authenticate for push operation
        // 3. Push manifest
    }

    #[test]
    fn test_push_result_blobs_pushed_order() {
        // This test documents that blobs_pushed should contain digests
        // in the order they were pushed (config first, then layers).
        //
        // For WASM artifacts:
        // - blobs_pushed[0] = config digest (empty JSON)
        // - blobs_pushed[1] = wasm layer digest
        let result = PushResult {
            manifest_digest: "sha256:manifest".to_string(),
            blobs_pushed: vec!["sha256:config".to_string(), "sha256:wasm_layer".to_string()],
            reference: "test:v1".to_string(),
        };

        assert_eq!(result.blobs_pushed.len(), 2);
        // Config is pushed first
        assert!(result.blobs_pushed[0].contains("config"));
        // Layer is pushed second
        assert!(result.blobs_pushed[1].contains("layer"));
    }

    // =========================================================================
    // is_mutable_tag Tests
    // =========================================================================

    #[test]
    fn is_mutable_tag_recognises_no_tag() {
        assert!(is_mutable_tag("nginx"));
        assert!(is_mutable_tag("zachhandley/zlayer-manager"));
        assert!(is_mutable_tag("registry.example.com:5000/img"));
    }

    #[test]
    fn is_mutable_tag_recognises_empty_tag() {
        assert!(is_mutable_tag("nginx:"));
    }

    #[test]
    fn is_mutable_tag_recognises_known_mutable_tags() {
        assert!(is_mutable_tag("nginx:latest"));
        assert!(is_mutable_tag("nginx:dev"));
        assert!(is_mutable_tag("nginx:edge"));
        assert!(is_mutable_tag("nginx:main"));
        assert!(is_mutable_tag("nginx:master"));
        assert!(is_mutable_tag("zachhandley/zlayer-manager:latest"));
        assert!(is_mutable_tag("registry.example.com:5000/img:latest"));
    }

    #[test]
    fn is_mutable_tag_rejects_pinned_tags() {
        assert!(!is_mutable_tag("nginx:1.25"));
        assert!(!is_mutable_tag("nginx:1.25.3"));
        assert!(!is_mutable_tag("zachhandley/zlayer-manager:v0.10.70"));
        assert!(!is_mutable_tag("registry.example.com:5000/img:v1"));
    }

    #[test]
    fn is_mutable_tag_rejects_digest_refs() {
        assert!(!is_mutable_tag(
            "img@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
        ));
        assert!(!is_mutable_tag(
            "nginx:latest@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
        ));
        assert!(!is_mutable_tag(
            "registry.example.com:5000/img@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
        ));
    }

    // =========================================================================
    // Foreign-layer redirect fallback tests (MCR urls[])
    // =========================================================================

    #[test]
    fn is_blob_not_found_detects_404_server_error() {
        use oci_client::errors::OciDistributionError;
        let err = OciDistributionError::ServerError {
            code: 404,
            url: "https://example.com/v2/foo/blobs/sha256:abc".to_string(),
            message: "not found".to_string(),
        };
        assert!(is_blob_not_found(&err));
    }

    #[test]
    fn is_blob_not_found_detects_manifest_not_found() {
        use oci_client::errors::OciDistributionError;
        let err = OciDistributionError::ImageManifestNotFoundError("foo".to_string());
        assert!(is_blob_not_found(&err));
    }

    #[test]
    fn is_blob_not_found_detects_blob_unknown_registry_error() {
        use oci_client::errors::{OciDistributionError, OciEnvelope, OciError, OciErrorCode};
        let envelope = OciEnvelope {
            errors: vec![OciError {
                code: OciErrorCode::BlobUnknown,
                message: "blob gone".to_string(),
                detail: serde_json::Value::Null,
            }],
        };
        let err = OciDistributionError::RegistryError {
            envelope,
            url: "https://example.com/v2/foo/blobs/sha256:abc".to_string(),
        };
        assert!(is_blob_not_found(&err));
    }

    #[test]
    fn is_blob_not_found_rejects_non_404_server_error() {
        use oci_client::errors::OciDistributionError;
        let err = OciDistributionError::ServerError {
            code: 500,
            url: "https://example.com/v2/foo/blobs/sha256:abc".to_string(),
            message: "boom".to_string(),
        };
        assert!(!is_blob_not_found(&err));
    }

    #[test]
    fn is_blob_not_found_rejects_auth_failure() {
        use oci_client::errors::OciDistributionError;
        let err = OciDistributionError::AuthenticationFailure("bad creds".to_string());
        assert!(!is_blob_not_found(&err));
    }

    #[test]
    fn max_foreign_layer_redirects_is_capped() {
        // Guard against silently lifting the redirect cap — the pull path uses
        // .take(MAX_FOREIGN_LAYER_REDIRECTS) to avoid redirect spam.
        assert_eq!(MAX_FOREIGN_LAYER_REDIRECTS, 5);
    }

    #[tokio::test]
    async fn fetch_blob_from_url_rejects_invalid_url() {
        let result = fetch_blob_from_url(
            "not-a-url",
            "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
            None,
        )
        .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn fetch_archive_from_url_rejects_invalid_url() {
        let result = fetch_archive_from_url("not-a-url", None).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn fetch_archive_from_url_rejects_unreachable_host() {
        // 127.0.0.1:1 is not bound; connect refused happens synchronously.
        let result = fetch_archive_from_url("http://127.0.0.1:1/archive.tar", None).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn fetch_archive_from_url_accepts_basic_auth_without_panic() {
        // Auth should be forwarded to the reqwest builder; errors still surface
        // cleanly when the host is unreachable. Regression guard for the
        // `.basic_auth(user, Some(pw))` call path.
        let result =
            fetch_archive_from_url("http://127.0.0.1:1/archive.tar", Some(("user", "password")))
                .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn fetch_from_url_surfaces_context_in_error() {
        let result = fetch_from_url("http://127.0.0.1:1/thing", None, "test-context").await;
        let Err(err) = result else {
            panic!("expected connect-refused error");
        };
        let msg = err.to_string();
        assert!(
            msg.contains("test-context"),
            "error should include context label, got: {msg}"
        );
    }

    #[tokio::test]
    async fn fetch_blob_from_url_rejects_unreachable_host() {
        // 127.0.0.1:1 is not bound; connect refused happens synchronously.
        let result = fetch_blob_from_url(
            "http://127.0.0.1:1/foo",
            "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
            None,
        )
        .await;
        assert!(result.is_err());
    }

    // =========================================================================
    // build_platform_resolver tests — Windows os.version handling
    // =========================================================================

    /// Helper: build a minimal `ImageIndexEntry` with `os` / `arch` / optional
    /// `os.version` — all we need for resolver tests.
    fn mk_entry(os: &str, arch: &str, os_version: Option<&str>, digest: &str) -> ImageIndexEntry {
        ImageIndexEntry {
            media_type: "application/vnd.oci.image.manifest.v1+json".to_string(),
            digest: digest.to_string(),
            size: 0,
            platform: Some(oci_client::manifest::Platform {
                architecture: arch.to_string(),
                os: os.to_string(),
                os_version: os_version.map(str::to_string),
                os_features: None,
                variant: None,
                features: None,
            }),
            annotations: None,
        }
    }

    #[test]
    fn platform_resolver_windows_os_version_prefers_prefix_match() {
        use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
        // Two windows/amd64 entries differing only by os.version. Target
        // matches the 26100 family (Server 2025 / Win11 24H2).
        let manifests = vec![
            mk_entry(
                "windows",
                "amd64",
                Some("10.0.20348.2113"),
                "sha256:server2022",
            ),
            mk_entry(
                "windows",
                "amd64",
                Some("10.0.26100.1742"),
                "sha256:server2025",
            ),
        ];
        let target =
            TargetPlatform::new(OsKind::Windows, ArchKind::Amd64).with_os_version("10.0.26100");
        let resolver = build_platform_resolver(Some(target));
        assert_eq!(resolver(&manifests).as_deref(), Some("sha256:server2025"));
    }

    #[test]
    fn platform_resolver_windows_os_version_exact_match() {
        use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
        let manifests = vec![
            mk_entry(
                "windows",
                "amd64",
                Some("10.0.20348.2113"),
                "sha256:server2022",
            ),
            mk_entry(
                "windows",
                "amd64",
                Some("10.0.26100.1742"),
                "sha256:server2025",
            ),
        ];
        let target = TargetPlatform::new(OsKind::Windows, ArchKind::Amd64)
            .with_os_version("10.0.26100.1742");
        let resolver = build_platform_resolver(Some(target));
        assert_eq!(resolver(&manifests).as_deref(), Some("sha256:server2025"));
    }

    #[test]
    fn platform_resolver_windows_no_os_version_falls_back_to_first_match() {
        use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
        // When the caller doesn't pin os_version the resolver's behavior is
        // unchanged from Phase A: it picks the first os+arch match.
        let manifests = vec![
            mk_entry("windows", "amd64", Some("10.0.20348.2113"), "sha256:first"),
            mk_entry("windows", "amd64", Some("10.0.26100.1742"), "sha256:second"),
        ];
        let target = TargetPlatform::new(OsKind::Windows, ArchKind::Amd64);
        let resolver = build_platform_resolver(Some(target));
        assert_eq!(resolver(&manifests).as_deref(), Some("sha256:first"));
    }

    #[test]
    fn platform_resolver_windows_os_version_falls_back_when_no_version_match() {
        use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
        // Target wants 26100 but the index only has 20348. Fall back to the
        // any-windows/amd64 entry rather than returning None — otherwise a
        // bootstrap image that ships a single old-build manifest is
        // unpullable on a new host.
        let manifests = vec![mk_entry(
            "windows",
            "amd64",
            Some("10.0.20348.2113"),
            "sha256:only",
        )];
        let target =
            TargetPlatform::new(OsKind::Windows, ArchKind::Amd64).with_os_version("10.0.26100");
        let resolver = build_platform_resolver(Some(target));
        assert_eq!(resolver(&manifests).as_deref(), Some("sha256:only"));
    }

    #[test]
    fn platform_resolver_non_windows_ignores_os_version() {
        use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
        // os_version is a Windows-only concept; setting it on a Linux target
        // must NOT accidentally filter out a valid linux/amd64 manifest.
        let manifests = vec![mk_entry("linux", "amd64", None, "sha256:linux")];
        let target =
            TargetPlatform::new(OsKind::Linux, ArchKind::Amd64).with_os_version("ignored.on.linux");
        let resolver = build_platform_resolver(Some(target));
        assert_eq!(resolver(&manifests).as_deref(), Some("sha256:linux"));
    }
}