biovault 0.1.64

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
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
use crate::cli::commands::run::{execute as run_execute, RunParams};
use crate::cli::syft_url::SyftURL;
use crate::config::Config;
use crate::messages::{Message, MessageDb, MessageSync};
use crate::types::ProjectYaml;
use crate::types::SyftPermissions;
use anyhow::Result;
use colored::Colorize;
use dialoguer::{Confirm, Input, Select};
use serde_json::json;
use std::fs;
use std::path::Path;
use std::path::PathBuf;

const MESSAGE_ENDPOINT: &str = "/message";

/// Clean up stale database locks
pub fn cleanup_locks(config: &Config, all: bool) -> Result<()> {
    use crate::messages::MessageDb;

    if all {
        println!("🧹 Scanning all BioVault virtualenvs for stale locks...");
        // This would be more complex - scan all possible BioVault installations
        println!("⚠️  --all mode not yet implemented. Cleaning current environment only.");
    }

    let db_path = get_message_db_path(config)?;
    let cleaned = MessageDb::clean_stale_lock(&db_path)?;

    if !cleaned {
        println!("✅ No stale locks found");
    }

    Ok(())
}

/// Expand environment variables in text (specifically $SYFTBOX_DATA_DIR)
fn expand_env_vars_in_text(text: &str) -> Result<String> {
    let mut result = text.to_string();

    // Expand $SYFTBOX_DATA_DIR
    if let Ok(data_dir) = std::env::var("SYFTBOX_DATA_DIR") {
        result = result.replace("$SYFTBOX_DATA_DIR", &data_dir);
    }

    Ok(result)
}

/// Get the path to the message database
pub fn get_message_db_path(config: &Config) -> Result<PathBuf> {
    let biovault_dir = config.get_biovault_dir()?;
    let db_path = biovault_dir.join("data").join("messages.db");

    // Ensure the data directory exists
    if let Some(parent) = db_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    Ok(db_path)
}

#[cfg(test)]
mod tests_fast_helpers {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn get_message_db_path_creates_parent_dir() {
        let tmp = TempDir::new().unwrap();
        crate::config::set_test_biovault_home(tmp.path().join(".bvtest"));
        let cfg = Config {
            email: "e@example".into(),
            syftbox_config: None,
            version: None,
            binary_paths: None,
            syftbox_credentials: None,
        };
        let path = get_message_db_path(&cfg).unwrap();
        // Parent dir should exist now
        assert!(path.parent().unwrap().exists());
        assert!(path.ends_with("messages.db"));
        crate::config::clear_test_biovault_home();
    }

    #[test]
    fn test_expand_env_vars_in_text_with_syftbox() {
        std::env::set_var("SYFTBOX_DATA_DIR", "/test/data");
        let result = expand_env_vars_in_text("Path: $SYFTBOX_DATA_DIR/file").unwrap();
        assert_eq!(result, "Path: /test/data/file");
        std::env::remove_var("SYFTBOX_DATA_DIR");
    }

    #[test]
    fn test_expand_env_vars_in_text_no_env() {
        std::env::remove_var("SYFTBOX_DATA_DIR");
        let result = expand_env_vars_in_text("Plain text").unwrap();
        assert_eq!(result, "Plain text");
    }

    #[test]
    fn test_cleanup_locks_no_stale_locks() {
        let tmp = TempDir::new().unwrap();
        crate::config::set_test_biovault_home(tmp.path().join(".bv"));
        let cfg = Config {
            email: "test@example.com".into(),
            syftbox_config: None,
            version: None,
            binary_paths: None,
            syftbox_credentials: None,
        };
        // Create db first
        let _ = get_message_db_path(&cfg).unwrap();
        // Should not panic
        let result = cleanup_locks(&cfg, false);
        assert!(result.is_ok());
        crate::config::clear_test_biovault_home();
    }
}

/// Initialize the message system
pub fn init_message_system(config: &Config) -> Result<(MessageDb, MessageSync)> {
    let db_path = get_message_db_path(config)?;
    let db = MessageDb::new(&db_path)?;

    let data_dir = config.get_syftbox_data_dir()?;
    let app = crate::syftbox::SyftBoxApp::new(&data_dir, &config.email, "biovault")?;
    app.register_endpoint(MESSAGE_ENDPOINT)?;

    let sync = MessageSync::new(&db_path, app)?;

    println!("BioVault messaging initialized for {}", config.email);

    Ok((db, sync))
}

/// Send a message
pub fn send_message(
    config: &Config,
    recipient: &str,
    body: &str,
    subject: Option<&str>,
) -> Result<()> {
    let (db, sync) = init_message_system(config)?;

    // Quietly sync first to check for any pending ACKs
    let _ = sync.sync_quiet();

    // Create the message
    let mut msg = Message::new(
        config.email.clone(),
        recipient.to_string(),
        body.to_string(),
    );

    if let Some(subj) = subject {
        msg.subject = Some(subj.to_string());
    }

    // Save to local database
    db.insert_message(&msg)?;

    // Send via RPC
    sync.send_message(&msg.id)?;

    println!("✉️  Message sent to {}", recipient);
    if let Some(subj) = &msg.subject {
        println!("   Subject: {}", subj);
    }

    Ok(())
}

/// Reply to a message
pub fn reply_message(config: &Config, message_id: &str, body: &str) -> Result<()> {
    let (db, sync) = init_message_system(config)?;

    // Quietly sync first to ensure we have the latest messages
    let _ = sync.sync_quiet();

    // Get the original message
    let original = db
        .get_message(message_id)?
        .ok_or_else(|| anyhow::anyhow!("Message not found: {}", message_id))?;

    // Create reply
    let reply = Message::reply_to(&original, config.email.clone(), body.to_string());

    // Save to local database
    db.insert_message(&reply)?;

    // Send via RPC
    sync.send_message(&reply.id)?;

    println!("↩️  Reply sent to {}", reply.to);

    Ok(())
}

/// Delete a message
pub fn delete_message(config: &Config, message_id: &str) -> Result<()> {
    let (db, _) = init_message_system(config)?;

    // First get the message to ensure it exists and get the full ID
    let msg = db
        .get_message(message_id)?
        .ok_or_else(|| anyhow::anyhow!("Message not found: {}", message_id))?;

    // Now delete with the full ID
    db.delete_message(&msg.id)?;

    println!(
        "🗑️  Message deleted: {} ({})",
        &msg.id[..8],
        msg.display_subject()
    );

    Ok(())
}

/// List messages
pub fn list_messages(
    config: &Config,
    unread_only: bool,
    sent_only: bool,
    projects_only: bool,
) -> Result<()> {
    let (db, sync) = init_message_system(config)?;

    // Quietly sync to get latest messages and show notification if new
    let (_new_msg_ids, count) = sync.sync_quiet()?;
    if count > 0 {
        println!("🆕 {} new message(s) received", count);
    }

    let mut messages = if unread_only {
        db.list_unread_messages()?
    } else if sent_only {
        db.list_sent_messages(Some(50))?
    } else {
        db.list_messages(Some(50))?
    };

    // Filter for projects if requested
    if projects_only {
        messages.retain(|msg| {
            matches!(
                msg.message_type,
                crate::messages::MessageType::Project { .. }
            )
        });
    }

    if messages.is_empty() {
        if unread_only {
            println!("No unread messages");
        } else {
            println!("No messages");
        }
        return Ok(());
    }

    println!("\n📬 Messages:");
    println!("─────────────");

    for msg in messages {
        let status_icon = match msg.status {
            crate::messages::MessageStatus::Draft => "📝",
            crate::messages::MessageStatus::Sent => "📤",
            crate::messages::MessageStatus::Received => "📥",
            crate::messages::MessageStatus::Read => "👁️",
            crate::messages::MessageStatus::Deleted => "🗑️",
            crate::messages::MessageStatus::Archived => "📁",
        };

        println!("\n{} [{}]", status_icon, &msg.id[..8]);
        println!("  From: {}", msg.from);
        println!("  To: {}", msg.to);
        println!("  Subject: {}", msg.display_subject());
        // Convert to local time
        let local_time = msg.created_at.with_timezone(&chrono::Local);
        println!("  Date: {}", local_time.format("%Y-%m-%d %H:%M:%S %Z"));

        // Show first 100 chars of body
        let preview = if msg.body.len() > 100 {
            format!("{}...", &msg.body[..100])
        } else {
            msg.body.clone()
        };
        println!("  Body: {}", preview);

        // If this is a project message with metadata, try quick verification
        if let Some(meta) = &msg.metadata {
            if msg.message_type.to_string() == "project" {
                match verify_project_from_metadata(config, meta) {
                    Ok((true, note)) => println!("  Project Verify: OK{}", note),
                    Ok((false, note)) => println!("  Project Verify: FAIL{}", note),
                    Err(e) => println!("  Project Verify: UNVERIFIED ({})", e),
                }
            }
        }

        if msg.parent_id.is_some() {
            println!("  ↩️  Reply to: {}", msg.parent_id.as_ref().unwrap());
        }
    }

    Ok(())
}

/// Read a specific message
pub async fn read_message(config: &Config, message_id: &str) -> Result<()> {
    let (db, sync) = init_message_system(config)?;

    // Quietly sync first in case there are new messages
    let _ = sync.sync_quiet();

    let msg = db
        .get_message(message_id)?
        .ok_or_else(|| anyhow::anyhow!("Message not found: {}", message_id))?;

    // Mark as read if it was received
    if msg.status == crate::messages::MessageStatus::Received {
        db.mark_as_read(message_id)?;
    }

    println!("\n📧 Message Details");
    println!("═══════════════════");
    println!("ID: {}", msg.id);
    println!("From: {}", msg.from);
    println!("To: {}", msg.to);
    println!("Subject: {}", msg.display_subject());
    let local_time = msg.created_at.with_timezone(&chrono::Local);
    println!("Date: {}", local_time.format("%Y-%m-%d %H:%M:%S %Z"));

    if let Some(parent_id) = &msg.parent_id {
        println!("Reply to: {}", parent_id);
    }

    if let Some(thread_id) = &msg.thread_id {
        println!("Thread: {}", thread_id);
    }

    println!("\nBody:");
    println!("─────");

    // Expand environment variables in message body
    let expanded_body = expand_env_vars_in_text(&msg.body)?;
    println!("{}", expanded_body);

    // If this is a project message with metadata, attempt verification and show details
    if let Some(meta) = &msg.metadata {
        if msg.message_type.to_string() == "project" {
            println!("\nProject Verification:");
            println!("──────────────────────");
            match verify_project_from_metadata(config, meta) {
                Ok((true, note)) => println!("Status: OK{}", note),
                Ok((false, note)) => println!("Status: FAIL{}", note),
                Err(e) => println!("Status: UNVERIFIED ({})", e),
            }

            println!("\nDetails:");
            println!("────────");
            if let Some(loc) = meta.get("project_location").and_then(|v| v.as_str()) {
                println!("Project location: {}", loc.cyan());
                if let Ok(p) = resolve_syft_url_to_path(config, loc) {
                    println!("Local path: {}", p.display());
                }
            }
            if let Some(date) = meta.get("date").and_then(|v| v.as_str()) {
                println!("Date: {}", date);
            }
            if let Some(project) = meta.get("project") {
                if let Some(participants) = project.get("participants").and_then(|v| v.as_array()) {
                    if !participants.is_empty() {
                        let parts: Vec<String> = participants
                            .iter()
                            .filter_map(|p| p.as_str().map(|s| s.to_string()))
                            .collect();
                        println!("Desired participants: {}", parts.join(", "));
                    }
                }
                if let Some(assets) = project.get("assets").and_then(|v| v.as_array()) {
                    if !assets.is_empty() {
                        println!("Assets:");
                        for a in assets {
                            if let Some(s) = a.as_str() {
                                println!("  - {}", s);
                            }
                        }
                    }
                }
            }

            if let Some(status) = meta.get("remote_status").and_then(|v| v.as_str()) {
                println!("Remote status: {}", status);
                if let Some(reason) = meta.get("remote_reason").and_then(|v| v.as_str()) {
                    if !reason.is_empty() {
                        println!("Reason: {}", reason);
                    }
                }
                if status == "approved" {
                    if let Some(path_str) = meta.get("results_path").and_then(|v| v.as_str()) {
                        let results = std::path::PathBuf::from(path_str);
                        println!("Results location: {}", results.display());
                        if results.exists() {
                            println!("Results tree:");
                            print_dir_tree(&results, 3)?;
                        }
                    } else if let Some(loc) = meta.get("project_location").and_then(|v| v.as_str())
                    {
                        if let Ok(root) = resolve_syft_url_to_path(config, loc) {
                            let results = root.join("results");
                            println!("Results location: {}", results.display());
                            if results.exists() {
                                println!("Results tree:");
                                print_dir_tree(&results, 3)?;
                            }
                        }
                    }
                }
            }

            // Offer actions to the recipient (show regardless of read status)
            if msg.to == config.email {
                println!("\nActions:");
                println!("────────");
                let actions = vec![
                    "Reject",
                    "Review",
                    "Approve (run if needed, release results)",
                    "Run on test data",
                    "Run on real data",
                    "Back",
                ];
                let choice = Select::new()
                    .with_prompt("Choose an action")
                    .items(&actions)
                    .default(5)
                    .interact_opt()?;

                if let Some(idx) = choice {
                    match idx {
                        0 => reject_project(config, &msg)?,
                        1 => review_project(config, &msg)?,
                        2 => approve_project(config, &msg).await?,
                        3 => run_project_test(config, &msg).await?,
                        4 => run_project_real(config, &msg).await?,
                        _ => {}
                    }
                }
            }

            // Sender-side archive action after approval to revoke write and mark done
            if msg.from == config.email {
                println!("\nSender Actions:");
                println!("───────────────");
                let actions = vec!["Archive (finalize and revoke write)", "Back"];
                let choice = Select::new()
                    .with_prompt("Choose an action")
                    .items(&actions)
                    .default(1)
                    .interact_opt()?;
                if let Some(0) = choice {
                    archive_project(config, &msg)?;
                }
            }
        }
        // If this is a status update reply, show status and results info directly
        if let crate::messages::MessageType::Request { request_type, .. } = &msg.message_type {
            if request_type == "status" {
                println!("\nStatus Update:");
                println!("──────────────");
                if let Some(update) = meta.get("status_update") {
                    if let Some(status) = update.get("status").and_then(|v| v.as_str()) {
                        println!("Status: {}", status);
                    }
                    if let Some(reason) = update.get("reason").and_then(|v| v.as_str()) {
                        if !reason.is_empty() {
                            println!("Note: {}", reason);
                        }
                    }
                }
                if let Some(path_str) = meta.get("results_path").and_then(|v| v.as_str()) {
                    let results = std::path::PathBuf::from(path_str);
                    println!("Results location: {}", results.display());
                    if results.exists() {
                        println!("Results tree:");
                        print_dir_tree(&results, 3)?;
                    }
                }
            }
        }
    }

    Ok(())
}

#[derive(Debug, Clone, Copy)]
pub enum ProjectAction {
    Reject,
    Review,
    Approve,
    RunTest,
    RunReal,
}

/// Public entrypoint so other commands (like inbox) can trigger project triage actions
pub async fn perform_project_action(
    config: &Config,
    message_id: &str,
    action: ProjectAction,
) -> anyhow::Result<()> {
    let (db, _sync) = init_message_system(config)?;
    let msg = db
        .get_message(message_id)?
        .ok_or_else(|| anyhow::anyhow!("Message not found: {}", message_id))?;

    match action {
        ProjectAction::Reject => reject_project(config, &msg)?,
        ProjectAction::Review => review_project(config, &msg)?,
        ProjectAction::Approve => approve_project(config, &msg).await?,
        ProjectAction::RunTest => run_project_test(config, &msg).await?,
        ProjectAction::RunReal => run_project_real(config, &msg).await?,
    }
    Ok(())
}

/// Process a project message non-interactively (for automated testing)
pub async fn process_project_message(
    config: &Config,
    message_id: &str,
    test: bool,
    _real: bool,
    participant: Option<String>,
    approve: bool,
    _non_interactive: bool, // Currently always non-interactive
) -> anyhow::Result<()> {
    let (db, _sync) = init_message_system(config)?;
    let msg = db
        .get_message(message_id)?
        .ok_or_else(|| anyhow::anyhow!("Message not found: {}", message_id))?;

    // Verify it's a project message
    if !matches!(
        msg.message_type,
        crate::messages::MessageType::Project { .. }
    ) {
        return Err(anyhow::anyhow!(
            "Message {} is not a project message",
            message_id
        ));
    }

    // Build the project copy in private directory
    let dest = build_run_project_copy(config, &msg)?;

    // Determine participant source
    let participant_source = if let Some(ref p) = participant {
        // Normalize the participant source if it's just an ID
        if !test {
            // For real data, normalize the participant ID to full path
            normalize_participant_source_for_real(p)?
        } else {
            // For test data, just use the ID as-is (sample data)
            p.clone()
        }
    } else {
        return Err(anyhow::anyhow!(
            "No participant specified. Please provide a participant source with --participant"
        ));
    };

    // Run the project
    use crate::cli::commands::run::{execute as run_execute, RunParams};

    let result = run_execute(RunParams {
        project_folder: dest.to_string_lossy().to_string(),
        participant_source: participant_source.clone(),
        test,
        download: true,
        dry_run: false,
        with_docker: false,
        work_dir: None,
        resume: false,
        template: Some("snp".to_string()),
        results_dir: None,
        nextflow_args: vec![],
    })
    .await;

    match result {
        Ok(_) => {
            println!(
                "✓ Project processed successfully with participant: {}",
                participant_source
            );

            // Show results location
            let results_base = if test { "results-test" } else { "results-real" };
            let results_dir = dest.join(results_base).join(&participant_source);
            if results_dir.exists() {
                println!("Results saved to: {}", results_dir.display());
            }

            // Approve if requested
            if approve {
                approve_project_non_interactive(config, &msg).await?;
                println!("✓ Project approved and results sent to sender");
            }
        }
        Err(e) => {
            eprintln!("✗ Failed to process project: {}", e);
            return Err(e);
        }
    }

    Ok(())
}

/// Archive a message (for non-interactive use)
pub fn archive_message(config: &Config, message_id: &str) -> anyhow::Result<()> {
    let (db, _sync) = init_message_system(config)?;
    let msg = db
        .get_message(message_id)?
        .ok_or_else(|| anyhow::anyhow!("Message not found: {}", message_id))?;

    archive_project(config, &msg)?;
    Ok(())
}

fn archive_project(config: &Config, msg: &Message) -> anyhow::Result<()> {
    // Update syft.pub.yaml by removing the results write rule
    let meta = msg
        .metadata
        .as_ref()
        .ok_or_else(|| anyhow::anyhow!("missing metadata"))?;
    let project_location = meta
        .get("project_location")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("missing project_location"))?;
    let root = resolve_syft_url_to_path(config, project_location)?;
    let perm_path = root.join("syft.pub.yaml");
    if perm_path.exists() {
        let content = fs::read_to_string(&perm_path)?;
        let mut perms: SyftPermissions = serde_yaml::from_str(&content)?;
        perms.rules.retain(|r| r.pattern != "results/**/*");
        perms.save(&perm_path)?;
        println!("Revoked write permissions to results for the recipient.");
    } else {
        println!(
            "Warning: permission file not found at {}",
            perm_path.display()
        );
    }

    // Mark the message as archived
    let (db, _) = init_message_system(config)?;
    if let Some(mut full) = db.get_message(&msg.id)? {
        full.status = crate::messages::MessageStatus::Archived;
        db.update_message(&full)?;
        println!("Message archived.");
    }
    Ok(())
}

fn sender_project_root(
    config: &Config,
    meta: &serde_json::Value,
) -> anyhow::Result<(PathBuf, String)> {
    let project_location = meta
        .get("project_location")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("missing project_location"))?;
    let path = resolve_syft_url_to_path(config, project_location)?;
    let folder = Path::new(project_location)
        .components()
        .next_back()
        .and_then(|c| match c {
            std::path::Component::Normal(os) => os.to_str(),
            _ => None,
        })
        .unwrap_or("submission")
        .to_string();
    Ok((path, folder))
}

fn receiver_private_submissions_path(config: &Config) -> anyhow::Result<PathBuf> {
    let data_dir = config.get_syftbox_data_dir()?;

    // Check if this is a normal SyftBox root (has datasites/ folder inside)
    let real_data_dir = if data_dir.join("datasites").exists() {
        // Normal case: data_dir/datasites/email exists, so data_dir is the root
        data_dir
    } else if data_dir.components().any(|c| c.as_os_str() == "datasites")
        && data_dir.to_string_lossy().contains(&config.email)
    {
        // Edge case: SYFTBOX_DATA_DIR is pointing to datasite itself (no datasites/ folder inside)
        // Walk up to find the parent that doesn't contain "datasites"
        let mut parent = data_dir.clone();
        while parent.components().any(|c| c.as_os_str() == "datasites") {
            if let Some(p) = parent.parent() {
                parent = p.to_path_buf();
            } else {
                break;
            }
        }
        parent
    } else {
        // Fallback: treat as normal case
        data_dir
    };

    // Private is at data_dir root level
    Ok(real_data_dir
        .join("private")
        .join("app_data")
        .join("biovault")
        .join("submissions"))
}

fn copy_dir_recursive(src: &Path, dst: &Path) -> anyhow::Result<()> {
    fs::create_dir_all(dst)?;
    for entry in walkdir::WalkDir::new(src)
        .into_iter()
        .filter_map(|e| e.ok())
    {
        let rel = entry.path().strip_prefix(src).unwrap();
        let out = dst.join(rel);
        if entry.file_type().is_dir() {
            fs::create_dir_all(&out)?;
        } else {
            // Skip any syft.pub.yaml files anywhere in the tree
            if entry
                .path()
                .file_name()
                .and_then(|n| n.to_str())
                .map(|n| n == "syft.pub.yaml")
                .unwrap_or(false)
            {
                continue;
            }
            if let Some(parent) = out.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::copy(entry.path(), &out)?;
        }
    }
    Ok(())
}

fn build_run_project_copy(config: &Config, msg: &Message) -> anyhow::Result<PathBuf> {
    let meta = msg
        .metadata
        .as_ref()
        .ok_or_else(|| anyhow::anyhow!("missing metadata"))?;
    let (sender_root, folder_name) = sender_project_root(config, meta)?;
    let dest_root = receiver_private_submissions_path(config)?;
    let dest_path = dest_root.join(&folder_name);

    // Always copy if project.yaml is missing (handles incomplete/failed copies)
    let project_yaml = dest_path.join("project.yaml");
    if !project_yaml.exists() {
        copy_dir_recursive(&sender_root, &dest_path)?;
    }

    Ok(dest_path)
}

fn prompt_participant_source(default_source: &str) -> anyhow::Result<String> {
    let input: String = Input::new()
        .with_prompt("Participant source (syft://, file.yaml#fragment, or sample ID)")
        .default(default_source.to_string())
        .interact_text()?;
    Ok(input)
}

fn normalize_participant_source_for_real(input: &str) -> anyhow::Result<String> {
    // If it already looks like a URL/path/fragment, keep as-is
    if input.contains("://")
        || input.contains('/')
        || input.contains(".yaml")
        || input.contains('#')
    {
        return Ok(input.to_string());
    }
    // Otherwise treat as participant ID under local participants.yaml
    let biovault_home = crate::config::get_biovault_home()?;
    let participants_file = biovault_home.join("participants.yaml");
    let file_str = participants_file.to_string_lossy();
    Ok(format!("{}#participants.{}", file_str, input))
}

fn send_status_ack_with_meta(
    config: &Config,
    original: &Message,
    status: &str,
    body: Option<String>,
    extra_metadata: Option<serde_json::Value>,
) -> anyhow::Result<()> {
    let (db, sync) = init_message_system(config)?;

    let mut reply = Message::reply_to(
        original,
        config.email.clone(),
        body.unwrap_or_else(|| status.to_string()),
    );
    reply.subject = Some(format!("Project {}", status));
    reply.message_type = crate::messages::MessageType::Request {
        request_type: "status".to_string(),
        params: None,
    };
    let mut md = json!({
        "status_update": {
            "message_id": original.id,
            "status": status,
            "reason": reply.body,
        }
    });
    if let Some(extra) = extra_metadata {
        if let Some(obj) = md.as_object_mut() {
            if let Some(extra_obj) = extra.as_object() {
                for (k, v) in extra_obj.iter() {
                    obj.insert(k.clone(), v.clone());
                }
            }
        }
    }
    reply.metadata = Some(md);

    db.insert_message(&reply)?;
    let _ = sync.send_message(&reply.id);
    Ok(())
}

fn reject_project(config: &Config, msg: &Message) -> anyhow::Result<()> {
    let custom = Confirm::new()
        .with_prompt("Add a rejection reason?")
        .default(true)
        .interact()
        .unwrap_or(true);
    let body = if custom {
        Some(
            Input::new()
                .with_prompt("Reason")
                .default("Sorry your request has been rejected.".to_string())
                .interact_text()?,
        )
    } else {
        Some("Sorry your request has been rejected.".to_string())
    };
    send_status_ack_with_meta(config, msg, "rejected", body, None)?;
    println!("{}", "Sent rejection to sender.".yellow());
    Ok(())
}

fn review_project(config: &Config, msg: &Message) -> anyhow::Result<()> {
    send_status_ack_with_meta(
        config,
        msg,
        "reviewing",
        Some("Request is under review.".to_string()),
        None,
    )?;
    println!("{}", "Marked as reviewing and notified sender.".yellow());
    Ok(())
}

async fn run_project_test(config: &Config, msg: &Message) -> anyhow::Result<()> {
    let dest = build_run_project_copy(config, msg)?;
    let source = prompt_participant_source("NA06985")?;
    let source_for_run = source.clone();
    run_execute(RunParams {
        project_folder: dest.to_string_lossy().to_string(),
        participant_source: source_for_run,
        test: true,
        download: true,
        dry_run: false,
        with_docker: false,
        work_dir: None,
        resume: false,
        template: None,
        results_dir: None,
        nextflow_args: vec![],
    })
    .await?;
    println!("{}", "Test run completed.".green());
    // Show results directory and a tree of contents
    print_results_location_and_tree(&dest, &source, true)?;
    Ok(())
}

async fn run_project_real(config: &Config, msg: &Message) -> anyhow::Result<()> {
    let dest = build_run_project_copy(config, msg)?;
    let biovault_home = crate::config::get_biovault_home()?;
    let participants_file = biovault_home.join("participants.yaml");
    let default_source = if participants_file.exists() {
        format!("{}#participants.ALL", participants_file.to_string_lossy())
    } else {
        "participants.yaml#participants.ALL".to_string()
    };
    let raw = prompt_participant_source(&default_source)?;
    let source = normalize_participant_source_for_real(&raw)?;
    let source_for_run = source.clone();
    run_execute(RunParams {
        project_folder: dest.to_string_lossy().to_string(),
        participant_source: source_for_run,
        test: false,
        download: false,
        dry_run: false,
        with_docker: false,
        work_dir: None,
        resume: false,
        template: None,
        results_dir: None,
        nextflow_args: vec![],
    })
    .await?;
    println!("{}", "Real data run completed.".green());
    // Show results directory and a tree of contents
    print_results_location_and_tree(&dest, &source, false)?;
    Ok(())
}

/// Non-interactive version of approve_project for automated testing
async fn approve_project_non_interactive(config: &Config, msg: &Message) -> anyhow::Result<()> {
    let dest = build_run_project_copy(config, msg)?;
    let results_dir = dest.join("results-real");
    let needs_run = !results_dir.exists()
        || fs::read_dir(&results_dir)
            .map(|mut i| i.next().is_none())
            .unwrap_or(true);
    if needs_run {
        println!("No results found. Running on real data before approval...");
        run_project_real(config, msg).await?;
    }

    // Release results to sender shared location
    let meta = msg
        .metadata
        .as_ref()
        .ok_or_else(|| anyhow::anyhow!("missing metadata"))?;
    let (sender_root, _folder) = sender_project_root(config, meta)?;
    let sender_results = sender_root.join("results");
    copy_dir_recursive(&results_dir, &sender_results)?;

    // Get project details for the message
    let project_location = meta
        .get("project_location")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown");

    // Check if results exist and get basic info
    let results_info = if sender_results.exists() {
        let mut info = Vec::new();
        if let Ok(entries) = fs::read_dir(&sender_results) {
            for entry in entries.flatten() {
                if entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
                    info.push(format!("{}/", entry.file_name().to_string_lossy()));
                } else {
                    info.push(entry.file_name().to_string_lossy().to_string());
                }
            }
        }
        if info.is_empty() {
            "No results found".to_string()
        } else {
            format!("Results:\n  {}", info.join("\n  "))
        }
    } else {
        "Results directory not found".to_string()
    };

    // Create relative path for results location
    let data_dir = config.get_syftbox_data_dir()?;
    let relative_results = if sender_results.starts_with(&data_dir) {
        format!(
            "$SYFTBOX_DATA_DIR/{}",
            sender_results.strip_prefix(&data_dir)?.to_string_lossy()
        )
    } else {
        sender_results.to_string_lossy().to_string()
    };

    // Create the default approval message with results location
    let body = format!(
        "Your project has been approved.\n\nProject location: {}\nResults location: {}\n\n{}",
        project_location, relative_results, results_info
    );

    // Include results_path in the status update so sender can see it directly
    let extra = json!({ "results_path": relative_results });
    send_status_ack_with_meta(config, msg, "approved", Some(body), Some(extra))?;
    println!(
        "{}",
        "Approved, results released, and sender notified.".green()
    );
    Ok(())
}

async fn approve_project(config: &Config, msg: &Message) -> anyhow::Result<()> {
    let dest = build_run_project_copy(config, msg)?;
    let results_dir = dest.join("results-real");
    let needs_run = !results_dir.exists()
        || fs::read_dir(&results_dir)
            .map(|mut i| i.next().is_none())
            .unwrap_or(true);
    if needs_run {
        println!("No results found. Running on real data before approval...");
        run_project_real(config, msg).await?;
    }

    // Release results to sender shared location
    let meta = msg
        .metadata
        .as_ref()
        .ok_or_else(|| anyhow::anyhow!("missing metadata"))?;
    let (sender_root, _folder) = sender_project_root(config, meta)?;
    let sender_results = sender_root.join("results");
    copy_dir_recursive(&results_dir, &sender_results)?;

    // Get project details for the message
    let project_location = meta
        .get("project_location")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown");

    // Check if results exist and get basic info
    let results_info = if sender_results.exists() {
        let mut info = Vec::new();
        if let Ok(entries) = fs::read_dir(&sender_results) {
            for entry in entries.flatten() {
                if entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
                    info.push(format!("{}/", entry.file_name().to_string_lossy()));
                } else {
                    info.push(entry.file_name().to_string_lossy().to_string());
                }
            }
        }
        if info.is_empty() {
            "No results found".to_string()
        } else {
            format!("Results:\n  {}", info.join("\n  "))
        }
    } else {
        "Results directory not found".to_string()
    };

    // Create relative path for results location
    let data_dir = config.get_syftbox_data_dir()?;
    let relative_results = if sender_results.starts_with(&data_dir) {
        format!(
            "$SYFTBOX_DATA_DIR/{}",
            sender_results.strip_prefix(&data_dir)?.to_string_lossy()
        )
    } else {
        sender_results.to_string_lossy().to_string()
    };

    // Create the default approval message with results location
    let default_message = format!(
        "Your project has been approved.\n\nProject location: {}\nResults location: {}\n\n{}",
        project_location, relative_results, results_info
    );

    // Optional approval message
    let add_note = Confirm::new()
        .with_prompt("Add a message to approval?")
        .default(false)
        .interact()
        .unwrap_or(false);
    let body = if add_note {
        Some(
            Input::new()
                .with_prompt("Message")
                .default(default_message.clone())
                .interact_text()?,
        )
    } else {
        Some(default_message)
    };

    // Include results_path in the status update so sender can see it directly
    let extra = json!({ "results_path": relative_results });
    send_status_ack_with_meta(config, msg, "approved", body, Some(extra))?;
    println!(
        "{}",
        "Approved, results released, and sender notified.".green()
    );
    Ok(())
}

fn extract_participant_id(source: &str) -> Option<String> {
    if let Some(pos) = source.find('#') {
        let frag = &source[pos + 1..];
        if let Some(rest) = frag.strip_prefix("participants.") {
            return Some(rest.to_string());
        }
    }
    // If it doesn't look like a path/URL and has no fragment, treat the whole string as the ID
    if !(source.contains("://")
        || source.contains('/')
        || source.contains(".yaml")
        || source.contains('#'))
    {
        return Some(source.to_string());
    }
    None
}

fn print_results_location_and_tree(
    project_root: &Path,
    participant_source: &str,
    is_test: bool,
) -> anyhow::Result<()> {
    let id = extract_participant_id(participant_source).unwrap_or_else(|| "ALL".to_string());
    let base = if is_test {
        "results-test"
    } else {
        "results-real"
    };
    let results_dir = project_root.join(base).join(&id);
    println!("Results location: {}", results_dir.display());
    if results_dir.exists() {
        println!("Results tree:");
        print_dir_tree(&results_dir, 3)?;
    } else {
        println!("Results folder not found yet at {}", results_dir.display());
    }
    Ok(())
}

fn print_dir_tree(root: &Path, max_depth: usize) -> anyhow::Result<()> {
    fn walk(dir: &Path, depth: usize, max_depth: usize) -> anyhow::Result<()> {
        if depth > max_depth {
            return Ok(());
        }
        let mut entries: Vec<_> = fs::read_dir(dir)?
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .collect();
        entries.sort();
        for path in entries {
            let indent = "  ".repeat(depth.saturating_sub(0));
            let name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
            if path.is_dir() {
                println!("{}{}/", indent, name);
                walk(&path, depth + 1, max_depth)?;
            } else {
                println!("{}{}", indent, name);
            }
        }
        Ok(())
    }
    println!("{}/", root.display());
    walk(root, 1, max_depth)
}

/// View a message thread
pub fn view_thread(config: &Config, thread_id: &str) -> Result<()> {
    let (db, sync) = init_message_system(config)?;

    // Quietly sync to get latest messages in thread
    let _ = sync.sync_quiet();

    let messages = db.get_thread_messages(thread_id)?;

    if messages.is_empty() {
        println!("No messages found in thread: {}", thread_id);
        return Ok(());
    }

    println!("\n💬 Thread: {}", thread_id);
    println!("═══════════════════════════");

    for msg in messages {
        let local_time = msg.created_at.with_timezone(&chrono::Local);
        println!("\n[{}] {}", local_time.format("%Y-%m-%d %H:%M"), msg.from);

        if let Some(subj) = &msg.subject {
            println!("Subject: {}", subj);
        }

        // Expand environment variables in message body
        let expanded_body = expand_env_vars_in_text(&msg.body)?;
        println!("{}", expanded_body);
        println!("─────────────────────");
    }

    Ok(())
}

/// Sync messages (check for new incoming and update ACKs)
pub fn sync_messages(config: &Config) -> Result<()> {
    let (_, sync) = init_message_system(config)?;

    println!("🔄 Syncing messages...");
    sync.sync()?;

    Ok(())
}

/// Resolve a syft:// URL to a local filesystem path within the SyftBox data dir
fn resolve_syft_url_to_path(config: &Config, url: &str) -> anyhow::Result<PathBuf> {
    let parsed = SyftURL::parse(url)?;
    let data_dir = config.get_syftbox_data_dir()?;
    Ok(data_dir
        .join("datasites")
        .join(parsed.email)
        .join(parsed.path))
}

/// Verify a project message using embedded metadata
/// Returns (is_ok, extra_note)
fn verify_project_from_metadata(
    config: &Config,
    metadata: &serde_json::Value,
) -> anyhow::Result<(bool, String)> {
    // Extract the embedded project.yaml
    let project_val = metadata
        .get("project")
        .ok_or_else(|| anyhow::anyhow!("missing project metadata"))?;

    let project: ProjectYaml = serde_json::from_value(project_val.clone())
        .map_err(|e| anyhow::anyhow!("invalid project metadata: {}", e))?;

    // Extract project location syft URL
    let project_location = metadata
        .get("project_location")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("missing project_location syft URL"))?;

    let root = resolve_syft_url_to_path(config, project_location)?;
    if !root.exists() {
        return Ok((false, format!(" (missing path: {})", root.display())));
    }

    // Need b3_hashes to verify
    let Some(expected_hashes) = project.b3_hashes.clone() else {
        return Ok((false, " (no hashes provided)".to_string()));
    };

    // Verify each expected file hash
    let mut mismatches: Vec<String> = Vec::new();
    for (rel, expected) in expected_hashes.iter() {
        let file_path = root.join(rel);
        if !file_path.exists() {
            mismatches.push(format!("missing: {}", rel));
            continue;
        }
        let bytes = std::fs::read(&file_path)
            .map_err(|e| anyhow::anyhow!("failed to read {}: {}", file_path.display(), e))?;
        let got = blake3::hash(&bytes).to_hex().to_string();
        if got != *expected {
            mismatches.push(format!("mismatch: {}", rel));
        }
    }

    if mismatches.is_empty() {
        Ok((true, String::new()))
    } else {
        let preview = if mismatches.len() > 3 {
            format!(" ({} issues; first: {})", mismatches.len(), mismatches[0])
        } else {
            format!(" ({})", mismatches.join(", "))
        };
        Ok((false, preview))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use tempfile::TempDir;

    fn create_test_config() -> Config {
        Config {
            email: "test@example.com".to_string(),
            syftbox_config: None,
            version: None,
            binary_paths: None,
            syftbox_credentials: None,
        }
    }

    #[test]
    fn test_init_message_system() -> Result<()> {
        let temp_dir = TempDir::new()?;
        crate::config::set_test_syftbox_data_dir(temp_dir.path());
        crate::config::set_test_biovault_home(temp_dir.path().join(".biovault_test"));
        let config = create_test_config();

        // Initialize the message system
        let db_path = get_message_db_path(&config)?;
        let db = MessageDb::new(&db_path)?;

        // Test that we can list messages (should be empty in fresh test DB)
        let messages = db.list_messages(None)?;
        assert_eq!(messages.len(), 0);

        Ok(())
    }

    #[test]
    fn test_message_crud() -> Result<()> {
        let temp_dir = TempDir::new()?;
        crate::config::set_test_syftbox_data_dir(temp_dir.path());
        crate::config::set_test_biovault_home(temp_dir.path().join(".biovault_test"));
        let config = create_test_config();

        // Initialize just the database, not the full system (to avoid sync)
        let db_path = get_message_db_path(&config)?;
        let db = MessageDb::new(&db_path)?;

        // Create a message
        let msg = Message::new(
            "test@example.com".to_string(),
            "recipient@example.com".to_string(),
            "Test message body".to_string(),
        );

        // Insert
        db.insert_message(&msg)?;

        // Read
        let retrieved = db.get_message(&msg.id)?;
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().body, "Test message body");

        // List
        let messages = db.list_messages(None)?;
        assert_eq!(messages.len(), 1);

        // Delete
        db.delete_message(&msg.id)?;

        // Verify it's marked as deleted (soft delete)
        let deleted_msg = db.get_message(&msg.id)?;
        assert!(deleted_msg.is_some());
        assert_eq!(
            deleted_msg.unwrap().status,
            crate::messages::MessageStatus::Deleted
        );

        // Verify it doesn't show in normal list
        let messages_after_delete = db.list_messages(None)?;
        assert_eq!(messages_after_delete.len(), 0);

        Ok(())
    }

    #[test]
    fn normalize_participant_source_for_real_behaviour() -> Result<()> {
        let tmp = TempDir::new()?;
        crate::config::set_test_biovault_home(tmp.path().join(".bv"));

        // Existing URL/path strings are preserved
        assert_eq!(
            normalize_participant_source_for_real("syft://x/y#z")?,
            "syft://x/y#z"
        );
        assert_eq!(
            normalize_participant_source_for_real("/abs/path/participants.yaml#p.ID")?,
            "/abs/path/participants.yaml#p.ID"
        );

        // Bare ID resolves to participants.yaml under BIOVAULT home
        let got = normalize_participant_source_for_real("TESTID")?;
        assert!(got.ends_with("participants.yaml#participants.TESTID"));
        Ok(())
    }

    #[test]
    fn resolve_and_paths_and_copy_dir() -> Result<()> {
        let tmp = TempDir::new()?;
        // SyftBox data dir and config email
        crate::config::set_test_syftbox_data_dir(tmp.path());
        let cfg = Config {
            email: "u@example.com".into(),
            syftbox_config: None,
            version: None,
            binary_paths: None,
            syftbox_credentials: None,
        };

        // Build a fake project tree under datasites/u@example.com/app_data/biovault/submissions/proj1
        let root = tmp
            .path()
            .join("datasites/u@example.com/app_data/biovault/submissions/proj1");
        std::fs::create_dir_all(root.join("a/b")).unwrap();
        std::fs::write(root.join("a/b/file.txt"), b"hi").unwrap();
        // This file should be skipped when copying
        std::fs::write(root.join("a/syft.pub.yaml"), b"rules:").unwrap();

        // sender_project_root from metadata
        let loc = format!(
            "syft://u@example.com/app_data/biovault/submissions/{}",
            "proj1"
        );
        let meta = json!({
            "project_location": loc
        });
        let (sender_root, folder) = sender_project_root(&cfg, &meta)?;
        assert_eq!(folder, "proj1");
        assert!(sender_root.ends_with("proj1"));

        // receiver path (should be at root level, not inside datasite)
        let recv = receiver_private_submissions_path(&cfg)?;
        assert!(recv.ends_with("private/app_data/biovault/submissions"));
        assert!(!recv
            .to_string_lossy()
            .contains("datasites/u@example.com/private"));

        // Copy behaviour: skip syft.pub.yaml and recreate tree
        let dest = recv.join(&folder);
        copy_dir_recursive(&sender_root, &dest)?;
        assert!(dest.join("a/b/file.txt").exists());
        assert!(!dest.join("a/syft.pub.yaml").exists());

        Ok(())
    }

    #[test]
    fn build_run_project_copy_creates_dest_once() -> Result<()> {
        let tmp = TempDir::new()?;
        crate::config::set_test_syftbox_data_dir(tmp.path());
        let cfg = Config {
            email: "u@example.com".into(),
            syftbox_config: None,
            version: None,
            binary_paths: None,
            syftbox_credentials: None,
        };

        // Make sender tree and one file
        let proj = tmp
            .path()
            .join("datasites/u@example.com/app_data/biovault/submissions/projX");
        std::fs::create_dir_all(proj.join("dir")).unwrap();
        std::fs::write(proj.join("dir/f.txt"), b"x").unwrap();
        let meta =
            json!({"project_location": "syft://u@example.com/app_data/biovault/submissions/projX"});
        let mut msg = Message::new("u@example.com".into(), "v@example.com".into(), "b".into());
        msg.metadata = Some(meta);

        let dest1 = build_run_project_copy(&cfg, &msg)?;
        assert!(dest1.join("dir/f.txt").exists());
        // Call again; should not error and keep same path
        let dest2 = build_run_project_copy(&cfg, &msg)?;
        assert_eq!(dest1, dest2);
        Ok(())
    }

    #[test]
    fn verify_project_from_metadata_ok_and_fail() -> Result<()> {
        let tmp = TempDir::new()?;
        crate::config::set_test_syftbox_data_dir(tmp.path());
        let cfg = Config {
            email: "u@example.com".into(),
            syftbox_config: None,
            version: None,
            binary_paths: None,
            syftbox_credentials: None,
        };

        // Build project root with two files and compute blake3
        let root = tmp
            .path()
            .join("datasites/u@example.com/app_data/biovault/submissions/projZ");
        std::fs::create_dir_all(&root).unwrap();
        let f1 = root.join("a.txt");
        let f2 = root.join("b.txt");
        std::fs::write(&f1, b"A").unwrap();
        std::fs::write(&f2, b"B").unwrap();
        let h1 = blake3::hash(&std::fs::read(&f1).unwrap())
            .to_hex()
            .to_string();
        let h2 = blake3::hash(&std::fs::read(&f2).unwrap())
            .to_hex()
            .to_string();

        // Construct embedded project.yaml equivalent in metadata
        let project = json!({
            "name": "n", "author":"a", "workflow":"w",
            "b3_hashes": {"a.txt": h1, "b.txt": h2}
        });
        let meta_ok = json!({
            "project": project,
            "project_location": "syft://u@example.com/app_data/biovault/submissions/projZ"
        });
        let (ok, note) = verify_project_from_metadata(&cfg, &meta_ok)?;
        assert!(ok, "expected OK, got note: {}", note);

        // Now break one file and expect failure with note
        std::fs::write(&f2, b"BROKEN").unwrap();
        let (ok2, note2) = verify_project_from_metadata(&cfg, &meta_ok)?;
        assert!(!ok2);
        assert!(!note2.is_empty());
        Ok(())
    }

    #[test]
    fn list_messages_displays_without_actions() -> Result<()> {
        let tmp = TempDir::new()?;
        crate::config::set_test_syftbox_data_dir(tmp.path());
        crate::config::set_test_biovault_home(tmp.path().join(".bv"));
        let cfg = Config {
            email: "me@example.com".into(),
            syftbox_config: None,
            version: None,
            binary_paths: None,
            syftbox_credentials: None,
        };
        // Init DB only
        let db_path = get_message_db_path(&cfg)?;
        let db = MessageDb::new(&db_path)?;
        // Insert a simple draft message from me -> other (so no interactive recipient actions)
        let m = Message::new(
            "me@example.com".into(),
            "you@example.com".into(),
            "body".into(),
        );
        db.insert_message(&m)?;
        // Should render list without interacting
        list_messages(&cfg, false, false, false)?;
        Ok(())
    }

    #[tokio::test]
    async fn read_message_marks_received_as_read() -> Result<()> {
        let tmp = TempDir::new()?;
        crate::config::set_test_syftbox_data_dir(tmp.path());
        crate::config::set_test_biovault_home(tmp.path().join(".bv"));
        let cfg = Config {
            email: "me@example.com".into(),
            syftbox_config: None,
            version: None,
            binary_paths: None,
            syftbox_credentials: None,
        };
        let db_path = get_message_db_path(&cfg)?;
        let db = MessageDb::new(&db_path)?;

        let mut m = Message::new(
            "you@example.com".into(),
            "me@example.com".into(),
            "hi".into(),
        );
        m.status = crate::messages::MessageStatus::Received;
        db.insert_message(&m)?;

        read_message(&cfg, &m.id).await?;
        let updated = db.get_message(&m.id)?.unwrap();
        assert_eq!(updated.status, crate::messages::MessageStatus::Read);
        Ok(())
    }

    #[test]
    fn send_and_delete_message_flow() -> Result<()> {
        let tmp = TempDir::new()?;
        // Point syftbox data dir and biovault home to temp
        crate::config::set_test_syftbox_data_dir(tmp.path());
        crate::config::set_test_biovault_home(tmp.path().join(".bv"));
        let cfg = create_test_config();

        // Send a message to another recipient
        super::send_message(&cfg, "you@example.com", "hello", Some("subj"))?;

        // Validate DB has a sent message
        let db_path = get_message_db_path(&cfg)?;
        let db = MessageDb::new(&db_path)?;
        let msgs = db.list_sent_messages(None)?;
        assert!(!msgs.is_empty());
        let first = &msgs[0];
        assert_eq!(first.status, crate::messages::MessageStatus::Sent);
        assert_eq!(first.to, "you@example.com");

        // Delete the message (soft delete)
        super::delete_message(&cfg, &first.id)?;
        let after = db.get_message(&first.id)?.unwrap();
        assert_eq!(after.status, crate::messages::MessageStatus::Deleted);
        Ok(())
    }

    #[test]
    fn reply_message_creates_response() -> Result<()> {
        let tmp = TempDir::new()?;
        crate::config::set_test_syftbox_data_dir(tmp.path());
        crate::config::set_test_biovault_home(tmp.path().join(".bv"));
        let cfg = create_test_config();
        // Initialize DB and insert an incoming message to reply to
        let db_path = get_message_db_path(&cfg)?;
        let db = MessageDb::new(&db_path)?;
        let mut original = Message::new("alice@example.com".into(), cfg.email.clone(), "hi".into());
        original.status = crate::messages::MessageStatus::Received;
        db.insert_message(&original)?;

        super::reply_message(&cfg, &original.id, "re: hi")?;

        // Should have at least one sent message now
        let sent = db.list_sent_messages(None)?;
        assert!(!sent.is_empty());
        Ok(())
    }

    #[test]
    fn list_messages_smoke() -> Result<()> {
        let tmp = TempDir::new()?;
        crate::config::set_test_syftbox_data_dir(tmp.path());
        crate::config::set_test_biovault_home(tmp.path().join(".bv"));
        let cfg = create_test_config();

        // With empty DB
        super::list_messages(&cfg, false, false, false)?;
        super::list_messages(&cfg, true, false, false)?;
        Ok(())
    }

    #[test]
    fn test_view_thread_empty() -> Result<()> {
        let tmp = TempDir::new()?;
        crate::config::set_test_syftbox_data_dir(tmp.path());
        crate::config::set_test_biovault_home(tmp.path().join(".bv"));
        let cfg = create_test_config();

        // View non-existent thread should not error
        super::view_thread(&cfg, "nonexistent-thread")?;
        Ok(())
    }

    #[test]
    fn test_sync_messages() -> Result<()> {
        let tmp = TempDir::new()?;
        crate::config::set_test_syftbox_data_dir(tmp.path());
        crate::config::set_test_biovault_home(tmp.path().join(".bv"));
        let cfg = create_test_config();

        // Should not error even without messages
        super::sync_messages(&cfg)?;
        Ok(())
    }

    #[test]
    fn test_resolve_syft_url_to_path() -> Result<()> {
        let tmp = TempDir::new()?;
        crate::config::set_test_syftbox_data_dir(tmp.path());
        let cfg = create_test_config();

        let url = "syft://user@example.com/path/to/file";
        let path = super::resolve_syft_url_to_path(&cfg, url)?;

        assert!(path.to_string_lossy().contains("datasites"));
        assert!(path.to_string_lossy().contains("user@example.com"));
        assert!(path.to_string_lossy().contains("path/to/file"));
        Ok(())
    }

    #[test]
    fn test_get_message_db_path() -> Result<()> {
        let tmp = TempDir::new()?;
        crate::config::set_test_biovault_home(tmp.path());
        let cfg = create_test_config();

        let path = get_message_db_path(&cfg)?;
        assert!(path.to_string_lossy().contains("messages.db"));
        assert!(path.parent().unwrap().exists());
        Ok(())
    }

    #[test]
    fn test_cleanup_locks() -> Result<()> {
        let tmp = TempDir::new()?;
        crate::config::set_test_biovault_home(tmp.path());
        let cfg = create_test_config();

        let result = cleanup_locks(&cfg, false);
        assert!(result.is_ok());
        Ok(())
    }

    #[test]
    fn test_expand_env_vars_in_text_multiple() -> Result<()> {
        std::env::set_var("SYFTBOX_DATA_DIR", "/data");
        let text = "$SYFTBOX_DATA_DIR/a and $SYFTBOX_DATA_DIR/b";
        let result = expand_env_vars_in_text(text)?;
        assert_eq!(result, "/data/a and /data/b");
        std::env::remove_var("SYFTBOX_DATA_DIR");
        Ok(())
    }

    #[test]
    fn test_receiver_private_submissions_path() -> Result<()> {
        let tmp = TempDir::new()?;
        crate::config::set_test_syftbox_data_dir(tmp.path());
        let cfg = create_test_config();

        let path = receiver_private_submissions_path(&cfg)?;
        assert!(path.to_string_lossy().contains("private"));
        assert!(path.to_string_lossy().contains("submissions"));
        Ok(())
    }

    #[test]
    fn test_copy_dir_recursive_empty() -> Result<()> {
        let tmp = TempDir::new()?;
        let src = tmp.path().join("src");
        let dst = tmp.path().join("dst");
        std::fs::create_dir(&src)?;

        copy_dir_recursive(&src, &dst)?;
        assert!(dst.exists());
        Ok(())
    }

    #[test]
    fn test_normalize_participant_source_for_real_url() -> Result<()> {
        let tmp = TempDir::new()?;
        crate::config::set_test_biovault_home(tmp.path());

        let url = "syft://user@example.com/file#id";
        let result = normalize_participant_source_for_real(url)?;
        assert_eq!(result, url);
        Ok(())
    }
}