biovault 0.1.48

A bioinformatics data vault CLI tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
use anyhow::Result;
use clap::{Parser, Subcommand};
use tracing_subscriber::{fmt, prelude::*, EnvFilter};

use biovault::cli;

use cli::commands;

// Validator for example names that also shows available examples
fn validate_example_name(s: &str) -> Result<String, String> {
    let examples = cli::examples::list_examples();
    if examples.contains(&s.to_string()) {
        Ok(s.to_string())
    } else {
        Err(format!(
            "Unknown example '{}'. Available examples: {}",
            s,
            examples.join(", ")
        ))
    }
}

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

    #[test]
    fn validate_example_name_accepts_known_and_rejects_unknown() {
        let list = cli::examples::list_examples();
        // When at least one example exists, it validates
        if let Some(first) = list.first() {
            assert!(validate_example_name(first).is_ok());
        }
        // Unknown example returns Err with helpful message
        let err = validate_example_name("__definitely_not_real__").unwrap_err();
        assert!(err.contains("Unknown example"));
    }
}

#[derive(Parser)]
#[command(
    name = "bv",
    version,
    about = "BioVault - A bioinformatics data management CLI",
    long_about = None
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,

    #[arg(short, long, global = true, help = "Increase verbosity")]
    verbose: bool,

    #[arg(long, global = true, help = "Path to config file")]
    config: Option<String>,
}

#[derive(Subcommand)]
enum Commands {
    #[command(about = "Check for updates and install the latest version")]
    Update,
    #[command(about = "Initialize a new BioVault repository")]
    Init {
        #[arg(
            help = "Email address for the vault configuration (optional, will detect from SYFTBOX_EMAIL)"
        )]
        email: Option<String>,

        #[arg(short, long, help = "Automatically accept defaults (for testing)")]
        quiet: bool,
    },

    #[command(about = "Show system information")]
    Info {
        #[arg(long, help = "Output as JSON")]
        json: bool,
    },

    #[command(about = "Check for required dependencies")]
    Check {
        #[arg(long, help = "Output as JSON")]
        json: bool,
    },

    #[command(about = "Setup environment for known systems (e.g., Google Colab)")]
    Setup,

    #[command(about = "Project management commands")]
    Project {
        #[command(subcommand)]
        command: ProjectCommands,
    },

    #[command(about = "Run a project workflow with Nextflow")]
    Run {
        #[arg(help = "Path to project directory")]
        project_folder: String,

        #[arg(
            help = "Participant source: local file path, Syft URL, or HTTP URL (with optional #fragment)"
        )]
        participant_source: String,

        #[arg(long, help = "Use mock data if available")]
        test: bool,

        #[arg(long, help = "Auto-confirm file downloads")]
        download: bool,

        #[arg(long, help = "Show commands without executing")]
        dry_run: bool,

        #[arg(long, default_value = "true", help = "Run with Docker")]
        with_docker: bool,

        #[arg(long, help = "Nextflow work directory")]
        work_dir: Option<String>,

        #[arg(long, help = "Resume from previous run")]
        resume: bool,

        #[arg(long, help = "Template to use (default, snp, etc.)")]
        template: Option<String>,

        #[arg(long, help = "Custom results directory name")]
        results_dir: Option<String>,
    },

    #[command(name = "sample-data", about = "Manage sample data")]
    SampleData {
        #[command(subcommand)]
        command: SampleDataCommands,
    },

    #[command(about = "Manage participants")]
    Participant {
        #[command(subcommand)]
        command: ParticipantCommands,
    },

    #[command(about = "Manage biobank data publishing")]
    Biobank {
        #[command(subcommand)]
        command: BiobankCommands,
    },

    #[command(about = "Manage BioVault configuration")]
    Config {
        #[command(subcommand)]
        command: Option<ConfigCommands>,

        #[arg(long, help = "Output as JSON")]
        json: bool,
    },

    #[command(about = "FASTQ file operations")]
    Fastq {
        #[command(subcommand)]
        command: FastqCommands,
    },

    #[command(about = "Submit a project to another biobank via SyftBox")]
    Submit {
        #[arg(help = "Path to project directory (use '.' for current directory)")]
        project_path: String,

        #[arg(
            help = "Destination: either a datasite email (e.g., user@domain.com) or full Syft URL (e.g., syft://user@domain.com/public/biovault/participants.yaml#participants.ID)"
        )]
        destination: String,

        #[arg(long, help = "Skip interactive prompts, use defaults")]
        non_interactive: bool,

        #[arg(
            long,
            help = "Force resubmission even if project was already submitted"
        )]
        force: bool,
    },

    #[command(about = "Clean up stale database locks")]
    Cleanup {
        #[arg(long, help = "Clean all locks in all virtualenvs")]
        all: bool,
    },

    #[command(about = "View and manage inbox messages")]
    Inbox {
        #[arg(short = 'i', long, help = "Interactive mode (default)")]
        interactive: bool,

        #[arg(long, help = "Plain, non-interactive list output")]
        plain: bool,

        #[arg(short = 's', long, help = "Show sent messages")]
        sent: bool,

        #[arg(short = 'a', long, help = "Show all messages (including deleted)")]
        all: bool,

        #[arg(short = 'u', long, help = "Show only unread messages")]
        unread: bool,

        #[arg(short = 'p', long, help = "Show project submissions")]
        projects: bool,

        #[arg(
            short = 't',
            long,
            help = "Filter by message type (text/project/request)"
        )]
        message_type: Option<String>,

        #[arg(short = 'f', long, help = "Filter by sender")]
        from: Option<String>,

        #[arg(long, help = "Search messages by content")]
        search: Option<String>,
    },

    #[command(about = "Manage messages via SyftBox RPC")]
    Message {
        #[command(subcommand)]
        command: MessageCommands,
    },

    #[command(about = "Sample sheet operations")]
    Samplesheet {
        #[command(subcommand)]
        command: SamplesheetCommands,
    },

    #[command(about = "Manage the BioVault daemon for automatic message processing")]
    Daemon {
        #[command(subcommand)]
        command: DaemonCommands,
    },

    #[command(
        name = "hard-reset",
        about = "Delete all BioVault data and configuration (DESTRUCTIVE)"
    )]
    HardReset {
        #[arg(long, help = "Skip confirmation prompts (use with caution)")]
        ignore_warning: bool,
    },

    #[command(about = "Launch BioVault Desktop GUI")]
    Desktop {
        #[arg(long, help = "Path to BioVault config directory")]
        config: Option<String>,
    },
}

#[derive(Subcommand)]
enum DaemonCommands {
    #[command(about = "Start the BioVault daemon")]
    Start {
        #[arg(long, help = "Run daemon in foreground (no background)")]
        foreground: bool,
    },

    #[command(about = "Stop the running daemon")]
    Stop,

    #[command(about = "Restart the daemon (stop if running, then start)")]
    Restart {
        #[arg(long, help = "Run daemon in foreground after restart")]
        foreground: bool,
    },

    #[command(about = "Check daemon status")]
    Status,

    #[command(about = "View daemon logs")]
    Logs {
        #[arg(short, long, help = "Follow log output (tail -f)")]
        follow: bool,

        #[arg(short, long, help = "Number of lines to show (default: 50)")]
        lines: Option<usize>,
    },

    #[command(about = "Install daemon as a systemd service (Linux only)")]
    Install,

    #[command(about = "Uninstall daemon systemd service (Linux only)")]
    Uninstall,

    #[command(about = "List all installed daemon services")]
    List,

    #[command(about = "Show the systemd service file")]
    Show,

    #[command(about = "Reinstall daemon service (uninstall + install)")]
    Reinstall,
}

#[derive(Subcommand)]
enum ProjectCommands {
    #[command(about = "Create a new project")]
    Create {
        #[arg(long, help = "Project name")]
        name: Option<String>,

        #[arg(long, help = "Folder path (defaults to ./{name})")]
        folder: Option<String>,

        #[arg(long, value_parser = validate_example_name, help = "Use example template (use 'bv project examples' to list available)")]
        example: Option<String>,
    },

    #[command(about = "List available example templates")]
    Examples,
}

#[derive(Subcommand)]
enum SampleDataCommands {
    #[command(about = "Fetch sample data")]
    Fetch {
        #[arg(
            value_delimiter = ',',
            help = "Participant IDs to fetch (comma-separated)"
        )]
        participant_ids: Option<Vec<String>>,

        #[arg(long, help = "Fetch all available sample data")]
        all: bool,
    },

    #[command(about = "List available sample data")]
    List,
}

#[derive(Subcommand)]
enum ParticipantCommands {
    #[command(about = "Add a new participant")]
    Add {
        #[arg(long, help = "Participant ID")]
        id: Option<String>,

        #[arg(long, help = "Aligned file path (.cram, .bam, or .sam)")]
        aligned: Option<String>,

        #[arg(
            long,
            help = "Template type (default or snp)",
            default_value = "default"
        )]
        template: Option<String>,

        #[arg(long, help = "SNP file path (for SNP template)")]
        snp: Option<String>,

        #[arg(long, help = "Reference genome file path (.fa or .fasta)")]
        reference: Option<String>,

        #[arg(long, help = "Reference version (GRCh38 or GRCh37)")]
        ref_version: Option<String>,

        #[arg(long, help = "Skip interactive prompts, use defaults")]
        non_interactive: bool,
    },

    #[command(about = "List all participants")]
    List,

    #[command(about = "Delete a participant")]
    Delete {
        #[arg(help = "Participant ID to delete")]
        id: String,
    },

    #[command(about = "Validate participant files")]
    Validate {
        #[arg(help = "Participant ID to validate (validates all if not specified)")]
        id: Option<String>,
    },
}

#[derive(Subcommand)]
enum BiobankCommands {
    #[command(about = "List biobanks in SyftBox")]
    List,

    #[command(about = "Publish participants to SyftBox")]
    Publish {
        #[arg(long, help = "Participant ID to publish")]
        participant_id: Option<String>,

        #[arg(long, help = "Publish all participants")]
        all: bool,

        #[arg(
            long,
            help = "HTTP relay servers (defaults to syftbox.net)",
            value_delimiter = ','
        )]
        http_relay_servers: Option<Vec<String>>,
    },

    #[command(about = "Unpublish participants from SyftBox")]
    Unpublish {
        #[arg(long, help = "Participant ID to unpublish")]
        participant_id: Option<String>,

        #[arg(long, help = "Unpublish all participants")]
        all: bool,
    },
}

#[derive(Subcommand)]
enum ConfigCommands {
    #[command(about = "Set email address")]
    Email {
        #[arg(help = "Email address")]
        email: String,
    },

    #[command(about = "Set SyftBox config path")]
    Syftbox {
        #[arg(help = "Path to SyftBox config.json (omit to use default)")]
        path: Option<String>,
    },
}

#[derive(Subcommand)]
enum FastqCommands {
    #[command(about = "Combine multiple FASTQ files into one")]
    Combine {
        #[arg(help = "Input folder containing FASTQ files")]
        input_folder: String,

        #[arg(help = "Output file path")]
        output_file: String,

        #[arg(long, help = "Validate files before combining")]
        validate: bool,

        #[arg(long, help = "Skip validation prompt and use default")]
        no_prompt: bool,

        #[arg(
            long,
            default_value = "tsv",
            help = "Stats output format (tsv, yaml, json)"
        )]
        stats_format: String,
    },
}

#[derive(Subcommand)]
enum SamplesheetCommands {
    #[command(about = "Create a sample sheet CSV from a folder of files")]
    Create {
        #[arg(help = "Input directory containing files")]
        input_dir: String,

        #[arg(help = "Output CSV file path")]
        output_file: String,

        #[arg(
            long = "file_filter",
            help = "File pattern filter (e.g., *.txt, default: all files)"
        )]
        file_filter: Option<String>,

        #[arg(
            long = "extract_cols",
            help = "Pattern for extracting fields from filenames (e.g., {participant_id}_X_X_GSAv3-DTC_GRCh38-{date}.txt)"
        )]
        extract_cols: Option<String>,

        #[arg(
            long = "ignore",
            help = "Add files even if they don't match the extraction pattern"
        )]
        ignore: bool,
    },
}

#[derive(Subcommand)]
enum MessageCommands {
    #[command(about = "Send a message to another datasite")]
    Send {
        #[arg(help = "Recipient email address")]
        recipient: String,

        #[arg(help = "Message content")]
        message: String,

        #[arg(short = 's', long = "subject", help = "Optional message subject")]
        subject: Option<String>,
    },

    #[command(about = "Reply to a message")]
    Reply {
        #[arg(help = "Message ID to reply to")]
        message_id: String,

        #[arg(help = "Reply content")]
        body: String,
    },

    #[command(about = "Read a specific message")]
    Read {
        #[arg(help = "Message ID to read")]
        message_id: String,
    },

    #[command(about = "Delete a message")]
    Delete {
        #[arg(help = "Message ID to delete")]
        message_id: String,
    },

    #[command(about = "List messages")]
    List {
        #[arg(short = 'u', long = "unread", help = "Show only unread messages")]
        unread: bool,

        #[arg(short = 's', long = "sent", help = "Show sent messages")]
        sent: bool,

        #[arg(short = 'p', long = "projects", help = "Show only project messages")]
        projects: bool,
    },

    #[command(about = "View a message thread")]
    Thread {
        #[arg(help = "Thread ID to view")]
        thread_id: String,
    },

    #[command(about = "Sync messages (check for new and update ACKs)")]
    Sync,

    #[command(about = "Process a project message (run test/real)")]
    Process {
        #[arg(help = "Message ID of the project to process")]
        message_id: String,

        #[arg(long, help = "Run with test data", conflicts_with = "real")]
        test: bool,

        #[arg(long, help = "Run with real data", conflicts_with = "test")]
        real: bool,

        #[arg(long, help = "Participant to use (defaults to first available)")]
        participant: Option<String>,

        #[arg(long, help = "Approve after successful run")]
        approve: bool,

        #[arg(long, help = "Non-interactive mode (skip prompts)")]
        non_interactive: bool,
    },

    #[command(about = "Archive a project message (revoke write permissions)")]
    Archive {
        #[arg(help = "Message ID to archive")]
        message_id: String,
    },
}

fn main() -> Result<()> {
    // Set up panic hook to log crashes
    std::panic::set_hook(Box::new(|panic_info| {
        let payload = panic_info.payload();
        let message = if let Some(s) = payload.downcast_ref::<&str>() {
            s.to_string()
        } else if let Some(s) = payload.downcast_ref::<String>() {
            s.clone()
        } else {
            "Unknown panic payload".to_string()
        };

        let location = panic_info
            .location()
            .map(|loc| format!("{}:{}:{}", loc.file(), loc.line(), loc.column()))
            .unwrap_or_else(|| "unknown location".to_string());

        let crash_log = format!(
            "\n=== PANIC/CRASH DETECTED ===\n\
             Time: {}\n\
             Message: {}\n\
             Location: {}\n\
             Backtrace: use RUST_BACKTRACE=1 for details\n\
             ============================\n",
            chrono::Utc::now().format("%Y-%m-%d %H:%M:%S%.3f UTC"),
            message,
            location
        );

        // Try to write to daemon log if we're in daemon mode
        if let Ok(syftbox_dir) = std::env::var("SYFTBOX_DATA_DIR") {
            let log_path = std::path::PathBuf::from(&syftbox_dir)
                .join(".biovault")
                .join("logs")
                .join("daemon.log");

            if let Ok(mut file) = std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(&log_path)
            {
                use std::io::Write;
                let _ = writeln!(file, "{}", crash_log);
            }
        }

        // Also write to stderr
        eprintln!("{}", crash_log);
    }));

    // Use a minimal tokio runtime - this is just a file-watching daemon, not a web server
    // 2 worker threads is plenty for occasional I/O operations
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .worker_threads(2)
        .thread_name("bv-worker")
        .enable_all()
        .build()
        .expect("Failed to create tokio runtime");

    runtime.block_on(async_main())
}

async fn async_main() -> Result<()> {
    let cli = Cli::parse();

    let filter_level = if cli.verbose { "debug" } else { "info" };

    tracing_subscriber::registry()
        .with(fmt::layer())
        .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(filter_level)))
        .init();

    // Random version check on startup (10% chance)
    let _ = commands::update::check_and_notify_random().await;

    // Check for upgrades and perform them if needed
    let _ = cli::upgrade::check_and_upgrade();

    match cli.command {
        Commands::Update => {
            commands::update::execute().await?;
        }
        Commands::Init { email, quiet } => {
            commands::init::execute(email.as_deref(), quiet).await?;
        }
        Commands::Info { json } => {
            commands::info::execute(json).await?;
        }
        Commands::Check { json } => {
            commands::check::execute(json).await?;
        }
        Commands::Setup => {
            commands::setup::execute().await?;
        }
        Commands::Project { command } => match command {
            ProjectCommands::Create {
                name,
                folder,
                example,
            } => {
                commands::project::create(name, folder, example).await?;
            }
            ProjectCommands::Examples => {
                commands::project::list_examples()?;
            }
        },
        Commands::Run {
            project_folder,
            participant_source,
            test,
            download,
            dry_run,
            with_docker,
            work_dir,
            resume,
            template,
            results_dir,
        } => {
            commands::run::execute(commands::run::RunParams {
                project_folder,
                participant_source,
                test,
                download,
                dry_run,
                with_docker,
                work_dir,
                resume,
                template,
                results_dir,
            })
            .await?;
        }
        Commands::SampleData { command } => match command {
            SampleDataCommands::Fetch {
                participant_ids,
                all,
            } => {
                commands::sample_data::fetch(participant_ids, all, false).await?;
            }
            SampleDataCommands::List => {
                commands::sample_data::list().await?;
            }
        },
        Commands::Participant { command } => match command {
            ParticipantCommands::Add {
                id,
                aligned,
                template,
                snp,
                reference,
                ref_version,
                non_interactive,
            } => {
                commands::participant::add(
                    id,
                    aligned,
                    template,
                    snp,
                    reference,
                    ref_version,
                    non_interactive,
                )
                .await?;
            }
            ParticipantCommands::List => {
                commands::participant::list().await?;
            }
            ParticipantCommands::Delete { id } => {
                commands::participant::delete(id).await?;
            }
            ParticipantCommands::Validate { id } => {
                commands::participant::validate(id).await?;
            }
        },
        Commands::Biobank { command } => match command {
            BiobankCommands::List => {
                commands::biobank::list(None).await?;
            }
            BiobankCommands::Publish {
                participant_id,
                all,
                http_relay_servers,
            } => {
                commands::biobank::publish(participant_id, all, http_relay_servers).await?;
            }
            BiobankCommands::Unpublish {
                participant_id,
                all,
            } => {
                commands::biobank::unpublish(participant_id, all).await?;
            }
        },
        Commands::Config { command, json } => {
            if let Some(cmd) = command {
                match cmd {
                    ConfigCommands::Email { email } => {
                        commands::config_cmd::set_email(email).await?;
                    }
                    ConfigCommands::Syftbox { path } => {
                        commands::config_cmd::set_syftbox(path).await?;
                    }
                }
            } else {
                commands::config_cmd::show(json).await?;
            }
        }
        Commands::Fastq { command } => match command {
            FastqCommands::Combine {
                input_folder,
                output_file,
                validate,
                no_prompt,
                stats_format,
            } => {
                let should_validate = if no_prompt { Some(validate) } else { None };
                commands::fastq::combine(
                    input_folder,
                    output_file,
                    should_validate,
                    Some(stats_format),
                )
                .await?;
            }
        },
        Commands::Submit {
            project_path,
            destination,
            non_interactive,
            force,
        } => {
            commands::submit::submit(project_path, destination, non_interactive, force).await?;
        }
        Commands::Cleanup { all } => {
            let config = biovault::config::Config::load()?;
            commands::messages::cleanup_locks(&config, all)?;
        }
        Commands::Inbox {
            interactive,
            plain,
            sent,
            all,
            unread,
            projects,
            message_type,
            from,
            search,
        } => {
            let config = biovault::config::Config::load()?;
            // Default behavior: interactive unless --plain is provided
            if plain && !interactive {
                let filters = commands::inbox::ListFilters {
                    sent,
                    all,
                    unread,
                    projects,
                    message_type,
                    from,
                    search,
                };
                commands::inbox::list(&config, filters)?;
            } else {
                // When both flags are provided, prefer interactive
                commands::inbox::interactive(&config, None).await?;
            }
        }
        Commands::Message { command } => match command {
            MessageCommands::Send {
                recipient,
                message,
                subject,
            } => {
                let config = biovault::config::Config::load()?;
                commands::messages::send_message(
                    &config,
                    &recipient,
                    &message,
                    subject.as_deref(),
                )?;
            }
            MessageCommands::Reply { message_id, body } => {
                let config = biovault::config::Config::load()?;
                commands::messages::reply_message(&config, &message_id, &body)?;
            }
            MessageCommands::Read { message_id } => {
                let config = biovault::config::Config::load()?;
                commands::messages::read_message(&config, &message_id).await?;
            }
            MessageCommands::Delete { message_id } => {
                let config = biovault::config::Config::load()?;
                commands::messages::delete_message(&config, &message_id)?;
            }
            MessageCommands::List {
                unread,
                sent,
                projects,
            } => {
                let config = biovault::config::Config::load()?;
                commands::messages::list_messages(&config, unread, sent, projects)?;
            }
            MessageCommands::Thread { thread_id } => {
                let config = biovault::config::Config::load()?;
                commands::messages::view_thread(&config, &thread_id)?;
            }
            MessageCommands::Sync => {
                let config = biovault::config::Config::load()?;
                commands::messages::sync_messages(&config)?;
            }
            MessageCommands::Process {
                message_id,
                test,
                real,
                participant,
                approve,
                non_interactive,
            } => {
                let config = biovault::config::Config::load()?;
                commands::messages::process_project_message(
                    &config,
                    &message_id,
                    test,
                    real,
                    participant,
                    approve,
                    non_interactive,
                )
                .await?;
            }
            MessageCommands::Archive { message_id } => {
                let config = biovault::config::Config::load()?;
                commands::messages::archive_message(&config, &message_id)?;
            }
        },
        Commands::Samplesheet { command } => match command {
            SamplesheetCommands::Create {
                input_dir,
                output_file,
                file_filter,
                extract_cols,
                ignore,
            } => {
                commands::samplesheet::create(
                    input_dir,
                    output_file,
                    file_filter,
                    extract_cols,
                    ignore,
                )
                .await?;
            }
        },
        Commands::Daemon { command } => {
            // If BV_DAEMON_CONFIG env var is set, use it (for spawned daemon processes)
            // Otherwise load config normally
            let config = if let Ok(config_json) = std::env::var("BV_DAEMON_CONFIG") {
                serde_json::from_str(&config_json)?
            } else {
                biovault::config::Config::load()?
            };

            match command {
                DaemonCommands::Start { foreground } => {
                    commands::daemon::start(&config, foreground).await?;
                }
                DaemonCommands::Stop => {
                    commands::daemon::stop(&config).await?;
                }
                DaemonCommands::Restart { foreground } => {
                    // Stop the daemon if it's running
                    let _ = commands::daemon::stop(&config).await;
                    // Small delay to ensure clean shutdown
                    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
                    // Start it again
                    commands::daemon::start(&config, foreground).await?;
                }
                DaemonCommands::Status => {
                    commands::daemon::service_status(&config).await?;
                }
                DaemonCommands::Logs { follow, lines } => {
                    commands::daemon::logs(&config, follow, lines).await?;
                }
                DaemonCommands::Install => {
                    commands::daemon::install_service(&config).await?;
                }
                DaemonCommands::Uninstall => {
                    commands::daemon::uninstall_service(&config).await?;
                }
                DaemonCommands::List => {
                    commands::daemon::list_services().await?;
                }
                DaemonCommands::Show => {
                    commands::daemon::show_service(&config).await?;
                }
                DaemonCommands::Reinstall => {
                    commands::daemon::reinstall_service(&config).await?;
                }
            }
        }
        Commands::HardReset { ignore_warning } => {
            commands::hard_reset::execute(ignore_warning).await?;
        }
        Commands::Desktop { config } => {
            let biovault_home = if let Some(cfg) = config {
                cfg
            } else if let Ok(env_home) = std::env::var("BIOVAULT_HOME") {
                env_home
            } else {
                biovault::config::get_biovault_home()?
                    .to_string_lossy()
                    .to_string()
            };

            #[cfg(target_os = "macos")]
            {
                let app_path = std::path::Path::new("/Applications/BioVault Desktop.app");
                if !app_path.exists() {
                    eprintln!("Error: BioVault Desktop is not installed.");
                    eprintln!("\nPlease install BioVault Desktop from:");
                    eprintln!("https://github.com/OpenMined/biovault-desktop");
                    eprintln!("\nOr download the latest release:");
                    eprintln!("https://github.com/OpenMined/biovault-desktop/releases/latest");
                    std::process::exit(1);
                }

                match std::process::Command::new("open")
                    .arg("-n")
                    .arg("/Applications/BioVault Desktop.app")
                    .arg("--args")
                    .arg("--biovault-config")
                    .arg(&biovault_home)
                    .spawn()
                {
                    Ok(_) => println!("Launching BioVault Desktop with config: {}", biovault_home),
                    Err(e) => {
                        eprintln!("Error launching BioVault Desktop: {}", e);
                        eprintln!("\nPlease ensure BioVault Desktop is installed from:");
                        eprintln!("https://github.com/OpenMined/biovault-desktop");
                        std::process::exit(1);
                    }
                }
            }

            #[cfg(not(target_os = "macos"))]
            {
                match which::which("bv-desktop").or_else(|_| which::which("biovault-desktop")) {
                    Ok(desktop_bin) => {
                        match std::process::Command::new(desktop_bin)
                            .arg("--biovault-config")
                            .arg(&biovault_home)
                            .spawn()
                        {
                            Ok(_) => println!(
                                "Launching BioVault Desktop with config: {}",
                                biovault_home
                            ),
                            Err(e) => {
                                eprintln!("Error launching BioVault Desktop: {}", e);
                                eprintln!("\nPlease ensure BioVault Desktop is installed from:");
                                eprintln!("https://github.com/OpenMined/biovault-desktop");
                                std::process::exit(1);
                            }
                        }
                    }
                    Err(_) => {
                        eprintln!("Error: BioVault Desktop is not installed or not in PATH.");
                        eprintln!("\nPlease install BioVault Desktop from:");
                        eprintln!("https://github.com/OpenMined/biovault-desktop");
                        eprintln!("\nOr download the latest release:");
                        eprintln!("https://github.com/OpenMined/biovault-desktop/releases/latest");
                        std::process::exit(1);
                    }
                }
            }
        }
    }

    Ok(())
}