zlayer-registry 0.10.63

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
//! 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,
    }
}

/// Platform resolver that works correctly on macOS.
///
/// On macOS, this performs a two-pass search:
/// 1. First tries `darwin/{arch}` for native macOS sandbox images from the
///    zlayer registry.
/// 2. Falls back to `linux/{arch}` for standard Docker Hub images (which run
///    inside a Linux VM via Docker Desktop or similar).
///
/// On all other platforms this behaves identically to oci-client's
/// `current_platform_resolver`: it matches `{os}/{arch}` using the runtime
/// values (with the standard Rust-to-Go name mapping).
fn zlayer_platform_resolver(manifests: &[ImageIndexEntry]) -> Option<String> {
    let target_arch = go_arch_name();

    // On macOS, try darwin first (for native zlayer sandbox images),
    // then fall back to linux (for standard Docker Hub images).
    if cfg!(target_os = "macos") {
        // Pass 1: darwin/{arch} (native macOS images)
        if let Some(entry) = manifests.iter().find(|entry| {
            entry
                .platform
                .as_ref()
                .is_some_and(|p| p.os == "darwin" && p.architecture == target_arch)
        }) {
            return Some(entry.digest.clone());
        }
        // Pass 2: linux/{arch} (standard container images for VM runtime)
        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());
    }

    // Non-macOS: match native platform
    let target_os = go_os_name();
    manifests
        .iter()
        .find(|entry| {
            entry
                .platform
                .as_ref()
                .is_some_and(|p| p.os == target_os && p.architecture == target_arch)
        })
        .map(|entry| entry.digest.clone())
}

/// Build a [`ClientConfig`] with the zlayer platform resolver and sensible
/// defaults for timeouts and protocol.
fn build_client_config() -> 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(zlayer_platform_resolver)),
        ..Default::default()
    }
}

/// OCI image puller with caching
pub struct ImagePuller {
    client: oci_client::Client,
    cache: Arc<Box<dyn BlobCacheBackend>>,
    concurrency_limit: Arc<Semaphore>,
}

impl ImagePuller {
    /// Create a new image puller with any cache backend
    pub fn new<C: BlobCacheBackend + 'static>(cache: C) -> Self {
        let client = oci_client::Client::new(build_client_config());

        Self {
            client,
            cache: Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>),
            concurrency_limit: Arc::new(Semaphore::new(3)),
        }
    }

    /// Create a new image puller with boxed cache backend
    #[must_use]
    pub fn with_cache(cache: Arc<Box<dyn BlobCacheBackend>>) -> Self {
        let client = oci_client::Client::new(build_client_config());

        Self {
            client,
            cache,
            concurrency_limit: Arc::new(Semaphore::new(3)),
        }
    }

    /// 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
    }

    /// 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>> {
        // 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();
        self.client
            .pull_blob(&reference, digest, &mut buffer)
            .await
            .map_err(|e| {
                tracing::error!(error = %e, digest = %digest, image = %image, "failed to pull blob from registry");
                RegistryError::Oci(e)
            })?;

        // 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)
    }

    /// Pull an image manifest from the registry
    ///
    /// Returns the manifest and its digest. Manifests are cached to avoid
    /// repeated network requests for the same image reference.
    ///
    /// # 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)> {
        // Cache key: use "manifest:" prefix + image reference
        let cache_key = format!("manifest:{image}");

        // Check cache first
        if let Ok(Some(data)) = self.cache.get(&cache_key).await {
            if let Ok(manifest) = serde_json::from_slice::<OciImageManifest>(&data) {
                let digest = crate::cache::compute_digest(&data);
                tracing::debug!(image = %image, "manifest cache hit");
                return Ok((manifest, digest));
            }
        }

        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");

        let (manifest, digest) = self
            .client
            .pull_image_manifest(&reference, auth)
            .await
            .map_err(|e| {
                tracing::error!(error = %e, image = %image, "failed to pull manifest");
                RegistryError::Oci(e)
            })?;

        tracing::debug!(
            image = %image,
            digest = %digest,
            layers = manifest.layers.len(),
            "manifest pulled successfully"
        );

        // Cache for next time
        if let Ok(bytes) = serde_json::to_vec(&manifest) {
            let _ = self.cache.put(&cache_key, &bytes).await;
        }

        Ok((manifest, digest))
    }

    /// 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)
    }

    /// 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 data = self.pull_blob(image, &layer.digest, auth).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)
    }

    /// 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)
    }
}

#[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"));
    }
}