kopi 0.1.4

Kopi is a JDK version management tool
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
// Copyright 2025 dentsusoken
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Local directory metadata source implementation.
//!
//! Reads metadata from pre-extracted JSON files in a directory structure,
//! typically extracted from bundled metadata archives during installation.

use crate::error::{KopiError, Result};
use crate::indicator::ProgressIndicator;
use crate::metadata::{IndexFile, IndexFileEntry, MetadataSource, PackageDetails};
use crate::models::metadata::JdkMetadata;
use crate::platform::{get_current_architecture, get_current_os, get_foojay_libc_type};
use std::fs::File;
use std::path::PathBuf;

/// Get the platform directory name for the current system.
///
/// All platforms include the libc type in the directory name:
/// - Linux: "linux-x64-glibc", "linux-x64-musl"
/// - macOS: "macos-x64-libc", "macos-aarch64-libc"
/// - Windows: "windows-x64-c_std_lib", "windows-aarch64-c_std_lib"
/// - Others: "aix-ppc64-libc", "solaris-x64-libc", etc.
///
/// This format must match the directory structure created by
/// MetadataGenerator::organize_metadata() in generator.rs.
fn get_current_platform_directory() -> String {
    let os = get_current_os();
    let arch = get_current_architecture();
    let libc = get_foojay_libc_type();

    format!("{os}-{arch}-{libc}")
}

/// Metadata source that reads from a local directory structure
pub struct LocalDirectorySource {
    directory: PathBuf,
}

impl LocalDirectorySource {
    /// Create a new LocalDirectorySource for the given directory
    pub fn new(directory: PathBuf) -> Self {
        Self { directory }
    }

    /// Read metadata from extracted directory structure
    fn read_metadata(&self, progress: &mut dyn ProgressIndicator) -> Result<Vec<JdkMetadata>> {
        // Read index.json
        progress.set_message(format!(
            "Reading local metadata directory: {}",
            self.directory.display()
        ));
        let index_path = self.directory.join("index.json");
        let index_file = File::open(&index_path).map_err(|e| {
            KopiError::NotFound(format!(
                "Bundled metadata not found at {}: {}",
                index_path.display(),
                e
            ))
        })?;

        let index: IndexFile = serde_json::from_reader(index_file)?;

        // Get platform directory for current system
        let platform_dir = get_current_platform_directory();

        // Filter files for current platform
        let platform_files = self.filter_files_for_platform(index.files, &platform_dir);
        let file_count = platform_files.len();
        if file_count > 0 {
            progress.set_message(format!(
                "Processing {file_count} metadata files for {platform_dir}"
            ));
        }

        // Read metadata files from the platform directory
        let mut all_metadata = Vec::new();
        for (index, file_info) in platform_files.into_iter().enumerate() {
            // Extract just the filename for progress display
            let filename = file_info
                .path
                .split('/')
                .next_back()
                .unwrap_or(&file_info.path);
            progress.set_message(format!("Reading {filename} ({}/{})", index + 1, file_count));

            let file_path = self.directory.join(&file_info.path);

            if let Ok(file) = File::open(&file_path) {
                match serde_json::from_reader::<_, Vec<JdkMetadata>>(file) {
                    Ok(metadata) => {
                        // Local files should have full metadata
                        all_metadata.extend(metadata);
                    }
                    Err(e) => {
                        log::warn!(
                            "Failed to parse metadata file {}: {}",
                            file_path.display(),
                            e
                        );
                    }
                }
            } else {
                log::warn!("Metadata file not found: {}", file_path.display());
            }
        }

        let package_count = all_metadata.len();
        progress.set_message(format!("Loaded {package_count} local packages"));
        Ok(all_metadata)
    }

    /// Filter metadata files based on current platform
    fn filter_files_for_platform(
        &self,
        files: Vec<IndexFileEntry>,
        platform_dir: &str,
    ) -> Vec<IndexFileEntry> {
        files
            .into_iter()
            .filter(|entry| {
                // Check if the file path starts with our platform directory
                entry.path.starts_with(&format!("{platform_dir}/"))
            })
            .collect()
    }
}

impl MetadataSource for LocalDirectorySource {
    fn id(&self) -> &str {
        "local"
    }

    fn name(&self) -> &str {
        "Local Directory"
    }

    fn is_available(&self) -> Result<bool> {
        // Check if the bundled metadata directory exists and has index.json
        let index_path = self.directory.join("index.json");
        Ok(index_path.exists())
    }

    fn fetch_all(&self, progress: &mut dyn ProgressIndicator) -> Result<Vec<JdkMetadata>> {
        self.read_metadata(progress)
    }

    fn fetch_distribution(
        &self,
        distribution: &str,
        progress: &mut dyn ProgressIndicator,
    ) -> Result<Vec<JdkMetadata>> {
        progress.set_message(format!(
            "Reading local metadata for distribution: {distribution}"
        ));
        let all_metadata = self.read_metadata(progress)?;
        let filtered: Vec<JdkMetadata> = all_metadata
            .into_iter()
            .filter(|m| m.distribution == distribution)
            .collect();

        let count = filtered.len();
        progress.set_message(format!("Found {count} {distribution} packages locally"));
        Ok(filtered)
    }

    fn fetch_package_details(
        &self,
        package_id: &str,
        progress: &mut dyn ProgressIndicator,
    ) -> Result<PackageDetails> {
        progress.set_message(format!("Looking up package details: {package_id}"));

        // Local directory source has complete metadata, so we can return details
        let all_metadata = self.read_metadata(progress)?;

        // Find the package with matching ID
        progress.set_message(format!("Searching for package: {package_id}"));
        let package = all_metadata
            .into_iter()
            .find(|m| m.id == package_id)
            .ok_or_else(|| KopiError::NotFound(format!("Package '{package_id}' not found")))?;

        // Extract package details
        let download_url = package.download_url.ok_or_else(|| {
            KopiError::NotFound(format!("Download URL not found for package '{package_id}'"))
        })?;

        progress.set_message(format!("Found package details for: {package_id}"));
        Ok(PackageDetails {
            download_url,
            checksum: package.checksum,
            checksum_type: package.checksum_type,
        })
    }

    fn last_updated(&self) -> Result<Option<chrono::DateTime<chrono::Utc>>> {
        // Try to get the bundle generation time from index.json
        let index_path = self.directory.join("index.json");
        if let Ok(file) = File::open(&index_path)
            && let Ok(index) = serde_json::from_reader::<_, serde_json::Value>(file)
            && let Some(updated) = index.get("updated").and_then(|v| v.as_str())
            && let Ok(dt) = chrono::DateTime::parse_from_rfc3339(updated)
        {
            return Ok(Some(dt.with_timezone(&chrono::Utc)));
        }

        // Fallback to index.json modification time
        if let Ok(metadata) = std::fs::metadata(&index_path)
            && let Ok(modified) = metadata.modified()
        {
            let datetime: chrono::DateTime<chrono::Utc> = modified.into();
            return Ok(Some(datetime));
        }

        Ok(None)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::indicator::SilentProgress;
    use crate::models::package::{ArchiveType, PackageType};
    use crate::models::platform::{Architecture, OperatingSystem};
    use crate::version::Version;
    use std::fs;
    use tempfile::TempDir;

    fn create_test_metadata() -> Vec<JdkMetadata> {
        vec![
            JdkMetadata {
                distribution: "temurin".to_string(),
                version: Version::new(21, 0, 0),
                distribution_version: Version::new(21, 0, 0),
                id: "temurin-21-linux-x64".to_string(),
                operating_system: OperatingSystem::Linux,
                architecture: Architecture::X64,
                lib_c_type: Some("glibc".to_string()),
                download_url: Some("https://example.com/temurin-21.tar.gz".to_string()),
                size: 100000000,
                checksum: Some("abc123".to_string()),
                checksum_type: Some(crate::models::package::ChecksumType::Sha256),
                package_type: PackageType::Jdk,
                archive_type: ArchiveType::TarGz,
                javafx_bundled: false,
                term_of_support: None,
                release_status: None,
                latest_build_available: None,
            },
            JdkMetadata {
                distribution: "corretto".to_string(),
                version: Version::new(21, 0, 0),
                distribution_version: Version::new(21, 0, 0),
                id: "corretto-21-linux-x64".to_string(),
                operating_system: OperatingSystem::Linux,
                architecture: Architecture::X64,
                lib_c_type: Some("glibc".to_string()),
                download_url: Some("https://example.com/corretto-21.tar.gz".to_string()),
                size: 110000000,
                checksum: Some("def456".to_string()),
                checksum_type: Some(crate::models::package::ChecksumType::Sha256),
                package_type: PackageType::Jdk,
                archive_type: ArchiveType::TarGz,
                javafx_bundled: false,
                term_of_support: None,
                release_status: None,
                latest_build_available: None,
            },
        ]
    }

    fn setup_test_directory(dir: &TempDir) -> PathBuf {
        let metadata_dir = dir.path().join("bundled-metadata");
        fs::create_dir_all(&metadata_dir).unwrap();

        // Create index.json
        let index = IndexFile {
            version: 2,
            updated: "2024-01-15T10:00:00Z".to_string(),
            files: vec![
                IndexFileEntry {
                    path: "linux-x64-glibc/temurin.json".to_string(),
                    distribution: "temurin".to_string(),
                    architectures: Some(vec!["x64".to_string()]),
                    operating_systems: Some(vec!["linux".to_string()]),
                    lib_c_types: Some(vec!["glibc".to_string()]),
                    size: 1024,
                    checksum: None,
                    last_modified: None,
                },
                IndexFileEntry {
                    path: "linux-x64-glibc/corretto.json".to_string(),
                    distribution: "corretto".to_string(),
                    architectures: Some(vec!["x64".to_string()]),
                    operating_systems: Some(vec!["linux".to_string()]),
                    lib_c_types: Some(vec!["glibc".to_string()]),
                    size: 1024,
                    checksum: None,
                    last_modified: None,
                },
                // This one should be filtered out on non-Windows platforms
                IndexFileEntry {
                    path: "windows-x64-c_std_lib/temurin.json".to_string(),
                    distribution: "temurin".to_string(),
                    architectures: Some(vec!["x64".to_string()]),
                    operating_systems: Some(vec!["windows".to_string()]),
                    lib_c_types: Some(vec!["c_std_lib".to_string()]),
                    size: 1024,
                    checksum: None,
                    last_modified: None,
                },
                // macOS x64 entries
                IndexFileEntry {
                    path: "macos-x64-libc/temurin.json".to_string(),
                    distribution: "temurin".to_string(),
                    architectures: Some(vec!["x64".to_string()]),
                    operating_systems: Some(vec!["macos".to_string()]),
                    lib_c_types: Some(vec!["libc".to_string()]),
                    size: 1024,
                    checksum: None,
                    last_modified: None,
                },
                IndexFileEntry {
                    path: "macos-x64-libc/corretto.json".to_string(),
                    distribution: "corretto".to_string(),
                    architectures: Some(vec!["x64".to_string()]),
                    operating_systems: Some(vec!["macos".to_string()]),
                    lib_c_types: Some(vec!["libc".to_string()]),
                    size: 1024,
                    checksum: None,
                    last_modified: None,
                },
                // macOS aarch64 entries
                IndexFileEntry {
                    path: "macos-aarch64-libc/temurin.json".to_string(),
                    distribution: "temurin".to_string(),
                    architectures: Some(vec!["aarch64".to_string()]),
                    operating_systems: Some(vec!["macos".to_string()]),
                    lib_c_types: Some(vec!["libc".to_string()]),
                    size: 1024,
                    checksum: None,
                    last_modified: None,
                },
                IndexFileEntry {
                    path: "macos-aarch64-libc/corretto.json".to_string(),
                    distribution: "corretto".to_string(),
                    architectures: Some(vec!["aarch64".to_string()]),
                    operating_systems: Some(vec!["macos".to_string()]),
                    lib_c_types: Some(vec!["libc".to_string()]),
                    size: 1024,
                    checksum: None,
                    last_modified: None,
                },
            ],
            generator_config: None,
        };

        let index_path = metadata_dir.join("index.json");
        fs::write(&index_path, serde_json::to_string_pretty(&index).unwrap()).unwrap();

        // Create platform directories
        let linux_dir = metadata_dir.join("linux-x64-glibc");
        fs::create_dir_all(&linux_dir).unwrap();

        let windows_dir = metadata_dir.join("windows-x64-c_std_lib");
        fs::create_dir_all(&windows_dir).unwrap();

        let macos_x64_dir = metadata_dir.join("macos-x64-libc");
        fs::create_dir_all(&macos_x64_dir).unwrap();

        let macos_aarch64_dir = metadata_dir.join("macos-aarch64-libc");
        fs::create_dir_all(&macos_aarch64_dir).unwrap();

        // Create metadata files
        let test_metadata = create_test_metadata();

        // Temurin Linux x64
        fs::write(
            linux_dir.join("temurin.json"),
            serde_json::to_string_pretty(&vec![test_metadata[0].clone()]).unwrap(),
        )
        .unwrap();

        // Corretto Linux x64
        fs::write(
            linux_dir.join("corretto.json"),
            serde_json::to_string_pretty(&vec![test_metadata[1].clone()]).unwrap(),
        )
        .unwrap();

        // Windows file (for testing filtering)
        fs::write(
            windows_dir.join("temurin.json"),
            serde_json::to_string_pretty(&vec![JdkMetadata {
                operating_system: OperatingSystem::Windows,
                ..test_metadata[0].clone()
            }])
            .unwrap(),
        )
        .unwrap();

        // macOS x64 files
        fs::write(
            macos_x64_dir.join("temurin.json"),
            serde_json::to_string_pretty(&vec![JdkMetadata {
                id: "temurin-21-macos-x64".to_string(),
                operating_system: OperatingSystem::MacOS,
                architecture: Architecture::X64,
                lib_c_type: Some("libc".to_string()),
                ..test_metadata[0].clone()
            }])
            .unwrap(),
        )
        .unwrap();

        fs::write(
            macos_x64_dir.join("corretto.json"),
            serde_json::to_string_pretty(&vec![JdkMetadata {
                id: "corretto-21-macos-x64".to_string(),
                operating_system: OperatingSystem::MacOS,
                architecture: Architecture::X64,
                lib_c_type: Some("libc".to_string()),
                ..test_metadata[1].clone()
            }])
            .unwrap(),
        )
        .unwrap();

        // macOS aarch64 files
        fs::write(
            macos_aarch64_dir.join("temurin.json"),
            serde_json::to_string_pretty(&vec![JdkMetadata {
                id: "temurin-21-macos-aarch64".to_string(),
                operating_system: OperatingSystem::MacOS,
                architecture: Architecture::Aarch64,
                lib_c_type: Some("libc".to_string()),
                ..test_metadata[0].clone()
            }])
            .unwrap(),
        )
        .unwrap();

        fs::write(
            macos_aarch64_dir.join("corretto.json"),
            serde_json::to_string_pretty(&vec![JdkMetadata {
                id: "corretto-21-macos-aarch64".to_string(),
                operating_system: OperatingSystem::MacOS,
                architecture: Architecture::Aarch64,
                lib_c_type: Some("libc".to_string()),
                ..test_metadata[1].clone()
            }])
            .unwrap(),
        )
        .unwrap();

        metadata_dir
    }

    #[test]
    fn test_local_directory_source_creation() {
        let dir = TempDir::new().unwrap();
        let metadata_dir = setup_test_directory(&dir);

        let source = LocalDirectorySource::new(metadata_dir.clone());
        assert_eq!(source.id(), "local");
        assert_eq!(source.name(), "Local Directory");
    }

    #[test]
    fn test_is_available() {
        let dir = TempDir::new().unwrap();
        let metadata_dir = setup_test_directory(&dir);

        let source = LocalDirectorySource::new(metadata_dir.clone());
        assert!(source.is_available().unwrap());

        // Test with non-existent directory
        let source = LocalDirectorySource::new(dir.path().join("non-existent"));
        assert!(!source.is_available().unwrap());
    }

    #[test]
    fn test_fetch_all() {
        let dir = TempDir::new().unwrap();
        let metadata_dir = setup_test_directory(&dir);

        let source = LocalDirectorySource::new(metadata_dir);
        let metadata = {
            let mut progress = SilentProgress;
            source.fetch_all(&mut progress).unwrap()
        };
        // Basic check that works on all platforms
        assert!(!metadata.is_empty());

        // Should only get Linux metadata on Linux platforms
        #[cfg(target_os = "linux")]
        {
            assert_eq!(metadata.len(), 2);
            assert!(
                metadata
                    .iter()
                    .all(|m| m.operating_system == OperatingSystem::Linux)
            );
            assert!(metadata.iter().all(|m| m.is_complete()));
        }

        // On Windows, would get only Windows metadata
        #[cfg(target_os = "windows")]
        {
            assert_eq!(metadata.len(), 1);
            assert!(
                metadata
                    .iter()
                    .all(|m| m.operating_system == OperatingSystem::Windows)
            );
        }

        // On macOS, should get macOS metadata for current architecture
        #[cfg(target_os = "macos")]
        {
            assert_eq!(metadata.len(), 2);
            assert!(
                metadata
                    .iter()
                    .all(|m| m.operating_system == OperatingSystem::MacOS)
            );
            assert!(metadata.iter().all(|m| m.is_complete()));

            // Verify architecture matches current system
            #[cfg(target_arch = "x86_64")]
            assert!(metadata.iter().all(|m| m.architecture == Architecture::X64));

            #[cfg(target_arch = "aarch64")]
            assert!(
                metadata
                    .iter()
                    .all(|m| m.architecture == Architecture::Aarch64)
            );
        }
    }

    #[test]
    fn test_fetch_distribution() {
        let dir = TempDir::new().unwrap();
        let metadata_dir = setup_test_directory(&dir);

        let source = LocalDirectorySource::new(metadata_dir);
        let metadata = {
            let mut progress = SilentProgress;
            source.fetch_distribution("temurin", &mut progress).unwrap()
        };
        // Basic check that works on all platforms
        assert!(!metadata.is_empty());

        #[cfg(target_os = "linux")]
        {
            assert_eq!(metadata.len(), 1);
            assert_eq!(metadata[0].distribution, "temurin");
        }

        #[cfg(target_os = "macos")]
        {
            assert_eq!(metadata.len(), 1);
            assert_eq!(metadata[0].distribution, "temurin");
            assert_eq!(metadata[0].operating_system, OperatingSystem::MacOS);
        }
    }

    #[test]
    fn test_last_updated() {
        let dir = TempDir::new().unwrap();
        let metadata_dir = setup_test_directory(&dir);

        let source = LocalDirectorySource::new(metadata_dir);
        let last_updated = source.last_updated().unwrap();

        assert!(last_updated.is_some());
        // Should parse the date from index.json
        let dt = last_updated.unwrap();
        assert_eq!(dt.format("%Y-%m-%d").to_string(), "2024-01-15");
    }

    #[test]
    fn test_missing_metadata_file() {
        let dir = TempDir::new().unwrap();
        let metadata_dir = setup_test_directory(&dir);

        // Delete one of the metadata files based on platform
        #[cfg(target_os = "linux")]
        fs::remove_file(metadata_dir.join("linux-x64-glibc").join("corretto.json")).unwrap();

        #[cfg(target_os = "macos")]
        {
            #[cfg(target_arch = "x86_64")]
            fs::remove_file(metadata_dir.join("macos-x64-libc").join("corretto.json")).unwrap();

            #[cfg(target_arch = "aarch64")]
            fs::remove_file(
                metadata_dir
                    .join("macos-aarch64-libc")
                    .join("corretto.json"),
            )
            .unwrap();
        }

        #[cfg(target_os = "windows")]
        {
            // Windows doesn't have corretto in test data, so we don't need to delete anything
        }

        let source = LocalDirectorySource::new(metadata_dir);
        let metadata = {
            let mut progress = SilentProgress;
            source.fetch_all(&mut progress).unwrap()
        };
        // Basic check that works on all platforms
        assert!(!metadata.is_empty());

        // Should still get temurin metadata
        #[cfg(target_os = "linux")]
        {
            assert_eq!(metadata.len(), 1);
            assert_eq!(metadata[0].distribution, "temurin");
        }

        #[cfg(target_os = "macos")]
        {
            assert_eq!(metadata.len(), 1);
            assert_eq!(metadata[0].distribution, "temurin");
            assert_eq!(metadata[0].operating_system, OperatingSystem::MacOS);
        }
    }

    #[test]
    fn test_corrupt_metadata_file() {
        let dir = TempDir::new().unwrap();
        let metadata_dir = setup_test_directory(&dir);

        // Write corrupt JSON to one file based on platform
        #[cfg(target_os = "linux")]
        fs::write(
            metadata_dir.join("linux-x64-glibc").join("corretto.json"),
            "{ invalid json",
        )
        .unwrap();

        #[cfg(target_os = "macos")]
        {
            #[cfg(target_arch = "x86_64")]
            fs::write(
                metadata_dir.join("macos-x64-libc").join("corretto.json"),
                "{ invalid json",
            )
            .unwrap();

            #[cfg(target_arch = "aarch64")]
            fs::write(
                metadata_dir
                    .join("macos-aarch64-libc")
                    .join("corretto.json"),
                "{ invalid json",
            )
            .unwrap();
        }

        #[cfg(target_os = "windows")]
        {
            // Windows only has one temurin file in test data, don't corrupt it
        }

        let source = LocalDirectorySource::new(metadata_dir);
        let metadata = {
            let mut progress = SilentProgress;
            source.fetch_all(&mut progress).unwrap()
        };
        // Basic check that works on all platforms
        assert!(!metadata.is_empty());

        // Should still get temurin metadata
        #[cfg(target_os = "linux")]
        {
            assert_eq!(metadata.len(), 1);
            assert_eq!(metadata[0].distribution, "temurin");
        }

        #[cfg(target_os = "macos")]
        {
            assert_eq!(metadata.len(), 1);
            assert_eq!(metadata[0].distribution, "temurin");
            assert_eq!(metadata[0].operating_system, OperatingSystem::MacOS);
        }
    }

    #[test]
    fn test_fetch_package_details() {
        let dir = TempDir::new().unwrap();
        let metadata_dir = setup_test_directory(&dir);

        let source = LocalDirectorySource::new(metadata_dir);

        // Test fetching existing package details - use platform-specific package ID
        #[cfg(target_os = "linux")]
        {
            let details = source
                .fetch_package_details("temurin-21-linux-x64", &mut SilentProgress)
                .unwrap();
            assert_eq!(
                details.download_url,
                "https://example.com/temurin-21.tar.gz"
            );
            assert_eq!(details.checksum, Some("abc123".to_string()));
            assert!(matches!(
                details.checksum_type,
                Some(crate::models::package::ChecksumType::Sha256)
            ));
        }

        #[cfg(target_os = "windows")]
        {
            // On Windows, we need to test with a Windows package ID
            // First check if any Windows metadata is available
            let all_metadata = {
                let mut progress = SilentProgress;
                source.fetch_all(&mut progress).unwrap()
            };
            if !all_metadata.is_empty() {
                // Use the first available package for testing
                let package_id = &all_metadata[0].id;
                let mut progress = SilentProgress;
                let details = source
                    .fetch_package_details(package_id, &mut progress)
                    .unwrap();
                assert!(details.download_url.starts_with("https://"));
            }
        }

        // Test fetching non-existent package
        let mut progress = SilentProgress;
        let result = source.fetch_package_details("non-existent-package", &mut progress);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), KopiError::NotFound(_)));
    }

    #[test]
    fn test_platform_filtering() {
        let dir = TempDir::new().unwrap();
        let metadata_dir = dir.path().join("bundled-metadata");
        fs::create_dir_all(&metadata_dir).unwrap();

        // Create index with multiple platform files
        let index = IndexFile {
            version: 2,
            updated: "2024-01-15T10:00:00Z".to_string(),
            files: vec![
                IndexFileEntry {
                    path: "linux-x64-glibc/temurin.json".to_string(),
                    distribution: "temurin".to_string(),
                    architectures: Some(vec!["x64".to_string()]),
                    operating_systems: Some(vec!["linux".to_string()]),
                    lib_c_types: Some(vec!["glibc".to_string()]),
                    size: 1024,
                    checksum: None,
                    last_modified: None,
                },
                IndexFileEntry {
                    path: "linux-x64-musl/temurin.json".to_string(),
                    distribution: "temurin".to_string(),
                    architectures: Some(vec!["x64".to_string()]),
                    operating_systems: Some(vec!["linux".to_string()]),
                    lib_c_types: Some(vec!["musl".to_string()]),
                    size: 1024,
                    checksum: None,
                    last_modified: None,
                },
                IndexFileEntry {
                    path: "linux-aarch64-glibc/temurin.json".to_string(),
                    distribution: "temurin".to_string(),
                    architectures: Some(vec!["aarch64".to_string()]),
                    operating_systems: Some(vec!["linux".to_string()]),
                    lib_c_types: Some(vec!["glibc".to_string()]),
                    size: 1024,
                    checksum: None,
                    last_modified: None,
                },
                IndexFileEntry {
                    path: "windows-x64/temurin.json".to_string(),
                    distribution: "temurin".to_string(),
                    architectures: Some(vec!["x64".to_string()]),
                    operating_systems: Some(vec!["windows".to_string()]),
                    lib_c_types: None,
                    size: 1024,
                    checksum: None,
                    last_modified: None,
                },
                IndexFileEntry {
                    path: "macos-x64/temurin.json".to_string(),
                    distribution: "temurin".to_string(),
                    architectures: Some(vec!["x64".to_string()]),
                    operating_systems: Some(vec!["macos".to_string()]),
                    lib_c_types: None,
                    size: 1024,
                    checksum: None,
                    last_modified: None,
                },
            ],
            generator_config: None,
        };

        fs::write(
            metadata_dir.join("index.json"),
            serde_json::to_string_pretty(&index).unwrap(),
        )
        .unwrap();

        let source = LocalDirectorySource::new(metadata_dir);

        // Get platform directory for current system
        let platform_dir = get_current_platform_directory();

        let filtered = source.filter_files_for_platform(index.files, &platform_dir);

        // Should only get files matching current platform directory
        for entry in &filtered {
            assert!(entry.path.starts_with(&format!("{platform_dir}/")));
        }

        // Verify we get at least some files on known platforms
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        {
            assert!(!filtered.is_empty());
        }
    }
}