portablesource-rs 1.2.8

Portable AI/ML Environment Manager - Rust implementation
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
// portablesource
// Copyright (C) 2025  PortableSource / NeuroDonu
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use portablesource_rs::{
    cli::{Cli, Commands},
    config::ConfigManager,
    gpu::GpuDetector,
    utils,
    envs_manager::PortableEnvironmentManager,
    repository_installer::RepositoryInstaller,
    PortableSourceError,
    Result,
};
use log::{info, error, warn, LevelFilter};
use std::path::{PathBuf, Path};
use std::sync::OnceLock;

// Глобальная переменная для хранения install_path в текущей сессии
static SESSION_INSTALL_PATH: OnceLock<PathBuf> = OnceLock::new();

#[tokio::main]
async fn main() {
    // Parse command line arguments
    let cli = Cli::parse_args();

    // Initialize logging with default INFO (DEBUG if --debug)
    let mut builder = env_logger::Builder::from_default_env();
    if cli.debug { builder.filter_level(LevelFilter::Debug); } else { builder.filter_level(LevelFilter::Info); }
    let _ = builder.try_init();
    
    // Run the application
    if let Err(e) = run(cli).await {
        error!("Application error: {}", e);
        std::process::exit(1);
    }
}

async fn run(cli: Cli) -> Result<()> {
    // Fast-path: commands that don't require config or install_path
    match cli.command.as_ref() {
        Some(Commands::CheckGpu) => {
            return check_gpu();
        }
        Some(Commands::Version) => {
            utils::show_version();
            return Ok(());
        }
        _ => {}
    }

    // Initialize configuration manager
    let mut config_manager = ConfigManager::new(None)?;
    
    // Handle install path from CLI, registry, config, or default
    // Skip interactive prompt for commands that don't need install_path
    #[cfg(windows)]
    let needs_install_path = matches!(cli.command, Some(Commands::SetupEnv) | Some(Commands::InstallRepo { .. }) | Some(Commands::UpdateRepo { .. }) | Some(Commands::DeleteRepo { .. }) | Some(Commands::ListRepos) | Some(Commands::CheckEnv) | Some(Commands::Pack { .. }));
    #[cfg(unix)]
    let needs_install_path = matches!(cli.command, Some(Commands::SetupEnv) | Some(Commands::InstallRepo { .. }) | Some(Commands::UpdateRepo { .. }) | Some(Commands::DeleteRepo { .. }) | Some(Commands::ListRepos) | Some(Commands::ChangePath) | Some(Commands::CheckEnv) | Some(Commands::Uninstall));
    #[cfg(all(not(windows), not(unix)))]
    let needs_install_path = matches!(cli.command, Some(Commands::SetupEnv) | Some(Commands::InstallRepo { .. }) | Some(Commands::UpdateRepo { .. }) | Some(Commands::DeleteRepo { .. }) | Some(Commands::ListRepos) | Some(Commands::CheckEnv));

    let install_path = if let Some(cached_path) = SESSION_INSTALL_PATH.get() {
        // Используем сохраненный путь из текущей сессии
        cached_path.clone()
    } else if let Some(path) = cli.install_path {
        let validated_path = utils::validate_and_create_path(&path)?;
        config_manager.set_install_path(validated_path.clone())?;
        
        // Сохраняем путь в сессии
        let _ = SESSION_INSTALL_PATH.set(validated_path.clone());
        
        // Портативная логика только для Windows
        #[cfg(windows)]
        {
            // Просто запоминаем путь установки для текущей сессии
            // Копирование exe произойдет после команды setup-env
        }
        
        // Для Linux сохраняем в реестр как раньше
        #[cfg(unix)]
        {
            let _ = utils::save_install_path_to_registry(&validated_path);
        }
        // Для Windows больше не используем реестр - только портативный режим
        
        validated_path
    } else {
        // Портативная логика только для Windows
        #[cfg(windows)]
        {
            // Путь не указан - определяем автоматически
            let current_dir = std::env::current_exe()?
                .parent()
                .ok_or_else(|| PortableSourceError::installation("Cannot determine current directory".to_string()))?
                .to_path_buf();
            
            // Проверяем, находимся ли мы уже в установленной директории
            if !utils::is_first_installation(&current_dir) {
                // Мы в установленной директории - используем её
                // Сохраняем путь в сессии
                let _ = SESSION_INSTALL_PATH.set(current_dir.clone());
                current_dir
            } else {
                // Первый запуск - нужно выбрать путь установки
                if !needs_install_path {
                    // Для команд, не требующих установки, используем текущую директорию
                    // Сохраняем путь в сессии
                    let _ = SESSION_INSTALL_PATH.set(current_dir.clone());
                    current_dir
                } else {
                    // Для команд установки показываем интерактивный выбор
                    let default_path = std::env::current_dir()?.join("portablesource");
                    println!("Choose installation path (default: {})", default_path.display());
                    print!("Enter path or press Enter: ");
                    use std::io::{self, Write};
                    io::stdout().flush().ok();
                    let mut input = String::new();
                    io::stdin().read_line(&mut input).ok();
                    let input = input.trim();
                    
                    let chosen_path = if input.is_empty() {
                        default_path
                    } else {
                        PathBuf::from(input)
                    };
                    
                    let validated_path = utils::validate_and_create_path(&chosen_path)?;
                    utils::copy_executable_to_install_path(&validated_path)?;
                    // Сохраняем путь в сессии
                    let _ = SESSION_INSTALL_PATH.set(validated_path.clone());
                    validated_path
                }
            }
        }
        
        // Для Linux оставляем старую логику
        #[cfg(unix)]
        {
            if !needs_install_path {
                // Use existing config or silent defaults without prompting
                if let Some(path) = utils::load_install_path_from_registry()? {
                    utils::validate_and_create_path(&path)?
                } else if !config_manager.get_config().install_path.as_os_str().is_empty() {
                    let existing = config_manager.get_config().install_path.clone();
                    utils::validate_and_create_path(&existing)?
                } else {
                    let default_path = utils::default_install_path_linux();
                    utils::validate_and_create_path(&default_path)?
                }
            } else if let Some(path) = utils::load_install_path_from_registry()? {
                let validated_path = utils::validate_and_create_path(&path)?;
                config_manager.set_install_path(validated_path.clone())?;
                validated_path
            } else if !config_manager.get_config().install_path.as_os_str().is_empty() {
                let existing = config_manager.get_config().install_path.clone();
                if matches!(cli.command, Some(Commands::SetupEnv)) {
                    println!("\nCurrent installation path: {}", existing.display());
                    let chosen = utils::prompt_install_path_linux(&existing)?;
                    let _ = utils::save_install_path_to_registry(&chosen);
                    config_manager.set_install_path(chosen.clone())?;
                    chosen
                } else {
                    let validated_path = utils::validate_and_create_path(&existing)?;
                    config_manager.set_install_path(validated_path.clone())?;
                    validated_path
                }
            } else {
                if matches!(cli.command, Some(Commands::SetupEnv)) {
                    let default_path = utils::default_install_path_linux();
                    let chosen = utils::prompt_install_path_linux(&default_path)?;
                    let _ = utils::save_install_path_to_registry(&chosen);
                    config_manager.set_install_path(chosen.clone())?;
                    chosen
                } else {
                    let default_path = utils::default_install_path_linux();
                    utils::validate_and_create_path(&default_path)?
                }
            }
        }
    };
    
    // Всегда привязываем конфиг к install_path и сохраняем туда
    // (для Linux не требуем root и не используем /etc для persist)
    let _ = config_manager.set_install_path(install_path.clone());
    config_manager.set_config_path_to_install_dir();
    // Конфигурация больше не сохраняется на диск - только сессионные настройки
    info!("Using install path: {:?}", install_path);
    #[cfg(not(windows))]
    {
        // На Linux работаем как менеджер репозиториев без постоянного конфига
        // (используем только в памяти ConfigManager)
    }
    // Hydrate config from current environment (no extra save here)
    ensure_config_initialized(&mut config_manager)?;
    config_manager.hydrate_from_existing_env()?;

    // Linux: выбор режима CLOUD/DESK и базовая подготовка — только когда действительно готовим базу
    #[cfg(unix)]
    if matches!(cli.command, Some(Commands::SetupEnv)) {
        use portablesource_rs::utils::{detect_linux_mode, LinuxMode, detect_cuda_version_from_system, setup_micromamba_base_env};
        match detect_linux_mode() {
                        LinuxMode::Cloud => {
                info!("Linux CLOUD mode detected: using system git/python/cuda");
                let _cv_for_indexes = detect_cuda_version_from_system();
                let check = |name: &str| -> bool { utils::is_command_available(name) };
                let git_ok = check("git");
                let py_ok = check("python3") || check("python");
                let ff_ok = check("ffmpeg");
                let nvcc_ok = check("nvcc");
                println!(
                    "CLOUD requirements: git={} python={} ffmpeg={} nvcc={}",
                    if git_ok { "OK" } else { "Missing" },
                    if py_ok { "OK" } else { "Missing" },
                    if ff_ok { "OK" } else { "Missing" },
                    if nvcc_ok { "OK" } else { "Missing" }
                );
                if !(git_ok && py_ok && ff_ok) {
                    warn!("Some system tools missing; attempting to install missing packages (best-effort). You can also set PORTABLESOURCE_MODE=DESK.");
                    let _ = utils::prepare_linux_system();
                }
            }
            LinuxMode::Desk => {
                info!("Linux DESK mode detected: setting up micromamba base env");
                let cv = match detect_cuda_version_from_system() {
                    Some(_) => None,
                    None => {
                        if config_manager.has_cuda() {
                            if let Some(cuda_version) = config_manager.get_cuda_version() {
                                Some(match cuda_version {
                                    portablesource_rs::config::CudaVersion::Cuda128 => portablesource_rs::config::CudaVersionLinux::Cuda128,
                                    portablesource_rs::config::CudaVersion::Cuda124 => portablesource_rs::config::CudaVersionLinux::Cuda124,
                                    portablesource_rs::config::CudaVersion::Cuda118 => portablesource_rs::config::CudaVersionLinux::Cuda118,
                                })
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    }
                };
                setup_micromamba_base_env(&install_path, cv)?;
            }
        }
    }
    
    // Handle commands
    match cli.command.as_ref() {
        Some(Commands::SetupEnv) => {
            setup_environment(&install_path, &mut config_manager).await
        }
        #[cfg(unix)]
        Some(Commands::SetupReg) => {
            utils::save_install_path_to_registry(&install_path)?;
            println!("Installation path registered successfully");
            Ok(())
        }
        #[cfg(unix)]
        Some(Commands::Unregister) => {
            utils::delete_install_path_from_registry()?;
            println!("Installation path unregistered successfully");
            Ok(())
        }
        #[cfg(unix)]
        Some(Commands::Uninstall) => {
            utils::uninstall_portablesource(&install_path).await
        }
        #[cfg(unix)]
        Some(Commands::ChangePath) => {
            change_installation_path(&mut config_manager).await
        }
        Some(Commands::InstallRepo { repo, python_ver }) => {
            install_repository(repo, python_ver.as_deref(), &install_path, &config_manager).await
        }
        Some(Commands::UpdateRepo { repo }) => {
            update_repository(repo.clone(), &install_path, &config_manager).await
        }
        Some(Commands::DeleteRepo { repo }) => {
            delete_repository(repo, &install_path, &config_manager)
        }
        Some(Commands::ListRepos) => {
            list_repositories(&install_path, &config_manager)
        }
        Some(Commands::RunRepo { repo, args }) => {
            utils::run_repository(repo, &install_path, args).await
        }
        Some(Commands::SystemInfo) => {
            show_system_info(&mut config_manager).await
        }
        Some(Commands::CheckEnv) => {
            check_environment(&install_path, &config_manager).await
        }
        #[cfg(windows)]
        Some(Commands::InstallMsvc) => {
            utils::install_msvc_build_tools()
        }
        #[cfg(windows)]
        Some(Commands::CheckMsvc) => {
            let installed = utils::check_msvc_build_tools_installed();
            println!("MSVC Build Tools: {}", if installed { "Installed" } else { "Not installed" });
            Ok(())
        }
        Some(Commands::CheckGpu) => {
            check_gpu()
        }
        Some(Commands::Version) => {
            utils::show_version();
            Ok(())
        }
        #[cfg(windows)]
        Some(Commands::SetVersion { version }) => {
            set_python_version(version, &config_manager)
        }
        #[cfg(windows)]
        Some(Commands::Pack { repo }) => {
            pack_repository(repo, &install_path, &config_manager)
        }
        None => {
            // No command provided, show system info by default
            show_system_info(&mut config_manager).await
        }
    }
}

async fn setup_environment(install_path: &PathBuf, config_manager: &mut ConfigManager) -> Result<()> {
    // Create directory structure
    utils::create_directory_structure(install_path)?;
    
    // Windows: ставим портативные инструменты (tar zstd архивы)
    #[cfg(windows)]
    {
        // Initialize environment manager
        let env_manager = PortableEnvironmentManager::new(install_path.clone());
        // Setup environment via portable archives
        env_manager.setup_environment().await?;
    }

    // Linux/macOS: используем системный tar, готовим базу через micromamba
    #[cfg(unix)]
    {
        use portablesource_rs::utils::{detect_cuda_version_from_system, setup_micromamba_base_env};
        // Если системная CUDA есть — не ставим CUDA в базу
        let cv = match detect_cuda_version_from_system() {
            Some(_) => None,
            None => {
                if config_manager.has_cuda() {
                    if let Some(cuda_version) = config_manager.get_cuda_version() {
                        Some(match cuda_version {
                            portablesource_rs::config::CudaVersion::Cuda128 => portablesource_rs::config::CudaVersionLinux::Cuda128,
                            portablesource_rs::config::CudaVersion::Cuda124 => portablesource_rs::config::CudaVersionLinux::Cuda124,
                            portablesource_rs::config::CudaVersion::Cuda118 => portablesource_rs::config::CudaVersionLinux::Cuda118,
                        })
                    } else {
                        None
                    }
                } else {
                    None
                }
            }
        };
        setup_micromamba_base_env(install_path, cv)?;
    }
    
    // GPU detection is now handled dynamically by ConfigManager
    let gpu_detector = GpuDetector::new();
    if let Some(gpu_info) = gpu_detector.get_best_gpu()? {
        info!("Detected GPU: {}", gpu_info.name);
    } else {
        warn!("No GPU detected, using CPU backend");
    }
    
    // Mark environment as setup (сохранение один раз в конце)
    config_manager.get_config_mut().environment_setup_completed = true;
    // Не сохраняем здесь повторно: итоговый save будет ниже, после GPU-конфига
    
    // Сохранение конфигурации ровно один раз после всех шагов
    // Конфигурация больше не сохраняется на диск - только сессионные настройки

    // Executable was already copied during initial setup

    println!("Environment setup completed successfully!");
    Ok(())
}

#[cfg(unix)]
async fn change_installation_path(config_manager: &mut ConfigManager) -> Result<()> {
    println!("Enter new installation path:");
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).unwrap();
    let path = PathBuf::from(input.trim());
    
    let validated_path = utils::validate_and_create_path(&path)?;
    config_manager.set_install_path(validated_path.clone())?;
    // Для Windows больше не используем реестр - только сессионные настройки
    #[cfg(unix)]
    {
        utils::save_install_path_to_registry(&validated_path)?;
    }
    
    println!("Installation path changed to: {:?}", validated_path);
    Ok(())
}

async fn install_repository(repo: &str, python_ver: Option<&str>, install_path: &PathBuf, config_manager: &ConfigManager) -> Result<()> {
    let mut installer = RepositoryInstaller::new(install_path.clone(), config_manager.clone());
    
    // Set Python version context if specified
    if let Some(ver_str) = python_ver {
        if let Some(version) = portablesource_rs::config::PythonVersion::from_str(ver_str) {
            info!("Using Python version: {}", version.as_str());
            // The version will be used during dependency installation
        } else {
            return Err(PortableSourceError::config(format!("Invalid Python version: {}. Use 310 or 311", ver_str)));
        }
    }
    
    installer.install_repository(repo).await
}

async fn update_repository(repo: Option<String>, install_path: &PathBuf, config_manager: &ConfigManager) -> Result<()> {
    let mut installer = RepositoryInstaller::new(install_path.clone(), config_manager.clone());
    if let Some(name) = repo {
        return installer.update_repository(&name).await;
    }

    // Simple TUI: показать список и выбрать номер
    let labeled = installer.list_repositories_labeled()?;
    let names: Vec<String> = labeled.iter().map(|(raw, _)| raw.clone()).collect();
    if names.is_empty() {
        println!("No repositories installed");
        return Ok(());
    }

    println!("Select repository to update:\n");
    for (i, item) in labeled.iter().enumerate() {
        println!("  [{}] {}", i + 1, item.1);
    }
    println!("\nEnter number (or 0 to cancel): ");

    use std::io;
    let mut input = String::new();
    io::stdin().read_line(&mut input).ok();
    let trimmed = input.trim();
    let choice: usize = trimmed.parse().unwrap_or(0);
    if choice == 0 || choice > names.len() {
        println!("Cancelled.");
        return Ok(());
    }

    let selected = &names[choice - 1];
    installer.update_repository(selected).await
}

fn delete_repository(repo: &str, install_path: &PathBuf, config_manager: &ConfigManager) -> Result<()> {
    let installer = RepositoryInstaller::new(install_path.clone(), config_manager.clone());
    installer.delete_repository(repo)
}

fn list_repositories(install_path: &PathBuf, config_manager: &ConfigManager) -> Result<()> {
    let installer = RepositoryInstaller::new(install_path.clone(), config_manager.clone());
    let repos = installer.list_repositories()?;
    
    if repos.is_empty() {
        println!("No repositories installed");
    } else {
        println!("Installed repositories:");
        for repo in repos {
            println!("  - {}", repo);
        }
    }
    
    Ok(())
}

async fn show_system_info(config_manager: &mut ConfigManager) -> Result<()> {
    println!("=== PortableSource System Information ===");
    // Assemble config if empty
    ensure_config_initialized(config_manager)?;
    // Hydrate from existing ps_env and nvidia-smi
    config_manager.hydrate_from_existing_env()?;
    
    // Show configuration summary
    println!("\n{}", config_manager.get_config_summary());
    
    // Show system info
    // On Unix: if DESK mode, show only micromamba base tools; if CLOUD mode, show only system tools
    #[cfg(unix)]
    {
        use portablesource_rs::utils::{detect_linux_mode, LinuxMode};
        match detect_linux_mode() {
            LinuxMode::Desk => {
                let base_bin = config_manager
                    .get_config()
                    .install_path
                    .join("ps_env")
                    .join("mamba_env")
                    .join("bin");
                println!("\n=== Micromamba Base ===");
                if base_bin.exists() {
                    let check = |name: &str| base_bin.join(name).exists();
                    let py_ok = check("python") || check("python3");
                    let pip_ok = check("pip") || check("pip3");
                    let git_ok = check("git");
                    let ff_ok = check("ffmpeg");
                    println!("python: {}", if py_ok { "Available" } else { "Not found" });
                    println!("pip: {}", if pip_ok { "Available" } else { "Not found" });
                    println!("git: {}", if git_ok { "Available" } else { "Not found" });
                    println!("ffmpeg: {}", if ff_ok { "Available" } else { "Not found" });
                    let cuda_ok = base_bin.join("nvcc").exists();
                    println!("cuda: {}", if cuda_ok { "Available" } else { "Not found" });
                } else {
                    println!("Micromamba base not found at {}", base_bin.display());
                }
            }
            LinuxMode::Cloud => {
                println!("\n=== System Information (CLOUD) ===");
                let system_info = utils::get_system_info()?;
                println!("{}", system_info);
                println!("\nTip: set PORTABLESOURCE_MODE=DESK to force micromamba-based portable env on Linux.");
            }
        }
    }
    #[cfg(windows)]
    {
        println!("\n=== System Information ===");
        let system_info = utils::get_system_info()?;
        println!("{}", system_info);
    }
    
    // Show GPU info
    let gpu_detector = GpuDetector::new();
    if let Some(gpu_info) = gpu_detector.get_best_gpu()? {
        println!("\n=== GPU Information ===");
        println!("Name: {}", gpu_info.name);
        println!("Type: {:?}", gpu_info.gpu_type);
        println!("Memory: {} MB", gpu_info.memory_mb);
        if let Some(driver) = &gpu_info.driver_version {
            println!("Driver: {}", driver);
        }
    }
    
    Ok(())
}

fn ensure_config_initialized(config_manager: &mut ConfigManager) -> Result<()> {
    // Ensure install path set (already set in run(), but double-check)
    if config_manager.get_config().install_path.as_os_str().is_empty() {
        #[cfg(windows)]
        {
            // Для Windows используем только текущую директорию - без реестра
            let default_path = std::env::current_dir()?.join("portablesource");
            let validated = utils::validate_and_create_path(&default_path)?;
            config_manager.set_install_path(validated)?;
        }
        #[cfg(unix)]
        {
            if let Some(reg_path) = utils::load_install_path_from_registry()? {
                config_manager.set_install_path(reg_path)?;
            } else {
                let default_path = std::env::current_dir()?.join("portablesource");
                let validated = utils::validate_and_create_path(&default_path)?;
                config_manager.set_install_path(validated)?;
            }
        }
    }
    // Ensure environment vars in config
    if config_manager.get_config().environment_vars.is_none() {
        let _ = config_manager.configure_environment_vars();
    }
    // GPU detection is now handled dynamically by ConfigManager
    // No need to store GPU config as it's computed on-demand
    Ok(())
}

async fn check_environment(install_path: &PathBuf, _config_manager: &ConfigManager) -> Result<()> {
    println!("=== Environment Status ===");
    
    #[cfg(windows)]
    let env_manager = PortableEnvironmentManager::new(install_path.clone());
    #[cfg(unix)]
    let status = {
        let base_bin = install_path.join("ps_env").join("mamba_env").join("bin");
        base_bin.join("python").exists() && base_bin.join("git").exists() && base_bin.join("ffmpeg").exists()
    };
    #[cfg(windows)]
    let status = env_manager.check_environment_status()?;
    
    println!("Environment setup: {}", if status { "OK" } else { "Not setup" });
    #[cfg(windows)]
    println!("MSVC Build Tools: {}", if utils::check_msvc_build_tools_installed() { "Installed" } else { "Not installed" });
    
    // Check for tools
    println!("\n=== Available Tools ===");
    #[cfg(unix)]
    {
        let base_bin = install_path.join("ps_env").join("mamba_env").join("bin");
        let chk = |name: &str| {
            let p = base_bin.join(name);
            std::fs::metadata(&p).is_ok() || p.exists()
        };
        println!("git: {}", if chk("git") { "Available" } else { "Not found" });
        println!("python: {}", if chk("python") || chk("python3") { "Available" } else { "Not found" });
        println!("ffmpeg: {}", if chk("ffmpeg") { "Available" } else { "Not found" });
        // CUDA availability (via nvcc) in micromamba base
        let nvcc_path = base_bin.join("nvcc");
        let cuda_ok = std::fs::metadata(&nvcc_path).is_ok();
        println!("cuda: {}", if cuda_ok { "Available" } else { "Not found" });
    }
    #[cfg(windows)]
    {
        let tools = ["git", "python", "ffmpeg"];
        for tool in &tools {
            let available = utils::is_command_available(tool);
            println!("{}: {}", tool, if available { "Available" } else { "Not found" });
        }
    }
    
    Ok(())
}



fn check_gpu() -> Result<()> {
    let gpu_detector = GpuDetector::new();
    let has_nvidia = gpu_detector.has_nvidia_gpu();
    println!("{}", has_nvidia);
    Ok(())
}

#[cfg(windows)]
fn set_python_version(version: &str, config_manager: &ConfigManager) -> Result<()> {
    use portablesource_rs::config::PythonVersion;
    
    let python_version = PythonVersion::from_str(version)
        .ok_or_else(|| PortableSourceError::config(format!("Invalid Python version: {}. Use 310 or 311", version)))?;
    
    config_manager.set_default_python_version(python_version)?;
    println!("Default Python version set to: {}", version);
    
    // Check if the version is installed
    if !config_manager.is_python_version_installed(&config_manager.get_default_python_version()) {
        println!("Warning: Python {} is not installed. Run 'setup-env' to install it.", version);
    }
    
    Ok(())
}

#[cfg(windows)]
fn pack_repository(repo: &str, install_path: &PathBuf, _config_manager: &ConfigManager) -> Result<()> {
    use std::fs;
    
    println!("Packing repository: {}", repo);
    
    // Check if repo exists
    let repos_path = install_path.join("repos");
    let repo_path = repos_path.join(repo);
    if !repo_path.exists() {
        return Err(PortableSourceError::repository(format!("Repository '{}' not found", repo)));
    }
    
    // Check if environment exists
    let envs_path = install_path.join("envs");
    let env_path = envs_path.join(repo);
    if !env_path.exists() {
        return Err(PortableSourceError::repository(format!("Environment for '{}' not found", repo)));
    }
    
    // Create pack directory
    let pack_path = install_path.join("pack");
    let pack_repo_path = pack_path.join(repo);
    if pack_repo_path.exists() {
        println!("Removing existing pack directory...");
        fs::remove_dir_all(&pack_repo_path)?;
    }
    fs::create_dir_all(&pack_repo_path)?;
    
    // Create ps_env directory in pack
    let pack_ps_env = pack_repo_path.join("ps_env");
    fs::create_dir_all(&pack_ps_env)?;
    
    println!("Copying portable environment...");
    
    // Copy CUDA if exists
    let ps_env_path = install_path.join("ps_env");
    let cuda_src = ps_env_path.join("CUDA");
    if cuda_src.exists() {
        println!("  - Copying CUDA...");
        let cuda_dst = pack_ps_env.join("CUDA");
        copy_dir_recursive(&cuda_src, &cuda_dst)?;
    }
    
    // Copy git
    let git_src = ps_env_path.join("git");
    if git_src.exists() {
        println!("  - Copying git...");
        let git_dst = pack_ps_env.join("git");
        copy_dir_recursive(&git_src, &git_dst)?;
    }
    
    // Copy ffmpeg
    let ffmpeg_src = ps_env_path.join("ffmpeg");
    if ffmpeg_src.exists() {
        println!("  - Copying ffmpeg...");
        let ffmpeg_dst = pack_ps_env.join("ffmpeg");
        copy_dir_recursive(&ffmpeg_src, &ffmpeg_dst)?;
    }
    
    // Copy repository environment
    println!("  - Copying repository environment...");
    let pack_envs = pack_repo_path.join("envs");
    fs::create_dir_all(&pack_envs)?;
    let env_dst = pack_envs.join(repo);
    copy_dir_recursive(&env_path, &env_dst)?;
    
    // Copy repository
    println!("  - Copying repository files...");
    let pack_repos = pack_repo_path.join("repos");
    fs::create_dir_all(&pack_repos)?;
    let repo_dst = pack_repos.join(repo);
    copy_dir_recursive(&repo_path, &repo_dst)?;
    
    // Create run batch file
    println!("  - Creating run_{}.bat...", repo);
    let run_bat_path = pack_repo_path.join(format!("run_{}.bat", repo));
    let bat_content = format!(
        "@echo off\n\
         echo Starting {}...\n\
         cd /d \"%~dp0\\repos\\{}\"\n\
         call \"start_{}.bat\"\n\
         pause\n",
        repo, repo, repo
    );
    fs::write(&run_bat_path, bat_content)?;
    
    println!("\nRepository '{}' packed successfully!", repo);
    println!("Pack location: {}", pack_repo_path.display());
    println!("To run: execute run_{}.bat in the pack directory", repo);
    
    Ok(())
}

/// Helper function to copy directories recursively
fn copy_dir_recursive(from: &Path, to: &Path) -> Result<()> {
    use std::fs;
    
    fs::create_dir_all(to)?;
    for entry in fs::read_dir(from)? {
        let entry = entry?;
        let ty = entry.file_type()?;
        let src = entry.path();
        let dst = to.join(entry.file_name());
        if ty.is_dir() {
            copy_dir_recursive(&src, &dst)?;
        } else {
            fs::copy(&src, &dst)?;
        }
    }
    Ok(())
}