kopi 0.1.1

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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
// 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.

use crate::error::{KopiError, Result};
use crate::storage::{InstallationMetadata, JdkMetadataWithInstallation};
use crate::version::Version;
use std::cell::RefCell;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::str::FromStr;

#[derive(Debug, Clone)]
pub struct InstalledJdk {
    pub distribution: String,
    pub version: Version,
    pub path: PathBuf,
    pub javafx_bundled: bool,
    /// Cached metadata, loaded lazily on first access
    metadata_cache: RefCell<Option<InstallationMetadata>>,
}

impl InstalledJdk {
    /// Create a new InstalledJdk instance
    pub fn new(
        distribution: String,
        version: Version,
        path: PathBuf,
        javafx_bundled: bool,
    ) -> Self {
        Self {
            distribution,
            version,
            path,
            javafx_bundled,
            metadata_cache: RefCell::new(None),
        }
    }

    /// Load metadata from the metadata file if it exists
    fn load_metadata(&self, jdks_dir: &Path) -> Option<InstallationMetadata> {
        let suffix = if self.javafx_bundled { "-fx" } else { "" };
        let dir_name = format!("{}-{}{suffix}", self.distribution, self.version);
        let metadata_filename = format!("{dir_name}.meta.json");
        let metadata_path = jdks_dir.join(&metadata_filename);

        if !metadata_path.exists() {
            log::debug!("Metadata file not found: {}", metadata_path.display());
            return None;
        }

        match std::fs::read_to_string(&metadata_path) {
            Ok(content) => match serde_json::from_str::<JdkMetadataWithInstallation>(&content) {
                Ok(metadata) => {
                    log::debug!("Loaded metadata from: {}", metadata_path.display());
                    Some(metadata.installation_metadata)
                }
                Err(e) => {
                    log::warn!(
                        "Failed to parse metadata file {}: {}",
                        metadata_path.display(),
                        e
                    );
                    None
                }
            },
            Err(e) => {
                log::warn!(
                    "Failed to read metadata file {}: {}",
                    metadata_path.display(),
                    e
                );
                None
            }
        }
    }

    /// Get cached metadata, loading it if necessary
    fn get_cached_metadata(&self) -> Option<InstallationMetadata> {
        let mut cache = self.metadata_cache.borrow_mut();

        if cache.is_none() {
            // Try to load metadata from disk
            // We need to determine the jdks_dir - typically it's the parent of the JDK path
            if let Some(parent) = self.path.parent()
                && let Some(metadata) = self.load_metadata(parent)
            {
                // Validate metadata has required fields
                if self.validate_metadata(&metadata) {
                    *cache = Some(metadata);
                } else {
                    log::warn!(
                        "Metadata for {} has incomplete fields, falling back to runtime detection",
                        self.distribution
                    );
                }
            }
        }

        cache.clone()
    }

    /// Validate that metadata has all required fields
    fn validate_metadata(&self, metadata: &InstallationMetadata) -> bool {
        // Check that critical fields are not empty or have valid values
        if metadata.platform.is_empty() {
            log::debug!("Metadata validation failed: empty platform field");
            return false;
        }

        if metadata.structure_type.is_empty() {
            log::debug!("Metadata validation failed: empty structure_type field");
            return false;
        }

        // java_home_suffix can be empty for direct structure, so we don't validate it
        // metadata_version should be > 0
        if metadata.metadata_version == 0 {
            log::debug!("Metadata validation failed: invalid metadata_version");
            return false;
        }

        true
    }

    pub fn write_to(&self, path: &Path) -> Result<()> {
        // Ensure parent directory exists
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).map_err(|e| {
                KopiError::SystemError(format!(
                    "Failed to create directory {}: {}",
                    parent.display(),
                    e
                ))
            })?;
        }

        // Try to format the version in a more user-friendly way
        // If the version has 4 components and no build (e.g., 24.0.2.12),
        // try to extract the build number for a cleaner format (e.g., 24.0.2+12)
        let formatted_version =
            if self.version.components.len() == 4 && self.version.build.is_none() {
                // Try to extract build from the 4th component
                if let Some(extracted) = self.version.try_extract_build() {
                    extracted.to_string()
                } else {
                    self.version.to_string()
                }
            } else {
                self.version.to_string()
            };

        // Format version string with JavaFX suffix if needed
        let javafx_suffix = if self.javafx_bundled { "+fx" } else { "" };
        let version_string = format!(
            "{}@{}{}",
            self.distribution, formatted_version, javafx_suffix
        );

        // Write atomically using a temporary file
        let temp_path = path.with_extension("tmp");

        {
            let mut file = fs::File::create(&temp_path).map_err(|e| {
                KopiError::SystemError(format!("Failed to create {}: {}", temp_path.display(), e))
            })?;

            file.write_all(version_string.as_bytes()).map_err(|e| {
                KopiError::SystemError(format!("Failed to write to {}: {}", temp_path.display(), e))
            })?;

            file.flush().map_err(|e| {
                KopiError::SystemError(format!("Failed to flush {}: {}", temp_path.display(), e))
            })?;
        }

        // Rename temp file to final location
        fs::rename(&temp_path, path).map_err(|e| {
            KopiError::SystemError(format!(
                "Failed to rename {} to {}: {}",
                temp_path.display(),
                path.display(),
                e
            ))
        })?;

        log::debug!("Wrote version file: {path:?}");
        Ok(())
    }

    /// Resolves the correct JAVA_HOME path for this JDK installation.
    ///
    /// On macOS, this handles different directory structures:
    /// - Bundle structure: Returns path/Contents/Home
    /// - Direct structure: Returns path directly
    ///
    /// On other platforms, always returns the path directly.
    pub fn resolve_java_home(&self) -> PathBuf {
        // Try to use cached metadata first
        if let Some(metadata) = self.get_cached_metadata() {
            let java_home = if metadata.java_home_suffix.is_empty() {
                self.path.clone()
            } else {
                self.path.join(&metadata.java_home_suffix)
            };

            log::debug!(
                "Resolved JAVA_HOME for {} using cached metadata ({}): {}",
                self.distribution,
                metadata.structure_type,
                java_home.display()
            );
            return java_home;
        }

        // Fall back to runtime detection
        log::warn!(
            "No metadata found for {} at {}, falling back to runtime detection. \
             This may impact performance. Consider reinstalling the JDK to create metadata.",
            self.distribution,
            self.path.display()
        );

        #[cfg(target_os = "macos")]
        {
            // Check for bundle structure (Contents/Home)
            let bundle_path = self.path.join("Contents").join("Home");
            if bundle_path.join("bin").exists() {
                log::debug!(
                    "Resolved JAVA_HOME for {} using bundle structure: {}",
                    self.distribution,
                    bundle_path.display()
                );
                return bundle_path;
            }

            // Direct structure or hybrid (has bin at root)
            if self.path.join("bin").exists() {
                log::debug!(
                    "Resolved JAVA_HOME for {} using direct structure: {}",
                    self.distribution,
                    self.path.display()
                );
                return self.path.clone();
            }

            // Fallback: return path as-is and log warning
            log::warn!(
                "Could not detect JDK structure for {} at {}, using path as-is",
                self.distribution,
                self.path.display()
            );
            self.path.clone()
        }

        #[cfg(not(target_os = "macos"))]
        {
            // On non-macOS platforms, always use direct structure
            log::debug!(
                "Resolved JAVA_HOME for {} on non-macOS platform: {}",
                self.distribution,
                self.path.display()
            );
            self.path.clone()
        }
    }

    /// Resolves the path to the bin directory for this JDK installation.
    ///
    /// This method uses resolve_java_home() and appends "bin" to get the
    /// correct bin directory path regardless of the JDK structure.
    pub fn resolve_bin_path(&self) -> Result<PathBuf> {
        let java_home = self.resolve_java_home();
        let bin_path = java_home.join("bin");

        if !bin_path.exists() {
            return Err(KopiError::SystemError(format!(
                "JDK bin directory not found at expected location: {}",
                bin_path.display()
            )));
        }

        log::debug!(
            "Resolved bin path for {}: {}",
            self.distribution,
            bin_path.display()
        );

        Ok(bin_path)
    }
}

pub struct JdkLister;

impl JdkLister {
    pub fn list_installed_jdks(jdks_dir: &Path) -> Result<Vec<InstalledJdk>> {
        if !jdks_dir.exists() {
            return Ok(Vec::new());
        }

        let mut installed = Vec::new();

        for entry in fs::read_dir(jdks_dir)? {
            let entry = entry?;
            let path = entry.path();

            if !path.is_dir() {
                continue;
            }

            if path
                .file_name()
                .and_then(|n| n.to_str())
                .map(|n| n.starts_with('.'))
                .unwrap_or(false)
            {
                continue;
            }

            if let Some(jdk_info) = Self::parse_jdk_dir_name(&path) {
                installed.push(jdk_info);
            }
        }

        installed.sort_by(|a, b| {
            a.distribution
                .cmp(&b.distribution)
                .then(b.version.cmp(&a.version))
        });

        Ok(installed)
    }

    pub fn parse_jdk_dir_name(path: &Path) -> Option<InstalledJdk> {
        let file_name = path.file_name()?.to_str()?;

        // Check if JavaFX bundled (-fx suffix)
        let (file_name_without_fx, javafx_bundled) =
            if let Some(stripped) = file_name.strip_suffix("-fx") {
                (stripped, true)
            } else {
                (file_name, false)
            };

        let mut split_pos = None;
        let chars: Vec<char> = file_name_without_fx.chars().collect();

        for i in 0..chars.len() - 1 {
            if chars[i] == '-' && chars[i + 1].is_numeric() {
                split_pos = Some(i);
                break;
            }
        }

        let (distribution, version) = if let Some(pos) = split_pos {
            let dist = &file_name_without_fx[..pos];
            let ver = &file_name_without_fx[pos + 1..];
            (dist, ver)
        } else {
            return None;
        };

        let parsed_version = match Version::from_str(version) {
            Ok(v) => v,
            Err(_) => return None,
        };

        Some(InstalledJdk::new(
            distribution.to_string(),
            parsed_version,
            path.to_path_buf(),
            javafx_bundled,
        ))
    }

    pub fn get_jdk_size(path: &Path) -> Result<u64> {
        let mut total_size = 0u64;

        for entry in walkdir::WalkDir::new(path) {
            let entry = entry?;
            if entry.file_type().is_file() {
                total_size += entry.metadata()?.len();
            }
        }

        Ok(total_size)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::api::{Links, Package};
    use crate::storage::{InstallationMetadata, JdkMetadataWithInstallation};
    use crate::version::Version;
    use std::time::Instant;
    use tempfile::TempDir;

    #[test]
    fn test_list_installed_jdks() {
        let temp_dir = TempDir::new().unwrap();
        let jdks_dir = temp_dir.path().join("jdks");
        fs::create_dir_all(&jdks_dir).unwrap();

        fs::create_dir_all(jdks_dir.join("temurin-21.0.1")).unwrap();
        fs::create_dir_all(jdks_dir.join("corretto-17.0.9")).unwrap();
        fs::create_dir_all(jdks_dir.join(".tmp")).unwrap();

        let installed = JdkLister::list_installed_jdks(&jdks_dir).unwrap();
        assert_eq!(installed.len(), 2);

        assert_eq!(installed[0].distribution, "corretto");
        assert_eq!(installed[0].version.to_string(), "17.0.9");

        assert_eq!(installed[1].distribution, "temurin");
        assert_eq!(installed[1].version.to_string(), "21.0.1");
    }

    #[test]
    fn test_parse_jdk_dir_name() {
        let jdk = JdkLister::parse_jdk_dir_name(Path::new("temurin-21.0.1")).unwrap();
        assert_eq!(jdk.distribution, "temurin");
        assert_eq!(jdk.version.to_string(), "21.0.1");

        let jdk = JdkLister::parse_jdk_dir_name(Path::new("temurin-22-ea")).unwrap();
        assert_eq!(jdk.distribution, "temurin");
        assert_eq!(jdk.version.to_string(), "22-ea");

        let jdk = JdkLister::parse_jdk_dir_name(Path::new("corretto-17.0.9+9")).unwrap();
        assert_eq!(jdk.distribution, "corretto");
        assert_eq!(jdk.version.to_string(), "17.0.9+9");

        let jdk = JdkLister::parse_jdk_dir_name(Path::new("graalvm-ce-21.0.1")).unwrap();
        assert_eq!(jdk.distribution, "graalvm-ce");
        assert_eq!(jdk.version.to_string(), "21.0.1");

        let jdk = JdkLister::parse_jdk_dir_name(Path::new("liberica-21.0.1-13")).unwrap();
        assert_eq!(jdk.distribution, "liberica");
        assert_eq!(jdk.version.to_string(), "21.0.1-13");

        let jdk = JdkLister::parse_jdk_dir_name(Path::new("temurin-17")).unwrap();
        assert_eq!(jdk.distribution, "temurin");
        assert_eq!(jdk.version.to_string(), "17");

        assert!(JdkLister::parse_jdk_dir_name(Path::new("invalid")).is_none());
        assert!(JdkLister::parse_jdk_dir_name(Path::new("no-hyphen-here")).is_none());
        assert!(JdkLister::parse_jdk_dir_name(Path::new("temurin")).is_none());

        // Version with 'v' prefix should not be parsed
        assert!(JdkLister::parse_jdk_dir_name(Path::new("zulu-v11.0.21")).is_none());

        // Test JavaFX bundled JDKs
        let jdk_fx = JdkLister::parse_jdk_dir_name(Path::new("liberica-21.0.5-fx")).unwrap();
        assert_eq!(jdk_fx.distribution, "liberica");
        assert_eq!(jdk_fx.version.to_string(), "21.0.5");
        assert!(jdk_fx.javafx_bundled);

        let jdk_fx2 = JdkLister::parse_jdk_dir_name(Path::new("temurin-17.0.9+9-fx")).unwrap();
        assert_eq!(jdk_fx2.distribution, "temurin");
        assert_eq!(jdk_fx2.version.to_string(), "17.0.9+9");
        assert!(jdk_fx2.javafx_bundled);
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_resolve_java_home_bundle_structure() {
        let temp_dir = TempDir::new().unwrap();
        let jdk_path = temp_dir.path().join("temurin-21.0.1");

        // Create bundle structure
        let bundle_bin_path = jdk_path.join("Contents").join("Home").join("bin");
        fs::create_dir_all(&bundle_bin_path).unwrap();

        let jdk = InstalledJdk::new(
            "temurin".to_string(),
            Version::new(21, 0, 1),
            jdk_path.clone(),
            false,
        );

        let java_home = jdk.resolve_java_home();
        assert_eq!(java_home, jdk_path.join("Contents").join("Home"));
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_resolve_java_home_direct_structure() {
        let temp_dir = TempDir::new().unwrap();
        let jdk_path = temp_dir.path().join("liberica-21.0.1");

        // Create direct structure
        let bin_path = jdk_path.join("bin");
        fs::create_dir_all(&bin_path).unwrap();

        let jdk = InstalledJdk::new(
            "liberica".to_string(),
            Version::new(21, 0, 1),
            jdk_path.clone(),
            false,
        );

        let java_home = jdk.resolve_java_home();
        assert_eq!(java_home, jdk_path);
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_resolve_java_home_hybrid_structure() {
        let temp_dir = TempDir::new().unwrap();
        let jdk_path = temp_dir.path().join("zulu-21.0.1");

        // Create hybrid structure (bin at root + Contents/Home exists)
        fs::create_dir_all(jdk_path.join("bin")).unwrap();
        fs::create_dir_all(jdk_path.join("Contents").join("Home").join("bin")).unwrap();

        let jdk = InstalledJdk::new(
            "zulu".to_string(),
            Version::new(21, 0, 1),
            jdk_path.clone(),
            false,
        );

        // Should prefer bundle structure when both exist
        let java_home = jdk.resolve_java_home();
        assert_eq!(java_home, jdk_path.join("Contents").join("Home"));
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_resolve_java_home_missing_structure() {
        let temp_dir = TempDir::new().unwrap();
        let jdk_path = temp_dir.path().join("broken-jdk");
        fs::create_dir_all(&jdk_path).unwrap();

        let jdk = InstalledJdk::new(
            "broken".to_string(),
            Version::new(21, 0, 1),
            jdk_path.clone(),
            false,
        );

        // Should return path as-is when structure cannot be detected
        let java_home = jdk.resolve_java_home();
        assert_eq!(java_home, jdk_path);
    }

    #[test]
    #[cfg(not(target_os = "macos"))]
    fn test_resolve_java_home_non_macos() {
        let temp_dir = TempDir::new().unwrap();
        let jdk_path = temp_dir.path().join("temurin-21.0.1");

        // Even if bundle structure exists, should return direct path on non-macOS
        fs::create_dir_all(jdk_path.join("Contents").join("Home").join("bin")).unwrap();
        fs::create_dir_all(jdk_path.join("bin")).unwrap();

        let jdk = InstalledJdk::new(
            "temurin".to_string(),
            Version::new(21, 0, 1),
            jdk_path.clone(),
            false,
        );

        let java_home = jdk.resolve_java_home();
        assert_eq!(java_home, jdk_path);
    }

    #[test]
    fn test_resolve_bin_path_success() {
        let temp_dir = TempDir::new().unwrap();
        let jdk_path = temp_dir.path().join("test-jdk");

        // Create a bin directory
        let bin_path = jdk_path.join("bin");
        fs::create_dir_all(&bin_path).unwrap();

        let jdk = InstalledJdk::new(
            "test".to_string(),
            Version::new(21, 0, 1),
            jdk_path.clone(),
            false,
        );

        let resolved_bin = jdk.resolve_bin_path().unwrap();
        assert_eq!(resolved_bin, bin_path);
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_resolve_bin_path_bundle_structure() {
        let temp_dir = TempDir::new().unwrap();
        let jdk_path = temp_dir.path().join("temurin-21.0.1");

        // Create bundle structure
        let bundle_bin_path = jdk_path.join("Contents").join("Home").join("bin");
        fs::create_dir_all(&bundle_bin_path).unwrap();

        let jdk = InstalledJdk::new(
            "temurin".to_string(),
            Version::new(21, 0, 1),
            jdk_path,
            false,
        );

        let resolved_bin = jdk.resolve_bin_path().unwrap();
        assert_eq!(resolved_bin, bundle_bin_path);
    }

    #[test]
    fn test_resolve_bin_path_missing_directory() {
        let temp_dir = TempDir::new().unwrap();
        let jdk_path = temp_dir.path().join("broken-jdk");
        fs::create_dir_all(&jdk_path).unwrap();

        let jdk = InstalledJdk::new(
            "broken".to_string(),
            Version::new(21, 0, 1),
            jdk_path,
            false,
        );

        let result = jdk.resolve_bin_path();
        assert!(result.is_err());

        if let Err(e) = result {
            match e {
                KopiError::SystemError(msg) => {
                    assert!(msg.contains("bin directory not found"));
                }
                _ => panic!("Expected SystemError"),
            }
        }
    }

    #[test]
    fn test_metadata_lazy_loading() {
        let temp_dir = TempDir::new().unwrap();
        let jdks_dir = temp_dir.path().join("jdks");
        fs::create_dir_all(&jdks_dir).unwrap();

        let jdk_path = jdks_dir.join("temurin-21.0.1");
        fs::create_dir_all(&jdk_path).unwrap();

        // Create metadata file
        let metadata_content = r#"{
            "id": "test-id",
            "archive_type": "tar.gz",
            "distribution": "temurin",
            "major_version": 21,
            "java_version": "21.0.1",
            "distribution_version": "21.0.1+35.1",
            "jdk_version": 21,
            "directly_downloadable": true,
            "filename": "test.tar.gz",
            "links": {
                "pkg_download_redirect": "https://example.com",
                "pkg_info_uri": "https://example.com/info"
            },
            "free_use_in_production": true,
            "tck_tested": "yes",
            "size": 190000000,
            "operating_system": "mac",
            "architecture": "aarch64",
            "lib_c_type": null,
            "package_type": "jdk",
            "javafx_bundled": false,
            "term_of_support": null,
            "release_status": null,
            "latest_build_available": null,
            "installation_metadata": {
                "java_home_suffix": "Contents/Home",
                "structure_type": "bundle",
                "platform": "macos_aarch64",
                "metadata_version": 1
            }
        }"#;

        let metadata_path = jdks_dir.join("temurin-21.0.1.meta.json");
        fs::write(&metadata_path, metadata_content).unwrap();

        let jdk = InstalledJdk::new(
            "temurin".to_string(),
            Version::new(21, 0, 1),
            jdk_path.clone(),
            false,
        );

        // First access should load metadata
        let java_home = jdk.resolve_java_home();
        assert_eq!(java_home, jdk_path.join("Contents/Home"));

        // Verify metadata was cached
        assert!(jdk.metadata_cache.borrow().is_some());

        // Second access should use cached data (delete file to ensure it's not re-read)
        fs::remove_file(&metadata_path).unwrap();
        let java_home2 = jdk.resolve_java_home();
        assert_eq!(java_home2, jdk_path.join("Contents/Home"));
    }

    #[test]
    fn test_metadata_cache_miss_fallback() {
        let temp_dir = TempDir::new().unwrap();
        let jdks_dir = temp_dir.path().join("jdks");
        fs::create_dir_all(&jdks_dir).unwrap();

        let jdk_path = jdks_dir.join("liberica-21.0.1");
        fs::create_dir_all(jdk_path.join("bin")).unwrap();

        let jdk = InstalledJdk::new(
            "liberica".to_string(),
            Version::new(21, 0, 1),
            jdk_path.clone(),
            false,
        );

        // No metadata file exists, should fall back to runtime detection
        let java_home = jdk.resolve_java_home();

        #[cfg(target_os = "macos")]
        assert_eq!(java_home, jdk_path);

        #[cfg(not(target_os = "macos"))]
        assert_eq!(java_home, jdk_path);

        // Cache should remain None
        assert!(jdk.metadata_cache.borrow().is_none());
    }

    #[test]
    fn test_metadata_corrupt_file_fallback() {
        let temp_dir = TempDir::new().unwrap();
        let jdks_dir = temp_dir.path().join("jdks");
        fs::create_dir_all(&jdks_dir).unwrap();

        let jdk_path = jdks_dir.join("temurin-21.0.1");
        fs::create_dir_all(jdk_path.join("bin")).unwrap();

        // Create corrupt metadata file
        let metadata_path = jdks_dir.join("temurin-21.0.1.meta.json");
        fs::write(&metadata_path, "{ invalid json").unwrap();

        let jdk = InstalledJdk::new(
            "temurin".to_string(),
            Version::new(21, 0, 1),
            jdk_path.clone(),
            false,
        );

        // Should fall back to runtime detection
        let java_home = jdk.resolve_java_home();

        #[cfg(target_os = "macos")]
        assert_eq!(java_home, jdk_path);

        #[cfg(not(target_os = "macos"))]
        assert_eq!(java_home, jdk_path);

        // Cache should remain None due to parse error
        assert!(jdk.metadata_cache.borrow().is_none());
    }

    #[test]
    fn test_metadata_performance() {
        use std::time::Instant;

        let temp_dir = TempDir::new().unwrap();
        let jdks_dir = temp_dir.path().join("jdks");
        fs::create_dir_all(&jdks_dir).unwrap();

        let jdk_path = jdks_dir.join("temurin-21.0.1");
        fs::create_dir_all(&jdk_path).unwrap();

        // Create metadata file
        let metadata_content = r#"{
            "id": "test-id",
            "archive_type": "tar.gz",
            "distribution": "temurin",
            "major_version": 21,
            "java_version": "21.0.1",
            "distribution_version": "21.0.1+35.1",
            "jdk_version": 21,
            "directly_downloadable": true,
            "filename": "test.tar.gz",
            "links": {
                "pkg_download_redirect": "https://example.com",
                "pkg_info_uri": null
            },
            "free_use_in_production": true,
            "tck_tested": "yes",
            "size": 190000000,
            "operating_system": "mac",
            "architecture": "aarch64",
            "lib_c_type": null,
            "package_type": "jdk",
            "javafx_bundled": false,
            "term_of_support": null,
            "release_status": null,
            "latest_build_available": null,
            "installation_metadata": {
                "java_home_suffix": "",
                "structure_type": "direct",
                "platform": "macos_aarch64",
                "metadata_version": 1
            }
        }"#;

        let metadata_path = jdks_dir.join("temurin-21.0.1.meta.json");
        fs::write(&metadata_path, metadata_content).unwrap();

        let jdk = InstalledJdk::new(
            "temurin".to_string(),
            Version::new(21, 0, 1),
            jdk_path.clone(),
            false,
        );

        // First access loads metadata
        let _ = jdk.resolve_java_home();

        // Measure cached access time
        let start = Instant::now();
        for _ in 0..1000 {
            let _ = jdk.resolve_java_home();
        }
        let elapsed = start.elapsed();

        // Average time per call should be < 1ms
        let avg_micros = elapsed.as_micros() / 1000;
        assert!(
            avg_micros < 1000,
            "Cached access took {avg_micros} microseconds on average"
        );
    }

    #[test]
    fn test_metadata_sequential_access() {
        let temp_dir = TempDir::new().unwrap();
        let jdks_dir = temp_dir.path().join("jdks");
        fs::create_dir_all(&jdks_dir).unwrap();

        let jdk_path = jdks_dir.join("temurin-21.0.1");
        fs::create_dir_all(&jdk_path).unwrap();

        // Create metadata file
        let metadata_content = r#"{
            "id": "test-id",
            "archive_type": "tar.gz",
            "distribution": "temurin",
            "major_version": 21,
            "java_version": "21.0.1",
            "distribution_version": "21.0.1+35.1",
            "jdk_version": 21,
            "directly_downloadable": true,
            "filename": "test.tar.gz",
            "links": {
                "pkg_download_redirect": "https://example.com",
                "pkg_info_uri": null
            },
            "free_use_in_production": true,
            "tck_tested": "yes",
            "size": 190000000,
            "operating_system": "mac",
            "architecture": "aarch64",
            "lib_c_type": null,
            "package_type": "jdk",
            "javafx_bundled": false,
            "term_of_support": null,
            "release_status": null,
            "latest_build_available": null,
            "installation_metadata": {
                "java_home_suffix": "Contents/Home",
                "structure_type": "bundle",
                "platform": "macos_aarch64",
                "metadata_version": 1
            }
        }"#;

        let metadata_path = jdks_dir.join("temurin-21.0.1.meta.json");
        fs::write(&metadata_path, metadata_content).unwrap();

        let jdk = InstalledJdk::new(
            "temurin".to_string(),
            Version::new(21, 0, 1),
            jdk_path.clone(),
            false,
        );

        // Note: RefCell is not thread-safe, so this test verifies
        // sequential access from the same thread (which is the actual use case)
        let expected_java_home = jdk_path.join("Contents/Home");

        // Multiple sequential accesses
        for _ in 0..10 {
            let java_home = jdk.resolve_java_home();
            assert_eq!(java_home, expected_java_home);
        }

        // Verify metadata was only loaded once
        assert!(jdk.metadata_cache.borrow().is_some());
    }

    #[test]
    fn test_metadata_incomplete_fields_fallback() {
        let temp_dir = TempDir::new().unwrap();
        let jdks_dir = temp_dir.path().join("jdks");
        fs::create_dir_all(&jdks_dir).unwrap();

        let jdk_path = jdks_dir.join("temurin-21.0.1");
        fs::create_dir_all(jdk_path.join("bin")).unwrap();

        // Create metadata file with missing required fields
        let incomplete_metadata = r#"{
            "id": "test-id",
            "archive_type": "tar.gz",
            "distribution": "temurin",
            "major_version": 21,
            "java_version": "21.0.1",
            "distribution_version": "21.0.1+35.1",
            "jdk_version": 21,
            "directly_downloadable": true,
            "filename": "test.tar.gz",
            "links": {
                "pkg_download_redirect": "https://example.com",
                "pkg_info_uri": null
            },
            "free_use_in_production": true,
            "tck_tested": "yes",
            "size": 190000000,
            "operating_system": "mac",
            "architecture": "aarch64",
            "lib_c_type": null,
            "package_type": "jdk",
            "javafx_bundled": false,
            "term_of_support": null,
            "release_status": null,
            "latest_build_available": null,
            "installation_metadata": {
                "java_home_suffix": "Contents/Home",
                "structure_type": "",
                "platform": "macos_aarch64",
                "metadata_version": 1
            }
        }"#;

        let metadata_path = jdks_dir.join("temurin-21.0.1.meta.json");
        fs::write(&metadata_path, incomplete_metadata).unwrap();

        let jdk = InstalledJdk::new(
            "temurin".to_string(),
            Version::new(21, 0, 1),
            jdk_path.clone(),
            false,
        );

        // Should fall back to runtime detection due to empty structure_type
        let java_home = jdk.resolve_java_home();

        #[cfg(target_os = "macos")]
        assert_eq!(java_home, jdk_path);

        #[cfg(not(target_os = "macos"))]
        assert_eq!(java_home, jdk_path);

        // Cache should remain None due to validation failure
        assert!(jdk.metadata_cache.borrow().is_none());
    }

    #[test]
    fn test_metadata_invalid_version_fallback() {
        let temp_dir = TempDir::new().unwrap();
        let jdks_dir = temp_dir.path().join("jdks");
        fs::create_dir_all(&jdks_dir).unwrap();

        let jdk_path = jdks_dir.join("liberica-21.0.1");
        fs::create_dir_all(jdk_path.join("bin")).unwrap();

        // Create metadata file with invalid metadata_version
        let invalid_metadata = r#"{
            "id": "test-id",
            "archive_type": "tar.gz",
            "distribution": "liberica",
            "major_version": 21,
            "java_version": "21.0.1",
            "distribution_version": "21.0.1",
            "jdk_version": 21,
            "directly_downloadable": true,
            "filename": "test.tar.gz",
            "links": {
                "pkg_download_redirect": "https://example.com",
                "pkg_info_uri": null
            },
            "free_use_in_production": true,
            "tck_tested": "yes",
            "size": 190000000,
            "operating_system": "linux",
            "architecture": "x64",
            "lib_c_type": null,
            "package_type": "jdk",
            "javafx_bundled": false,
            "term_of_support": null,
            "release_status": null,
            "latest_build_available": null,
            "installation_metadata": {
                "java_home_suffix": "",
                "structure_type": "direct",
                "platform": "linux_x64",
                "metadata_version": 0
            }
        }"#;

        let metadata_path = jdks_dir.join("liberica-21.0.1.meta.json");
        fs::write(&metadata_path, invalid_metadata).unwrap();

        let jdk = InstalledJdk::new(
            "liberica".to_string(),
            Version::new(21, 0, 1),
            jdk_path.clone(),
            false,
        );

        // Should fall back to runtime detection due to invalid metadata_version
        let java_home = jdk.resolve_java_home();
        assert_eq!(java_home, jdk_path);

        // Cache should remain None due to validation failure
        assert!(jdk.metadata_cache.borrow().is_none());
    }

    #[test]
    fn test_metadata_empty_platform_fallback() {
        let temp_dir = TempDir::new().unwrap();
        let jdks_dir = temp_dir.path().join("jdks");
        fs::create_dir_all(&jdks_dir).unwrap();

        let jdk_path = jdks_dir.join("zulu-21.0.1");
        fs::create_dir_all(jdk_path.join("bin")).unwrap();

        // Create metadata file with empty platform field
        let invalid_metadata = r#"{
            "id": "test-id",
            "archive_type": "tar.gz",
            "distribution": "zulu",
            "major_version": 21,
            "java_version": "21.0.1",
            "distribution_version": "21.0.1",
            "jdk_version": 21,
            "directly_downloadable": true,
            "filename": "test.tar.gz",
            "links": {
                "pkg_download_redirect": "https://example.com",
                "pkg_info_uri": null
            },
            "free_use_in_production": true,
            "tck_tested": "yes",
            "size": 190000000,
            "operating_system": "mac",
            "architecture": "aarch64",
            "lib_c_type": null,
            "package_type": "jdk",
            "javafx_bundled": false,
            "term_of_support": null,
            "release_status": null,
            "latest_build_available": null,
            "installation_metadata": {
                "java_home_suffix": "",
                "structure_type": "direct",
                "platform": "",
                "metadata_version": 1
            }
        }"#;

        let metadata_path = jdks_dir.join("zulu-21.0.1.meta.json");
        fs::write(&metadata_path, invalid_metadata).unwrap();

        let jdk = InstalledJdk::new(
            "zulu".to_string(),
            Version::new(21, 0, 1),
            jdk_path.clone(),
            false,
        );

        // Should fall back to runtime detection due to empty platform
        let java_home = jdk.resolve_java_home();
        assert_eq!(java_home, jdk_path);

        // Cache should remain None due to validation failure
        assert!(jdk.metadata_cache.borrow().is_none());
    }

    #[test]
    fn test_fallback_no_user_errors() {
        // This test verifies that all fallback scenarios work without returning errors to users
        let temp_dir = TempDir::new().unwrap();
        let jdks_dir = temp_dir.path().join("jdks");
        fs::create_dir_all(&jdks_dir).unwrap();

        // Test 1: Missing metadata file - should work without errors
        let jdk_path1 = jdks_dir.join("temurin-17.0.1");
        fs::create_dir_all(jdk_path1.join("bin")).unwrap();
        let jdk1 = InstalledJdk::new(
            "temurin".to_string(),
            Version::new(17, 0, 1),
            jdk_path1.clone(),
            false,
        );

        // These operations should succeed without errors
        let java_home1 = jdk1.resolve_java_home();
        assert!(!java_home1.as_os_str().is_empty());
        let bin_path1 = jdk1.resolve_bin_path();
        assert!(bin_path1.is_ok());

        // Test 2: Corrupted metadata file - should work without errors
        let jdk_path2 = jdks_dir.join("liberica-17.0.1");
        fs::create_dir_all(jdk_path2.join("bin")).unwrap();
        fs::write(jdks_dir.join("liberica-17.0.1.meta.json"), "{ corrupt json").unwrap();
        let jdk2 = InstalledJdk::new(
            "liberica".to_string(),
            Version::new(17, 0, 1),
            jdk_path2.clone(),
            false,
        );

        let java_home2 = jdk2.resolve_java_home();
        assert!(!java_home2.as_os_str().is_empty());
        let bin_path2 = jdk2.resolve_bin_path();
        assert!(bin_path2.is_ok());

        // Test 3: Incomplete metadata - should work without errors
        let jdk_path3 = jdks_dir.join("zulu-17.0.1");
        fs::create_dir_all(jdk_path3.join("bin")).unwrap();
        let incomplete_meta = r#"{
            "id": "test",
            "installation_metadata": {
                "java_home_suffix": "",
                "structure_type": "",
                "platform": "test",
                "metadata_version": 1
            }
        }"#;
        fs::write(jdks_dir.join("zulu-17.0.1.meta.json"), incomplete_meta).unwrap();
        let jdk3 = InstalledJdk::new(
            "zulu".to_string(),
            Version::new(17, 0, 1),
            jdk_path3.clone(),
            false,
        );

        let java_home3 = jdk3.resolve_java_home();
        assert!(!java_home3.as_os_str().is_empty());
        let bin_path3 = jdk3.resolve_bin_path();
        assert!(bin_path3.is_ok());
    }

    #[test]
    fn test_fallback_logging_output() {
        use log::{Level, Log, Metadata, Record};
        use std::sync::Mutex;

        // Custom logger to capture log messages
        struct TestLogger {
            messages: Mutex<Vec<(Level, String)>>,
        }

        impl Log for TestLogger {
            fn enabled(&self, _metadata: &Metadata) -> bool {
                true
            }

            fn log(&self, record: &Record) {
                let mut messages = self.messages.lock().unwrap();
                messages.push((record.level(), record.args().to_string()));
            }

            fn flush(&self) {}
        }

        let _logger = TestLogger {
            messages: Mutex::new(Vec::new()),
        };

        // Note: In a real test environment, we'd use a proper logging framework
        // This is a simplified example to demonstrate the concept

        let temp_dir = TempDir::new().unwrap();
        let jdks_dir = temp_dir.path().join("jdks");
        fs::create_dir_all(&jdks_dir).unwrap();

        // Test missing metadata logging
        let jdk_path = jdks_dir.join("test-jdk");
        fs::create_dir_all(jdk_path.join("bin")).unwrap();
        let jdk = InstalledJdk::new(
            "test".to_string(),
            Version::new(21, 0, 1),
            jdk_path.clone(),
            false,
        );

        // This should trigger fallback warning
        let _ = jdk.resolve_java_home();

        // In a real test, we would verify the log messages contain expected warnings
        // For now, we just ensure the operation completes without panic
    }

    #[test]
    fn test_installed_jdk_write_to() {
        let temp_dir = TempDir::new().unwrap();
        let version_file = temp_dir.path().join("test-version");

        let jdk = InstalledJdk::new(
            "temurin".to_string(),
            Version::new(21, 0, 1),
            temp_dir.path().join("temurin-21.0.1"),
            false,
        );

        jdk.write_to(&version_file).unwrap();

        let content = fs::read_to_string(&version_file).unwrap();
        assert_eq!(content, "temurin@21.0.1");

        // Test overwriting
        let jdk2 = InstalledJdk::new(
            "corretto".to_string(),
            Version::new(17, 0, 9),
            temp_dir.path().join("corretto-17.0.9"),
            false,
        );

        jdk2.write_to(&version_file).unwrap();

        let content2 = fs::read_to_string(&version_file).unwrap();
        assert_eq!(content2, "corretto@17.0.9");

        // Test JavaFX version writing
        let jdk_fx = InstalledJdk::new(
            "liberica".to_string(),
            Version::new(21, 0, 5),
            temp_dir.path().join("liberica-21.0.5-fx"),
            true,
        );

        jdk_fx.write_to(&version_file).unwrap();

        let content_fx = fs::read_to_string(&version_file).unwrap();
        assert_eq!(content_fx, "liberica@21.0.5+fx");
    }

    #[test]
    fn test_path_resolution_performance_regression() {
        // This test ensures that path resolution performance doesn't regress
        let temp_dir = TempDir::new().unwrap();
        let jdks_dir = temp_dir.path();
        let jdk_path = jdks_dir.join("temurin-21.0.1");
        fs::create_dir_all(&jdk_path).unwrap();

        // Create metadata for fast cached access
        let metadata = JdkMetadataWithInstallation {
            package: Package {
                id: "perf-test".to_string(),
                archive_type: "tar.gz".to_string(),
                distribution: "temurin".to_string(),
                major_version: 21,
                java_version: "21.0.1".to_string(),
                distribution_version: "21.0.1".to_string(),
                jdk_version: 21,
                directly_downloadable: true,
                filename: "temurin-21.0.1.tar.gz".to_string(),
                links: Links {
                    pkg_download_redirect: "https://example.com/jdk.tar.gz".to_string(),
                    pkg_info_uri: None,
                },
                free_use_in_production: true,
                tck_tested: "yes".to_string(),
                size: 100000000,
                operating_system: "macos".to_string(),
                architecture: Some("x64".to_string()),
                lib_c_type: None,
                package_type: "jdk".to_string(),
                javafx_bundled: false,
                term_of_support: None,
                release_status: None,
                latest_build_available: Some(true),
            },
            installation_metadata: InstallationMetadata {
                java_home_suffix: "Contents/Home".to_string(),
                structure_type: "bundle".to_string(),
                platform: "macos".to_string(),
                metadata_version: 1,
            },
        };

        let metadata_file = jdks_dir.join("temurin-21.0.1.meta.json");
        fs::write(&metadata_file, serde_json::to_string(&metadata).unwrap()).unwrap();

        let jdk = InstalledJdk::new(
            "temurin".to_string(),
            Version::new(21, 0, 1),
            jdk_path.clone(),
            false,
        );

        // Pre-load cache
        let _ = jdk.resolve_java_home();

        // Measure cached access time
        let start = Instant::now();
        for _ in 0..1000 {
            let _ = jdk.resolve_java_home();
        }
        let elapsed = start.elapsed();

        // Average time per call should be < 1 microsecond (1000ns)
        let avg_ns = elapsed.as_nanos() / 1000;
        assert!(
            avg_ns < 1000,
            "Path resolution with cache too slow: {avg_ns} ns/call (expected < 1000 ns)"
        );

        // Test bin path resolution performance
        let start = Instant::now();
        for _ in 0..1000 {
            let _ = jdk.resolve_bin_path();
        }
        let elapsed = start.elapsed();

        // Bin path resolution should also be fast
        // Windows file system operations can be slower, so we use a more lenient threshold
        let avg_ns = elapsed.as_nanos() / 1000;
        let threshold_ns = if cfg!(windows) { 100000 } else { 10000 };
        assert!(
            avg_ns < threshold_ns,
            "Bin path resolution too slow: {avg_ns} ns/call (expected < {threshold_ns} ns)"
        );
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_structure_detection_performance_regression() {
        use crate::archive::detect_jdk_root;

        // Test that structure detection performance is acceptable
        let temp_dir = TempDir::new().unwrap();
        let jdk_path = temp_dir.path();

        // Create bundle structure
        let contents_home = jdk_path.join("Contents").join("Home");
        fs::create_dir_all(contents_home.join("bin")).unwrap();
        fs::File::create(contents_home.join("bin").join("java")).unwrap();

        // Measure detection time
        let start = Instant::now();
        for _ in 0..100 {
            let _ = detect_jdk_root(jdk_path).unwrap();
        }
        let elapsed = start.elapsed();

        // Average time should be < 1ms
        let avg_ms = elapsed.as_millis() / 100;
        assert!(
            avg_ms < 1,
            "Structure detection too slow: {avg_ms} ms/call (expected < 1 ms)"
        );
    }

    #[test]
    fn test_memory_usage_with_multiple_jdks() {
        // Test that memory usage is reasonable with many JDKs
        let temp_dir = TempDir::new().unwrap();
        let mut jdks = Vec::new();

        // Create 100 JDKs with metadata
        for i in 0..100 {
            let distribution = format!("dist{i}");
            let version = Version::new(21, 0, i as u32);
            let jdk_path = temp_dir.path().join(format!("{distribution}-{version}"));
            fs::create_dir_all(&jdk_path).unwrap();

            // Create metadata
            let metadata = JdkMetadataWithInstallation {
                package: Package {
                    id: format!("id-{i}"),
                    archive_type: "tar.gz".to_string(),
                    distribution: distribution.clone(),
                    major_version: 21,
                    java_version: version.to_string(),
                    distribution_version: version.to_string(),
                    jdk_version: 21,
                    directly_downloadable: true,
                    filename: format!("{distribution}-{version}.tar.gz"),
                    links: Links {
                        pkg_download_redirect: format!("https://example.com/jdk{i}.tar.gz"),
                        pkg_info_uri: None,
                    },
                    free_use_in_production: true,
                    tck_tested: "yes".to_string(),
                    size: 100000000,
                    operating_system: "macos".to_string(),
                    architecture: Some("x64".to_string()),
                    lib_c_type: None,
                    package_type: "jdk".to_string(),
                    javafx_bundled: false,
                    term_of_support: None,
                    release_status: None,
                    latest_build_available: Some(true),
                },
                installation_metadata: InstallationMetadata {
                    java_home_suffix: if i % 2 == 0 {
                        "".to_string()
                    } else {
                        "Contents/Home".to_string()
                    },
                    structure_type: if i % 2 == 0 {
                        "direct".to_string()
                    } else {
                        "bundle".to_string()
                    },
                    platform: "macos".to_string(),
                    metadata_version: 1,
                },
            };

            let metadata_file = temp_dir
                .path()
                .join(format!("{distribution}-{version}.meta.json"));
            fs::write(&metadata_file, serde_json::to_string(&metadata).unwrap()).unwrap();

            jdks.push(InstalledJdk::new(distribution, version, jdk_path, false));
        }

        // Access all JDKs to load metadata
        for jdk in &jdks {
            let _ = jdk.resolve_java_home();
        }

        // Verify we can still access them efficiently
        let start = Instant::now();
        for jdk in &jdks {
            let _ = jdk.resolve_java_home();
        }
        let elapsed = start.elapsed();

        // Should still be fast even with 100 JDKs
        let elapsed_ms = elapsed.as_millis();
        assert!(
            elapsed_ms < 10,
            "Accessing 100 JDKs took too long: {elapsed_ms} ms (expected < 10 ms)"
        );
    }

    // This test is commented out because it causes a compilation error
    // that demonstrates the thread-safety issue.
    /*
    #[test]
    #[should_panic(expected = "cannot be shared between threads safely")]
    #[ignore = "This test reveals a thread-safety issue with RefCell - metadata_cache should use RwLock instead"]
    fn test_concurrent_metadata_access_reveals_race_condition() {
        use std::sync::Arc;
        use std::thread;

        let temp_dir = TempDir::new().unwrap();
        let jdks_dir = temp_dir.path().join("jdks");
        fs::create_dir_all(&jdks_dir).unwrap();

        // Create JDK directory structure with bundle format
        let jdk_path = jdks_dir.join("temurin-21.0.0");
        fs::create_dir_all(&jdk_path).unwrap();
        let bundle_home = jdk_path.join("Contents/Home");
        let bundle_bin = bundle_home.join("bin");
        fs::create_dir_all(&bundle_bin).unwrap();

        // Create java binary
        let java_binary = if cfg!(windows) { "java.exe" } else { "java" };
        fs::write(bundle_bin.join(java_binary), "#!/bin/sh\necho 'test java'").unwrap();

        // Create metadata file
        let metadata = JdkMetadataWithInstallation {
            package: Package {
                id: "test-id".to_string(),
                archive_type: "tar.gz".to_string(),
                distribution: "temurin".to_string(),
                major_version: 21,
                java_version: "21".to_string(),
                distribution_version: "21.0.0".to_string(),
                jdk_version: 21,
                directly_downloadable: true,
                filename: "test.tar.gz".to_string(),
                links: Links {
                    pkg_download_redirect: "".to_string(),
                    pkg_info_uri: None,
                },
                free_use_in_production: true,
                tck_tested: "yes".to_string(),
                size: 100000000,
                operating_system: "mac".to_string(),
                lib_c_type: None,
                architecture: Some("aarch64".to_string()),
                package_type: "jdk".to_string(),
                javafx_bundled: false,
                term_of_support: Some("sts".to_string()),
                release_status: None,
                latest_build_available: Some(true),
            },
            installation_metadata: InstallationMetadata {
                java_home_suffix: "Contents/Home".to_string(),
                structure_type: "bundle".to_string(),
                platform: "macos".to_string(),
                metadata_version: 1,
            },
        };

        let metadata_file = jdks_dir.join("temurin-21.0.0.meta.json");
        fs::write(&metadata_file, serde_json::to_string(&metadata).unwrap()).unwrap();

        // Create shared InstalledJdk instance
        let version = Version::new(21, 0, 0);
        let jdk = Arc::new(InstalledJdk::new(
            "temurin".to_string(),
            version,
            jdk_path,
        ));

        // Spawn multiple threads accessing metadata concurrently
        let mut handles = vec![];
        for _ in 0..10 {
            let jdk_clone = Arc::clone(&jdk);
            let handle = thread::spawn(move || {
                // Each thread tries to resolve paths multiple times
                for _ in 0..100 {
                    let java_home = jdk_clone.resolve_java_home();
                    assert!(java_home.to_string_lossy().contains("Contents/Home"));

                    let bin_path = jdk_clone.resolve_bin_path();
                    assert!(bin_path.is_ok());
                    assert!(bin_path.unwrap().to_string_lossy().contains("Contents/Home/bin"));
                }
            });
            handles.push(handle);
        }

        // Wait for all threads to complete
        for handle in handles {
            handle.join().unwrap();
        }

        // FINDING: This test reveals a thread-safety issue in InstalledJdk.
        // The metadata_cache field uses RefCell which is not Sync, preventing
        // safe concurrent access. The implementation should use RwLock or OnceCell
        // for thread-safe lazy initialization of metadata.
        //
        // The compile error proves that Arc<InstalledJdk> cannot be safely shared
        // between threads due to RefCell not implementing Sync.
    }
    */

    #[test]
    fn test_error_recovery_missing_bin_directory() {
        let temp_dir = TempDir::new().unwrap();
        let jdks_dir = temp_dir.path().join("jdks");
        fs::create_dir_all(&jdks_dir).unwrap();

        // Create JDK without bin directory
        let jdk_path = jdks_dir.join("temurin-21.0.0");
        fs::create_dir_all(&jdk_path).unwrap();

        // Create metadata indicating bundle structure
        let metadata = JdkMetadataWithInstallation {
            package: create_test_package("temurin", "21.0.0"),
            installation_metadata: InstallationMetadata {
                java_home_suffix: "Contents/Home".to_string(),
                structure_type: "bundle".to_string(),
                platform: "macos".to_string(),
                metadata_version: 1,
            },
        };

        let metadata_file = jdks_dir.join("temurin-21.0.0.meta.json");
        fs::write(&metadata_file, serde_json::to_string(&metadata).unwrap()).unwrap();

        let jdk = InstalledJdk::new(
            "temurin".to_string(),
            Version::new(21, 0, 0),
            jdk_path,
            false,
        );

        // Should return error when bin directory is missing
        let bin_path_result = jdk.resolve_bin_path();
        assert!(bin_path_result.is_err());
        assert!(
            bin_path_result
                .unwrap_err()
                .to_string()
                .contains("bin directory not found")
        );
    }

    #[test]
    fn test_error_recovery_invalid_json_metadata() {
        let temp_dir = TempDir::new().unwrap();
        let jdks_dir = temp_dir.path().join("jdks");
        fs::create_dir_all(&jdks_dir).unwrap();

        // Create JDK with proper structure based on platform
        let jdk_path = jdks_dir.join("temurin-21.0.0");

        #[cfg(target_os = "macos")]
        {
            // macOS: Create bundle structure
            let bundle_home = jdk_path.join("Contents/Home");
            let bundle_bin = bundle_home.join("bin");
            fs::create_dir_all(&bundle_bin).unwrap();

            // Create java binary
            let java_binary = "java";
            fs::write(bundle_bin.join(java_binary), "#!/bin/sh\necho 'test java'").unwrap();
        }

        #[cfg(not(target_os = "macos"))]
        {
            // Other platforms: Create direct structure
            let bin_dir = jdk_path.join("bin");
            fs::create_dir_all(&bin_dir).unwrap();

            // Create java binary
            let java_binary = if cfg!(windows) { "java.exe" } else { "java" };
            fs::write(bin_dir.join(java_binary), "#!/bin/sh\necho 'test java'").unwrap();
        }

        // Write invalid JSON to metadata file
        let metadata_file = jdks_dir.join("temurin-21.0.0.meta.json");
        fs::write(&metadata_file, "{ invalid json content }").unwrap();

        let jdk = InstalledJdk::new(
            "temurin".to_string(),
            Version::new(21, 0, 0),
            jdk_path.clone(),
            false,
        );

        // Should fall back to runtime detection when metadata is invalid
        let java_home = jdk.resolve_java_home();

        // Expected path depends on platform
        #[cfg(target_os = "macos")]
        let expected_java_home = jdk_path.join("Contents/Home");
        #[cfg(not(target_os = "macos"))]
        let expected_java_home = jdk_path.clone();

        assert_eq!(java_home, expected_java_home);

        // Bin path should still work via fallback
        let bin_path = jdk.resolve_bin_path();
        assert!(bin_path.is_ok());

        #[cfg(target_os = "macos")]
        assert_eq!(bin_path.unwrap(), jdk_path.join("Contents/Home/bin"));
        #[cfg(not(target_os = "macos"))]
        assert_eq!(bin_path.unwrap(), jdk_path.join("bin"));
    }

    #[test]
    fn test_error_recovery_partially_missing_metadata() {
        let temp_dir = TempDir::new().unwrap();
        let jdks_dir = temp_dir.path().join("jdks");
        fs::create_dir_all(&jdks_dir).unwrap();

        // Create JDK with direct structure
        let jdk_path = jdks_dir.join("liberica-17.0.9");
        let bin_path = jdk_path.join("bin");
        fs::create_dir_all(&bin_path).unwrap();

        let java_binary = if cfg!(windows) { "java.exe" } else { "java" };
        fs::write(bin_path.join(java_binary), "#!/bin/sh\necho 'test java'").unwrap();

        // Create metadata with missing installation_metadata field
        let incomplete_metadata = r#"{
            "id": "test-id",
            "distribution": "liberica",
            "version": "17.0.9",
            "java_version": "17",
            "major_version": 17
        }"#;

        let metadata_file = jdks_dir.join("liberica-17.0.9.meta.json");
        fs::write(&metadata_file, incomplete_metadata).unwrap();

        let jdk = InstalledJdk::new(
            "liberica".to_string(),
            Version::new(17, 0, 9),
            jdk_path.clone(),
            false,
        );

        // Should fall back to runtime detection
        let java_home = jdk.resolve_java_home();
        assert_eq!(java_home, jdk_path);

        let bin_path = jdk.resolve_bin_path();
        assert!(bin_path.is_ok());
        assert_eq!(bin_path.unwrap(), jdk_path.join("bin"));
    }

    // Helper function to create a test Package
    fn create_test_package(distribution: &str, version: &str) -> Package {
        Package {
            id: "test-id".to_string(),
            archive_type: "tar.gz".to_string(),
            distribution: distribution.to_string(),
            major_version: 21,
            java_version: version.to_string(),
            distribution_version: version.to_string(),
            jdk_version: 21,
            directly_downloadable: true,
            filename: "test.tar.gz".to_string(),
            links: Links {
                pkg_download_redirect: "".to_string(),
                pkg_info_uri: None,
            },
            free_use_in_production: true,
            tck_tested: "yes".to_string(),
            size: 100000000,
            operating_system: "mac".to_string(),
            lib_c_type: None,
            architecture: Some("aarch64".to_string()),
            package_type: "jdk".to_string(),
            javafx_bundled: false,
            term_of_support: Some("sts".to_string()),
            release_status: None,
            latest_build_available: Some(true),
        }
    }
}