zlayer-registry 0.14.2

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
//! OCI Image Layout export/import functionality
//!
//! This module provides functionality to export images to OCI Image Layout format
//! (as tar archives) and import images from OCI Image Layout archives.
//!
//! ## OCI Image Layout Specification
//!
//! The OCI Image Layout defines a directory structure for storing OCI images:
//!
//! ```text
//! image-layout/
//! |-- blobs/
//! |   |-- sha256/
//! |       |-- <digest>   # blob content (layers, config, manifest)
//! |-- oci-layout         # JSON file marking OCI layout version
//! |-- index.json         # image index referencing manifests
//! ```
//!
//! ## Usage
//!
//! ```rust,no_run
//! use zlayer_registry::oci_export::{export_image, import_image};
//! use zlayer_registry::LocalRegistry;
//! use std::path::Path;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let registry = LocalRegistry::new("/var/lib/zlayer/registry".into()).await?;
//!
//! // Export an image to a tar.gz file
//! let info = export_image(&registry, "myapp:latest", Path::new("/tmp/myapp.tar.gz")).await?;
//! println!("Exported {} layers, digest: {}", info.layers, info.digest);
//!
//! // Import an image from a tar file
//! let info = import_image(&registry, Path::new("/tmp/myapp.tar.gz"), Some("myapp:imported"), None).await?;
//! println!("Imported {} layers, digest: {}", info.layers, info.digest);
//! # Ok(())
//! # }
//! ```

use crate::cache::compute_digest;
use crate::local_registry::LocalRegistry;
use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use flate2::Compression;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use tar::{Archive, Builder};
use thiserror::Error;
use tokio::fs;

/// OCI Image Layout version marker file content
///
/// This struct represents the contents of the `oci-layout` file that
/// marks a directory as containing an OCI Image Layout.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OciLayout {
    /// The version of the OCI Image Layout specification
    #[serde(rename = "imageLayoutVersion")]
    pub image_layout_version: String,
}

impl Default for OciLayout {
    fn default() -> Self {
        Self {
            image_layout_version: "1.0.0".to_string(),
        }
    }
}

/// OCI Image Index (index.json)
///
/// The image index is the entry point for an OCI Image Layout. It contains
/// references to one or more image manifests.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OciIndex {
    /// Schema version (must be 2 for OCI Image Spec)
    #[serde(rename = "schemaVersion")]
    pub schema_version: u32,

    /// Media type of this index
    #[serde(rename = "mediaType", skip_serializing_if = "Option::is_none")]
    pub media_type: Option<String>,

    /// List of manifest descriptors
    pub manifests: Vec<OciDescriptor>,

    /// Optional annotations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<HashMap<String, String>>,
}

impl OciIndex {
    /// Create a new OCI Index with a single manifest
    #[must_use]
    pub fn new(manifest_descriptor: OciDescriptor) -> Self {
        Self {
            schema_version: 2,
            media_type: Some("application/vnd.oci.image.index.v1+json".to_string()),
            manifests: vec![manifest_descriptor],
            annotations: None,
        }
    }
}

/// OCI Content Descriptor
///
/// A descriptor is used to reference content by digest, media type, and size.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OciDescriptor {
    /// MIME type of the referenced content
    #[serde(rename = "mediaType")]
    pub media_type: String,

    /// Content digest (e.g., "sha256:...")
    pub digest: String,

    /// Size of the content in bytes
    pub size: u64,

    /// URLs from which this content may be downloaded
    #[serde(skip_serializing_if = "Option::is_none")]
    pub urls: Option<Vec<String>>,

    /// Optional annotations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<HashMap<String, String>>,

    /// Platform specification (for manifest lists)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub platform: Option<OciPlatform>,
}

/// OCI Platform specification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OciPlatform {
    /// Target architecture (e.g., "amd64", "arm64")
    pub architecture: String,

    /// Target operating system (e.g., "linux", "windows")
    pub os: String,

    /// Optional OS version
    #[serde(rename = "os.version", skip_serializing_if = "Option::is_none")]
    pub os_version: Option<String>,

    /// Optional OS features
    #[serde(rename = "os.features", skip_serializing_if = "Option::is_none")]
    pub os_features: Option<Vec<String>>,

    /// Optional CPU variant
    #[serde(skip_serializing_if = "Option::is_none")]
    pub variant: Option<String>,
}

/// OCI Image Manifest
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OciManifest {
    /// Schema version (must be 2)
    #[serde(rename = "schemaVersion")]
    pub schema_version: u32,

    /// Media type of this manifest
    #[serde(rename = "mediaType", skip_serializing_if = "Option::is_none")]
    pub media_type: Option<String>,

    /// Config descriptor
    #[serde(skip_serializing_if = "Option::is_none")]
    pub config: Option<OciDescriptor>,

    /// Layer descriptors
    #[serde(default)]
    pub layers: Vec<OciDescriptor>,

    /// Optional annotations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<HashMap<String, String>>,
}

/// Information about an exported image
#[derive(Debug, Clone)]
pub struct ExportInfo {
    /// Manifest digest of the exported image
    pub digest: String,

    /// Total size of the exported archive in bytes
    pub size: u64,

    /// Number of layers in the image
    pub layers: usize,

    /// Path to the output file
    pub output_path: PathBuf,
}

/// Information about an imported image
#[derive(Debug, Clone)]
pub struct ImportInfo {
    /// Manifest digest of the imported image
    pub digest: String,

    /// Tag applied to the imported image (if any)
    pub tag: Option<String>,

    /// Number of layers in the image
    pub layers: usize,
}

/// Errors that can occur during export operations
#[derive(Debug, Error)]
pub enum ExportError {
    /// Image was not found in the registry
    #[error("image not found: {0}")]
    ImageNotFound(String),

    /// IO error during export
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// Registry error
    #[error("registry error: {0}")]
    Registry(String),

    /// JSON serialization error
    #[error("serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

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

/// Errors that can occur during import operations
#[derive(Debug, Error)]
pub enum ImportError {
    /// The archive does not have a valid OCI Image Layout
    #[error("invalid OCI layout: {0}")]
    InvalidLayout(String),

    /// IO error during import
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// Registry error
    #[error("registry error: {0}")]
    Registry(String),

    /// JSON deserialization error
    #[error("serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    /// Blob referenced in manifest not found in archive
    #[error("blob not found in archive: {0}")]
    BlobNotFound(String),
}

/// Parse an image reference into name and reference (tag or digest)
///
/// Supports formats:
/// - `name:tag` -> ("name", "tag")
/// - `name@sha256:...` -> ("name", "sha256:...")
/// - `name` -> ("name", "latest")
fn parse_image_reference(image: &str) -> Result<(String, String), ExportError> {
    // Check for digest reference first
    if let Some(at_pos) = image.find('@') {
        let name = &image[..at_pos];
        let digest = &image[at_pos + 1..];
        if !digest.starts_with("sha256:") {
            return Err(ExportError::InvalidReference(format!(
                "digest must start with sha256: in '{image}'"
            )));
        }
        return Ok((name.to_string(), digest.to_string()));
    }

    // Check for tag reference
    if let Some(colon_pos) = image.rfind(':') {
        // Make sure it's not part of a port number or registry URL
        let potential_tag = &image[colon_pos + 1..];
        if !potential_tag.contains('/') && !potential_tag.is_empty() {
            let name = &image[..colon_pos];
            return Ok((name.to_string(), potential_tag.to_string()));
        }
    }

    // Default to latest tag
    Ok((image.to_string(), "latest".to_string()))
}

/// Export an image from the local registry to an OCI Image Layout tar archive
///
/// # Arguments
///
/// * `registry` - The local registry containing the image
/// * `image` - Image reference in the format `name:tag` or `name@sha256:...`
/// * `output` - Output path for the tar file. If it ends with `.gz`, the archive
///   will be gzip compressed.
///
/// # Returns
///
/// Returns `ExportInfo` containing details about the exported image.
///
/// # Errors
///
/// Returns an error if the image reference is invalid, the manifest or blobs cannot be
/// read, or the output file cannot be written.
///
/// # Example
///
/// ```rust,no_run
/// use zlayer_registry::oci_export::export_image;
/// use zlayer_registry::LocalRegistry;
/// use std::path::Path;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let registry = LocalRegistry::new("/tmp/zlayer/registry".into()).await?;
/// let info = export_image(&registry, "myapp:v1.0", Path::new("/tmp/myapp.tar.gz")).await?;
/// println!("Exported image to {:?}", info.output_path);
/// # Ok(())
/// # }
/// ```
pub async fn export_image(
    registry: &LocalRegistry,
    image: &str,
    output: &Path,
) -> Result<ExportInfo, ExportError> {
    let (name, reference) = parse_image_reference(image)?;

    // Get the manifest
    let manifest_data = registry
        .get_manifest(&name, &reference)
        .await
        .map_err(|e| ExportError::Registry(e.to_string()))?;

    let manifest_digest = compute_digest(&manifest_data);

    // Parse the manifest to get layer and config digests
    let manifest: OciManifest = serde_json::from_slice(&manifest_data)?;

    // Collect all blobs we need to export
    let mut blobs_to_export: Vec<(String, Vec<u8>)> = Vec::new();

    // Add config blob if present
    if let Some(ref config) = manifest.config {
        let config_data = registry
            .get_blob(&config.digest)
            .await
            .map_err(|e| ExportError::Registry(e.to_string()))?;
        blobs_to_export.push((config.digest.clone(), config_data));
    }

    // Add layer blobs
    for layer in &manifest.layers {
        let layer_data = registry
            .get_blob(&layer.digest)
            .await
            .map_err(|e| ExportError::Registry(e.to_string()))?;
        blobs_to_export.push((layer.digest.clone(), layer_data));
    }

    // Add manifest blob
    blobs_to_export.push((manifest_digest.clone(), manifest_data.clone()));

    // Create OCI layout structure
    let oci_layout = OciLayout::default();
    let oci_layout_json = serde_json::to_string_pretty(&oci_layout)?;

    // Create index.json
    let mut annotations = HashMap::new();
    // Store original reference if it was a tag
    if !reference.starts_with("sha256:") {
        annotations.insert(
            "org.opencontainers.image.ref.name".to_string(),
            format!("{name}:{reference}"),
        );
    }

    let manifest_descriptor = OciDescriptor {
        media_type: manifest
            .media_type
            .clone()
            .unwrap_or_else(|| "application/vnd.oci.image.manifest.v1+json".to_string()),
        digest: manifest_digest.clone(),
        size: manifest_data.len() as u64,
        urls: None,
        annotations: if annotations.is_empty() {
            None
        } else {
            Some(annotations)
        },
        platform: None,
    };

    let index = OciIndex::new(manifest_descriptor);
    let index_json = serde_json::to_string_pretty(&index)?;

    // Determine if we should compress
    let output_str = output.to_string_lossy();
    let compress = output_str.ends_with(".gz") || output_str.ends_with(".tgz");

    // Build the tar archive in memory first, then write to file
    let tar_data = {
        let mut tar_builder = Builder::new(Vec::new());

        // Add oci-layout file
        add_file_to_tar(&mut tar_builder, "oci-layout", oci_layout_json.as_bytes())?;

        // Add index.json
        add_file_to_tar(&mut tar_builder, "index.json", index_json.as_bytes())?;

        // Add all blobs
        for (digest, data) in &blobs_to_export {
            let hash = digest.strip_prefix("sha256:").unwrap_or(digest);
            let blob_path = format!("blobs/sha256/{hash}");
            add_file_to_tar(&mut tar_builder, &blob_path, data)?;
        }

        tar_builder.finish()?;
        tar_builder.into_inner()?
    };

    // Write the tar (optionally compressed) to the output file
    let output_data = if compress {
        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(&tar_data)?;
        encoder.finish()?
    } else {
        tar_data
    };

    fs::write(output, &output_data).await?;

    let export_info = ExportInfo {
        digest: manifest_digest,
        size: output_data.len() as u64,
        layers: manifest.layers.len(),
        output_path: output.to_path_buf(),
    };

    tracing::info!(
        digest = %export_info.digest,
        layers = export_info.layers,
        size = export_info.size,
        output = %export_info.output_path.display(),
        "exported image to OCI layout"
    );

    Ok(export_info)
}

/// Import an image from an OCI Image Layout tar archive into the local registry
///
/// # Arguments
///
/// * `registry` - The local registry to import into
/// * `input` - Path to the tar file (supports both `.tar` and `.tar.gz`)
/// * `tag` - Optional tag to apply to the imported image. If not provided, the
///   original tag from the archive annotations will be used if available.
///
/// # Returns
///
/// Returns `ImportInfo` containing details about the imported image.
///
/// # Errors
///
/// Returns an error if the archive cannot be read, the OCI layout is invalid,
/// or blobs/manifests cannot be stored in the registry.
///
/// # Example
///
/// ```rust,no_run
/// use zlayer_registry::oci_export::import_image;
/// use zlayer_registry::LocalRegistry;
/// use std::path::Path;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let registry = LocalRegistry::new("/tmp/zlayer/registry".into()).await?;
/// let info = import_image(&registry, Path::new("/tmp/myapp.tar.gz"), Some("myapp:imported"), None).await?;
/// println!("Imported image with digest: {}", info.digest);
/// # Ok(())
/// # }
/// ```
pub async fn import_image(
    registry: &LocalRegistry,
    input: &Path,
    tag: Option<&str>,
    blob_cache: Option<&dyn crate::cache::BlobCacheBackend>,
) -> Result<ImportInfo, ImportError> {
    let archive_data = fs::read(input).await?;
    import_image_from_bytes(registry, archive_data, tag, blob_cache).await
}

/// Import an image from OCI tar archive bytes already resident in memory.
///
/// Same semantics as [`import_image`], but accepts an in-memory byte buffer
/// instead of reading from disk. Used by the `zlayer import --url` code path
/// (which fetches the archive over HTTP via [`crate::fetch_archive_from_url`])
/// and by any other caller that already has the archive bytes in hand.
///
/// Compression is auto-detected from the gzip magic number — no filename is
/// needed. Bytes may be a plain tar or a gzip-compressed tar.
///
/// # Errors
///
/// Returns [`ImportError`] on invalid OCI layout, missing/malformed manifest,
/// unknown blob references, or local registry I/O failures.
#[allow(clippy::too_many_lines)]
pub async fn import_image_from_bytes(
    registry: &LocalRegistry,
    archive_data: Vec<u8>,
    tag: Option<&str>,
    blob_cache: Option<&dyn crate::cache::BlobCacheBackend>,
) -> Result<ImportInfo, ImportError> {
    // Decompress if gzipped (magic-number detection, no filename required)
    let tar_data = if is_gzip(&archive_data) {
        let mut decoder = GzDecoder::new(&archive_data[..]);
        let mut decompressed = Vec::new();
        decoder.read_to_end(&mut decompressed)?;
        decompressed
    } else {
        archive_data
    };

    // Extract archive contents into memory
    let mut archive = Archive::new(&tar_data[..]);
    let mut files: HashMap<String, Vec<u8>> = HashMap::new();

    for entry in archive.entries()? {
        let mut entry = entry?;
        let path = entry.path()?.to_string_lossy().to_string();

        let mut contents = Vec::new();
        entry.read_to_end(&mut contents)?;
        files.insert(path, contents);
    }

    // Dispatch on archive format. An OCI Image Layout is marked by an
    // `oci-layout` file; `docker save` / `podman save` instead emit a Docker
    // Archive whose entry point is a top-level `manifest.json` array (and which
    // has no `oci-layout`). Prefer OCI when both are present (hybrid archives).
    if files.contains_key("oci-layout") {
        import_from_oci_layout(registry, &files, tag, blob_cache).await
    } else if files.contains_key("manifest.json") {
        import_from_docker_archive(registry, &files, tag, blob_cache).await
    } else {
        Err(ImportError::InvalidLayout(
            "archive is neither an OCI image layout (no oci-layout) nor a Docker \
             archive (no manifest.json)"
                .to_string(),
        ))
    }
}

/// A single image entry in a Docker Archive `manifest.json` (the format produced
/// by `docker save` and `podman save --format docker-archive`).
#[derive(Debug, Clone, Deserialize)]
struct DockerManifestEntry {
    /// Path within the archive to the image config JSON (e.g.
    /// `blobs/sha256/<hash>` on modern engines, or `<hash>.json` on older ones).
    #[serde(rename = "Config")]
    config: String,
    /// Repository tags this image was saved under (e.g. `["nginx:latest"]`).
    #[serde(rename = "RepoTags")]
    repo_tags: Option<Vec<String>>,
    /// Ordered list of layer paths within the archive. Each entry may be an
    /// uncompressed `tar` (`<id>/layer.tar`) or a `blobs/sha256/<hash>` blob.
    #[serde(rename = "Layers", default)]
    layers: Vec<String>,
}

/// Look up a file in an extracted archive, tolerating a leading `./` on either
/// the stored tar path or the manifest-referenced path.
fn archive_lookup<'a>(files: &'a HashMap<String, Vec<u8>>, key: &str) -> Option<&'a Vec<u8>> {
    files
        .get(key)
        .or_else(|| files.get(key.trim_start_matches("./")))
        .or_else(|| files.get(&format!("./{key}")))
}

/// Resolve the `(name, tag)` to store an imported image under.
///
/// Precedence: an explicit user-supplied `tag`, then the archive's own
/// reference (OCI `ref.name` annotation or Docker `RepoTags[0]`), then a
/// generated `imported-<shortdigest>` name. A trailing `:<tag>` is only treated
/// as a tag when it is not actually a `registry:port` segment (i.e. the part
/// after the last colon contains no `/`).
fn resolve_name_and_tag(
    tag: Option<&str>,
    original_ref: Option<&str>,
    manifest_digest: &str,
) -> (String, Option<String>) {
    let split_ref = |r: &str| -> (String, Option<String>) {
        if let Some(at_pos) = r.find('@') {
            return (r[..at_pos].to_string(), None);
        }
        if let Some(colon_pos) = r.rfind(':') {
            let potential = &r[colon_pos + 1..];
            if !potential.contains('/') && !potential.is_empty() {
                return (r[..colon_pos].to_string(), Some(potential.to_string()));
            }
        }
        (r.to_string(), Some("latest".to_string()))
    };

    if let Some(t) = tag {
        split_ref(t)
    } else if let Some(orig) = original_ref {
        split_ref(orig)
    } else {
        // First 12 hex chars of the digest (skip the "sha256:" prefix).
        let short_digest = &manifest_digest[7..19];
        (format!("imported-{short_digest}"), None)
    }
}

/// Import an image from a Docker Archive (`docker save` / `podman save`).
///
/// Docker archives differ from OCI image layouts: their entry point is a
/// top-level `manifest.json` array referencing a config blob and an ordered set
/// of layer blobs (which may be uncompressed `tar` or gzip-compressed). We read
/// those blobs, synthesize an equivalent OCI image manifest over the bytes we
/// store (labelling each layer `tar` or `tar+gzip` by gzip magic), and persist
/// the config, layers, and manifest into the local registry + daemon blob cache
/// exactly as the OCI path does — so an imported Docker archive is afterwards
/// indistinguishable from a pulled image.
async fn import_from_docker_archive(
    registry: &LocalRegistry,
    files: &HashMap<String, Vec<u8>>,
    tag: Option<&str>,
    blob_cache: Option<&dyn crate::cache::BlobCacheBackend>,
) -> Result<ImportInfo, ImportError> {
    let manifest_json = files
        .get("manifest.json")
        .ok_or_else(|| ImportError::InvalidLayout("missing manifest.json".to_string()))?;

    let entries: Vec<DockerManifestEntry> = serde_json::from_slice(manifest_json)?;
    let entry = entries.into_iter().next().ok_or_else(|| {
        ImportError::InvalidLayout("manifest.json contains no images".to_string())
    })?;

    // Config blob.
    let config_data = archive_lookup(files, &entry.config)
        .ok_or_else(|| ImportError::BlobNotFound(entry.config.clone()))?;
    let config_digest = compute_digest(config_data);
    registry
        .put_blob(config_data)
        .await
        .map_err(|e| ImportError::Registry(e.to_string()))?;
    if let Some(cache) = blob_cache {
        let _ = cache.put(&config_digest, config_data).await;
    }
    let config_desc = OciDescriptor {
        media_type: "application/vnd.oci.image.config.v1+json".to_string(),
        digest: config_digest,
        size: config_data.len() as u64,
        urls: None,
        annotations: None,
        platform: None,
    };

    // Layer blobs (preserve manifest order).
    let mut layer_descs = Vec::with_capacity(entry.layers.len());
    for layer_ref in &entry.layers {
        let layer_data = archive_lookup(files, layer_ref)
            .ok_or_else(|| ImportError::BlobNotFound(layer_ref.clone()))?;
        let digest = compute_digest(layer_data);
        let media_type = if is_gzip(layer_data) {
            "application/vnd.oci.image.layer.v1.tar+gzip"
        } else {
            "application/vnd.oci.image.layer.v1.tar"
        };
        registry
            .put_blob(layer_data)
            .await
            .map_err(|e| ImportError::Registry(e.to_string()))?;
        if let Some(cache) = blob_cache {
            let _ = cache.put(&digest, layer_data).await;
        }
        layer_descs.push(OciDescriptor {
            media_type: media_type.to_string(),
            digest,
            size: layer_data.len() as u64,
            urls: None,
            annotations: None,
            platform: None,
        });
    }
    let layer_count = layer_descs.len();

    // Synthesize an OCI manifest over the stored bytes.
    let manifest = OciManifest {
        schema_version: 2,
        media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
        config: Some(config_desc),
        layers: layer_descs,
        annotations: None,
    };
    let manifest_data = serde_json::to_vec(&manifest)?;
    let manifest_digest = compute_digest(&manifest_data);

    let original_ref = entry
        .repo_tags
        .as_ref()
        .and_then(|tags| tags.first())
        .cloned();
    let (name, final_tag) = resolve_name_and_tag(tag, original_ref.as_deref(), &manifest_digest);

    let reference = final_tag.clone().unwrap_or_else(|| manifest_digest.clone());
    registry
        .put_manifest(&name, &reference, &manifest_data)
        .await
        .map_err(|e| ImportError::Registry(e.to_string()))?;

    if let Some(cache) = blob_cache {
        let image_ref = if let Some(ref t) = final_tag {
            format!("{name}:{t}")
        } else {
            name.clone()
        };
        let cache_key = crate::client::manifest_cache_key(&image_ref);
        let _ = cache.put(&cache_key, &manifest_data).await;
    }

    let import_info = ImportInfo {
        digest: manifest_digest.clone(),
        tag: final_tag.map(|t| format!("{name}:{t}")),
        layers: layer_count,
    };

    tracing::info!(
        digest = %import_info.digest,
        tag = ?import_info.tag,
        layers = import_info.layers,
        "imported image from Docker archive"
    );

    Ok(import_info)
}

/// Import an image from an OCI Image Layout archive (the format produced by
/// `zlayer export`, `skopeo copy ... oci-archive:`, etc.).
#[allow(clippy::too_many_lines)]
/// Media types that denote an image *index* / manifest list (a nested set of
/// per-platform manifests) rather than a concrete image manifest.
fn is_index_media_type(media_type: &str) -> bool {
    matches!(
        media_type,
        "application/vnd.oci.image.index.v1+json"
            | "application/vnd.docker.distribution.manifest.list.v2+json"
    )
}

/// True when a descriptor is an attestation/SBOM manifest rather than a
/// runnable image. `buildx` emits these alongside the platform images in a
/// `docker save` / OCI layout, tagged with `platform.os == "unknown"` (and/or a
/// `vnd.docker.reference.type == attestation-manifest` annotation). Selecting
/// one yields a config-less, 0-layer "image" — exactly the corrupt import we
/// must avoid.
fn is_attestation_descriptor(descriptor: &OciDescriptor) -> bool {
    if let Some(platform) = &descriptor.platform {
        if platform.os == "unknown" || platform.architecture == "unknown" {
            return true;
        }
    }
    descriptor
        .annotations
        .as_ref()
        .and_then(|a| a.get("vnd.docker.reference.type"))
        .is_some_and(|v| v == "attestation-manifest")
}

/// From an OCI layout's top-level `index.json` manifest list, pick the
/// descriptor of the concrete image manifest to import.
///
/// The selection mirrors the pull path's platform preference
/// ([`crate::client`]'s `build_platform_resolver`): the host `{os}/{arch}` with
/// the macOS `darwin → linux` fallback (multi-arch images run inside a Linux VM
/// on macOS). It transparently descends into a nested image index (buildx
/// `docker save` archives commonly wrap the platform manifests in one), and
/// skips attestation manifests. A plain single-arch archive whose sole image
/// manifest carries no platform is imported directly.
///
/// Returns an actionable error when the archive references no image manifest,
/// or is multi-arch with no entry for this host — instead of silently importing
/// the wrong architecture (or a 0-layer attestation manifest) as the old
/// `manifests[0]` behaviour did.
fn select_import_manifest(
    top: &[OciDescriptor],
    files: &HashMap<String, Vec<u8>>,
) -> Result<OciDescriptor, ImportError> {
    // Flatten any index nesting into a flat list of concrete image-manifest
    // descriptors. `seen` guards against a self-referential/cyclic index.
    let mut image_descriptors: Vec<OciDescriptor> = Vec::new();
    let mut queue: Vec<OciDescriptor> = top.to_vec();
    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
    while let Some(descriptor) = queue.pop() {
        if !seen.insert(descriptor.digest.clone()) {
            continue;
        }
        if is_index_media_type(&descriptor.media_type) {
            let hash = descriptor
                .digest
                .strip_prefix("sha256:")
                .unwrap_or(&descriptor.digest);
            let path = format!("blobs/sha256/{hash}");
            let Some(bytes) = files.get(&path) else {
                // A nested index whose blob isn't packed in the archive can't
                // be followed — skip it rather than fail the whole import.
                continue;
            };
            let nested: OciIndex = serde_json::from_slice(bytes)?;
            queue.extend(nested.manifests);
        } else {
            image_descriptors.push(descriptor);
        }
    }

    if image_descriptors.is_empty() {
        return Err(ImportError::InvalidLayout(
            "index.json references no image manifests".to_string(),
        ));
    }

    // Prefer runnable (non-attestation) images; fall back to the full set only
    // if every entry looked like an attestation (should never happen for a real
    // image archive, but keeps a degenerate archive importable).
    let runnable: Vec<&OciDescriptor> = image_descriptors
        .iter()
        .filter(|d| !is_attestation_descriptor(d))
        .collect();
    let pool: Vec<&OciDescriptor> = if runnable.is_empty() {
        image_descriptors.iter().collect()
    } else {
        runnable
    };

    let host_os = crate::client::go_os_name();
    let host_arch = crate::client::go_arch_name();

    // Pass 1: exact {os}/{arch} match.
    if let Some(d) = pool.iter().find(|d| {
        d.platform
            .as_ref()
            .is_some_and(|p| p.os == host_os && p.architecture == host_arch)
    }) {
        return Ok((*d).clone());
    }
    // Pass 2: macOS-only fallback to linux/{arch} (runs in a Linux VM).
    if cfg!(target_os = "macos") {
        if let Some(d) = pool.iter().find(|d| {
            d.platform
                .as_ref()
                .is_some_and(|p| p.os == "linux" && p.architecture == host_arch)
        }) {
            return Ok((*d).clone());
        }
    }
    // Pass 3: a plain archive whose (sole) image manifest carries no platform
    // — a single-arch `docker save`. Import it directly.
    if let Some(d) = pool.iter().find(|d| d.platform.is_none()) {
        return Ok((*d).clone());
    }

    // Multi-arch archive with no entry matching this host.
    Err(ImportError::InvalidLayout(format!(
        "OCI archive contains no image manifest for this platform ({host_os}/{host_arch}); \
         available platforms: {}",
        pool.iter()
            .filter_map(|d| d.platform.as_ref())
            .map(|p| format!("{}/{}", p.os, p.architecture))
            .collect::<Vec<_>>()
            .join(", ")
    )))
}

/// Import a manifest's config + layer blobs into the registry, warming the
/// daemon blob cache, and return the layer count.
///
/// Windows foreign / nondistributable base layers (nanoserver / servercore on
/// MCR) are intentionally NOT carried inside the archive: the producing backend
/// (the native HCS Windows builder) skips them for the same reason the
/// registry-push path does — their bytes are non-distributable and must not be
/// re-emitted. The manifest descriptor preserves the upstream `urls[]`, so the
/// runtime rehydrates them via `ImagePuller::pull_blob_with_urls` at run time.
/// They are counted so `ImportInfo::layers` still matches the manifest's layer
/// total, but not required to be present locally (Linux/macOS archives never
/// contain these media types, so the skip is a no-op for them).
async fn import_manifest_blobs(
    registry: &LocalRegistry,
    files: &HashMap<String, Vec<u8>>,
    manifest: &OciManifest,
    blob_cache: Option<&dyn crate::cache::BlobCacheBackend>,
) -> Result<usize, ImportError> {
    // Import config blob if present. Warming the daemon's blob cache here is
    // what lets a `pull_policy: never` container load its image config (with the
    // real `entrypoint`/`cmd`) instead of falling back to `/bin/sh`.
    if let Some(ref config) = manifest.config {
        let config_hash = config
            .digest
            .strip_prefix("sha256:")
            .unwrap_or(&config.digest);
        let config_path = format!("blobs/sha256/{config_hash}");
        let config_data = files
            .get(&config_path)
            .ok_or_else(|| ImportError::BlobNotFound(config.digest.clone()))?;

        registry
            .put_blob(config_data)
            .await
            .map_err(|e| ImportError::Registry(e.to_string()))?;

        if let Some(cache) = blob_cache {
            let _ = cache.put(&config.digest, config_data).await;
        }
    }

    let mut layer_count = 0;
    for layer in &manifest.layers {
        if crate::unpack::is_windows_layer(&layer.media_type) {
            tracing::debug!(
                digest = %layer.digest,
                media_type = %layer.media_type,
                "skipping foreign/nondistributable base layer during OCI import \
                 (rehydrated from urls[] at run time)"
            );
            layer_count += 1;
            continue;
        }

        let layer_hash = layer
            .digest
            .strip_prefix("sha256:")
            .unwrap_or(&layer.digest);
        let layer_path = format!("blobs/sha256/{layer_hash}");
        let layer_data = files
            .get(&layer_path)
            .ok_or_else(|| ImportError::BlobNotFound(layer.digest.clone()))?;

        registry
            .put_blob(layer_data)
            .await
            .map_err(|e| ImportError::Registry(e.to_string()))?;

        if let Some(cache) = blob_cache {
            let _ = cache.put(&layer.digest, layer_data).await;
        }

        layer_count += 1;
    }
    Ok(layer_count)
}

async fn import_from_oci_layout(
    registry: &LocalRegistry,
    files: &HashMap<String, Vec<u8>>,
    tag: Option<&str>,
    blob_cache: Option<&dyn crate::cache::BlobCacheBackend>,
) -> Result<ImportInfo, ImportError> {
    // Validate OCI layout
    let oci_layout_data = files
        .get("oci-layout")
        .ok_or_else(|| ImportError::InvalidLayout("missing oci-layout file".to_string()))?;

    let oci_layout: OciLayout = serde_json::from_slice(oci_layout_data)?;
    if oci_layout.image_layout_version != "1.0.0" {
        return Err(ImportError::InvalidLayout(format!(
            "unsupported OCI layout version: {}",
            oci_layout.image_layout_version
        )));
    }

    // Parse index.json
    let index_data = files
        .get("index.json")
        .ok_or_else(|| ImportError::InvalidLayout("missing index.json".to_string()))?;

    let index: OciIndex = serde_json::from_slice(index_data)?;

    if index.manifests.is_empty() {
        return Err(ImportError::InvalidLayout(
            "index.json contains no manifests".to_string(),
        ));
    }

    // Pick the platform-correct image manifest: follow any nested index, skip
    // attestation manifests, and match the host platform (with the macOS
    // darwin→linux fallback). The old `manifests[0]` grabbed whatever came
    // first — for a multi-arch buildx `docker save` that is often an
    // attestation or wrong-arch entry, producing a 0-layer corrupt import.
    let manifest_descriptor = select_import_manifest(&index.manifests, files)?;
    let manifest_digest = &manifest_descriptor.digest;

    // Get original reference from annotations if available
    let original_ref = manifest_descriptor
        .annotations
        .as_ref()
        .and_then(|a| a.get("org.opencontainers.image.ref.name"))
        .cloned();

    // Get manifest blob
    let manifest_hash = manifest_digest
        .strip_prefix("sha256:")
        .unwrap_or(manifest_digest);
    let manifest_path = format!("blobs/sha256/{manifest_hash}");
    let manifest_data = files
        .get(&manifest_path)
        .ok_or_else(|| ImportError::BlobNotFound(manifest_digest.clone()))?;

    // Parse manifest
    let manifest: OciManifest = serde_json::from_slice(manifest_data)?;

    // Import the manifest's config + layer blobs (and warm the daemon cache).
    let layer_count = import_manifest_blobs(registry, files, &manifest, blob_cache).await?;

    // Determine the name/tag to use (shared with the Docker-archive path).
    let (name, final_tag) = resolve_name_and_tag(tag, original_ref.as_deref(), manifest_digest);

    // Store the manifest
    let reference = final_tag.clone().unwrap_or_else(|| manifest_digest.clone());
    registry
        .put_manifest(&name, &reference, manifest_data)
        .await
        .map_err(|e| ImportError::Registry(e.to_string()))?;

    // Also populate the daemon's manifest cache so ImagePuller
    // finds this manifest without hitting the remote registry.
    // The cache key format must match client.rs pull_manifest():
    //   "manifest:{name}:{tag}"  (e.g. "manifest:zachhandley/zlayer-manager:latest")
    if let Some(cache) = blob_cache {
        let image_ref = if let Some(ref t) = final_tag {
            format!("{name}:{t}")
        } else {
            name.clone()
        };
        let cache_key = crate::client::manifest_cache_key(&image_ref);
        let _ = cache.put(&cache_key, manifest_data).await;
    }

    let import_info = ImportInfo {
        digest: manifest_digest.clone(),
        tag: final_tag.map(|t| format!("{name}:{t}")),
        layers: layer_count,
    };

    tracing::info!(
        digest = %import_info.digest,
        tag = ?import_info.tag,
        layers = import_info.layers,
        "imported image from OCI layout"
    );

    Ok(import_info)
}

/// Add a file to a tar archive
fn add_file_to_tar<W: Write>(
    builder: &mut Builder<W>,
    path: &str,
    data: &[u8],
) -> Result<(), std::io::Error> {
    let mut header = tar::Header::new_gnu();
    header.set_path(path)?;
    header.set_size(data.len() as u64);
    header.set_mode(0o644);
    header.set_mtime(0);
    header.set_cksum();

    builder.append(&header, data)?;
    Ok(())
}

/// Check if data appears to be gzip compressed
fn is_gzip(data: &[u8]) -> bool {
    data.len() >= 2 && data[0] == 0x1f && data[1] == 0x8b
}

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

    async fn create_test_registry() -> (LocalRegistry, TempDir) {
        let temp_dir = TempDir::new().unwrap();
        let registry = LocalRegistry::new(temp_dir.path().to_path_buf())
            .await
            .unwrap();
        (registry, temp_dir)
    }

    /// Build an image-manifest `OciDescriptor` with an optional platform.
    fn img_desc(digest: &str, os: Option<&str>, arch: Option<&str>) -> OciDescriptor {
        OciDescriptor {
            media_type: "application/vnd.oci.image.manifest.v1+json".to_string(),
            digest: digest.to_string(),
            size: 0,
            urls: None,
            annotations: None,
            platform: match (os, arch) {
                (Some(os), Some(arch)) => Some(OciPlatform {
                    architecture: arch.to_string(),
                    os: os.to_string(),
                    os_version: None,
                    os_features: None,
                    variant: None,
                }),
                _ => None,
            },
        }
    }

    #[test]
    fn select_import_manifest_picks_host_over_attestation() {
        let host_os = crate::client::go_os_name();
        let host_arch = crate::client::go_arch_name();
        // `manifests[0]` is a buildx attestation (unknown/unknown) — the old
        // `manifests[0]` behaviour grabbed it and imported a 0-layer image.
        let top = vec![
            img_desc("sha256:attest", Some("unknown"), Some("unknown")),
            img_desc("sha256:host", Some(host_os), Some(host_arch)),
        ];
        let chosen = select_import_manifest(&top, &HashMap::new()).unwrap();
        assert_eq!(chosen.digest, "sha256:host");
    }

    #[test]
    fn select_import_manifest_follows_nested_index() {
        let host_os = crate::client::go_os_name();
        let host_arch = crate::client::go_arch_name();
        let inner = OciIndex {
            schema_version: 2,
            media_type: Some("application/vnd.oci.image.index.v1+json".to_string()),
            manifests: vec![img_desc("sha256:host", Some(host_os), Some(host_arch))],
            annotations: None,
        };
        let mut files = HashMap::new();
        files.insert(
            "blobs/sha256/nested".to_string(),
            serde_json::to_vec(&inner).unwrap(),
        );
        let top = vec![OciDescriptor {
            media_type: "application/vnd.oci.image.index.v1+json".to_string(),
            digest: "sha256:nested".to_string(),
            size: 0,
            urls: None,
            annotations: None,
            platform: None,
        }];
        let chosen = select_import_manifest(&top, &files).unwrap();
        assert_eq!(chosen.digest, "sha256:host");
    }

    #[test]
    fn select_import_manifest_accepts_single_arch_no_platform() {
        let top = vec![img_desc("sha256:only", None, None)];
        let chosen = select_import_manifest(&top, &HashMap::new()).unwrap();
        assert_eq!(chosen.digest, "sha256:only");
    }

    #[test]
    fn select_import_manifest_errors_when_no_platform_matches() {
        // A foreign-only arch (never the host or its linux fallback) → an
        // actionable error rather than importing the wrong architecture.
        let top = vec![img_desc("sha256:foreign", Some("plan9"), Some("mips"))];
        assert!(select_import_manifest(&top, &HashMap::new()).is_err());
    }

    #[test]
    fn test_parse_image_reference() {
        // name:tag format
        let (name, reference) = parse_image_reference("myapp:v1.0").unwrap();
        assert_eq!(name, "myapp");
        assert_eq!(reference, "v1.0");

        // name only (defaults to latest)
        let (name, reference) = parse_image_reference("myapp").unwrap();
        assert_eq!(name, "myapp");
        assert_eq!(reference, "latest");

        // name@digest format
        let (name, reference) = parse_image_reference(
            "myapp@sha256:1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
        )
        .unwrap();
        assert_eq!(name, "myapp");
        assert_eq!(
            reference,
            "sha256:1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
        );

        // namespaced image
        let (name, reference) = parse_image_reference("library/nginx:latest").unwrap();
        assert_eq!(name, "library/nginx");
        assert_eq!(reference, "latest");
    }

    #[test]
    fn test_oci_layout_default() {
        let layout = OciLayout::default();
        assert_eq!(layout.image_layout_version, "1.0.0");
    }

    #[test]
    fn test_oci_index_new() {
        let descriptor = OciDescriptor {
            media_type: "application/vnd.oci.image.manifest.v1+json".to_string(),
            digest: "sha256:abc123".to_string(),
            size: 1234,
            urls: None,
            annotations: None,
            platform: None,
        };

        let index = OciIndex::new(descriptor);
        assert_eq!(index.schema_version, 2);
        assert_eq!(index.manifests.len(), 1);
    }

    #[test]
    fn test_is_gzip() {
        // Gzip magic bytes
        assert!(is_gzip(&[0x1f, 0x8b, 0x08, 0x00]));

        // Not gzip
        assert!(!is_gzip(&[0x00, 0x00, 0x00, 0x00]));

        // Too short
        assert!(!is_gzip(&[0x1f]));
    }

    #[tokio::test]
    async fn test_export_import_roundtrip() {
        let (registry, temp_dir) = create_test_registry().await;

        // Create a simple image with one layer
        let layer_data = b"layer content data";
        let layer_digest = registry.put_blob(layer_data).await.unwrap();

        let config_data = br#"{"architecture":"amd64","os":"linux"}"#;
        let config_digest = registry.put_blob(config_data).await.unwrap();

        let manifest = serde_json::json!({
            "schemaVersion": 2,
            "mediaType": "application/vnd.oci.image.manifest.v1+json",
            "config": {
                "mediaType": "application/vnd.oci.image.config.v1+json",
                "digest": config_digest,
                "size": config_data.len()
            },
            "layers": [{
                "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip",
                "digest": layer_digest,
                "size": layer_data.len()
            }]
        });

        let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
        registry
            .put_manifest("testapp", "v1.0", &manifest_bytes)
            .await
            .unwrap();

        // Export the image
        let export_path = temp_dir.path().join("export.tar.gz");
        let export_info = export_image(&registry, "testapp:v1.0", &export_path)
            .await
            .unwrap();

        assert_eq!(export_info.layers, 1);
        assert!(export_path.exists());

        // Create a new registry for import
        let (import_registry, _import_temp) = create_test_registry().await;

        // Import the image
        let import_info = import_image(&import_registry, &export_path, Some("imported:v1"), None)
            .await
            .unwrap();

        assert_eq!(import_info.layers, 1);
        assert_eq!(import_info.tag, Some("imported:v1".to_string()));

        // Verify the imported image exists
        assert!(import_registry.has_manifest("imported", "v1").await);
        assert!(import_registry.has_blob(&layer_digest).await);
        assert!(import_registry.has_blob(&config_digest).await);
    }

    #[tokio::test]
    async fn test_export_nonexistent_image() {
        let (registry, _temp_dir) = create_test_registry().await;

        let result =
            export_image(&registry, "nonexistent:latest", Path::new("/tmp/test.tar")).await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_import_invalid_archive() {
        let (registry, temp_dir) = create_test_registry().await;

        // Create an invalid tar file
        let invalid_tar = temp_dir.path().join("invalid.tar");
        fs::write(&invalid_tar, b"not a valid tar file")
            .await
            .unwrap();

        let result = import_image(&registry, &invalid_tar, None, None).await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_export_uncompressed() {
        let (registry, temp_dir) = create_test_registry().await;

        // Create a minimal image
        let layer_data = b"test layer";
        let layer_digest = registry.put_blob(layer_data).await.unwrap();

        let manifest = serde_json::json!({
            "schemaVersion": 2,
            "layers": [{
                "mediaType": "application/vnd.oci.image.layer.v1.tar",
                "digest": layer_digest,
                "size": layer_data.len()
            }]
        });

        let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
        registry
            .put_manifest("test", "latest", &manifest_bytes)
            .await
            .unwrap();

        // Export without compression
        let export_path = temp_dir.path().join("export.tar");
        let _export_info = export_image(&registry, "test:latest", &export_path)
            .await
            .unwrap();

        assert!(export_path.exists());

        // Verify it's not gzip compressed
        let data = fs::read(&export_path).await.unwrap();
        assert!(!is_gzip(&data));

        // Should still be importable - keep import_temp alive for the duration
        let (import_registry, _import_temp) = create_test_registry().await;
        let import_info = import_image(&import_registry, &export_path, Some("test:imported"), None)
            .await
            .unwrap();

        assert_eq!(import_info.layers, 1);
    }

    /// Build an in-memory Docker Archive (the `docker save` / `podman save`
    /// layout): a top-level `manifest.json` array plus a config blob and the
    /// listed layer blobs, stored at legacy `<id>/layer.tar` style paths.
    fn build_docker_archive(repo_tags: &[&str], config: &[u8], layers: &[&[u8]]) -> Vec<u8> {
        let mut builder = Builder::new(Vec::new());
        add_file_to_tar(&mut builder, "config.json", config).unwrap();

        let mut layer_paths = Vec::new();
        for (i, layer) in layers.iter().enumerate() {
            let path = format!("layer{i}/layer.tar");
            add_file_to_tar(&mut builder, &path, layer).unwrap();
            layer_paths.push(path);
        }

        let manifest = serde_json::json!([{
            "Config": "config.json",
            "RepoTags": repo_tags,
            "Layers": layer_paths,
        }]);
        let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
        add_file_to_tar(&mut builder, "manifest.json", &manifest_bytes).unwrap();

        builder.into_inner().unwrap()
    }

    #[tokio::test]
    async fn test_import_docker_archive_with_tag() {
        let (registry, _temp) = create_test_registry().await;

        let config =
            br#"{"architecture":"amd64","os":"linux","rootfs":{"type":"layers","diff_ids":["sha256:aaa"]}}"#;
        let layer = b"uncompressed layer tar bytes";
        let archive = build_docker_archive(&["nginx:latest"], config, &[layer]);

        let info = import_image_from_bytes(&registry, archive, Some("myimg:v1"), None)
            .await
            .expect("docker archive should import");

        assert_eq!(info.layers, 1);
        assert_eq!(info.tag.as_deref(), Some("myimg:v1"));

        // A synthesized OCI manifest is stored under the requested name:tag.
        let manifest_bytes = registry.get_manifest("myimg", "v1").await.unwrap();
        let manifest: OciManifest = serde_json::from_slice(&manifest_bytes).unwrap();
        assert_eq!(manifest.layers.len(), 1);
        // Uncompressed layer -> tar media type, digest over the stored bytes.
        assert_eq!(
            manifest.layers[0].media_type,
            "application/vnd.oci.image.layer.v1.tar"
        );
        assert_eq!(manifest.layers[0].digest, compute_digest(layer));

        // Config + layer blobs are retrievable from the registry.
        let cfg = manifest.config.expect("config descriptor");
        assert_eq!(cfg.digest, compute_digest(config));
        assert!(registry.get_blob(&cfg.digest).await.is_ok());
        assert!(registry.get_blob(&manifest.layers[0].digest).await.is_ok());
    }

    #[tokio::test]
    async fn test_import_docker_archive_repotags_fallback() {
        let (registry, _temp) = create_test_registry().await;

        let config = br#"{"architecture":"amd64","os":"linux"}"#;
        let layer = b"layer";
        // No explicit tag -> name/tag taken from RepoTags[0].
        let archive = build_docker_archive(&["library/nginx:1.27"], config, &[layer]);

        let info = import_image_from_bytes(&registry, archive, None, None)
            .await
            .unwrap();

        assert_eq!(info.tag.as_deref(), Some("library/nginx:1.27"));
        assert!(registry.get_manifest("library/nginx", "1.27").await.is_ok());
    }

    #[tokio::test]
    async fn test_import_docker_archive_gzipped_layer() {
        let (registry, _temp) = create_test_registry().await;

        // A gzip-compressed layer must be labelled tar+gzip in the manifest.
        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(b"compressed layer contents").unwrap();
        let gz_layer = encoder.finish().unwrap();
        assert!(is_gzip(&gz_layer));

        let config = br#"{"os":"linux"}"#;
        let archive = build_docker_archive(&["x:y"], config, &[&gz_layer]);

        import_image_from_bytes(&registry, archive, Some("g:1"), None)
            .await
            .unwrap();

        let manifest: OciManifest =
            serde_json::from_slice(&registry.get_manifest("g", "1").await.unwrap()).unwrap();
        assert_eq!(
            manifest.layers[0].media_type,
            "application/vnd.oci.image.layer.v1.tar+gzip"
        );
    }

    #[tokio::test]
    async fn test_import_archive_without_oci_or_docker_manifest_errors() {
        let (registry, _temp) = create_test_registry().await;

        // A valid tar that is neither an OCI layout nor a Docker archive.
        let mut builder = Builder::new(Vec::new());
        add_file_to_tar(&mut builder, "random.txt", b"hello").unwrap();
        let archive = builder.into_inner().unwrap();

        let err = import_image_from_bytes(&registry, archive, None, None)
            .await
            .unwrap_err();
        assert!(matches!(err, ImportError::InvalidLayout(_)));
    }
}