ghost-link 2.3.0

CLI and API runtime for Ghostlink, a distributed inference fabric for routing and scheduling custom LLM workloads across heterogeneous hardware.
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
//! Runtime detection and model availability management
//! Supports GPU (CUDA/Metal), NPU, and CPU runtimes with auto-detection

use serde::{Deserialize, Serialize};

#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Runtime {
    CUDA,     // NVIDIA GPUs
    Metal,    // Apple Silicon / Apple GPUs
    ROCm,     // AMD GPUs (Linux / discrete)
    DirectML, // DirectML on Windows (AMD iGPU, Intel ARC, any DirectX 12 GPU)
    NPU,      // Neural Processing Units (AMD XDNA, Qualcomm, Intel NPU)
    CPU,      // CPU fallback
}

impl std::fmt::Display for Runtime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Runtime::CUDA => write!(f, "CUDA (NVIDIA GPU)"),
            Runtime::Metal => write!(f, "Metal (Apple Silicon)"),
            Runtime::ROCm => write!(f, "ROCm (AMD GPU)"),
            Runtime::DirectML => write!(f, "DirectML (DirectX 12 GPU)"),
            Runtime::NPU => write!(f, "NPU (Neural Processor)"),
            Runtime::CPU => write!(f, "CPU (Default)"),
        }
    }
}

impl std::str::FromStr for Runtime {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value.trim().to_ascii_lowercase().as_str() {
            "cuda" | "nvidia" | "nvidia-gpu" | "nvidia gpu" => Ok(Runtime::CUDA),
            "metal" | "apple" | "apple-metal" => Ok(Runtime::Metal),
            "rocm" | "amd" | "amd-gpu" | "amd gpu" => Ok(Runtime::ROCm),
            "directml" | "dml" | "directml-gpu" => Ok(Runtime::DirectML),
            "npu" | "neural" | "neural-processor" => Ok(Runtime::NPU),
            "cpu" | "default" => Ok(Runtime::CPU),
            other => Err(format!("unknown runtime '{other}'")),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuntimeInfo {
    pub detected_runtime: Runtime,
    pub is_available: bool,
    pub compute_capability: Option<String>,
    pub memory_gb: Option<f32>,
    pub device_count: Option<usize>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelInfo {
    pub name: String,
    pub parameters: String,
    pub size_gb: f32,
    pub memory_required_gb: f32,
    pub recommended_runtimes: Vec<Runtime>,
    pub inference_speed: ModelSpeed,
    pub quality_tier: QualityTier,
    pub use_cases: Vec<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ModelSpeed {
    Fast,     // <50ms response
    Standard, // 50-200ms response
    Slow,     // >200ms response
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum QualityTier {
    Lightweight, // 3B-7B models, fast inference
    Standard,    // 7B-13B models, good quality/speed
    Premium,     // 13B-70B models, high quality
    Specialized, // Domain-specific models
}

/// Runtime detection system
pub struct RuntimeDetector;

#[allow(dead_code)]
impl RuntimeDetector {
    /// Auto-detect available runtimes on the system
    ///
    /// Delegates to `SystemProfile` when available, falls back to
    /// individual probe methods for backward compatibility.
    pub fn detect() -> Vec<RuntimeInfo> {
        Self::detect_from_profile()
    }

    /// Detect runtimes by querying the unified `SystemProfile`.
    fn detect_from_profile() -> Vec<RuntimeInfo> {
        let profile = ghostlink_core::system_profile::SystemProfile::detect_fast();
        let mut runtimes = Vec::new();

        // Map detected GPUs to runtime info
        for gpu in &profile.gpus {
            let runtime = match gpu.backend {
                ghostlink_core::host::GpuBackend::Cuda => Runtime::CUDA,
                ghostlink_core::host::GpuBackend::Rocm => Runtime::ROCm,
                ghostlink_core::host::GpuBackend::Metal => Runtime::Metal,
                ghostlink_core::host::GpuBackend::Directml => Runtime::DirectML,
                ghostlink_core::host::GpuBackend::Npu => Runtime::NPU,
                ghostlink_core::host::GpuBackend::Vulkan
                | ghostlink_core::host::GpuBackend::Cpu => continue,
            };
            runtimes.push(RuntimeInfo {
                detected_runtime: runtime,
                is_available: true,
                compute_capability: Some(gpu.compute_capability.clone()),
                memory_gb: Some(gpu.vram_gb),
                device_count: Some(
                    profile
                        .gpus
                        .iter()
                        .filter(|g| g.backend == gpu.backend)
                        .count(),
                ),
            });
        }

        // Add NPUs
        for npu in &profile.npus {
            runtimes.push(RuntimeInfo {
                detected_runtime: Runtime::NPU,
                is_available: true,
                compute_capability: Some(npu.name.clone()),
                memory_gb: Some(npu.memory_gb),
                device_count: Some(profile.npus.len()),
            });
        }

        // CPU is always last
        runtimes.push(RuntimeInfo {
            detected_runtime: Runtime::CPU,
            is_available: true,
            compute_capability: None,
            memory_gb: Some(profile.memory.total_gb),
            device_count: Some(profile.cpu.logical_cores),
        });

        runtimes
    }

    /// Detect primary runtime (best available), honoring environment overrides.
    pub fn detect_primary() -> Runtime {
        if let Some(runtime) = Self::detect_override_runtime() {
            return runtime;
        }

        let runtimes = Self::detect();
        runtimes
            .first()
            .map(|r| r.detected_runtime)
            .unwrap_or(Runtime::CPU)
    }

    fn detect_override_runtime() -> Option<Runtime> {
        let runtime_str = std::env::var("GHOSTLINK_RUNTIME").ok()?;
        let runtime = runtime_str.parse::<Runtime>().ok()?;
        let force = std::env::var("GHOSTLINK_FORCE_RUNTIME")
            .map(|value| {
                matches!(
                    value.to_ascii_lowercase().as_str(),
                    "1" | "true" | "yes" | "on"
                )
            })
            .unwrap_or(false);

        if force {
            return Some(runtime);
        }

        let available = Self::detect()
            .into_iter()
            .any(|info| info.detected_runtime == runtime);

        if available {
            Some(runtime)
        } else {
            None
        }
    }

    /// Detect NVIDIA CUDA — checks toolkit path, env vars, and nvidia-smi
    fn detect_cuda() -> Option<RuntimeInfo> {
        // Check for CUDA toolkit or nvidia-smi
        let has_cuda_toolkit = std::path::Path::new("/usr/local/cuda").exists()
            || std::env::var("CUDA_PATH").is_ok()
            || std::env::var("CUDA_HOME").is_ok();
        let has_nvidia_smi = std::process::Command::new("nvidia-smi")
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);

        if has_cuda_toolkit || has_nvidia_smi {
            // Detect number of GPUs and compute capability via nvidia-smi
            let (device_count, compute_capability) = if has_nvidia_smi {
                let count = std::process::Command::new("nvidia-smi")
                    .args(["--query-gpu=index", "--format=csv,noheader"])
                    .output()
                    .ok()
                    .map(|o| String::from_utf8_lossy(&o.stdout).lines().count());
                let cc = std::process::Command::new("nvidia-smi")
                    .args(["--query-gpu=compute_cap", "--format=csv,noheader"])
                    .output()
                    .ok()
                    .and_then(|o| {
                        String::from_utf8_lossy(&o.stdout)
                            .lines()
                            .next()
                            .map(|l| l.trim().to_string())
                    });
                (count.or(Some(1)), cc.or(Some("7.0+".to_string())))
            } else {
                (Some(1), Some("7.0+".to_string()))
            };

            return Some(RuntimeInfo {
                detected_runtime: Runtime::CUDA,
                is_available: true,
                compute_capability,
                memory_gb: Self::detect_gpu_memory(),
                device_count,
            });
        }
        None
    }

    /// Detect Apple Metal
    fn detect_metal() -> Option<RuntimeInfo> {
        #[cfg(target_os = "macos")]
        {
            // Metal is always available on macOS with Apple Silicon
            if Self::is_apple_silicon() {
                return Some(RuntimeInfo {
                    detected_runtime: Runtime::Metal,
                    is_available: true,
                    compute_capability: Some("Apple Neural Engine".to_string()),
                    memory_gb: Self::detect_system_memory(),
                    device_count: Some(1),
                });
            }
        }
        None
    }

    /// Detect AMD ROCm — works on Linux (/opt/rocm, rocm-smi) and Windows (HIP_PATH, ROCM_PATH)
    #[cfg(feature = "rocm")]
    fn detect_rocm() -> Option<RuntimeInfo> {
        // Linux: /opt/rocm directory or ROCM_HOME env var
        let has_rocm_linux = std::path::Path::new("/opt/rocm").exists()
            || std::env::var("ROCM_HOME").is_ok()
            || std::env::var("ROCM_PATH").is_ok();

        // Windows: HIP SDK path or ROCM_PATH
        let has_rocm_windows = std::env::var("HIP_PATH").is_ok()
            || std::env::var("ROCM_PATH").is_ok()
            || std::path::Path::new("C:\\Program Files\\AMD\\ROCm").exists()
            || std::path::Path::new("C:\\Program Files\\AMD\\HIP").exists();

        // Check via rocm-smi tool (cross-platform)
        let has_rocm_smi = std::process::Command::new("rocm-smi")
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);

        // Check via hipconfig (AMD's HIP config tool)
        let has_hipconfig = std::process::Command::new("hipconfig")
            .arg("--full")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);

        // Check visible device env vars
        let has_visible_devices = std::env::var("ROCR_VISIBLE_DEVICES").is_ok()
            || std::env::var("HIP_VISIBLE_DEVICES").is_ok();

        if has_rocm_linux
            || has_rocm_windows
            || has_rocm_smi
            || has_hipconfig
            || has_visible_devices
        {
            let device_count = if has_rocm_smi {
                // Count AMD GPUs via rocm-smi
                std::process::Command::new("rocm-smi")
                    .args(["--showid"])
                    .output()
                    .ok()
                    .map(|o| {
                        String::from_utf8_lossy(&o.stdout)
                            .lines()
                            .filter(|l| l.contains("GPU["))
                            .count()
                    })
                    .or_else(|| {
                        std::env::var("ROCR_VISIBLE_DEVICES")
                            .or_else(|_| std::env::var("HIP_VISIBLE_DEVICES"))
                            .ok()
                            .map(|v| v.split(',').count())
                    })
                    .or(Some(1))
            } else {
                Some(1)
            };

            // Try to get actual GPU memory via rocm-smi
            let memory_gb = std::process::Command::new("rocm-smi")
                .args(["--showmeminfo", "vram"])
                .output()
                .ok()
                .and_then(|o| {
                    let stdout = String::from_utf8_lossy(&o.stdout);
                    stdout
                        .lines()
                        .find(|l| l.contains("Total Memory"))
                        .and_then(|l| {
                            let val = l.split(':').nth(1)?.trim().to_lowercase();
                            let num: f32 = val.split_whitespace().next()?.parse().ok()?;
                            if val.contains("gb") {
                                Some(num)
                            } else if val.contains("mb") {
                                Some(num / 1024.0)
                            } else {
                                None
                            }
                        })
                })
                .or_else(|| Self::detect_gpu_memory());

            return Some(RuntimeInfo {
                detected_runtime: Runtime::ROCm,
                is_available: true,
                compute_capability: Some("RDNA3/CDNA3".to_string()),
                memory_gb,
                device_count,
            });
        }

        None
    }

    /// Detect DirectML-capable GPUs (Windows)
    /// This catches AMD iGPUs, Intel ARC, and any DirectX 12 GPU not detected by CUDA/ROCm
    fn detect_directml() -> Option<RuntimeInfo> {
        #[cfg(windows)]
        {
            // On Windows, check for GPUs via PowerShell (wmic is deprecated)
            // Check for NVIDIA first (handled by CUDA detection)
            let has_nvidia = std::process::Command::new("nvidia-smi")
                .arg("--version")
                .output()
                .map(|o| o.status.success())
                .unwrap_or(false);

            if !has_nvidia {
                // Check for AMD or Intel GPUs via PowerShell
                if let Ok(output) = std::process::Command::new("powershell")
                    .args([
                        "-NoProfile",
                        "-Command",
                        "Get-CimInstance Win32_VideoController | Where-Object { $_.Name -notmatch 'Microsoft Basic Display' } | Select-Object -ExpandProperty Name"
                    ])
                    .output()
                {
                    if output.status.success() {
                        let stdout = String::from_utf8_lossy(&output.stdout);
                        for line in stdout.lines() {
                            let name = line.trim();
                            if name.is_empty() {
                                continue;
                            }
                            let lower = name.to_lowercase();
                            let is_amd = lower.contains("amd") || lower.contains("radeon");
                            let is_intel = lower.contains("intel")
                                || lower.contains("iris")
                                || lower.contains("arc");

                            if is_amd || is_intel {
                                // Check for DirectX 12 / WDDM 2.0+ support
                                let d3d12_available =
                                    std::path::Path::new("C:\\Windows\\System32\\d3d12.dll")
                                        .exists();
                                if d3d12_available {
                                    return Some(RuntimeInfo {
                                        detected_runtime: Runtime::DirectML,
                                        is_available: true,
                                        compute_capability: Some("DirectX 12".to_string()),
                                        memory_gb: Self::detect_gpu_memory(),
                                        device_count: Some(1),
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }
        None
    }

    /// Detect Neural Processing Units (AMD XDNA, Qualcomm, MediaTek, Intel)
    fn detect_npu() -> Option<RuntimeInfo> {
        #[cfg(windows)]
        {
            // Windows: check for AMD Ryzen AI NPU (XDNA) or Intel NPU via PowerShell
            let has_amd_npu = std::process::Command::new("powershell")
                .args([
                    "-NoProfile",
                    "-Command",
                    "Get-CimInstance -ClassName Win32_PnPEntity -ErrorAction SilentlyContinue | Where-Object { $_.Name -match '(?i)(NPU|Neural Processor|AI Accelerator|XDNA|Ryzen AI)' } | ForEach-Object { $_.Name }"
                ])
                .output()
                .map(|output| {
                    if output.status.success() {
                        let stdout = String::from_utf8_lossy(&output.stdout);
                        let lower = stdout.to_lowercase();
                        lower.contains("npu")
                            || lower.contains("neural")
                            || lower.contains("xdna")
                            || lower.contains("ai accelerator")
                            || lower.contains("ryzen ai")
                            || lower.contains("intel npu")
                    } else {
                        false
                    }
                })
                .unwrap_or(false);

            if has_amd_npu {
                return Some(RuntimeInfo {
                    detected_runtime: Runtime::NPU,
                    is_available: true,
                    compute_capability: Some("AI Accelerator".to_string()),
                    memory_gb: Some(2.0),
                    device_count: Some(1),
                });
            }
        }
        // Check for common NPU environments
        let has_npu_env = std::env::var("NPU_DEVICE").is_ok()
            || std::env::var("QUALCOMM_NPU").is_ok()
            || std::env::var("MEDIATEK_NPU").is_ok();

        let npu_indicators = [
            "/sys/devices/platform/soc/*/npu", // Qualcomm NPUs
            "/sys/devices/virtual/npu",        // Generic NPU
        ];

        if has_npu_env
            || npu_indicators.iter().any(|indicator| {
                if let Some(path) = indicator.strip_prefix("/") {
                    std::path::Path::new(path).exists()
                } else {
                    false
                }
            })
        {
            return Some(RuntimeInfo {
                detected_runtime: Runtime::NPU,
                is_available: true,
                compute_capability: Some("AI Accelerator".to_string()),
                memory_gb: Some(2.0), // Typical NPU memory
                device_count: Some(1),
            });
        }
        None
    }

    /// CPU is always available as fallback
    fn detect_cpu() -> Option<RuntimeInfo> {
        Some(RuntimeInfo {
            detected_runtime: Runtime::CPU,
            is_available: true,
            compute_capability: None,
            memory_gb: Self::detect_system_memory(),
            device_count: Some(
                std::thread::available_parallelism()
                    .map(|n| n.get())
                    .unwrap_or(1),
            ),
        })
    }

    #[cfg(target_os = "macos")]
    fn is_apple_silicon() -> bool {
        std::process::Command::new("sysctl")
            .arg("hw.optional.arm64")
            .output()
            .map(|output| String::from_utf8_lossy(&output.stdout).contains("1"))
            .unwrap_or(false)
    }

    #[cfg(not(target_os = "macos"))]
    #[allow(dead_code)]
    fn is_apple_silicon() -> bool {
        false
    }

    fn detect_gpu_memory() -> Option<f32> {
        // Try NVIDIA SMI first
        if let Ok(output) = std::process::Command::new("nvidia-smi")
            .args(["--query-gpu=memory.total", "--format=csv,noheader,nounits"])
            .output()
        {
            if output.status.success() {
                let stdout = String::from_utf8_lossy(&output.stdout);
                if let Some(line) = stdout.lines().next() {
                    if let Ok(mib) = line.trim().parse::<f32>() {
                        return Some(mib / 1024.0);
                    }
                }
            }
        }

        // Try ROCm SMI for AMD GPUs
        if let Ok(output) = std::process::Command::new("rocm-smi")
            .args(["--showmeminfo", "vram"])
            .output()
        {
            if output.status.success() {
                let stdout = String::from_utf8_lossy(&output.stdout);
                if let Some(line) = stdout.lines().find(|l| l.contains("Total Memory")) {
                    let val = line.split(':').nth(1)?.trim().to_lowercase();
                    let num: f32 = val.split_whitespace().next()?.parse().ok()?;
                    if val.contains("gb") {
                        return Some(num);
                    }
                    if val.contains("mb") {
                        return Some(num / 1024.0);
                    }
                }
            }
        }

        // Windows PowerShell fallback for any GPU
        #[cfg(windows)]
        {
            if let Ok(output) = std::process::Command::new("powershell")
                .args([
                    "-NoProfile",
                    "-Command",
                    "Get-CimInstance Win32_VideoController | Select-Object -ExpandProperty AdapterRAM"
                ])
                .output()
            {
                if output.status.success() {
                    let stdout = String::from_utf8_lossy(&output.stdout);
                    for line in stdout.lines() {
                        if let Ok(bytes) = line.trim().parse::<f64>() {
                            if bytes > 0.0 {
                                return Some((bytes / 1_073_741_824.0) as f32);
                            }
                        }
                    }
                }
            }
        }

        None
    }

    fn detect_system_memory() -> Option<f32> {
        // Get total system RAM in GB
        #[cfg(target_os = "linux")]
        {
            if let Ok(output) = std::process::Command::new("free").arg("-g").output() {
                if let Ok(text) = String::from_utf8(output.stdout) {
                    if let Some(line) = text.lines().next() {
                        if let Some(mem_str) = line.split_whitespace().nth(1) {
                            if let Ok(mem) = mem_str.parse::<f32>() {
                                return Some(mem);
                            }
                        }
                    }
                }
            }
            Some(8.0) // Default
        }

        #[cfg(target_os = "macos")]
        {
            if let Ok(output) = std::process::Command::new("sysctl")
                .arg("-n")
                .arg("hw.memsize")
                .output()
            {
                if let Ok(text) = String::from_utf8(output.stdout) {
                    if let Ok(bytes) = text.trim().parse::<f64>() {
                        return Some((bytes / 1_073_741_824.0) as f32); // Convert to GB
                    }
                }
            }
            Some(16.0) // Default for Mac
        }

        #[cfg(windows)]
        {
            Some(16.0) // Default for Windows
        }

        #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
        {
            Some(8.0) // Generic default
        }
    }
}

/// Model registry with runtime-specific availability
pub struct ModelRegistry;

impl ModelRegistry {
    /// Get all models optimized for a specific runtime
    pub fn models_for_runtime(runtime: Runtime) -> Vec<ModelInfo> {
        Self::all_models()
            .into_iter()
            .filter(|m| m.recommended_runtimes.contains(&runtime))
            .collect()
    }

    /// Get all available models
    pub fn all_models() -> Vec<ModelInfo> {
        vec![
            // LIGHTWEIGHT MODELS (3B-7B) - Fast on all runtimes
            ModelInfo {
                name: "orca-mini".to_string(),
                parameters: "3B".to_string(),
                size_gb: 1.7,
                memory_required_gb: 2.0,
                recommended_runtimes: vec![Runtime::CPU, Runtime::NPU, Runtime::DirectML],
                inference_speed: ModelSpeed::Fast,
                quality_tier: QualityTier::Lightweight,
                use_cases: vec![
                    "Quick responses".to_string(),
                    "Edge devices".to_string(),
                    "Real-time chat".to_string(),
                ],
            },
            ModelInfo {
                name: "phi".to_string(),
                parameters: "3B".to_string(),
                size_gb: 2.0,
                memory_required_gb: 3.0,
                recommended_runtimes: vec![Runtime::CPU, Runtime::NPU, Runtime::DirectML],
                inference_speed: ModelSpeed::Fast,
                quality_tier: QualityTier::Lightweight,
                use_cases: vec![
                    "Mobile deployment".to_string(),
                    "Embedded systems".to_string(),
                    "Low-latency".to_string(),
                ],
            },
            ModelInfo {
                name: "mistral".to_string(),
                parameters: "7B".to_string(),
                size_gb: 4.1,
                memory_required_gb: 6.0,
                recommended_runtimes: vec![
                    Runtime::CPU,
                    Runtime::NPU,
                    Runtime::DirectML,
                    Runtime::CUDA,
                    Runtime::Metal,
                    Runtime::ROCm,
                ],
                inference_speed: ModelSpeed::Standard,
                quality_tier: QualityTier::Standard,
                use_cases: vec![
                    "General purpose".to_string(),
                    "Default choice".to_string(),
                    "Balanced quality/speed".to_string(),
                ],
            },
            ModelInfo {
                name: "neural-chat".to_string(),
                parameters: "7B".to_string(),
                size_gb: 4.0,
                memory_required_gb: 6.0,
                recommended_runtimes: vec![
                    Runtime::CPU,
                    Runtime::DirectML,
                    Runtime::CUDA,
                    Runtime::Metal,
                ],
                inference_speed: ModelSpeed::Standard,
                quality_tier: QualityTier::Standard,
                use_cases: vec![
                    "Conversational AI".to_string(),
                    "Chat applications".to_string(),
                    "Instruction following".to_string(),
                ],
            },
            // STANDARD MODELS (7B-13B) - Good quality/speed balance
            ModelInfo {
                name: "llama2".to_string(),
                parameters: "7B".to_string(),
                size_gb: 3.8,
                memory_required_gb: 5.5,
                recommended_runtimes: vec![
                    Runtime::CPU,
                    Runtime::DirectML,
                    Runtime::CUDA,
                    Runtime::Metal,
                    Runtime::ROCm,
                ],
                inference_speed: ModelSpeed::Standard,
                quality_tier: QualityTier::Standard,
                use_cases: vec![
                    "Text generation".to_string(),
                    "Code generation".to_string(),
                    "Versatile tasks".to_string(),
                ],
            },
            ModelInfo {
                name: "openhermes".to_string(),
                parameters: "7B".to_string(),
                size_gb: 4.1,
                memory_required_gb: 6.0,
                recommended_runtimes: vec![
                    Runtime::CPU,
                    Runtime::DirectML,
                    Runtime::CUDA,
                    Runtime::Metal,
                ],
                inference_speed: ModelSpeed::Standard,
                quality_tier: QualityTier::Standard,
                use_cases: vec![
                    "Instruction following".to_string(),
                    "Question answering".to_string(),
                    "Reasoning tasks".to_string(),
                ],
            },
            ModelInfo {
                name: "llama2-13b".to_string(),
                parameters: "13B".to_string(),
                size_gb: 7.3,
                memory_required_gb: 10.0,
                recommended_runtimes: vec![
                    Runtime::DirectML,
                    Runtime::CUDA,
                    Runtime::Metal,
                    Runtime::ROCm,
                ],
                inference_speed: ModelSpeed::Standard,
                quality_tier: QualityTier::Premium,
                use_cases: vec![
                    "Complex reasoning".to_string(),
                    "Advanced reasoning".to_string(),
                    "Long context".to_string(),
                ],
            },
            // PREMIUM MODELS (13B-70B) - High quality, requires GPU
            ModelInfo {
                name: "mistral-medium".to_string(),
                parameters: "13B".to_string(),
                size_gb: 8.0,
                memory_required_gb: 12.0,
                recommended_runtimes: vec![
                    Runtime::DirectML,
                    Runtime::CUDA,
                    Runtime::Metal,
                    Runtime::ROCm,
                ],
                inference_speed: ModelSpeed::Slow,
                quality_tier: QualityTier::Premium,
                use_cases: vec![
                    "High quality responses".to_string(),
                    "Complex analysis".to_string(),
                    "Multi-step reasoning".to_string(),
                ],
            },
            ModelInfo {
                name: "llama2-70b".to_string(),
                parameters: "70B".to_string(),
                size_gb: 39.0,
                memory_required_gb: 48.0,
                recommended_runtimes: vec![Runtime::DirectML, Runtime::CUDA, Runtime::ROCm],
                inference_speed: ModelSpeed::Slow,
                quality_tier: QualityTier::Premium,
                use_cases: vec![
                    "Expert-level reasoning".to_string(),
                    "Complex code".to_string(),
                    "Research applications".to_string(),
                ],
            },
            // SPECIALIZED MODELS
            ModelInfo {
                name: "codeup".to_string(),
                parameters: "13B".to_string(),
                size_gb: 7.5,
                memory_required_gb: 10.0,
                recommended_runtimes: vec![Runtime::DirectML, Runtime::CUDA, Runtime::Metal],
                inference_speed: ModelSpeed::Slow,
                quality_tier: QualityTier::Specialized,
                use_cases: vec![
                    "Code generation".to_string(),
                    "Code completion".to_string(),
                    "Programming assistance".to_string(),
                ],
            },
            ModelInfo {
                name: "dolphin-mixtral".to_string(),
                parameters: "8x7B".to_string(),
                size_gb: 26.0,
                memory_required_gb: 32.0,
                recommended_runtimes: vec![Runtime::DirectML, Runtime::CUDA, Runtime::ROCm],
                inference_speed: ModelSpeed::Slow,
                quality_tier: QualityTier::Specialized,
                use_cases: vec![
                    "Advanced conversations".to_string(),
                    "High complexity tasks".to_string(),
                    "Multi-task handling".to_string(),
                ],
            },
        ]
    }

    /// Get model recommendations based on system specs
    pub fn recommend_models(runtime: Runtime, available_memory_gb: f32) -> Vec<ModelInfo> {
        Self::models_for_runtime(runtime)
            .into_iter()
            .filter(|m| m.memory_required_gb <= available_memory_gb)
            .collect()
    }

    /// Get best model for runtime (fastest/highest quality balance)
    pub fn best_for_runtime(runtime: Runtime) -> Option<ModelInfo> {
        let models = Self::models_for_runtime(runtime);

        // Prefer standard quality tier, then premium, then lightweight
        models
            .iter()
            .find(|m| m.quality_tier == QualityTier::Standard)
            .or_else(|| {
                models
                    .iter()
                    .find(|m| m.quality_tier == QualityTier::Premium)
            })
            .or_else(|| {
                models
                    .iter()
                    .find(|m| m.quality_tier == QualityTier::Lightweight)
            })
            .cloned()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Mutex, OnceLock};

    static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();

    fn with_runtime_env<R>(runtime: &str, force: Option<&str>, f: impl FnOnce() -> R) -> R {
        let _guard = ENV_LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .expect("env lock poisoned");

        let prev_runtime = std::env::var("GHOSTLINK_RUNTIME").ok();
        let prev_force = std::env::var("GHOSTLINK_FORCE_RUNTIME").ok();

        std::env::set_var("GHOSTLINK_RUNTIME", runtime);
        match force {
            Some(v) => std::env::set_var("GHOSTLINK_FORCE_RUNTIME", v),
            None => std::env::remove_var("GHOSTLINK_FORCE_RUNTIME"),
        }

        let out = f();

        match prev_runtime {
            Some(v) => std::env::set_var("GHOSTLINK_RUNTIME", v),
            None => std::env::remove_var("GHOSTLINK_RUNTIME"),
        }
        match prev_force {
            Some(v) => std::env::set_var("GHOSTLINK_FORCE_RUNTIME", v),
            None => std::env::remove_var("GHOSTLINK_FORCE_RUNTIME"),
        }

        out
    }

    #[test]
    fn test_runtime_detection() {
        let runtimes = RuntimeDetector::detect();
        assert!(!runtimes.is_empty(), "CPU should always be detected");
    }

    #[test]
    fn test_runtime_always_detected() {
        let primary = RuntimeDetector::detect_primary();
        // At worst, CPU should be available as fallback
        let valid = matches!(
            primary,
            Runtime::CPU
                | Runtime::DirectML
                | Runtime::CUDA
                | Runtime::ROCm
                | Runtime::Metal
                | Runtime::NPU
        );
        assert!(valid, "A runtime should always be detected");
    }

    #[test]
    fn test_model_registry() {
        let models = ModelRegistry::all_models();
        assert!(!models.is_empty());

        let cpu_models = ModelRegistry::models_for_runtime(Runtime::CPU);
        assert!(!cpu_models.is_empty(), "CPU models should be available");
    }

    #[test]
    fn test_model_recommendations() {
        let recommended = ModelRegistry::recommend_models(Runtime::CPU, 8.0);
        assert!(!recommended.is_empty());
    }

    #[test]
    fn test_best_model() {
        let best = ModelRegistry::best_for_runtime(Runtime::CPU);
        assert!(best.is_some());
    }

    #[test]
    fn test_rocm_models_include_amd_compatible_models() {
        let rocm_models = ModelRegistry::models_for_runtime(Runtime::ROCm);
        assert!(
            !rocm_models.is_empty(),
            "ROCm should have compatible models"
        );

        let names: Vec<&str> = rocm_models.iter().map(|m| m.name.as_str()).collect();
        assert!(
            names.contains(&"mistral"),
            "mistral should be ROCm compatible"
        );
        assert!(
            names.contains(&"llama2"),
            "llama2 should be ROCm compatible"
        );
        assert!(
            names.contains(&"llama2-13b"),
            "llama2-13b should be ROCm compatible"
        );
    }

    #[test]
    fn test_rocm_best_model() {
        let best = ModelRegistry::best_for_runtime(Runtime::ROCm);
        assert!(best.is_some());
        assert_eq!(best.unwrap().quality_tier, QualityTier::Standard);
    }

    #[test]
    fn test_rocm_model_recommendations_fit_memory() {
        let recommended = ModelRegistry::recommend_models(Runtime::ROCm, 12.0);
        assert!(!recommended.is_empty());
        for model in &recommended {
            assert!(model.memory_required_gb <= 12.0);
        }
    }

    #[test]
    fn test_rocm_recommendation_filters_by_vram() {
        let limited = ModelRegistry::recommend_models(Runtime::ROCm, 6.0);
        let abundant = ModelRegistry::recommend_models(Runtime::ROCm, 48.0);
        assert!(
            limited.len() < abundant.len(),
            "More VRAM should allow more models"
        );
    }

    #[cfg(feature = "rocm")]
    #[test]
    fn test_rocm_detection_is_available() {
        let runtimes = RuntimeDetector::detect();
        // On a system without AMD ROCm installed, ROCm detection returns no entry,
        // but the detection should at least run without panicking.
        assert!(
            !runtimes.is_empty(),
            "Runtime detection should always return at least CPU"
        );
    }

    #[test]
    fn test_runtime_from_str_parsing() {
        assert_eq!("cuda".parse::<Runtime>().unwrap(), Runtime::CUDA);
        assert_eq!("RoCm".parse::<Runtime>().unwrap(), Runtime::ROCm);
        assert_eq!("DirectML".parse::<Runtime>().unwrap(), Runtime::DirectML);
        assert_eq!("npu".parse::<Runtime>().unwrap(), Runtime::NPU);
        assert_eq!("cpu".parse::<Runtime>().unwrap(), Runtime::CPU);
        assert!("unknown".parse::<Runtime>().is_err());
    }

    #[test]
    fn test_runtime_override_force_ignores_detection() {
        let runtime = with_runtime_env("metal", Some("true"), RuntimeDetector::detect_primary);
        assert_eq!(runtime, Runtime::Metal);
    }

    #[test]
    fn test_runtime_override_falls_back_when_not_forced() {
        let runtime = with_runtime_env("metal", None, RuntimeDetector::detect_primary);
        assert!(matches!(
            runtime,
            Runtime::Metal
                | Runtime::CPU
                | Runtime::CUDA
                | Runtime::ROCm
                | Runtime::DirectML
                | Runtime::NPU
        ));
    }
}