vera2-core 0.12.16-aristoddle.1

Core engine for Vera: parsing, indexing, retrieval, storage, and embedding
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
//! ONNX Runtime library acquisition, provider dependency inspection,
//! and archive extraction.

use crate::config::OnnxExecutionProvider;
use anyhow::{Context, Result};
use reqwest::Client;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use tokio::fs;

use super::cuda::*;
use super::*;

/// Ensure the ONNX Runtime shared library is loaded and initialized.
///
/// Accepts an optional pre-resolved library path (from `ensure_ort_library`).
/// Falls back to system library search if no path is provided.
///
/// Safe to call multiple times with the same path. A different path after
/// initialization is rejected because `ort` can load only one global runtime.
pub fn ensure_ort_runtime(lib_path: Option<&std::path::Path>) -> Result<()> {
    let requested = lib_path
        .map(|path| path.display().to_string())
        .unwrap_or_else(ort_lib_filename);
    if let Some(initialized) = ORT_INIT_LIBRARY_PATH.get() {
        validate_ort_library_path(Some(initialized), &requested)?;
    }

    let result = ORT_INIT_RESULT.get_or_init(|| match ::ort::init_from(&requested) {
        Ok(builder) => {
            builder.commit();
            let _ = ORT_INIT_LIBRARY_PATH.set(requested.clone());
            Ok(())
        }
        Err(e) => Err(format!(
            "ONNX Runtime shared library not found.\n\
                 Run `vera setup` to auto-download it, or use API mode instead.\n\
                 Original error: {e}"
        )),
    });

    if let Some(initialized) = ORT_INIT_LIBRARY_PATH.get() {
        validate_ort_library_path(Some(initialized), &requested)?;
    }

    match result {
        Ok(()) => Ok(()),
        Err(msg) => anyhow::bail!("{msg}"),
    }
}

fn validate_ort_library_path(initialized: Option<&str>, requested: &str) -> Result<()> {
    if let Some(initialized) = initialized.filter(|path| *path != requested) {
        anyhow::bail!(
            "ONNX Runtime is already initialized with `{initialized}`, but `{requested}` was requested; one process cannot load both libraries"
        );
    }
    Ok(())
}

static ORT_INIT_LIBRARY_PATH: OnceLock<String> = OnceLock::new();

/// Return whether ONNX Runtime has already been initialized successfully.
pub(crate) fn ort_runtime_initialized() -> bool {
    ORT_INIT_RESULT
        .get()
        .is_some_and(std::result::Result::is_ok)
}

#[cfg(test)]
mod tests {
    use super::validate_ort_library_path;

    #[test]
    fn rejects_cpu_after_gpu_runtime_initialization() {
        let error = validate_ort_library_path(
            Some("/vera/lib/libonnxruntime-cuda.so"),
            "/vera/lib/libonnxruntime-cpu.so",
        )
        .expect_err("different runtime paths must be rejected");
        let message = error.to_string();
        assert!(message.contains("libonnxruntime-cuda.so"));
        assert!(message.contains("libonnxruntime-cpu.so"));
    }

    #[test]
    fn rejects_gpu_after_cpu_runtime_initialization() {
        let error = validate_ort_library_path(
            Some("/vera/lib/libonnxruntime-cpu.so"),
            "/vera/lib/libonnxruntime-cuda.so",
        )
        .expect_err("different runtime paths must be rejected");
        let message = error.to_string();
        assert!(message.contains("libonnxruntime-cpu.so"));
        assert!(message.contains("libonnxruntime-cuda.so"));
    }

    #[test]
    fn accepts_repeated_initialization_with_same_path() {
        validate_ort_library_path(
            Some("/vera/lib/libonnxruntime.so"),
            "/vera/lib/libonnxruntime.so",
        )
        .expect("same runtime path should be accepted");
    }
}

/// Returns the pip package name for EPs that require pip-based installation, or None
/// for EPs that have pre-built GitHub release archives.
pub(super) fn pip_package_for_ep(ep: OnnxExecutionProvider) -> Option<&'static str> {
    match ep {
        OnnxExecutionProvider::OpenVino => Some("onnxruntime-openvino"),
        OnnxExecutionProvider::Rocm => Some("onnxruntime-rocm"),
        _ => None,
    }
}

/// Try installing ORT via pip into a managed venv under `~/.vera/venv/`.
/// Returns the lib directory where .so files were copied on success.
#[cfg(target_os = "linux")]
pub(super) async fn try_pip_install_ort(
    ep: OnnxExecutionProvider,
    lib_dir: &std::path::Path,
) -> Result<()> {
    let pkg = pip_package_for_ep(ep).context("not a pip-based EP")?;
    let vera_home = vera_home_dir()?;
    let venv_dir = vera_home.join("venv");

    // Find python3
    let python = find_python3()
        .context("python3 not found. Install Python 3.11+ to enable automatic ORT installation.")?;

    eprintln!("Installing {pkg} via pip (this may take a minute)...");

    // Create venv if it doesn't exist
    if !venv_dir.join("bin").join("python3").exists() {
        eprintln!(
            "  Creating virtual environment at {}...",
            venv_dir.display()
        );
        let status = tokio::process::Command::new(&python)
            .args(["-m", "venv", &venv_dir.to_string_lossy()])
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::piped())
            .status()
            .await
            .context("failed to create venv")?;
        if !status.success() {
            anyhow::bail!(
                "failed to create virtual environment at {}",
                venv_dir.display()
            );
        }
    }

    let venv_pip = venv_dir.join("bin").join("pip");
    let venv_python = venv_dir.join("bin").join("python3");

    // Upgrade pip quietly, then install the package
    let _ = tokio::process::Command::new(&venv_python)
        .args(["-m", "pip", "install", "--upgrade", "pip"])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .await;

    eprintln!("  Running: pip install {pkg}");
    let output = tokio::process::Command::new(&venv_pip)
        .args(["install", pkg])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .await
        .context("failed to run pip install")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("pip install {pkg} failed:\n{stderr}");
    }

    // Find and copy .so files from the installed package
    let site_packages = find_site_packages(&venv_dir)?;
    let capi_dir = site_packages.join("onnxruntime").join("capi");
    if !capi_dir.exists() {
        anyhow::bail!(
            "pip install succeeded but onnxruntime/capi/ not found in {}",
            site_packages.display()
        );
    }

    copy_so_files_from_dir(&capi_dir, lib_dir).await?;
    Ok(())
}

/// Try downloading a wheel directly from PyPI and extracting .so files.
#[cfg(target_os = "linux")]
pub(super) async fn try_wheel_download_ort(
    ep: OnnxExecutionProvider,
    lib_dir: &std::path::Path,
) -> Result<()> {
    let pkg = pip_package_for_ep(ep).context("not a pip-based EP")?;
    if !cfg!(target_arch = "x86_64") {
        anyhow::bail!(
            "direct PyPI wheel fallback for {pkg} is only supported on Linux x86_64; install it manually"
        );
    }
    let pypi_name = pkg.replace('-', "_");

    eprintln!("Trying direct wheel download from PyPI...");

    crate::init_tls();
    let client = Client::new();

    // Query PyPI JSON API for the latest version's wheel URLs
    let api_url = format!("https://pypi.org/pypi/{pkg}/json");
    let resp = client
        .get(&api_url)
        .header("User-Agent", "vera")
        .send()
        .await?
        .error_for_status()
        .context("failed to query PyPI")?;
    let body: serde_json::Value = resp.json().await?;

    // Find a manylinux x86_64 wheel
    let urls = body["urls"]
        .as_array()
        .context("unexpected PyPI response format")?;
    let wheel_url = urls
        .iter()
        .filter_map(|entry| {
            let filename = entry["filename"].as_str()?;
            if filename.contains("linux") && filename.contains("x86_64") {
                entry["url"].as_str().map(|u| u.to_string())
            } else {
                None
            }
        })
        .next()
        .context("no compatible Linux x86_64 wheel found on PyPI")?;

    let version = body["info"]["version"].as_str().unwrap_or("unknown");
    eprintln!("  Downloading {pypi_name} v{version} wheel...");
    eprintln!("  {wheel_url}");

    let res = client
        .get(&wheel_url)
        .header("User-Agent", "vera")
        .send()
        .await?
        .error_for_status()?;
    let bytes = res.bytes().await?;

    // Wheels are zip files; extract .so files from onnxruntime/capi/
    let lib_dir_owned = lib_dir.to_path_buf();
    tokio::task::spawn_blocking(move || extract_wheel_libs(&bytes, &lib_dir_owned)).await??;

    Ok(())
}

/// Extract all shared libraries from `onnxruntime/capi/` inside a wheel (zip).
#[cfg(target_os = "linux")]
pub(super) fn extract_wheel_libs(data: &[u8], dest_dir: &std::path::Path) -> Result<()> {
    let cursor = std::io::Cursor::new(data);
    let mut archive = zip::ZipArchive::new(cursor)?;
    let mut extracted = 0usize;

    for i in 0..archive.len() {
        let mut entry = archive.by_index(i)?;
        let path = entry.name().to_string();
        if !path.starts_with("onnxruntime/capi/") {
            continue;
        }
        let filename = path.rsplit('/').next().unwrap_or("");
        if !filename.contains(".so") {
            continue;
        }
        let local_name = strip_so_version(filename);
        let dest = dest_dir.join(&local_name);
        let mut out = std::fs::File::create(&dest)?;
        std::io::copy(&mut entry, &mut out)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o755))?;
        }
        create_versioned_symlink(dest_dir, filename, &local_name);
        extracted += 1;
    }

    if extracted == 0 {
        anyhow::bail!("no shared libraries found in wheel");
    }
    eprintln!("  Extracted {extracted} libraries from wheel");
    Ok(())
}

/// Find a working python3 binary.
#[cfg(target_os = "linux")]
pub(super) fn find_python3() -> Option<String> {
    for name in ["python3", "python"] {
        if std::process::Command::new(name)
            .arg("--version")
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .is_ok_and(|s| s.success())
        {
            return Some(name.to_string());
        }
    }
    None
}

/// Find the site-packages directory inside a venv.
#[cfg(target_os = "linux")]
pub(super) fn find_site_packages(venv_dir: &std::path::Path) -> Result<PathBuf> {
    let lib_dir = venv_dir.join("lib");
    if !lib_dir.exists() {
        anyhow::bail!("venv lib directory not found");
    }
    for entry in std::fs::read_dir(&lib_dir)? {
        let entry = entry?;
        let sp = entry.path().join("site-packages");
        if sp.exists() {
            return Ok(sp);
        }
    }
    anyhow::bail!("site-packages not found in venv")
}

/// Copy all .so files from a directory to the target lib directory.
#[cfg(target_os = "linux")]
pub(super) async fn copy_so_files_from_dir(
    src_dir: &std::path::Path,
    dest_dir: &std::path::Path,
) -> Result<()> {
    let mut extracted = 0usize;
    let mut entries = fs::read_dir(src_dir).await?;
    while let Some(entry) = entries.next_entry().await? {
        let path = entry.path();
        let filename = path.file_name().and_then(|f| f.to_str()).unwrap_or("");
        if !filename.contains(".so") {
            continue;
        }
        let local_name = strip_so_version(filename);
        let dest = dest_dir.join(&local_name);
        fs::copy(&path, &dest).await?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o755)).await?;
        }
        create_versioned_symlink(dest_dir, filename, &local_name);
        extracted += 1;
    }
    if extracted == 0 {
        anyhow::bail!("no .so files found in {}", src_dir.display());
    }
    eprintln!("  Copied {extracted} libraries from pip package");
    Ok(())
}

/// Ensure the ONNX Runtime shared library is available locally.
///
/// Returns the path to the library. Downloads it automatically if needed.
/// Respects `ORT_DYLIB_PATH` — if set, skips auto-download.
/// GPU execution providers download a different (larger) ORT build.
///
/// For OpenVINO and ROCm (no pre-built GitHub archives), tries in order:
/// 1. `pip install` into a managed venv at `~/.vera/venv/`
/// 2. Direct wheel download from PyPI
/// 3. Bail with manual instructions
pub async fn ensure_ort_library_for_ep(ep: OnnxExecutionProvider) -> Result<PathBuf> {
    if ort_dylib_path_from_env().is_some() {
        return ensure_ort_library_for_ep_with_cuda_major(ep, None).await;
    }

    let detected_cuda_major = match ep {
        OnnxExecutionProvider::Cuda => detected_cuda_major_for_ep(ep),
        _ => None,
    };

    ensure_ort_library_for_ep_with_cuda_major(ep, detected_cuda_major).await
}

pub(super) async fn ensure_ort_library_for_ep_with_cuda_major(
    ep: OnnxExecutionProvider,
    detected_cuda_major: Option<u32>,
) -> Result<PathBuf> {
    let target_path = ort_library_path_for_ep_with_cuda_major(ep, detected_cuda_major)?;
    if ort_dylib_path_from_env().is_some() {
        return Ok(target_path);
    }

    let lib_dir = target_path
        .parent()
        .context("failed to determine ONNX Runtime directory")?
        .to_path_buf();
    fs::create_dir_all(&lib_dir).await?;

    // OpenVINO and ROCm: pip-based install with fallback chain
    #[cfg(target_os = "linux")]
    if pip_package_for_ep(ep).is_some() {
        if target_path.exists() {
            return Ok(target_path);
        }
        return ensure_ort_via_pip_chain(ep, &lib_dir, &target_path).await;
    }

    // DirectML: distributed via NuGet, not GitHub release archives.
    #[cfg(target_os = "windows")]
    if matches!(ep, OnnxExecutionProvider::DirectMl) {
        if target_path.exists() {
            return Ok(target_path);
        }
        return ensure_ort_via_nuget_directml(&lib_dir, &target_path).await;
    }

    // Standard path: download from GitHub releases
    let (ext, archive_name, lib_path_in_archive, local_lib_name, ort_version) =
        ort_platform_info_with_cuda_major(ep, detected_cuda_major)?;
    let is_gpu = ep != OnnxExecutionProvider::Cpu;
    let archive_filename = if ext == "tgz" {
        format!("{archive_name}.tgz")
    } else {
        format!("{archive_name}.zip")
    };
    let marker_path = ort_digest_marker_path(&target_path);
    let expected_digest = expected_ort_archive_sha256(&archive_filename);
    if target_path.exists() && marker_matches(&marker_path, &target_path, expected_digest).await {
        return Ok(target_path);
    }

    let url = format!(
        "https://github.com/microsoft/onnxruntime/releases/download/v{ort_version}/{archive_filename}"
    );

    eprintln!("Downloading ONNX Runtime v{ort_version} ({ep})...");
    eprintln!("  {url}");

    crate::init_tls();
    let client = Client::new();
    let res = client
        .get(&url)
        .header("User-Agent", "vera")
        .send()
        .await?
        .error_for_status()?;
    let _ = expected_digest.context("no pinned checksum for ONNX Runtime archive")?;
    let bytes = res.bytes().await?;
    if let Some(expected) = expected_digest {
        verify_sha256(
            bytes.as_ref(),
            expected,
            &format!("ONNX Runtime archive {archive_name}"),
        )?;
    }

    let lib_dir_clone = lib_dir.clone();
    let lib_path_in_archive_clone = lib_path_in_archive.clone();

    let extract_result = tokio::task::spawn_blocking(move || -> Result<()> {
        if ext == "tgz" {
            if is_gpu {
                extract_tgz_all_libs(&bytes, &lib_dir_clone)
            } else {
                extract_tgz_single(
                    &bytes,
                    &lib_path_in_archive_clone,
                    &lib_dir_clone.join(local_lib_name),
                )
            }
        } else if is_gpu {
            extract_zip_all_libs(&bytes, &archive_name, &lib_dir_clone)
        } else {
            extract_zip(
                &bytes,
                &lib_path_in_archive_clone,
                &lib_dir_clone.join(local_lib_name),
            )
        }
    })
    .await?;

    if let Err(e) = extract_result {
        return Err(e).context("Failed to extract ONNX Runtime from archive");
    }

    if let Some(expected) = expected_digest {
        let library_digest = sha256_hex(File::open(&target_path)?)?;
        fs::write(
            &marker_path,
            format!("archive={expected}\nlibrary={library_digest}\n"),
        )
        .await?;
    }

    eprintln!(
        "ONNX Runtime v{ort_version} installed to {}",
        lib_dir.display()
    );
    Ok(target_path)
}

fn ort_digest_marker_path(path: &Path) -> PathBuf {
    path.with_file_name(format!(
        "{}.sha256",
        path.file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("ort")
    ))
}

async fn marker_matches(path: &Path, target: &Path, expected: Option<&str>) -> bool {
    let Some(expected) = expected else {
        return false;
    };
    match fs::read_to_string(path).await {
        Ok(marker) => {
            let mut archive = None;
            let mut library = None;
            for line in marker.lines() {
                if let Some(value) = line.strip_prefix("archive=") {
                    archive = Some(value);
                } else if let Some(value) = line.strip_prefix("library=") {
                    library = Some(value);
                }
            }
            let Some(library) = library else {
                return false;
            };
            let library_matches = File::open(target)
                .ok()
                .and_then(|file| sha256_hex(file).ok())
                .is_some_and(|actual| actual.eq_ignore_ascii_case(library));
            archive.is_some_and(|value| value.eq_ignore_ascii_case(expected)) && library_matches
        }
        Err(_) => false,
    }
}

/// Re-fetch the ONNX Runtime library for the selected execution provider.
///
/// `vera setup` and `vera repair` call this for CUDA so switching between CUDA
/// toolkits refreshes the downloaded ORT build instead of reusing a stale one.
pub async fn refresh_ort_library_for_ep(ep: OnnxExecutionProvider) -> Result<PathBuf> {
    if let Some(path) = ort_dylib_path_from_env() {
        return Ok(path);
    }

    let detected_cuda_major = detected_cuda_major_for_ep(ep);
    let target_path = preferred_ort_library_path_for_ep_with_cuda_major(ep, detected_cuda_major)?;
    if ep == OnnxExecutionProvider::Cpu {
        if target_path.exists() {
            fs::remove_file(&target_path).await.with_context(|| {
                format!(
                    "failed to remove stale ONNX Runtime at {}",
                    target_path.display()
                )
            })?;
        }
    } else if let Some(dir) = target_path.parent()
        && dir.exists()
    {
        fs::remove_dir_all(dir).await.with_context(|| {
            format!(
                "failed to remove stale ONNX Runtime directory {}",
                dir.display()
            )
        })?;
    }

    ensure_ort_library_for_ep_with_cuda_major(ep, detected_cuda_major).await
}

/// Download ONNX Runtime DirectML from NuGet.
///
/// DirectML builds are not published as GitHub release archives; they are only
/// distributed via NuGet. The `.nupkg` is a zip containing DLLs at
/// `runtimes/win-x64/native/`.
#[cfg(target_os = "windows")]
pub(super) async fn ensure_ort_via_nuget_directml(
    lib_dir: &std::path::Path,
    target_path: &std::path::Path,
) -> Result<PathBuf> {
    let nuget_url = format!(
        "https://api.nuget.org/v3-flatcontainer/microsoft.ml.onnxruntime.directml/{ORT_VERSION}/microsoft.ml.onnxruntime.directml.{ORT_VERSION}.nupkg"
    );

    eprintln!("Downloading ONNX Runtime v{ORT_VERSION} (directml) from NuGet...");
    eprintln!("  {nuget_url}");

    crate::init_tls();
    let client = Client::new();
    let res = client
        .get(&nuget_url)
        .header("User-Agent", "vera")
        .send()
        .await?
        .error_for_status()
        .context("failed to download DirectML NuGet package")?;
    let bytes = res.bytes().await?;

    let lib_dir_owned = lib_dir.to_path_buf();
    tokio::task::spawn_blocking(move || {
        extract_nuget_native_dlls(&bytes, "runtimes/win-x64/native/", &lib_dir_owned)
    })
    .await??;

    eprintln!(
        "ONNX Runtime v{ORT_VERSION} (directml) installed to {}",
        lib_dir.display()
    );
    Ok(target_path.to_path_buf())
}

/// Extract native DLLs from a NuGet package (zip) at the given prefix.
#[cfg(target_os = "windows")]
pub(super) fn extract_nuget_native_dlls(
    data: &[u8],
    prefix: &str,
    dest_dir: &std::path::Path,
) -> Result<()> {
    let cursor = std::io::Cursor::new(data);
    let mut archive = zip::ZipArchive::new(cursor)?;
    let mut extracted = 0usize;

    for i in 0..archive.len() {
        let mut entry = archive.by_index(i)?;
        let path = entry.name().to_string();
        if !path.starts_with(prefix) {
            continue;
        }
        let filename = path.rsplit('/').next().unwrap_or("");
        if !filename.ends_with(".dll") {
            continue;
        }
        let dest = dest_dir.join(filename);
        let mut out = std::fs::File::create(&dest)?;
        std::io::copy(&mut entry, &mut out)?;
        extracted += 1;
    }

    if extracted == 0 {
        anyhow::bail!("no DLLs found in NuGet package at {prefix}");
    }
    eprintln!("  Extracted {extracted} libraries from NuGet package");
    Ok(())
}

/// Pip-based fallback chain for OpenVINO and ROCm.
#[cfg(target_os = "linux")]
pub(super) async fn ensure_ort_via_pip_chain(
    ep: OnnxExecutionProvider,
    lib_dir: &std::path::Path,
    target_path: &std::path::Path,
) -> Result<PathBuf> {
    let pkg = pip_package_for_ep(ep).unwrap();

    // Option 1: pip install into managed venv
    match try_pip_install_ort(ep, lib_dir).await {
        Ok(()) => {
            eprintln!(
                "ONNX Runtime ({ep}) installed via pip to {}",
                lib_dir.display()
            );
            return Ok(target_path.to_path_buf());
        }
        Err(e) => {
            tracing::warn!("pip install failed, trying direct wheel download: {e:#}");
            eprintln!("  pip install failed, trying direct wheel download...");
        }
    }

    // Option 2: download wheel directly from PyPI
    match try_wheel_download_ort(ep, lib_dir).await {
        Ok(()) => {
            eprintln!(
                "ONNX Runtime ({ep}) installed via wheel to {}",
                lib_dir.display()
            );
            return Ok(target_path.to_path_buf());
        }
        Err(e) => {
            tracing::warn!("wheel download failed: {e:#}");
            eprintln!("  Wheel download also failed.");
        }
    }

    // Option 3: bail with manual instructions
    anyhow::bail!(
        "Could not automatically install ONNX Runtime with {ep} support.\n\
         Install manually:\n\
         \n\
         1. pip install {pkg}\n\
         2. Locate libonnxruntime.so inside the installed package:\n\
            python3 -c \"import onnxruntime; import os; print(os.path.join(os.path.dirname(onnxruntime.__file__), 'capi'))\"\n\
         3. Set ORT_DYLIB_PATH to the full path of libonnxruntime.so\n\
         4. Run `vera setup` again"
    )
}

pub fn ort_library_path_for_ep(ep: OnnxExecutionProvider) -> Result<PathBuf> {
    if let Some(path) = ort_dylib_path_from_env() {
        return Ok(path);
    }

    let detected_cuda_major = match ep {
        OnnxExecutionProvider::Cuda => detected_cuda_major_for_ep(ep),
        _ => None,
    };

    ort_library_path_for_ep_with_cuda_major(ep, detected_cuda_major)
}

pub(super) fn preferred_ort_library_path_for_ep_in_home(
    vera_home: &Path,
    ep: OnnxExecutionProvider,
    detected_cuda_major: Option<u32>,
) -> PathBuf {
    let lib_dir = match ep {
        OnnxExecutionProvider::Cpu => vera_home.join("lib"),
        OnnxExecutionProvider::Cuda => vera_home
            .join("lib")
            .join(cuda_ort_cache_dir_name(detected_cuda_major)),
        _ => vera_home.join("lib").join(ep.to_string()),
    };

    lib_dir.join(platform_ort_lib_name())
}

pub(super) fn cached_ort_library_path_for_ep_in_home(
    vera_home: &Path,
    ep: OnnxExecutionProvider,
    detected_cuda_major: Option<u32>,
) -> PathBuf {
    let preferred_path =
        preferred_ort_library_path_for_ep_in_home(vera_home, ep, detected_cuda_major);
    if matches!(ep, OnnxExecutionProvider::Cuda)
        && detected_cuda_major.is_none()
        && !preferred_path.exists()
    {
        let cuda13_path =
            preferred_ort_library_path_for_ep_in_home(vera_home, ep, Some(CUDA_13_ORT_MIN_MAJOR));
        if cuda13_path.exists() {
            return cuda13_path;
        }
    }
    preferred_path
}

pub(super) fn preferred_ort_library_path_for_ep_with_cuda_major(
    ep: OnnxExecutionProvider,
    detected_cuda_major: Option<u32>,
) -> Result<PathBuf> {
    if let Some(path) = ort_dylib_path_from_env() {
        return Ok(path);
    }

    let vera_home = vera_home_dir()?;
    Ok(preferred_ort_library_path_for_ep_in_home(
        &vera_home,
        ep,
        detected_cuda_major,
    ))
}

pub(super) fn ort_library_path_for_ep_with_cuda_major(
    ep: OnnxExecutionProvider,
    detected_cuda_major: Option<u32>,
) -> Result<PathBuf> {
    if let Some(path) = ort_dylib_path_from_env() {
        return Ok(path);
    }

    let vera_home = vera_home_dir()?;
    Ok(cached_ort_library_path_for_ep_in_home(
        &vera_home,
        ep,
        detected_cuda_major,
    ))
}

pub fn ensure_provider_dependencies(
    ep: OnnxExecutionProvider,
    runtime_path: &std::path::Path,
) -> Result<()> {
    // CPU mode only needs the core runtime library; skip provider dependency checks.
    if matches!(ep, OnnxExecutionProvider::Cpu) {
        return Ok(());
    }

    let Some(status) = inspect_provider_dependencies(ep, runtime_path)? else {
        return Ok(());
    };

    let mut missing_libraries = status.missing_libraries;
    missing_libraries.sort();
    missing_libraries.dedup();

    if missing_libraries.is_empty() {
        return Ok(());
    }

    let backend_name = match ep {
        OnnxExecutionProvider::Cpu => "CPU",
        OnnxExecutionProvider::Cuda => "CUDA",
        OnnxExecutionProvider::Rocm => "ROCm",
        OnnxExecutionProvider::DirectMl => "DirectML",
        OnnxExecutionProvider::CoreMl => "CoreML",
        OnnxExecutionProvider::OpenVino => "OpenVINO",
    };

    let mut message =
        format!("{backend_name} backend selected, but required libraries are missing:\n");
    for library in &missing_libraries {
        message.push_str(&format!("  {library}\n"));
    }
    if let Some(hint) = dependency_hint(ep) {
        message.push_str(&hint);
        message.push('\n');
    }
    message.push_str("Run `vera doctor --probe` for details.");
    anyhow::bail!("{}", message.trim_end());
}

pub fn inspect_provider_dependencies(
    ep: OnnxExecutionProvider,
    runtime_path: &std::path::Path,
) -> Result<Option<SharedLibraryDependencyStatus>> {
    Ok(inspect_shared_library_deps_impl(runtime_path, Some(ep))?
        .map(|status| required_dependency_status(ep, status)))
}

pub(super) fn required_dependency_status(
    ep: OnnxExecutionProvider,
    mut status: SharedLibraryDependencyStatus,
) -> SharedLibraryDependencyStatus {
    if matches!(ep, OnnxExecutionProvider::Cuda) {
        // CUDA ORT archives also ship a TensorRT provider. TensorRT is optional
        // for Vera's CUDA path, so missing TensorRT libraries must not make the
        // CUDA backend look broken.
        status
            .missing_details
            .retain(|detail| !detail.starts_with("libonnxruntime_providers_tensorrt"));
        status.missing_libraries = status
            .missing_details
            .iter()
            .filter_map(|detail| detail.split(": ").nth(1))
            .map(str::to_string)
            .collect();
        status.missing_libraries.sort();
        status.missing_libraries.dedup();
    }
    status
}

#[cfg(target_os = "linux")]
pub(super) fn inspect_shared_library_deps_impl(
    runtime_path: &std::path::Path,
    _ep: Option<OnnxExecutionProvider>,
) -> Result<Option<SharedLibraryDependencyStatus>> {
    if !runtime_path.exists() {
        return Ok(None);
    }

    if !command_exists("ldd", &["--version"]) {
        return Ok(None);
    }

    let inspected_files = collect_runtime_libraries(runtime_path, ".so");

    let mut missing_details = Vec::new();
    let mut missing_libraries = Vec::new();

    for inspected in &inspected_files {
        let output = std::process::Command::new("ldd")
            .arg(inspected)
            .output()
            .with_context(|| format!("failed to run `ldd` on {}", inspected.display()))?;
        let text = format!(
            "{}\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        let file_name = inspected
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("unknown");
        for line in text.lines().filter(|line| line.contains("not found")) {
            let library = line.split("=>").next().unwrap_or(line).trim().to_string();
            missing_details.push(format!("{file_name}: {library}"));
            missing_libraries.push(library);
        }
    }

    missing_details.sort();
    missing_details.dedup();
    missing_libraries.sort();
    missing_libraries.dedup();

    Ok(Some(SharedLibraryDependencyStatus {
        inspected_files,
        missing_details,
        missing_libraries,
    }))
}

#[cfg(target_os = "macos")]
pub(super) fn inspect_shared_library_deps_impl(
    runtime_path: &std::path::Path,
    _ep: Option<OnnxExecutionProvider>,
) -> Result<Option<SharedLibraryDependencyStatus>> {
    if !runtime_path.exists() {
        return Ok(None);
    }

    if !command_exists("otool", &["-L", runtime_path.to_string_lossy().as_ref()]) {
        return Ok(None);
    }

    let inspected_files = collect_runtime_libraries(runtime_path, ".dylib");
    let mut missing_details = Vec::new();
    let mut missing_libraries = Vec::new();

    for inspected in &inspected_files {
        let dependencies = macos_dependencies(inspected)?;
        let rpaths = macos_rpaths(inspected)?;
        let file_name = inspected
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("unknown");
        for dependency in dependencies {
            if macos_dependency_exists(&dependency, inspected, &rpaths) {
                continue;
            }
            missing_details.push(format!("{file_name}: {dependency}"));
            missing_libraries.push(dependency);
        }
    }

    missing_details.sort();
    missing_details.dedup();
    missing_libraries.sort();
    missing_libraries.dedup();

    Ok(Some(SharedLibraryDependencyStatus {
        inspected_files,
        missing_details,
        missing_libraries,
    }))
}

#[cfg(target_os = "windows")]
pub(super) fn inspect_shared_library_deps_impl(
    runtime_path: &std::path::Path,
    ep: Option<OnnxExecutionProvider>,
) -> Result<Option<SharedLibraryDependencyStatus>> {
    if !runtime_path.exists() {
        return Ok(None);
    }

    let inspected_files = collect_runtime_libraries(runtime_path, ".dll");

    // Use dumpbin if available (Visual Studio), otherwise fall back to a
    // known-list check for provider DLLs alongside onnxruntime.dll.
    let mut missing_details = Vec::new();
    let mut missing_libraries = Vec::new();

    if command_exists("dumpbin", &["/?"]) {
        for inspected in &inspected_files {
            let output = std::process::Command::new("dumpbin")
                .args(["/dependents", inspected.to_string_lossy().as_ref()])
                .output();
            let Ok(output) = output else { continue };
            let text = String::from_utf8_lossy(&output.stdout);
            let file_name = inspected
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or("unknown");
            for line in text.lines() {
                let dep = line.trim();
                if dep.ends_with(".dll") && !dep.contains(' ') {
                    // Check if the DLL can be found by the loader: same dir or system PATH.
                    let in_same_dir = inspected
                        .parent()
                        .map(|dir| dir.join(dep).exists())
                        .unwrap_or(false);
                    if !in_same_dir && which_dll(dep).is_none() {
                        missing_details.push(format!("{file_name}: {dep}"));
                        missing_libraries.push(dep.to_string());
                    }
                }
            }
        }
    } else {
        // No dumpbin: check that the selected provider DLLs exist alongside the runtime.
        if let Some(dir) = runtime_path.parent() {
            let expected_provider_libs = if matches!(ep, Some(OnnxExecutionProvider::DirectMl)) {
                [
                    "onnxruntime_providers_shared.dll",
                    "onnxruntime_providers_dml.dll",
                ]
            } else {
                [
                    "onnxruntime_providers_shared.dll",
                    "onnxruntime_providers_cuda.dll",
                ]
            };
            for lib in &expected_provider_libs {
                if !dir.join(lib).exists() {
                    missing_details.push(format!("onnxruntime.dll: {lib}"));
                    missing_libraries.push(lib.to_string());
                }
            }
        }
    }

    missing_details.sort();
    missing_details.dedup();
    missing_libraries.sort();
    missing_libraries.dedup();

    Ok(Some(SharedLibraryDependencyStatus {
        inspected_files,
        missing_details,
        missing_libraries,
    }))
}

#[cfg(target_os = "windows")]
pub(super) fn which_dll(name: &str) -> Option<std::path::PathBuf> {
    let path_var = std::env::var("PATH").unwrap_or_default();
    for dir in path_var.split(';') {
        let candidate = std::path::Path::new(dir).join(name);
        if candidate.exists() {
            return Some(candidate);
        }
    }
    None
}

#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
pub(super) fn inspect_shared_library_deps_impl(
    _: &std::path::Path,
    _ep: Option<OnnxExecutionProvider>,
) -> Result<Option<SharedLibraryDependencyStatus>> {
    Ok(None)
}

pub(super) fn collect_runtime_libraries(
    runtime_path: &std::path::Path,
    suffix: &str,
) -> Vec<PathBuf> {
    let mut inspected_files = vec![runtime_path.to_path_buf()];
    if let Some(dir) = runtime_path.parent()
        && let Ok(entries) = std::fs::read_dir(dir)
    {
        for entry in entries.flatten() {
            let path = entry.path();
            let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
                continue;
            };
            if (name.starts_with("libonnxruntime") || name.starts_with("onnxruntime"))
                && name.contains(suffix)
                && path != runtime_path
            {
                inspected_files.push(path);
            }
        }
    }
    inspected_files.sort();
    inspected_files.dedup();
    inspected_files
}

pub(super) fn command_exists(program: &str, args: &[&str]) -> bool {
    std::process::Command::new(program)
        .args(args)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok()
}

#[cfg(target_os = "macos")]
pub(super) fn macos_dependencies(inspected: &std::path::Path) -> Result<Vec<String>> {
    let output = std::process::Command::new("otool")
        .args(["-L", inspected.to_string_lossy().as_ref()])
        .output()
        .with_context(|| format!("failed to run `otool -L` on {}", inspected.display()))?;
    let text = format!(
        "{}\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    Ok(text
        .lines()
        .skip(1)
        .filter_map(|line| line.split_whitespace().next())
        .map(|line| line.trim().to_string())
        .filter(|line| !line.is_empty())
        .collect())
}

#[cfg(target_os = "macos")]
pub(super) fn macos_rpaths(inspected: &std::path::Path) -> Result<Vec<String>> {
    let output = std::process::Command::new("otool")
        .args(["-l", inspected.to_string_lossy().as_ref()])
        .output()
        .with_context(|| format!("failed to run `otool -l` on {}", inspected.display()))?;
    let text = format!(
        "{}\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    let mut rpaths = Vec::new();
    let mut in_rpath = false;
    for line in text.lines() {
        let trimmed = line.trim();
        if trimmed == "cmd LC_RPATH" {
            in_rpath = true;
            continue;
        }
        if in_rpath && trimmed.starts_with("path ") {
            if let Some(path) = trimmed
                .strip_prefix("path ")
                .and_then(|rest| rest.split(" (offset").next())
            {
                rpaths.push(path.trim().to_string());
            }
            in_rpath = false;
        }
    }
    Ok(rpaths)
}

#[cfg(target_os = "macos")]
pub(super) fn macos_dependency_exists(
    dependency: &str,
    inspected: &std::path::Path,
    rpaths: &[String],
) -> bool {
    if dependency.starts_with("/System/Library/") || dependency.starts_with("/usr/lib/") {
        return true;
    }

    if let Some(rest) = dependency.strip_prefix("@loader_path/") {
        return inspected
            .parent()
            .map(|parent| parent.join(rest).exists())
            .unwrap_or(false);
    }

    if let Some(rest) = dependency.strip_prefix("@executable_path/") {
        let exe_path = std::env::current_exe().ok();
        let exe_exists = exe_path
            .as_deref()
            .and_then(|exe| exe.parent())
            .map(|parent| parent.join(rest).exists())
            .unwrap_or(false);
        return exe_exists
            || inspected
                .parent()
                .map(|parent| parent.join(rest).exists())
                .unwrap_or(false);
    }

    if let Some(rest) = dependency.strip_prefix("@rpath/") {
        return rpaths
            .iter()
            .map(|rpath| resolve_macos_rpath(rpath, inspected))
            .any(|candidate| candidate.join(rest).exists());
    }

    if dependency.starts_with('@') {
        return false;
    }

    std::path::Path::new(dependency).exists()
}

#[cfg(target_os = "macos")]
pub(super) fn resolve_macos_rpath(rpath: &str, inspected: &std::path::Path) -> PathBuf {
    if rpath == "@loader_path" || rpath.starts_with("@loader_path/") {
        let rest = rpath.strip_prefix("@loader_path/").unwrap_or("");
        return inspected
            .parent()
            .unwrap_or_else(|| std::path::Path::new(""))
            .join(rest);
    }

    if rpath == "@executable_path" || rpath.starts_with("@executable_path/") {
        let rest = rpath.strip_prefix("@executable_path/").unwrap_or("");
        if let Ok(exe) = std::env::current_exe() {
            if let Some(parent) = exe.parent() {
                return parent.join(rest);
            }
        }
    }

    PathBuf::from(rpath)
}

pub(super) fn dependency_hint(ep: OnnxExecutionProvider) -> Option<String> {
    match ep {
        OnnxExecutionProvider::Cpu => None,
        OnnxExecutionProvider::Cuda => Some(match detect_cuda_major_version() {
            Some(cuda_major) => format!(
                "Install the CUDA {cuda_major} toolkit and cuDNN 9, then ensure they're on the linker path."
            ),
            None => {
                "Install the CUDA toolkit and cuDNN 9, then ensure they're on the linker path."
                    .to_string()
            }
        }),
        OnnxExecutionProvider::Rocm => {
            Some("Install the ROCm userspace libraries, then ensure they're on the linker path.".to_string())
        }
        OnnxExecutionProvider::DirectMl => {
            Some("Install the DirectML runtime and required GPU drivers.".to_string())
        }
        OnnxExecutionProvider::CoreMl => {
            Some("Verify you are running on Apple Silicon with a supported macOS version.".to_string())
        }
        OnnxExecutionProvider::OpenVino => {
            Some("Install the Intel OpenVINO runtime or compute libraries, then ensure they're on the linker path.".to_string())
        }
    }
}

pub(super) fn platform_ort_lib_name() -> &'static str {
    if cfg!(target_os = "windows") {
        "onnxruntime.dll"
    } else if cfg!(target_os = "macos") {
        "libonnxruntime.dylib"
    } else {
        "libonnxruntime.so"
    }
}

/// Extract a single shared library from a tgz archive (CPU builds).
pub(super) fn extract_tgz_single(
    data: &[u8],
    entry_path: &str,
    dest: &std::path::Path,
) -> Result<()> {
    use flate2::read::GzDecoder;

    let decoder = GzDecoder::new(data);
    let mut archive = tar::Archive::new(decoder);

    for entry in archive.entries()? {
        let mut entry = entry?;
        let path = entry.path()?;
        if path.to_string_lossy() == entry_path {
            write_lib_file(&mut entry, dest)?;
            return Ok(());
        }
    }

    // Suffix fallback (archive structure may vary)
    let decoder2 = GzDecoder::new(data);
    let mut archive2 = tar::Archive::new(decoder2);
    let suffix = entry_path.rsplit('/').next().unwrap_or(entry_path);

    for entry in archive2.entries()? {
        let mut entry = entry?;
        let path = entry.path()?;
        let path_str = path.to_string_lossy();
        if path_str.ends_with(suffix) && path_str.contains("/lib/") {
            write_lib_file(&mut entry, dest)?;
            return Ok(());
        }
    }

    anyhow::bail!("Could not find {entry_path} in ORT archive")
}

/// Extract all shared libraries from a tgz archive (GPU builds need provider libs).
pub(super) fn extract_tgz_all_libs(data: &[u8], dest_dir: &std::path::Path) -> Result<()> {
    use flate2::read::GzDecoder;

    let decoder = GzDecoder::new(data);
    let mut archive = tar::Archive::new(decoder);
    let mut extracted = 0usize;

    for entry in archive.entries()? {
        let mut entry = entry?;
        // Skip symlinks — we want the real files
        if entry.header().entry_type() != tar::EntryType::Regular {
            continue;
        }
        let path = entry.path()?;
        let path_str = path.to_string_lossy();
        if !path_str.contains("/lib/") {
            continue;
        }
        let filename = path
            .file_name()
            .and_then(|f| f.to_str())
            .unwrap_or("")
            .to_string();
        // Extract .so, .dylib, .dll files (skip .pc and other non-library files)
        let is_lib =
            filename.contains(".so") || filename.ends_with(".dylib") || filename.ends_with(".dll");
        if !is_lib {
            continue;
        }
        // Normalize versioned names: libonnxruntime.so.1.23.2 → libonnxruntime.so
        let local_name = strip_so_version(&filename);
        let dest = dest_dir.join(&local_name);
        write_lib_file(&mut entry, &dest)?;
        create_versioned_symlink(dest_dir, &filename, &local_name);
        extracted += 1;
    }

    if extracted == 0 {
        anyhow::bail!("No shared libraries found in ORT archive");
    }
    Ok(())
}

/// Strip .so version suffix: "libonnxruntime.so.1.23.2" → "libonnxruntime.so"
pub(super) fn strip_so_version(name: &str) -> String {
    if let Some(pos) = name.find(".so.") {
        name[..pos + 3].to_string()
    } else {
        name.to_string()
    }
}

/// Create a versioned symlink if the original filename differs from the
/// stripped name. For example, if `original` is "libopenvino.so.2541" and
/// `stripped` is "libopenvino.so", creates a symlink
/// `dest_dir/libopenvino.so.2541 -> libopenvino.so`.
#[cfg(unix)]
pub(super) fn create_versioned_symlink(dest_dir: &std::path::Path, original: &str, stripped: &str) {
    if original == stripped {
        return;
    }
    let link = dest_dir.join(original);
    if link.exists() || link.symlink_metadata().is_ok() {
        return;
    }
    if let Err(e) = std::os::unix::fs::symlink(stripped, &link) {
        tracing::debug!(link = %link.display(), target = stripped, error = %e, "failed to create versioned symlink");
    }
}

#[cfg(not(unix))]
pub(super) fn create_versioned_symlink(
    _dest_dir: &std::path::Path,
    _original: &str,
    _stripped: &str,
) {
}

pub(super) fn write_lib_file(
    reader: &mut impl std::io::Read,
    dest: &std::path::Path,
) -> Result<()> {
    let attempt = MODEL_DOWNLOAD_ATTEMPT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let temp_path = dest.with_extension(format!("part.{}.{}", std::process::id(), attempt));

    let result: Result<()> = (|| {
        let mut options = std::fs::OpenOptions::new();
        options.write(true).create_new(true);
        let mut out = options.open(&temp_path)?;
        std::io::copy(reader, &mut out)?;
        out.flush()?;
        out.sync_all()?;
        drop(out);

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&temp_path, std::fs::Permissions::from_mode(0o755))?;
        }

        #[cfg(windows)]
        if dest.exists() {
            std::fs::remove_file(dest)?;
        }
        std::fs::rename(&temp_path, dest)?;
        Ok(())
    })();

    if let Err(error) = result {
        let _ = std::fs::remove_file(&temp_path);
        return Err(error);
    }
    Ok(())
}

pub(super) fn extract_zip(data: &[u8], entry_path: &str, dest: &std::path::Path) -> Result<()> {
    // Windows .zip extraction using tar crate's zip support is not available,
    // so we use a minimal zip reader via the `zip` crate. Since we only compile
    // this path on Windows and want to avoid an extra dependency, we fall back
    // to extracting via the system `tar` command or manual parsing.
    //
    // For simplicity, use the zip crate. But since it's not added as a dep,
    // we'll use a raw approach: download the tgz variant if available, or
    // shell out to PowerShell on Windows.
    #[cfg(target_os = "windows")]
    {
        let temp_zip = dest.with_extension("zip");
        std::fs::write(&temp_zip, data)?;
        let output = std::process::Command::new("powershell")
            .args([
                "-NoProfile",
                "-Command",
                &format!(
                    "Add-Type -AssemblyName System.IO.Compression.FileSystem; \
                     $zip = [System.IO.Compression.ZipFile]::OpenRead('{}'); \
                     $entry = $zip.Entries | Where-Object {{ $_.FullName -eq '{}' }}; \
                     if ($entry) {{ \
                         $stream = $entry.Open(); \
                         $file = [System.IO.File]::Create('{}'); \
                         $stream.CopyTo($file); \
                         $file.Close(); $stream.Close(); \
                     }}; $zip.Dispose()",
                    temp_zip.display(),
                    entry_path.replace('/', "\\"),
                    dest.display()
                ),
            ])
            .output()?;
        let _ = std::fs::remove_file(&temp_zip);
        if !output.status.success() {
            anyhow::bail!(
                "Failed to extract ORT zip: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
        if !dest.exists() {
            // Try with forward slashes
            let temp_zip2 = dest.with_extension("zip2");
            std::fs::write(&temp_zip2, data)?;
            let output2 = std::process::Command::new("powershell")
                .args([
                    "-NoProfile",
                    "-Command",
                    &format!(
                        "Add-Type -AssemblyName System.IO.Compression.FileSystem; \
                         $zip = [System.IO.Compression.ZipFile]::OpenRead('{}'); \
                         $entry = $zip.Entries | Where-Object {{ $_.FullName -eq '{}' }}; \
                         if ($entry) {{ \
                             $stream = $entry.Open(); \
                             $file = [System.IO.File]::Create('{}'); \
                             $stream.CopyTo($file); \
                             $file.Close(); $stream.Close(); \
                         }}; $zip.Dispose()",
                        temp_zip2.display(),
                        entry_path,
                        dest.display()
                    ),
                ])
                .output()?;
            let _ = std::fs::remove_file(&temp_zip2);
            if !output2.status.success() || !dest.exists() {
                anyhow::bail!("Could not find {entry_path} in ORT zip archive");
            }
        }
        Ok(())
    }
    #[cfg(not(target_os = "windows"))]
    {
        let _ = (data, entry_path, dest);
        anyhow::bail!("ZIP extraction not expected on this platform")
    }
}

/// Extract all DLL files from a zip archive's lib/ directory (GPU builds need provider libs).
pub(super) fn extract_zip_all_libs(
    data: &[u8],
    _archive_name: &str,
    dest_dir: &std::path::Path,
) -> Result<()> {
    #[cfg(target_os = "windows")]
    {
        let temp_zip = dest_dir.join("_ort_download.zip");
        std::fs::write(&temp_zip, data)?;
        // Extract all .dll files from any lib/ subdirectory inside the archive.
        // We match loosely because the CUDA 13 archive filename contains `_cuda13`
        // but the internal directory does not.
        let script = format!(
            "Add-Type -AssemblyName System.IO.Compression.FileSystem; \
             $zip = [System.IO.Compression.ZipFile]::OpenRead('{zip}'); \
             $count = 0; \
             foreach ($entry in $zip.Entries) {{ \
                 if ($entry.FullName -match '/lib/[^/]+\\.dll$' -and $entry.Length -gt 0) {{ \
                     $name = $entry.Name; \
                     $dest = Join-Path '{dest}' $name; \
                     $stream = $entry.Open(); \
                     $file = [System.IO.File]::Create($dest); \
                     $stream.CopyTo($file); \
                     $file.Close(); $stream.Close(); \
                     $count++; \
                 }} \
             }}; \
             $zip.Dispose(); \
             if ($count -eq 0) {{ exit 1 }}",
            zip = temp_zip.display(),
            dest = dest_dir.display(),
        );
        let output = std::process::Command::new("powershell")
            .args(["-NoProfile", "-Command", &script])
            .output()?;
        let _ = std::fs::remove_file(&temp_zip);
        if !output.status.success() {
            anyhow::bail!(
                "Failed to extract DLLs from ORT zip: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
        Ok(())
    }
    #[cfg(not(target_os = "windows"))]
    {
        let _ = (data, _archive_name, dest_dir);
        anyhow::bail!("ZIP extraction not expected on this platform")
    }
}

/// Wrap an ort error with a user-friendly message suggesting alternatives.
pub fn wrap_ort_error(e: impl std::fmt::Display) -> String {
    let err_msg = e.to_string();
    let lower = err_msg.to_ascii_lowercase();
    if lower.contains("required libraries are missing") {
        return err_msg;
    }
    if lower.contains("libonnxruntime")
        || lower.contains("onnxruntime.dll")
        || lower.contains("libonnxruntime.so")
        || lower.contains("libonnxruntime.dylib")
        || lower.contains("loadlibrary")
        || lower.contains("shared library")
        || lower.contains("specified module could not be found")
        || lower.contains(".dll")
        || lower.contains(".dylib")
        || lower.contains(".so")
    {
        format!(
            "ONNX Runtime shared library not found.\n\
             Run `vera setup` to auto-download it, or use API mode instead.\n\
             Original error: {err_msg}"
        )
    } else {
        format!(
            "Failed to initialize ONNX session: {err_msg}\nRun `vera doctor --probe` for details."
        )
    }
}

#[cfg(test)]
mod finding_tests {
    use super::*;
    use std::io::{self, Read};

    struct FailingReader {
        yielded_data: bool,
    }

    impl Read for FailingReader {
        fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
            if self.yielded_data {
                return Err(io::Error::other("synthetic extraction failure"));
            }
            self.yielded_data = true;
            buffer[..4].copy_from_slice(b"part");
            Ok(4)
        }
    }

    #[test]
    fn failed_library_write_leaves_destination_unchanged() {
        let temp_dir = tempfile::tempdir().unwrap();
        let destination = temp_dir.path().join("libonnxruntime.so");
        std::fs::write(&destination, b"existing").unwrap();

        let result = write_lib_file(
            &mut FailingReader {
                yielded_data: false,
            },
            &destination,
        );

        assert!(result.is_err());
        assert_eq!(std::fs::read(&destination).unwrap(), b"existing");
        assert_eq!(std::fs::read_dir(temp_dir.path()).unwrap().count(), 1);
    }
}