nvm-windows 0.1.3

A tool to manage Node.js versions.
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
use std::{
  env::{self},
  ffi::c_void,
  fs::{self, File},
  io::{self, BufReader, Read, Seek},
  os::windows::ffi::OsStrExt,
  path::{Path, PathBuf},
  time::Duration,
};

use anyhow::bail;
use comfy_table::{Cell, CellAlignment, Table, presets};
use indicatif::{ProgressBar, ProgressStyle};
use inquire::validator::Validation;
use path_clean::PathClean;
use regex::{Regex, RegexBuilder};
use url::Url;
use windows_sys::Win32::Storage::FileSystem::{
  GetFileVersionInfoSizeW, GetFileVersionInfoW, VS_FIXEDFILEINFO,
  VerQueryValueW,
};
use winreg::{
  RegKey, RegValue,
  enums::{HKEY_CURRENT_USER, RegType},
};
use zip::ZipArchive;

use std::sync::LazyLock;
#[cfg(feature = "debug")]
use tracing_appender::{
  non_blocking::WorkerGuard,
  rolling::{RollingFileAppender, Rotation},
};
#[cfg(feature = "debug")]
use tracing_subscriber::{
  EnvFilter, Layer, fmt, layer::SubscriberExt, util::SubscriberInitExt,
};

use crate::model::{ArchSpec, Config, ReleaseDatabase, VersionSpec};

pub mod model;

#[cfg(feature = "debug")]
static LOG_GUARD: std::sync::OnceLock<WorkerGuard> = std::sync::OnceLock::new();

#[cfg(feature = "debug")]
const LOG_FILTER: &str = "info,nvm_windows=debug";

static HTTP_CLIENT: LazyLock<ureq::Agent> = LazyLock::new(|| {
  let agent_config = ureq::Agent::config_builder()
    .timeout_global(Some(Duration::from_secs(15 * 60)))
    .timeout_recv_response(Some(Duration::from_secs(60)))
    .timeout_recv_body(Some(Duration::from_secs(10 * 60)))
    .build();
  ureq::Agent::new_with_config(agent_config)
});

const LIST_COUNT: usize = 20;

static VERSION_REGEX: LazyLock<Regex> =
  LazyLock::new(|| Regex::new(r"^v\d+\.\d+\.\d+$").unwrap());

static NVM_SYMLINK_REGEX: LazyLock<Regex> = LazyLock::new(|| {
  RegexBuilder::new(r"%NVM_SYMLINK%")
    .case_insensitive(true)
    .build()
    .unwrap()
});

pub type Result<T = ()> = anyhow::Result<T>;

pub fn activate_symlink(config: Config) -> Result {
  let symlink = get_nvm_symlink()?;
  if let Ok(metadata) = fs::symlink_metadata(&symlink)
    && metadata.is_symlink()
  {
    println!("node is already activated.");
    return Ok(());
  }

  let root = get_root(&config)?;
  let versions = get_local_versions(&root)?;
  let Some(last) = versions.last() else {
    bail!("no node version installed");
  };

  create_junction_link(symlink, root.join(last))?;

  println!("node {} is activated.", last);

  Ok(())
}

/// Create a junction link
/// # Params
/// * `link` - The symlink path, e.g. c:\\program files\\nodejs
/// * `target` - The target path, e.g. d:\\nodejs_root\\v18.16.0
fn create_junction_link<T, L>(link: T, target: L) -> Result
where
  T: AsRef<Path>,
  L: AsRef<Path>,
{
  let target = target.as_ref();
  let link = link.as_ref();
  log::debug!("create link: {:?} -> {:?}", target, link);
  #[cfg(target_os = "windows")]
  junction::create(target, link)?;

  Ok(())
}

pub fn deactivate_symlink() -> Result {
  let symlink = get_nvm_symlink()?;
  let Ok(_) = fs::symlink_metadata(&symlink) else {
    println!("node is already deactivated.");
    return Ok(());
  };

  delete_junction_link(symlink)?;

  println!("node is deactivated.");

  Ok(())
}

fn delete_junction_link<T>(link: T) -> Result
where
  T: AsRef<Path>,
{
  let path = link.as_ref();
  log::debug!("delete link: {:?}", path);
  // The link might not exist, so ignore failed deletion.
  if let Err(e) = fs::remove_dir(path) {
    log::debug!("remove_dir failed: {e}");
  }

  Ok(())
}

fn delete_version(root: &Path, ver: &str) -> Result {
  let path = root.join(ver);
  log::debug!("delete: {:?}", path);
  fs::remove_dir_all(&path)?;

  Ok(())
}

pub fn display_current() -> Result {
  if let Some(current_version) = get_current_version() {
    println!("current version is {}", current_version);
  } else {
    println!("No current version.");
    println!();
    println!("Tips:");
    println!(" * Run 'nvm use x.x.x' to set a version.");
    println!(" * Run 'nvm ls' to list available versions locally.");
    println!(" * Run 'nvm ls --remote' to list available versions online.");
    println!(" * Run 'nvm install latest' to install the latest version.");
  }

  Ok(())
}

pub fn display_or_update_npm_mirror(
  mut config: Config,
  url: Option<Url>,
) -> Result {
  if url.is_some() {
    config.npm_mirror = url;
    config.save()?;
  }

  if let Some(npm_mirror) = config.npm_mirror {
    println!("Current NpmMirror: {}", npm_mirror);
  } else {
    println!("No NpmMirror set.");
  }

  Ok(())
}

pub fn display_or_update_node_mirror(
  mut config: Config,
  url: Option<Url>,
) -> Result {
  if url.is_some() {
    config.node_mirror = url;
    config.save()?;
  }

  if let Some(node_mirror) = config.node_mirror {
    println!("Current NodeMirror: {}", node_mirror);
  } else {
    println!("No NodeMirror set.");
  }

  Ok(())
}

pub fn display_or_update_root<T>(mut config: Config, path: Option<T>) -> Result
where
  T: AsRef<Path>,
{
  if let Some(path) = path {
    let p = path.as_ref();
    if !p.exists() {
      bail!("path {:?} does not exist", p);
    }
    if !p.is_dir() {
      bail!("path {:?} is not a directory", p);
    }
    config.root = Some(p.to_path_buf());
    config.save()?;
    println!("Current Root: {:?}", p);
  } else if let Some(root) = config.root {
    println!("Current Root: {:?}", root);
  } else {
    println!("No Root set.");
  }

  Ok(())
}

fn download_file<U>(url: U, dest: &mut File) -> Result
where
  U: AsRef<str>,
{
  let url = url.as_ref();
  // 1. send request
  let mut resp = HTTP_CLIENT.get(url).call()?;

  // 2. get Content-Length header
  let total_size = resp
    .headers()
    .get("Content-Length")
    .and_then(|v| v.to_str().ok())
    .and_then(|s| s.parse::<u64>().ok())
    .unwrap_or(0);

  // 3. create progress bar
  let pb = if total_size > 0 {
    let pb = ProgressBar::new(total_size);
    pb.set_style(
            ProgressStyle::default_bar()
                .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})")?
                .progress_chars("#>-"),
        );
    pb
  } else {
    // 4. unknown size, use progress spinner
    let pb = ProgressBar::new_spinner();
    pb.set_style(
      ProgressStyle::default_spinner()
        .template("{spinner:.green} [{elapsed_precise}] {bytes} downloaded")?,
    );
    pb
  };

  // 4. wrap response body
  let reader = resp.body_mut().as_reader();
  let mut progress_reader = pb.wrap_read(reader);

  // 5. write to file
  io::copy(&mut progress_reader, dest)?;

  // 6. complete
  pb.finish_with_message("Download complete!");
  Ok(())
}

fn file_validate(file: &File, sha256_checksum: &str) -> Result<bool> {
  use sha2::Digest;

  let mut file = file.try_clone()?;
  file.rewind()?;

  let mut reader = BufReader::with_capacity(256 * 1024, file);
  let mut hasher = sha2::Sha256::new();
  let mut buf = [0u8; 64 * 1024];

  loop {
    let n = reader.read(&mut buf)?;
    if n == 0 {
      break;
    }
    hasher.update(&buf[..n]);
  }

  Ok(hex::encode(hasher.finalize()) == sha256_checksum)
}

pub fn setup(mut config: Config) -> Result {
  let link_path =
    inquire::Text::new("Which directory to use as the symlink path?")
      .with_default(r"C:\Program Files\nodejs")
      .with_help_message("Tip: The symlink must not already exist.")
      .with_validator(symlink_validator)
      .prompt()?;

  let node_store_root =
    inquire::Text::new("Which directory to use as the node store root?")
      .with_default(&config.dir.data_local_dir().to_string_lossy())
      // .with_help_message("Tip: The node store root must not already exist.")
      .with_validator(node_store_root_validator)
      .prompt()?;

  let node_mirror = node_mirror_prompt()?;

  let npm_mirror = npm_mirror_prompt()?;

  std::fs::create_dir_all(&node_store_root)?;
  config.root = Some(node_store_root.into());
  config.node_mirror = node_mirror;
  config.npm_mirror = npm_mirror;

  update_environment(link_path)?;

  log::debug!("config: {:?}", config);
  config.save()?;

  println!("Finished. Please restart the console to update the environment.");

  Ok(())
}

type ValidatorResult =
  core::result::Result<Validation, Box<dyn core::error::Error + Send + Sync>>;

fn symlink_validator(value: &str) -> ValidatorResult {
  // if std::fs::symlink_metadata(value.trim()).is_ok() {
  //   return Ok(Validation::Invalid(
  //     "The symlink or directory already exists.".into(),
  //   ));
  // }

  let path = std::path::Path::new(value.trim());
  if path.extension().is_some() {
    return Ok(Validation::Invalid(
      "The symlink path must be a directory.".into(),
    ));
  }

  Ok(Validation::Valid)
}

fn node_store_root_validator(value: &str) -> ValidatorResult {
  let path = std::path::Path::new(value.trim());

  if path.extension().is_some() {
    return Ok(Validation::Invalid("Must be a directory.".into()));
  }

  Ok(Validation::Valid)
}

fn url_validator(value: &str) -> ValidatorResult {
  let Ok(path) = url::Url::parse(value.trim()) else {
    return Ok(Validation::Invalid("Must be a valid URL.".into()));
  };

  if !matches!(path.scheme(), "https" | "http") || path.host().is_none() {
    return Ok(Validation::Invalid(
      "Only HTTP and HTTPS protocols are supported.".into(),
    ));
  }

  Ok(Validation::Valid)
}

fn node_mirror_prompt() -> Result<Option<Url>> {
  let node_mirror_list = vec!["https://npmmirror.com/mirrors/node/"];

  mirror_prompt(
    node_mirror_list,
    "Which mirror to use for nodejs?",
    "Please input the node mirror address:",
  )
}

fn npm_mirror_prompt() -> Result<Option<Url>> {
  let npm_mirror_list = vec!["https://npmmirror.com/mirrors/npm/"];

  mirror_prompt(
    npm_mirror_list,
    "Which mirror to use for npm?",
    "Please input the npm mirror address:",
  )
}

/// Prompts the user to select a mirror from a predefined list or enter a custom mirror address.
///
/// This function automatically prepends `"none"` and appends `"custom"` to the provided
/// `options` list, then presents an interactive selection menu. If the user selects
/// `"custom"`, they will be further prompted to input a custom mirror value.
///
/// # Arguments
///
/// * `options` - A list of predefined mirror options (e.g., mirror names or URLs).
/// * `select_prompt` - The prompt message displayed for the selection menu
///   (e.g., "Please select a mirror:").
/// * `text_prompt` - The prompt message displayed in the text input when the user
///   selects "custom" (e.g., "Enter custom mirror URL:").
///
/// # Returns
///
/// * `Ok(String)` - The selected predefined mirror name, or the custom mirror
///   string entered by the user.
///
/// # Errors
///
/// * Returns an `Err` variant of `Result` when the user cancels the interaction
///   (e.g., by pressing `Ctrl+C` / `Esc`) or when an underlying I/O error occurs.
///   The error is typically converted from an `inquire` error.
fn mirror_prompt(
  mut options: Vec<&'static str>,
  select_prompt: &str,
  text_prompt: &str,
) -> Result<Option<Url>> {
  // Pre-allocate capacity to avoid reallocation
  options.reserve(2);
  // Insert "none" at the head
  options.insert(0, "none");
  // Append "custom" at the tail
  options.push("custom");

  let mirror = inquire::Select::new(select_prompt, options).prompt()?;
  match mirror {
    "none" => Ok(None),
    "custom" => {
      let mirror_url = inquire::Text::new(text_prompt)
        // .with_help_message("Tip: The node store root must not already exist.")
        .with_validator(url_validator)
        .prompt()?;

      Ok(Some(Url::parse(&mirror_url)?))
    }
    s => Ok(Some(Url::parse(s)?)),
  }
}

/// Get the current version of Node.js.
/// # Returns
/// A string, the version number.
/// (e.g. "v24.2.2")
pub fn get_current_version() -> Option<String> {
  let Ok(symlink) = get_nvm_symlink() else {
    return None;
  };
  // 1. Convert the path to a wide string (null-terminated).
  let wide_path: Vec<u16> = symlink
    .join("node.exe")
    .as_os_str()
    .encode_wide()
    .chain(std::iter::once(0))
    .collect();

  // 2. Get the version info buffer size.
  // SAFETY: wide_path is valid (null-terminated).
  let size = unsafe {
    GetFileVersionInfoSizeW(wide_path.as_ptr(), std::ptr::null_mut())
  };
  if size == 0 {
    return None; // File does not exist or has no version resource
  }

  // 3. Allocate buffer and read version info.
  let mut buffer: Vec<u8> = vec![0u8; size as usize];
  // SAFETY: buffer length >= size, wide_path is valid (null-terminated).
  let ok = unsafe {
    GetFileVersionInfoW(
      wide_path.as_ptr(),
      0,
      size,
      buffer.as_mut_ptr() as *mut c_void,
    )
  };
  if ok == 0 {
    return None;
  }

  // 4. Query the root block "\" to get VS_FIXEDFILEINFO.
  let query: Vec<u16> = "\\".encode_utf16().chain(std::iter::once(0)).collect();
  let mut info_ptr: *const VS_FIXEDFILEINFO = std::ptr::null();
  let mut info_len: u32 = 0;

  // SAFETY: Buffer contains valid version data; query is a valid wide string.
  let found = unsafe {
    VerQueryValueW(
      buffer.as_ptr() as *const c_void,
      query.as_ptr(),
      &mut info_ptr as *mut _ as *mut *mut c_void,
      &mut info_len,
    )
  };
  if found == 0
    || info_ptr.is_null()
    || info_len < std::mem::size_of::<VS_FIXEDFILEINFO>() as u32
  {
    return None;
  }

  // 5. Extract version number from VS_FIXEDFILEINFO.
  // SAFETY: info_ptr points to a valid VS_FIXEDFILEINFO struct.
  let ffi = unsafe { &*info_ptr };

  let version = format!(
    "v{}.{}.{}",
    ffi.dwFileVersionMS >> 16,
    ffi.dwFileVersionMS & 0xFFFF,
    ffi.dwFileVersionLS >> 16
  );

  Some(version)
}

/// Get all local installed versions.
/// # Returns
/// A vector of strings, each string is a version number. (e.g. "v24.2.2")
fn get_local_versions<T>(root: T) -> Result<Vec<String>>
where
  T: AsRef<Path>,
{
  let mut versions = Vec::new();

  for entry in fs::read_dir(root.as_ref())? {
    let entry = entry?;
    if !entry.file_type()?.is_dir() {
      continue;
    }

    if let Some(name) = entry.file_name().to_str()
      && VERSION_REGEX.is_match(name)
    {
      versions.push(name.to_string());
    } else {
      log::debug!("skipping invalid directory entry: {:?}", entry.path());
    }
  }

  versions.sort();
  Ok(versions)
}

fn get_nvm_symlink() -> Result<PathBuf> {
  match env::var("NVM_SYMLINK") {
    Ok(path) => Ok(path.into()),
    Err(e) => {
      log::error!("get nvm symlink failed: {:?}", e);
      bail!("get nvm symlink failed. use 'nvm setup' to set it up.");
    }
  }
}

fn get_root(config: &Config) -> Result<PathBuf> {
  Ok(match &config.root {
    Some(root) => root.clone(),
    None => env::current_dir()?,
  })
}

pub fn install_version(
  config: Config,
  version: VersionSpec,
  skip_checksum: bool,
) -> Result {
  let root = get_root(&config)?;

  let arch = ArchSpec::get_from_machine();
  log::debug!("install: {:?} {}", version, arch);

  let db = ReleaseDatabase::load_from_url(
    &HTTP_CLIENT,
    config.get_node_url(&["index.json"]),
  )?;
  let (exists, ver) = version_exists(&db, &version, &root)?;
  if exists {
    bail!("version {} already installed", ver);
  }

  let url = format!("node-{}-win-{}.zip", ver, arch);
  let url = config.get_node_url(&[&ver, &url]);
  log::debug!("download url: {}", url);

  // full file name: node-version-win-x64.zip
  let Some(file_name) = url
    .path_segments()
    .and_then(|mut segments| segments.next_back())
    .filter(|s| !s.is_empty())
  else {
    bail!("invalid url: {url}");
  };
  let mut zip_path = tempfile::tempfile()?;

  download_file(&url, &mut zip_path)?;

  print!("checksum...");
  if !skip_checksum {
    let url = config.get_node_url(&[&ver, "SHASUMS256.txt"]);
    log::debug!("url: {:?}", url);
    let checksum = load_checksum(&url, &ver, &arch)?;
    let valid = file_validate(&zip_path, &checksum)?;
    if !valid {
      println!("failed.");
      let msg = format!("sha256 checksum failed: {:?}", file_name);
      log::error!("{}", msg);
      bail!(msg);
    }

    println!("OK.");
  } else {
    println!("skip.");
  }

  zip_extract(&zip_path, &root)?;

  let org_path = &root.join(file_name).with_extension("");
  let dist_path = &root.join(&ver);
  log::debug!("rename {:?} -> {:?}", org_path, dist_path);
  fs::rename(org_path, dist_path)?;

  println!("install {} completed.", ver);

  Ok(())
}

fn load_checksum<B, V>(
  base_url: B,
  version: V,
  arch: &ArchSpec,
) -> Result<String>
where
  B: AsRef<str>,
  V: AsRef<str>,
{
  let base_url = base_url.as_ref();
  let version = version.as_ref();

  let text_data = HTTP_CLIENT
    .get(base_url)
    .call()?
    .body_mut()
    .read_to_string()?;
  log::debug!("body len: {}", text_data.len());

  let package_name = format!("node-{}-win-{}.zip", version, arch);
  for line in text_data.lines() {
    // SHASUMS256.txt: "<64-bit hash>  node-vX.Y.Z-win-x64.zip"
    let mut parts = line.split_ascii_whitespace();
    let (Some(checksum), Some(name)) = (parts.next(), parts.next()) else {
      continue;
    };

    if name.trim_start_matches('*') == package_name {
      return Ok(checksum.to_string());
    }
  }

  bail!("checksum not found: {:?}", package_name);
}

pub fn list_local_versions(config: Config) -> Result {
  let current_version = get_current_version();
  log::debug!("current version: {:?}", current_version);

  let path = get_root(&config)?;
  let versions = get_local_versions(path)?;

  if versions.is_empty() {
    println!("No versions are installed.");
  } else {
    println!();

    for version in versions {
      log::debug!("found version: {version}");

      print!("    {}", version);
      if current_version.as_deref() == Some(version.as_str()) {
        println!(" <- In use");
      } else {
        println!();
      }
    }

    println!();
  }

  Ok(())
}

pub fn list_remote_versions(config: Config) -> Result {
  let release_database = ReleaseDatabase::load_from_url(
    &HTTP_CLIENT,
    config.get_node_url(&["index.json"]),
  )?;

  let latest_version = release_database.latest_list(LIST_COUNT);

  let lts_version = release_database.lts_list(LIST_COUNT);

  log::debug!("latest_version: {:?}", latest_version);
  log::debug!("lts_version: {:?}", lts_version);

  let mut table = Table::new();
  table.load_style(presets::UTF8_FULL_CONDENSED).set_header([
    Cell::new("current").set_alignment(CellAlignment::Center),
    Cell::new("lts").set_alignment(CellAlignment::Center),
  ]);

  for (c, l) in latest_version.iter().zip(lts_version.iter()) {
    table.add_row(vec![
      Cell::new(c).set_alignment(CellAlignment::Center),
      Cell::new(l).set_alignment(CellAlignment::Center),
    ]);
  }

  println!("{}", table);

  println!(
    "\n * Note: The list only shows the latest {} versions. Visit https://nodejs.org/en/ for more info.",
    LIST_COUNT
  );

  Ok(())
}

pub fn list_versions(config: Config, is_remote_request: bool) -> Result {
  if is_remote_request {
    list_remote_versions(config)
  } else {
    list_local_versions(config)
  }
}

#[cfg(feature = "debug")]
pub fn log_init() {
  // 1. Rolling file appender (daily rotation, retain 30 days)
  std::fs::create_dir_all("./logs").expect("failed to create logs directory");
  let file_appender = RollingFileAppender::builder()
    .rotation(Rotation::DAILY)
    .filename_prefix("app")
    .filename_suffix("log")
    .max_log_files(30)
    .build("./logs")
    .expect("failed to create rolling file appender");

  // Non-blocking write to avoid log I/O blocking the main thread
  let (non_blocking_file, guard) =
    tracing_appender::non_blocking(file_appender);

  // Store `guard` in a global static to keep it alive until program exit
  LOG_GUARD.set(guard).expect("logging already initialized");

  // 2. Build layers
  // Console: colored, human-readable, INFO and above
  let console_layer = fmt::layer()
    .with_writer(std::io::stderr)
    .pretty()
    .with_filter(EnvFilter::new(LOG_FILTER));

  // File: no color, with timestamps, DEBUG and above (more detailed)
  let file_layer = fmt::layer()
    .with_writer(non_blocking_file)
    .with_ansi(false)
    .with_target(true)
    .with_line_number(true)
    .with_filter(EnvFilter::new(LOG_FILTER));

  // 3. Combine and initialize
  tracing_subscriber::registry()
    .with(console_layer)
    .with(file_layer)
    .init();
}

/// Reset a junction link
/// # Params
/// * `link` - The symlink path, e.g. c:\\program files\\nodejs
/// * `target` - The target path, e.g. d:\\nodejs_root\\v18.16.0
fn reset_junction_link<T, L>(link: T, target: L) -> Result
where
  T: AsRef<Path>,
  L: AsRef<Path>,
{
  delete_junction_link(&link)?;
  create_junction_link(link, target)?;

  Ok(())
}

fn safe_extract<T>(
  entry: &mut zip::read::ZipFile<'_, BufReader<File>>,
  dest: T,
) -> Result<()>
where
  T: AsRef<Path>,
{
  use std::fs::{File, create_dir_all};
  use std::io::{BufWriter, copy};

  let dest_dir = dest.as_ref();

  // Prevent Zip Slip: extracted path must remain within the destination directory
  let out_path = dest_dir.join(entry.mangled_name());
  if !out_path.starts_with(dest_dir) {
    bail!("illegal path in archive: {}", entry.name());
  }

  if entry.is_dir() {
    create_dir_all(&out_path)?;
  } else if let Some(parent) = out_path.parent() {
    create_dir_all(parent)?;
    let mut writer = BufWriter::new(File::create(&out_path)?);

    copy(entry, &mut writer)?;
  }
  Ok(())
}

pub fn switch_version(config: Config, version: VersionSpec) -> Result {
  let root = get_root(&config)?;
  let arch = ArchSpec::get_from_machine();

  let db = ReleaseDatabase::load_from_url(
    &HTTP_CLIENT,
    config.get_node_url(&["index.json"]),
  )?;
  let (exists, ver) = version_exists(&db, &version, &root)?;
  let current_ver = get_current_version();
  if !exists {
    bail!("version {:?} not installed", ver);
  }
  if let Some(current_ver) = current_ver
    && current_ver == ver
  {
    bail!("version {:?} is already used", ver);
  }

  log::debug!("ready switch to {}({})", ver, arch);

  let node_path = root.join(&ver).clean();

  reset_junction_link(get_nvm_symlink()?, node_path)?;

  println!("switch to {} success.", ver);

  Ok(())
}

pub fn uninstall_version(config: Config, version: VersionSpec) -> Result {
  let root = get_root(&config)?;
  let versions = get_local_versions(&root)?;
  log::debug!("local versions: {:?}", versions);

  match version {
    VersionSpec::Latest | VersionSpec::Lts => {
      bail!(
        "The version must be a specific version. Can not use 'latest' or 'lts' to uninstall."
      );
    }
    VersionSpec::Exact(ver) => {
      if !versions.contains(&ver) {
        bail!("version {:?} not installed", ver);
      }
      if let Some(current_ver) = get_current_version()
        && current_ver == ver
      {
        bail!("version {:?} is in use, can not uninstall it", ver);
      }

      delete_version(&root, &ver)?;

      println!("uninstall {:?} completed.", ver);
    }
  }

  Ok(())
}

/// Check if the version exists on the server; error if not.<br>
/// Check if the version directory exists locally.<br>
/// Returns the version string if it exists, e.g. v1.1.0
fn version_exists<T>(
  db: &ReleaseDatabase,
  version: &VersionSpec,
  root: T,
) -> Result<(bool, String)>
where
  T: AsRef<Path>,
{
  let ver = match version {
    VersionSpec::Latest => {
      if let Some(latest_version) = db.latest() {
        latest_version
      } else {
        bail!("No latest version found.")
      }
    }
    VersionSpec::Lts => {
      if let Some(lts_version) = db.latest_lts() {
        lts_version
      } else {
        bail!("No LTS version found.")
      }
    }
    VersionSpec::Exact(s) => {
      if db.version_exists(s) {
        s.clone()
      } else {
        bail!("version {:?} not exists.", s)
      }
    }
  };

  let root = root.as_ref();
  let exists = fs::exists(root.join(&ver))?;

  Ok((exists, ver))
}

fn zip_extract<D>(source: &File, dest: D) -> Result
where
  D: AsRef<Path>,
{
  let mut file = source.try_clone()?;
  file.rewind()?;
  let reader = BufReader::new(file);
  let mut archive = ZipArchive::new(reader)?;
  let pb = ProgressBar::new(archive.len() as u64);
  pb.set_style(
    ProgressStyle::default_bar()
      .template("extracting [{bar:40}] [{percent:.2}%]")
      .expect("invalid template")
      .progress_chars("=> "),
  );
  for i in 0..archive.len() {
    let mut entry = archive.by_index(i)?;
    safe_extract(&mut entry, &dest)?;
    pb.inc(1);
  }
  pb.finish();
  log::debug!("extract done");
  Ok(())
}

fn update_environment(symlink: impl AsRef<Path>) -> Result {
  let symlink = symlink.as_ref().to_string_lossy().to_string();
  let root = RegKey::predef(HKEY_CURRENT_USER);
  let (env, _) = root.create_subkey("Environment")?;
  env.set_value("NVM_SYMLINK", &symlink)?;
  let mut path: String = env.get_value("Path")?;

  log::debug!("Environment Path: {}", path);

  if NVM_SYMLINK_REGEX.is_match(&path) {
    log::debug!("NVM_SYMLINK is already in Path");
  } else {
    log::debug!("NVM_SYMLINK is not in Path");

    if !path.ends_with(r";") {
      path.push_str(r";%NVM_SYMLINK%;");
    } else {
      path.push_str(r"%NVM_SYMLINK%;");
    }

    let bytes = path
      .encode_utf16()
      .chain(std::iter::once(0))
      .flat_map(|c| c.to_ne_bytes())
      .collect();
    let value = RegValue {
      vtype: RegType::REG_EXPAND_SZ,
      bytes,
    };
    env.set_raw_value("Path", &value)?;
  }

  Ok(())
}

#[cfg(test)]
mod tests {
  use super::*;
  #[allow(unused_imports)]
  use pretty_assertions::{assert_eq, assert_ne};
  use rstest::{fixture, rstest};

  #[fixture]
  fn config() -> Config {
    Config {
      root: Some(PathBuf::from("nvmroot")),
      node_mirror: Some(
        Url::parse("https://npmmirror.com/mirrors/node/").unwrap(),
      ),
      ..Default::default()
    }
  }

  // ---------- get_nvm_symlink ----------

  #[rstest]
  fn get_nvm_symlink_test() {
    let saved = env::var("NVM_SYMLINK").ok();
    unsafe { env::set_var("NVM_SYMLINK", r"C:\Program Files\nodejs") };

    let nvm_symlink = get_nvm_symlink().unwrap();
    assert_eq!(nvm_symlink, PathBuf::from(r"C:\Program Files\nodejs"));

    // Restore
    match saved {
      Some(val) => unsafe { env::set_var("NVM_SYMLINK", val) },
      None => unsafe { env::remove_var("NVM_SYMLINK") },
    }
  }

  // SAFETY: This test is not run in parallel with other tests that
  // depend on NVM_SYMLINK (single-threaded test harness by default).
  #[rstest]
  fn get_nvm_symlink_fails_without_env_var() {
    // Save and remove the env var for the duration of this test.
    let saved = env::var("NVM_SYMLINK").ok();
    // SAFETY: no other thread should be reading/writing this env var.
    unsafe { env::remove_var("NVM_SYMLINK") };

    let result = get_nvm_symlink();
    assert!(result.is_err());
    assert!(
      result
        .unwrap_err()
        .to_string()
        .contains("get nvm symlink failed")
    );

    // Restore the env var if it was set before.
    if let Some(val) = saved {
      unsafe { env::set_var("NVM_SYMLINK", val) };
    }
  }

  // ---------- get_root ----------

  #[rstest]
  fn get_root_test(config: Config) {
    let root = get_root(&config).unwrap();
    assert_eq!(root, PathBuf::from("nvmroot"));
  }

  #[rstest]
  fn get_root_with_none_falls_back_to_current_dir(config: Config) {
    let mut cfg = config;
    cfg.root = None;
    let root = get_root(&cfg).unwrap();
    assert_eq!(root, env::current_dir().unwrap());
  }

  // ---------- get_current_version / display_current ----------

  #[rstest]
  fn get_current_version_test() {
    let saved = env::var("NVM_SYMLINK").ok();
    let tmp = tempfile::tempdir().unwrap();
    // Point to a directory that exists but has no node.exe
    unsafe { env::set_var("NVM_SYMLINK", tmp.path()) };

    // Should return None because there's no node.exe in the temp dir
    let result = get_current_version();
    assert!(result.is_none());

    // Restore
    match saved {
      Some(val) => unsafe { env::set_var("NVM_SYMLINK", val) },
      None => unsafe { env::remove_var("NVM_SYMLINK") },
    }
  }

  #[rstest]
  fn display_current_test() {
    let saved = env::var("NVM_SYMLINK").ok();
    let tmp = tempfile::tempdir().unwrap();
    unsafe { env::set_var("NVM_SYMLINK", tmp.path()) };

    assert!(display_current().is_ok());

    match saved {
      Some(val) => unsafe { env::set_var("NVM_SYMLINK", val) },
      None => unsafe { env::remove_var("NVM_SYMLINK") },
    }
  }

  // ---------- deactivate / activate ----------

  #[rstest]
  fn deactivate_and_activate_version_test() {
    let saved = env::var("NVM_SYMLINK").ok();
    let tmp = tempfile::tempdir().unwrap();
    let symlink_path = tmp.path().join("nodejs");
    let root = tmp.path().join("root");
    fs::create_dir_all(&root).unwrap();
    // Create a fake version directory
    let ver_dir = root.join("v18.0.0");
    fs::create_dir_all(&ver_dir).unwrap();

    unsafe { env::set_var("NVM_SYMLINK", &symlink_path) };

    // deactivate when no symlink exists -> should succeed
    assert!(deactivate_symlink().is_ok());

    // activate with a version installed
    let config = Config {
      root: Some(root.clone()),
      ..Default::default()
    };
    assert!(activate_symlink(config).is_ok());

    // The symlink (junction) should now exist
    assert!(symlink_path.exists());

    // deactivate again -> should succeed
    assert!(deactivate_symlink().is_ok());

    // Restore
    match saved {
      Some(val) => unsafe { env::set_var("NVM_SYMLINK", val) },
      None => unsafe { env::remove_var("NVM_SYMLINK") },
    }
  }

  // ---------- install / uninstall ----------

  #[rstest]
  fn install_version_network_error() {
    let tmp = tempfile::tempdir().unwrap();
    let config = Config {
      root: Some(tmp.path().to_path_buf()),
      node_mirror: Some(Url::parse("http://localhost:1/").unwrap()), // unreachable
      ..Default::default()
    };
    let ver = VersionSpec::Exact("v23.0.0".to_string());
    let result = install_version(config, ver, false);
    assert!(result.is_err(), "expected network error");
  }

  // ---------- list_local_versions / list_remote_versions ----------

  #[rstest]
  fn list_local_versions_empty() {
    let saved = env::var("NVM_SYMLINK").ok();
    let tmp = tempfile::tempdir().unwrap();
    unsafe { env::set_var("NVM_SYMLINK", tmp.path()) };

    let config = Config {
      root: Some(tmp.path().to_path_buf()),
      ..Default::default()
    };
    assert!(list_local_versions(config).is_ok());

    match saved {
      Some(val) => unsafe { env::set_var("NVM_SYMLINK", val) },
      None => unsafe { env::remove_var("NVM_SYMLINK") },
    }
  }

  #[rstest]
  fn list_local_versions_with_versions() {
    let saved = env::var("NVM_SYMLINK").ok();
    let tmp = tempfile::tempdir().unwrap();
    unsafe { env::set_var("NVM_SYMLINK", tmp.path()) };

    // Create fake version dirs
    fs::create_dir(tmp.path().join("v18.0.0")).unwrap();
    fs::create_dir(tmp.path().join("v20.0.0")).unwrap();

    let config = Config {
      root: Some(tmp.path().to_path_buf()),
      ..Default::default()
    };
    assert!(list_local_versions(config).is_ok());

    match saved {
      Some(val) => unsafe { env::set_var("NVM_SYMLINK", val) },
      None => unsafe { env::remove_var("NVM_SYMLINK") },
    }
  }

  #[rstest]
  fn list_remote_versions_network_error() {
    let config = Config {
      root: None,
      node_mirror: Some(Url::parse("http://localhost:1/").unwrap()),
      ..Default::default()
    };
    let result = list_remote_versions(config);
    assert!(result.is_err(), "expected network error");
  }

  // ---------- mirror display ----------

  #[rstest]
  fn display_npm_mirror_test(config: Config) {
    assert!(display_or_update_npm_mirror(config.clone(), None).is_ok());
  }

  #[rstest]
  fn display_node_mirror_test(config: Config) {
    assert!(display_or_update_node_mirror(config.clone(), None).is_ok());
  }

  #[rstest]
  fn display_or_update_npm_mirror_with_url(config: Config) {
    let url =
      Url::parse("https://registry.npmmirror.com/-/binary/npm/").unwrap();
    assert!(display_or_update_npm_mirror(config, Some(url)).is_ok());
  }

  #[rstest]
  fn display_or_update_node_mirror_with_url(config: Config) {
    let url = Url::parse("https://cdn.npmmirror.com/binaries/node/").unwrap();
    assert!(display_or_update_node_mirror(config, Some(url)).is_ok());
  }

  // ---------- display_root ----------

  #[rstest]
  fn display_root_test(config: Config) {
    // display current root
    assert!(display_or_update_root::<&str>(config.clone(), None).is_ok());
    // error: non-existent path
    let r = display_or_update_root(
      config.clone(),
      Some(PathBuf::from("nonexistent_dir_xyz")),
    );
    assert!(r.is_err());
  }

  // ---------- switch_version ----------

  #[rstest]
  fn switch_version_not_installed_errors() {
    let tmp = tempfile::tempdir().unwrap();
    let config = Config {
      root: Some(tmp.path().to_path_buf()),
      node_mirror: Some(Url::parse("http://localhost:1/").unwrap()),
      ..Default::default()
    };
    let ver = VersionSpec::Exact("v24.2.0".to_string());
    let result = switch_version(config, ver);
    assert!(result.is_err());
  }

  // ---------- uninstall_version boundary tests ----------

  #[rstest]
  fn uninstall_version_latest_errors() {
    let tmp = tempfile::tempdir().unwrap();
    let config = Config {
      root: Some(tmp.path().to_path_buf()),
      ..Default::default()
    };
    let result = uninstall_version(config, VersionSpec::Latest);
    assert!(result.is_err());
    let err_msg = result.unwrap_err().to_string();
    assert!(
      err_msg.contains("latest") || err_msg.contains("lts"),
      "unexpected error message: {err_msg}"
    );
  }

  #[rstest]
  fn uninstall_version_lts_errors() {
    let tmp = tempfile::tempdir().unwrap();
    let config = Config {
      root: Some(tmp.path().to_path_buf()),
      ..Default::default()
    };
    let result = uninstall_version(config, VersionSpec::Lts);
    assert!(result.is_err());
    let err_msg = result.unwrap_err().to_string();
    assert!(
      err_msg.contains("latest") || err_msg.contains("lts"),
      "unexpected error message: {err_msg}"
    );
  }

  #[rstest]
  fn uninstall_version_not_installed_errors() {
    let tmp = tempfile::tempdir().unwrap();
    let config = Config {
      root: Some(tmp.path().to_path_buf()),
      ..Default::default()
    };
    let result =
      uninstall_version(config, VersionSpec::Exact("v99.99.99".to_string()));
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("not installed"));
  }

  // ---------- delete_junction_link ----------

  #[rstest]
  fn delete_junction_link_nonexistent_is_ok() {
    let tmp = tempfile::tempdir().unwrap();
    let nonexistent = tmp.path().join("does_not_exist");
    // Deleting a non-existent link should still succeed (the function
    // intentionally ignores errors from `remove_dir`).
    assert!(delete_junction_link(&nonexistent).is_ok());
  }

  // ---------- safe_extract ----------

  /// Helper: create a zip archive on disk with the given entry names and
  /// optional content.  Returns the path to the zip file inside a `TempDir`
  /// (the `TempDir` must be kept alive for the duration of the test).
  fn create_test_zip(
    entries: &[(&str, &[u8], bool)],
  ) -> (tempfile::TempDir, PathBuf) {
    let tmp = tempfile::tempdir().unwrap();
    let zip_path = tmp.path().join("test.zip");
    let file = File::create(&zip_path).unwrap();
    let mut zip = zip::ZipWriter::new(file);

    for &(name, data, is_dir) in entries {
      let options = zip::write::SimpleFileOptions::default();
      if is_dir {
        zip.add_directory(name, options).unwrap();
      } else {
        zip.start_file(name, options).unwrap();
        std::io::Write::write_all(&mut zip, data).unwrap();
      }
    }
    zip.finish().unwrap();
    (tmp, zip_path)
  }

  #[rstest]
  fn safe_extract_normal_file() {
    let (tmp, zip_path) =
      create_test_zip(&[("hello.txt", b"hello world", false)]);
    let dest = tmp.path().join("out");
    fs::create_dir(&dest).unwrap();

    let file = File::open(&zip_path).unwrap();
    let mut archive = ZipArchive::new(BufReader::new(file)).unwrap();
    let mut entry = archive.by_index(0).unwrap();
    safe_extract(&mut entry, &dest).unwrap();

    let extracted = dest.join("hello.txt");
    assert!(extracted.exists());
    assert_eq!(fs::read_to_string(&extracted).unwrap(), "hello world");
  }

  #[rstest]
  fn safe_extract_directory() {
    let (tmp, zip_path) = create_test_zip(&[
      ("subdir/", b"", true),
      ("subdir/file.txt", b"data", false),
    ]);
    let dest = tmp.path().join("out");
    fs::create_dir(&dest).unwrap();

    let file = File::open(&zip_path).unwrap();
    let mut archive = ZipArchive::new(BufReader::new(file)).unwrap();

    // Extract directory entry
    {
      let mut entry = archive.by_index(0).unwrap();
      safe_extract(&mut entry, &dest).unwrap();
    }
    assert!(dest.join("subdir").is_dir());

    // Extract file inside directory
    {
      let mut entry = archive.by_index(1).unwrap();
      safe_extract(&mut entry, &dest).unwrap();
    }
    assert_eq!(
      fs::read_to_string(dest.join("subdir/file.txt")).unwrap(),
      "data"
    );
  }

  #[rstest]
  fn safe_extract_zip_slip_detected() {
    let (tmp, zip_path) =
      create_test_zip(&[("../../evil.txt", b"malicious", false)]);
    let dest = tmp.path().join("out");
    fs::create_dir(&dest).unwrap();

    let file = File::open(&zip_path).unwrap();
    let mut archive = ZipArchive::new(BufReader::new(file)).unwrap();
    let mut entry = archive.by_index(0).unwrap();

    // The zip crate's `mangled_name()` strips leading `../`, so the
    // extraction should succeed but the file must land *inside* `dest`,
    // NOT outside it.
    safe_extract(&mut entry, &dest).unwrap();

    // The evil file must NOT exist outside the destination directory.
    let escaped = tmp.path().join("evil.txt");
    assert!(!escaped.exists(), "Zip Slip: file escaped destination");

    // It should have been sanitized into the destination directory.
    let sanitized = dest.join("evil.txt");
    assert!(
      sanitized.exists(),
      "sanitized file should exist inside dest"
    );
  }

  #[rstest]
  fn safe_extract_nested_dirs() {
    let (tmp, zip_path) = create_test_zip(&[
      ("a/", b"", true),
      ("a/b/", b"", true),
      ("a/b/c/", b"", true),
      ("a/b/c/deep.txt", b"deep content", false),
    ]);
    let dest = tmp.path().join("out");
    fs::create_dir(&dest).unwrap();

    let file = File::open(&zip_path).unwrap();
    let mut archive = ZipArchive::new(BufReader::new(file)).unwrap();

    for i in 0..archive.len() {
      let mut entry = archive.by_index(i).unwrap();
      safe_extract(&mut entry, &dest).unwrap();
    }

    let deep_file = dest.join("a/b/c/deep.txt");
    assert!(deep_file.exists());
    assert_eq!(fs::read_to_string(&deep_file).unwrap(), "deep content");
  }

  // ---------- symlink_validator ----------

  #[rstest]
  #[case("C:\\Program Files\\nodejs", true)]
  #[case("D:\\nodejs", true)]
  #[case("nodejs", true)]
  #[case("C:\\path\\to\\node.exe", false)]
  #[case("test.txt", false)]
  fn symlink_validator_test(#[case] input: &str, #[case] expect_valid: bool) {
    let result = symlink_validator(input).unwrap();
    if expect_valid {
      assert!(matches!(result, Validation::Valid));
    } else {
      assert!(matches!(result, Validation::Invalid(_)));
    }
  }

  // ---------- node_store_root_validator ----------

  #[rstest]
  #[case("D:\\nvm_root", true)]
  #[case("C:\\Users\\test\\AppData\\Local\\nvm", true)]
  #[case("nvm", true)]
  #[case("test.exe", false)]
  #[case("config.toml", false)]
  fn node_store_root_validator_test(
    #[case] input: &str,
    #[case] expect_valid: bool,
  ) {
    let result = node_store_root_validator(input).unwrap();
    if expect_valid {
      assert!(matches!(result, Validation::Valid));
    } else {
      assert!(matches!(result, Validation::Invalid(_)));
    }
  }

  // ---------- url_validator ----------

  #[rstest]
  #[case("https://nodejs.org/dist/", true)]
  #[case("http://example.com", true)]
  #[case("HTTPS://NPMMIRROR.COM/mirrors/node/", true)]
  #[case("ftp://files.example.com", false)]
  #[case("file:///local/path", false)]
  #[case("not-a-url", false)]
  #[case("https://", false)]
  fn url_validator_test(#[case] input: &str, #[case] expect_valid: bool) {
    let result = url_validator(input).unwrap();
    if expect_valid {
      assert!(matches!(result, Validation::Valid));
    } else {
      assert!(matches!(result, Validation::Invalid(_)));
    }
  }

  // ---------- file_validate ----------

  #[rstest]
  fn file_validate_correct_checksum() {
    use sha2::Digest;
    let content = b"hello world";
    let expected_hash = hex::encode(sha2::Sha256::digest(content));

    let mut tmp = tempfile::tempfile().unwrap();
    std::io::Write::write_all(&mut tmp, content).unwrap();

    assert!(file_validate(&tmp, &expected_hash).unwrap());
  }

  #[rstest]
  fn file_validate_incorrect_checksum() {
    let content = b"hello world";
    let mut tmp = tempfile::tempfile().unwrap();
    std::io::Write::write_all(&mut tmp, content).unwrap();

    assert!(!file_validate(&tmp, "deadbeef").unwrap());
  }

  #[rstest]
  fn file_validate_empty_file() {
    use sha2::Digest;
    let expected_hash = hex::encode(sha2::Sha256::digest(b""));

    let tmp = tempfile::tempfile().unwrap();
    assert!(file_validate(&tmp, &expected_hash).unwrap());
  }

  // ---------- get_local_versions ----------

  #[rstest]
  fn get_local_versions_empty_dir() {
    let tmp = tempfile::tempdir().unwrap();
    let versions = get_local_versions(tmp.path()).unwrap();
    assert_eq!(versions.len(), 0);
  }

  #[rstest]
  fn get_local_versions_filters_non_version_dirs() {
    let tmp = tempfile::tempdir().unwrap();
    fs::create_dir(tmp.path().join("v18.0.0")).unwrap();
    fs::create_dir(tmp.path().join("v20.1.0")).unwrap();
    fs::create_dir(tmp.path().join("not-a-version")).unwrap();
    fs::create_dir(tmp.path().join("v1.2")).unwrap();
    fs::create_dir(tmp.path().join("v1.2.3.4")).unwrap();

    let versions = get_local_versions(tmp.path()).unwrap();
    assert_eq!(versions, vec!["v18.0.0", "v20.1.0"]);
  }

  #[rstest]
  fn get_local_versions_skips_files() {
    let tmp = tempfile::tempdir().unwrap();
    fs::create_dir(tmp.path().join("v18.0.0")).unwrap();
    fs::write(tmp.path().join("v20.0.0"), "file not dir").unwrap();

    let versions = get_local_versions(tmp.path()).unwrap();
    assert_eq!(versions, vec!["v18.0.0"]);
  }

  #[rstest]
  fn get_local_versions_sorted() {
    let tmp = tempfile::tempdir().unwrap();
    fs::create_dir(tmp.path().join("v22.0.0")).unwrap();
    fs::create_dir(tmp.path().join("v18.0.0")).unwrap();
    fs::create_dir(tmp.path().join("v20.0.0")).unwrap();

    let versions = get_local_versions(tmp.path()).unwrap();
    assert_eq!(versions, vec!["v18.0.0", "v20.0.0", "v22.0.0"]);
  }

  // ---------- version_exists ----------

  #[rstest]
  fn version_exists_latest(sample_db: ReleaseDatabase) {
    let tmp = tempfile::tempdir().unwrap();
    let version = VersionSpec::Latest;
    let (exists, ver) =
      version_exists(&sample_db, &version, tmp.path()).unwrap();
    assert_eq!(ver, "v22.0.0");
    assert!(!exists);
  }

  #[rstest]
  fn version_exists_lts(sample_db: ReleaseDatabase) {
    let tmp = tempfile::tempdir().unwrap();
    let version = VersionSpec::Lts;
    let (exists, ver) =
      version_exists(&sample_db, &version, tmp.path()).unwrap();
    assert_eq!(ver, "v20.0.0");
    assert!(!exists);
  }

  #[rstest]
  fn version_exists_exact_found(sample_db: ReleaseDatabase) {
    let tmp = tempfile::tempdir().unwrap();
    let version = VersionSpec::Exact("v18.0.0".to_string());
    let (exists, ver) =
      version_exists(&sample_db, &version, tmp.path()).unwrap();
    assert_eq!(ver, "v18.0.0");
    assert!(!exists);
  }

  #[rstest]
  fn version_exists_exact_with_local_dir(sample_db: ReleaseDatabase) {
    let tmp = tempfile::tempdir().unwrap();
    fs::create_dir(tmp.path().join("v18.0.0")).unwrap();
    let version = VersionSpec::Exact("v18.0.0".to_string());
    let (exists, ver) =
      version_exists(&sample_db, &version, tmp.path()).unwrap();
    assert_eq!(ver, "v18.0.0");
    assert!(exists);
  }

  #[rstest]
  fn version_exists_exact_not_in_db(sample_db: ReleaseDatabase) {
    let tmp = tempfile::tempdir().unwrap();
    let version = VersionSpec::Exact("v99.0.0".to_string());
    let result = version_exists(&sample_db, &version, tmp.path());
    assert!(result.is_err(), "expected error for non-existent version");
  }

  #[rstest]
  fn version_exists_latest_empty_db() {
    let db: ReleaseDatabase = serde_json::from_str("[]").unwrap();
    let tmp = tempfile::tempdir().unwrap();
    let version = VersionSpec::Latest;
    let result = version_exists(&db, &version, tmp.path());
    assert!(result.is_err(), "expected error for empty database");
  }

  #[rstest]
  fn version_exists_lts_empty_db() {
    let db: ReleaseDatabase = serde_json::from_str("[]").unwrap();
    let tmp = tempfile::tempdir().unwrap();
    let version = VersionSpec::Lts;
    let result = version_exists(&db, &version, tmp.path());
    assert!(result.is_err(), "expected error for empty database");
  }

  // ---------- delete_version ----------

  #[rstest]
  fn delete_version_removes_directory() {
    let tmp = tempfile::tempdir().unwrap();
    let ver_dir = tmp.path().join("v18.0.0");
    fs::create_dir(&ver_dir).unwrap();
    fs::write(ver_dir.join("node.exe"), "fake").unwrap();

    assert!(ver_dir.exists());
    delete_version(tmp.path(), "v18.0.0").unwrap();
    assert!(!ver_dir.exists());
  }

  #[rstest]
  fn delete_version_nonexistent_errors() {
    let tmp = tempfile::tempdir().unwrap();
    let result = delete_version(tmp.path(), "v99.0.0");
    assert!(result.is_err(), "expected error for non-existent version");
  }

  // ---------- display_or_update_root ----------

  #[rstest]
  fn display_or_update_root_with_file_path(config: Config) {
    let tmp = tempfile::tempdir().unwrap();
    let file_path = tmp.path().join("not_a_dir.txt");
    fs::write(&file_path, "test").unwrap();

    let result = display_or_update_root(config, Some(&file_path));
    assert!(result.is_err(), "expected error for file path");
    assert!(result.unwrap_err().to_string().contains("not a directory"));
  }

  #[rstest]
  fn display_or_update_root_with_valid_dir(config: Config) {
    let tmp = tempfile::tempdir().unwrap();
    let result = display_or_update_root(config, Some(tmp.path()));
    assert!(result.is_ok(), "expected success for valid directory");
  }

  #[rstest]
  fn display_or_update_root_none_with_root_set(config: Config) {
    let result = display_or_update_root::<&str>(config, None);
    assert!(
      result.is_ok(),
      "expected success when displaying current root"
    );
  }

  #[rstest]
  fn display_or_update_root_none_with_no_root() {
    let config = Config {
      root: None,
      ..Default::default()
    };
    let result = display_or_update_root::<&str>(config, None);
    assert!(result.is_ok(), "expected success when root is None");
  }

  // ---------- VERSION_REGEX ----------

  #[rstest]
  #[case("v1.0.0", true)]
  #[case("v18.16.0", true)]
  #[case("v24.2.2", true)]
  #[case("1.0.0", false)]
  #[case("v1.0", false)]
  #[case("v1.0.0.0", false)]
  #[case("vX.Y.Z", false)]
  #[case("", false)]
  fn version_regex_test(#[case] input: &str, #[case] expect_match: bool) {
    assert_eq!(VERSION_REGEX.is_match(input), expect_match);
  }

  // ---------- NVM_SYMLINK_REGEX ----------

  #[rstest]
  #[case("C:\\path;%NVM_SYMLINK%;", true)]
  #[case("C:\\path;%nvm_symlink%;", true)]
  #[case("C:\\path\\nodejs", false)]
  #[case("%NVM_SYMLINK%", true)]
  fn nvm_symlink_regex_test(#[case] input: &str, #[case] expect_match: bool) {
    assert_eq!(NVM_SYMLINK_REGEX.is_match(input), expect_match);
  }

  // ---------- fixture: sample_db ----------

  #[fixture]
  fn sample_db() -> ReleaseDatabase {
    let json = r#"[
      {"version": "v22.0.0", "date": "2024-04-01", "lts": false},
      {"version": "v20.0.0", "date": "2023-04-01", "lts": "Iron"},
      {"version": "v18.0.0", "date": "2022-04-01", "lts": "Hydrogen"},
      {"version": "v21.0.0", "date": "2023-10-01", "lts": false}
    ]"#;
    serde_json::from_str(json).unwrap()
  }
}