terraphim_middleware 1.16.34

Terraphim middleware for searching haystacks
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
use serde_json::json;
use std::collections::HashMap;
use std::path::PathBuf;
use terraphim_atomic_client::{self, Store};
use terraphim_config::{ConfigBuilder, Haystack, Role, ServiceType};
use terraphim_middleware::{
    haystack::AtomicHaystackIndexer, indexer::IndexMiddleware, search_haystacks,
};
use terraphim_types::{RelevanceFunction, SearchQuery};
use uuid::Uuid;

/// Test that demonstrates atomic server haystack integration with Title Scorer role
/// This test creates a complete config with atomic server haystack using TitleScorer,
/// sets up sample documents, and tests the search functionality through the standard terraphim search pipeline.
#[tokio::test]
async fn test_atomic_haystack_title_scorer_role() {
    // Initialize logging for test debugging
    let _ = env_logger::builder()
        .filter_level(log::LevelFilter::Info)
        .is_test(true)
        .try_init();

    // Load atomic server configuration from environment
    dotenvy::dotenv().ok();
    let server_url =
        std::env::var("ATOMIC_SERVER_URL").unwrap_or_else(|_| "http://localhost:9883".to_string());
    let atomic_secret = std::env::var("ATOMIC_SERVER_SECRET").ok();

    if atomic_secret.is_none() {
        log::warn!("ATOMIC_SERVER_SECRET not set, test may fail with authentication");
    }

    // Create atomic store for setup and cleanup
    let atomic_config = terraphim_atomic_client::Config {
        server_url: server_url.clone(),
        agent: atomic_secret
            .as_ref()
            .and_then(|secret| terraphim_atomic_client::Agent::from_base64(secret).ok()),
    };
    let store = Store::new(atomic_config).expect("Failed to create atomic store");

    // 1. Create test documents in the atomic server
    let test_id = Uuid::new_v4();
    let server_base = server_url.trim_end_matches('/');

    // Create parent collection for test documents
    let parent_subject = format!("{}/test-title-scorer-{}", server_base, test_id);
    let mut parent_properties = HashMap::new();
    parent_properties.insert(
        "https://atomicdata.dev/properties/isA".to_string(),
        json!(["https://atomicdata.dev/classes/Collection"]),
    );
    parent_properties.insert(
        "https://atomicdata.dev/properties/name".to_string(),
        json!("Title Scorer Test Documents"),
    );
    parent_properties.insert(
        "https://atomicdata.dev/properties/description".to_string(),
        json!("Collection of test documents for Title Scorer role"),
    );
    parent_properties.insert(
        "https://atomicdata.dev/properties/parent".to_string(),
        json!(server_base),
    );

    store
        .create_with_commit(&parent_subject, parent_properties)
        .await
        .expect("Failed to create parent collection");

    let mut created_documents = Vec::new();

    // Create test documents with clear titles for title-based scoring
    let documents = vec![
        (
            "terraphim-guide",
            "Terraphim User Guide",
            "A comprehensive guide to using Terraphim for knowledge management and search.",
        ),
        (
            "terraphim-arch",
            "Terraphim Architecture Overview",
            "Detailed overview of Terraphim system architecture and components.",
        ),
        (
            "atomic-server",
            "Atomic Server Integration",
            "How to integrate and use Atomic Server with Terraphim.",
        ),
        (
            "search-algorithms",
            "Search Algorithm Implementation",
            "Implementation details of various search algorithms in Terraphim.",
        ),
        (
            "knowledge-graph",
            "Knowledge Graph Construction",
            "Building and maintaining knowledge graphs for semantic search.",
        ),
    ];

    for (shortname, title, content) in documents {
        let doc_subject = format!("{}/{}", parent_subject, shortname);
        let mut doc_properties = HashMap::new();
        doc_properties.insert(
            "https://atomicdata.dev/properties/isA".to_string(),
            json!(["https://atomicdata.dev/classes/Article"]),
        );
        doc_properties.insert(
            "https://atomicdata.dev/properties/name".to_string(),
            json!(title),
        );
        doc_properties.insert(
            "https://atomicdata.dev/properties/description".to_string(),
            json!(content),
        );
        doc_properties.insert(
            "https://atomicdata.dev/properties/parent".to_string(),
            json!(&parent_subject),
        );
        doc_properties.insert(
            "https://atomicdata.dev/properties/shortname".to_string(),
            json!(shortname),
        );

        // Add Terraphim-specific body property for better content extraction
        doc_properties.insert(
            "http://localhost:9883/terraphim-drive/terraphim/property/body".to_string(),
            json!(content),
        );

        store
            .create_with_commit(&doc_subject, doc_properties)
            .await
            .unwrap_or_else(|_| panic!("Failed to create document {}", shortname));

        created_documents.push(doc_subject);
        log::info!("Created test document: {} - {}", shortname, title);
    }

    // Wait for indexing - reduced for faster tests
    tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;

    // 2. Create Terraphim config with atomic server haystack and TitleScorer
    let config = ConfigBuilder::new()
        .global_shortcut("Ctrl+T")
        .add_role(
            "AtomicTitleScorer",
            Role {
                shortname: Some("title-scorer".to_string()),
                name: "Atomic Title Scorer".into(),
                relevance_function: RelevanceFunction::TitleScorer,
                terraphim_it: false,
                theme: "cerulean".to_string(),
                kg: None, // No knowledge graph for title scorer
                haystacks: vec![Haystack::new(server_url.clone(), ServiceType::Atomic, true)
                    .with_atomic_secret(atomic_secret.clone())],
                extra: ahash::AHashMap::new(),
                ..Default::default()
            },
        )
        .build()
        .expect("Failed to build config");

    // 3. Test direct atomic haystack indexer with title-based search
    let indexer = AtomicHaystackIndexer::default();
    let haystack = &config
        .roles
        .get(&"AtomicTitleScorer".into())
        .unwrap()
        .haystacks[0];

    // Test search with terms that should match titles (both test docs and real docs)
    let search_terms = vec![
        ("Terraphim", 2),    // Should find test doc + real docs with 'Terraphim' in title
        ("Architecture", 1), // Should find architecture-related docs
        ("Search", 1),       // Should find the Search Algorithm doc
        ("Knowledge", 1),    // Should find the Knowledge Graph doc
        ("Server", 1),       // Should find the Atomic Server doc
        ("Guide", 1),        // Should find guide documents
        ("Introduction", 1), // Should find introduction documents
        ("nonexistent", 0),  // Should find nothing
    ];

    for (search_term, expected_min_results) in search_terms {
        log::info!("Testing title-based search for: '{}'", search_term);

        // Single search call - indexing should be instant for local server
        let start_time = std::time::Instant::now();
        let index = indexer
            .index(search_term, haystack)
            .await
            .unwrap_or_else(|_| panic!("Search failed for term: {}", search_term));
        let search_duration = start_time.elapsed();

        let found_docs = index.len();
        log::info!(
            "  Search took {:?} and found {} documents for '{}' (expected at least {})",
            search_duration,
            found_docs,
            search_term,
            expected_min_results
        );

        if expected_min_results > 0 {
            assert!(
                found_docs >= expected_min_results,
                "Expected at least {} results for '{}', but got {}",
                expected_min_results,
                search_term,
                found_docs
            );

            // Verify document content and that titles are being used for scoring
            for doc in index.values() {
                assert!(!doc.title.is_empty(), "Document title should not be empty");
                assert!(!doc.body.is_empty(), "Document body should not be empty");
                log::debug!(
                    "  Found document: {} - {}",
                    doc.title,
                    doc.body.chars().take(100).collect::<String>()
                );

                // For title scorer, verify that matching terms are in the title or body (since full-text search includes body)
                if search_term != "nonexistent" {
                    let term_lower = search_term.to_lowercase();
                    let title_lower = doc.title.to_lowercase();
                    let body_lower = doc.body.to_lowercase();

                    // Check if the search term appears in title or body (atomic server does full-text search)
                    let found_in_content = title_lower.contains(&term_lower) ||
                                          body_lower.contains(&term_lower) ||
                                          // Also check for partial matches (first word of search term)
                                          title_lower.contains(term_lower.split_whitespace().next().unwrap_or("")) ||
                                          body_lower.contains(term_lower.split_whitespace().next().unwrap_or(""));

                    if !found_in_content {
                        log::warn!(
                            "Document '{}' doesn't contain search term '{}' in title or body",
                            doc.title,
                            search_term
                        );
                        log::debug!(
                            "Title: '{}', Body preview: '{}'",
                            doc.title,
                            doc.body.chars().take(200).collect::<String>()
                        );
                    }

                    // For atomic server, we expect the search term to be found somewhere in the document
                    // since it uses full-text search across all properties
                    assert!(found_in_content,
                           "Document should contain search term '{}' somewhere for full-text search. Title: '{}', Body preview: '{}'",
                           search_term, doc.title, doc.body.chars().take(100).collect::<String>());
                }
            }
        } else {
            assert_eq!(
                found_docs, 0,
                "Expected no results for '{}', but got {}",
                search_term, found_docs
            );
        }
    }

    // 4. Test integration with terraphim search pipeline
    log::info!("Testing integration with terraphim search pipeline (Title Scorer)");

    let config_state = terraphim_config::ConfigState::new(&mut config.clone())
        .await
        .expect("Failed to create config state");

    let search_query = SearchQuery {
        search_term: "Terraphim".to_string().into(),
        skip: Some(0),
        limit: Some(10),
        role: Some("AtomicTitleScorer".into()),
        operator: None,
        search_terms: None,
    };

    let pipeline_start_time = std::time::Instant::now();
    let search_results = search_haystacks(config_state, search_query)
        .await
        .expect("Failed to search haystacks");
    let pipeline_duration = pipeline_start_time.elapsed();

    assert!(
        !search_results.is_empty(),
        "Search pipeline should return results for 'Terraphim'"
    );
    log::info!(
        "Search pipeline took {:?} and returned {} results",
        pipeline_duration,
        search_results.len()
    );

    // Verify search results have proper content and title-based ranking
    for doc in search_results.values() {
        assert!(!doc.title.is_empty(), "Document title should not be empty");
        assert!(!doc.body.is_empty(), "Document body should not be empty");

        // Check if 'terraphim' appears in title or body (atomic server does full-text search)
        let title_lower = doc.title.to_lowercase();
        let body_lower = doc.body.to_lowercase();
        let contains_terraphim =
            title_lower.contains("terraphim") || body_lower.contains("terraphim");

        if !contains_terraphim {
            log::warn!(
                "Document '{}' doesn't contain 'terraphim' in title or body",
                doc.title
            );
        }

        assert!(
            contains_terraphim,
            "Document should contain 'terraphim' somewhere for full-text search. Title: '{}', Body preview: '{}'",
            doc.title,
            doc.body.chars().take(100).collect::<String>()
        );
        log::debug!(
            "Pipeline result: {} - {}",
            doc.title,
            doc.body.chars().take(100).collect::<String>()
        );
    }

    // 5. Cleanup - delete test documents
    log::info!("Cleaning up test documents");
    for doc_subject in &created_documents {
        match store.delete_with_commit(doc_subject).await {
            Ok(_) => log::debug!("Deleted test document: {}", doc_subject),
            Err(e) => log::warn!("Failed to delete test document {}: {}", doc_subject, e),
        }
    }

    // Delete parent collection
    match store.delete_with_commit(&parent_subject).await {
        Ok(_) => log::info!("Deleted parent collection: {}", parent_subject),
        Err(e) => log::warn!(
            "Failed to delete parent collection {}: {}",
            parent_subject,
            e
        ),
    }

    log::info!("✅ Atomic haystack Title Scorer role test completed successfully");
}

/// Test that demonstrates atomic server haystack integration with Graph Embeddings role
/// This test creates a complete config with atomic server haystack using TerraphimGraph,
/// sets up sample documents, and tests the search functionality through the standard terraphim search pipeline.
#[tokio::test]
async fn test_atomic_haystack_graph_embeddings_role() {
    // Initialize logging for test debugging
    let _ = env_logger::builder()
        .filter_level(log::LevelFilter::Info)
        .is_test(true)
        .try_init();

    // Load atomic server configuration from environment
    dotenvy::dotenv().ok();
    let server_url =
        std::env::var("ATOMIC_SERVER_URL").unwrap_or_else(|_| "http://localhost:9883".to_string());
    let atomic_secret = std::env::var("ATOMIC_SERVER_SECRET").ok();

    if atomic_secret.is_none() {
        log::warn!("ATOMIC_SERVER_SECRET not set, test may fail with authentication");
    }

    // Create atomic store for setup and cleanup
    let atomic_config = terraphim_atomic_client::Config {
        server_url: server_url.clone(),
        agent: atomic_secret
            .as_ref()
            .and_then(|secret| terraphim_atomic_client::Agent::from_base64(secret).ok()),
    };
    let store = Store::new(atomic_config).expect("Failed to create atomic store");

    // 1. Create test documents in the atomic server with graph-related content
    let test_id = Uuid::new_v4();
    let server_base = server_url.trim_end_matches('/');

    // Create parent collection for test documents
    let parent_subject = format!("{}/test-graph-embeddings-{}", server_base, test_id);
    let mut parent_properties = HashMap::new();
    parent_properties.insert(
        "https://atomicdata.dev/properties/isA".to_string(),
        json!(["https://atomicdata.dev/classes/Collection"]),
    );
    parent_properties.insert(
        "https://atomicdata.dev/properties/name".to_string(),
        json!("Graph Embeddings Test Documents"),
    );
    parent_properties.insert(
        "https://atomicdata.dev/properties/description".to_string(),
        json!("Collection of test documents for Graph Embeddings role"),
    );
    parent_properties.insert(
        "https://atomicdata.dev/properties/parent".to_string(),
        json!(server_base),
    );

    store
        .create_with_commit(&parent_subject, parent_properties)
        .await
        .expect("Failed to create parent collection");

    let mut created_documents = Vec::new();

    // Create test documents with graph-related content for graph-based scoring
    let documents = vec![
        (
            "terraphim-graph",
            "Terraphim Graph Implementation",
            "Implementation of the Terraphim knowledge graph with nodes, edges, and embeddings.",
        ),
        (
            "graph-embeddings",
            "Graph Embeddings and Vector Search",
            "Using graph embeddings for semantic search and knowledge discovery.",
        ),
        (
            "knowledge-nodes",
            "Knowledge Graph Nodes and Relationships",
            "Building knowledge graph nodes and establishing semantic relationships.",
        ),
        (
            "semantic-search",
            "Semantic Search with Graph Embeddings",
            "Implementing semantic search using graph embeddings and vector similarity.",
        ),
        (
            "graph-algorithms",
            "Graph Algorithms for Knowledge Discovery",
            "Algorithms for traversing and analyzing knowledge graphs.",
        ),
    ];

    for (shortname, title, content) in documents {
        let doc_subject = format!("{}/{}", parent_subject, shortname);
        let mut doc_properties = HashMap::new();
        doc_properties.insert(
            "https://atomicdata.dev/properties/isA".to_string(),
            json!(["https://atomicdata.dev/classes/Article"]),
        );
        doc_properties.insert(
            "https://atomicdata.dev/properties/name".to_string(),
            json!(title),
        );
        doc_properties.insert(
            "https://atomicdata.dev/properties/description".to_string(),
            json!(content),
        );
        doc_properties.insert(
            "https://atomicdata.dev/properties/parent".to_string(),
            json!(&parent_subject),
        );
        doc_properties.insert(
            "https://atomicdata.dev/properties/shortname".to_string(),
            json!(shortname),
        );

        // Add Terraphim-specific body property for better content extraction
        doc_properties.insert(
            "http://localhost:9883/terraphim-drive/terraphim/property/body".to_string(),
            json!(content),
        );

        store
            .create_with_commit(&doc_subject, doc_properties)
            .await
            .unwrap_or_else(|_| panic!("Failed to create document {}", shortname));

        created_documents.push(doc_subject);
        log::info!("Created test document: {} - {}", shortname, title);
    }

    // Wait for indexing - reduced for faster tests
    tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;

    // 2. Create Terraphim config with atomic server haystack and TerraphimGraph
    let config = ConfigBuilder::new()
        .global_shortcut("Ctrl+G")
        .add_role(
            "AtomicGraphEmbeddings",
            Role {
                shortname: Some("graph-embeddings".to_string()),
                name: "Atomic Graph Embeddings".into(),
                relevance_function: RelevanceFunction::TerraphimGraph,
                terraphim_it: true,
                theme: "superhero".to_string(),
                kg: Some(terraphim_config::KnowledgeGraph {
                    automata_path: None, // Will be built from local files
                    knowledge_graph_local: Some(terraphim_config::KnowledgeGraphLocal {
                        input_type: terraphim_types::KnowledgeGraphInputType::Markdown,
                        path: PathBuf::from("docs/src"),
                    }),
                    public: true,
                    publish: true,
                }),
                haystacks: vec![Haystack::new(server_url.clone(), ServiceType::Atomic, true)
                    .with_atomic_secret(atomic_secret.clone())],
                extra: ahash::AHashMap::new(),
                ..Default::default()
            },
        )
        .build()
        .expect("Failed to build config");

    // 3. Test direct atomic haystack indexer with graph-based search
    let indexer = AtomicHaystackIndexer::default();
    let haystack = &config
        .roles
        .get(&"AtomicGraphEmbeddings".into())
        .unwrap()
        .haystacks[0];

    // Test search with graph-related terms
    let search_terms = vec![
        ("graph", 3),       // Should find graph-related docs
        ("embeddings", 2),  // Should find embedding-related docs
        ("knowledge", 2),   // Should find knowledge-related docs
        ("semantic", 1),    // Should find semantic search doc
        ("terraphim", 1),   // Should find Terraphim graph doc
        ("algorithms", 1),  // Should find graph algorithms doc
        ("nonexistent", 0), // Should find nothing
    ];

    for (search_term, expected_min_results) in search_terms {
        log::info!("Testing graph-based search for: '{}'", search_term);

        // Single search call - indexing should be instant for local server
        let start_time = std::time::Instant::now();
        let index = indexer
            .index(search_term, haystack)
            .await
            .unwrap_or_else(|_| panic!("Search failed for term: {}", search_term));
        let search_duration = start_time.elapsed();

        let found_docs = index.len();
        log::info!(
            "  Search took {:?} and found {} documents for '{}' (expected at least {})",
            search_duration,
            found_docs,
            search_term,
            expected_min_results
        );

        if expected_min_results > 0 {
            assert!(
                found_docs >= expected_min_results,
                "Expected at least {} results for '{}', but got {}",
                expected_min_results,
                search_term,
                found_docs
            );

            // Verify document content
            for doc in index.values() {
                assert!(!doc.title.is_empty(), "Document title should not be empty");
                assert!(!doc.body.is_empty(), "Document body should not be empty");
                log::debug!(
                    "  Found document: {} - {}",
                    doc.title,
                    doc.body.chars().take(100).collect::<String>()
                );
            }
        } else {
            assert_eq!(
                found_docs, 0,
                "Expected no results for '{}', but got {}",
                search_term, found_docs
            );
        }
    }

    // 4. Test integration with terraphim search pipeline
    log::info!("Testing integration with terraphim search pipeline (Graph Embeddings)");

    let config_state = terraphim_config::ConfigState::new(&mut config.clone())
        .await
        .expect("Failed to create config state");

    let search_query = SearchQuery {
        search_term: "graph".to_string().into(),
        skip: Some(0),
        limit: Some(10),
        role: Some("AtomicGraphEmbeddings".into()),
        operator: None,
        search_terms: None,
    };

    let pipeline_start_time = std::time::Instant::now();
    let search_results = search_haystacks(config_state, search_query)
        .await
        .expect("Failed to search haystacks");
    let pipeline_duration = pipeline_start_time.elapsed();

    assert!(
        !search_results.is_empty(),
        "Search pipeline should return results for 'graph'"
    );
    log::info!(
        "Search pipeline took {:?} and returned {} results",
        pipeline_duration,
        search_results.len()
    );

    // Verify search results have proper content and graph-based ranking
    for doc in search_results.values() {
        assert!(!doc.title.is_empty(), "Document title should not be empty");
        assert!(!doc.body.is_empty(), "Document body should not be empty");
        log::debug!(
            "Pipeline result: {} - {}",
            doc.title,
            doc.body.chars().take(100).collect::<String>()
        );
    }

    // 5. Cleanup - delete test documents
    log::info!("Cleaning up test documents");
    for doc_subject in &created_documents {
        match store.delete_with_commit(doc_subject).await {
            Ok(_) => log::debug!("Deleted test document: {}", doc_subject),
            Err(e) => log::warn!("Failed to delete test document {}: {}", doc_subject, e),
        }
    }

    // Delete parent collection
    match store.delete_with_commit(&parent_subject).await {
        Ok(_) => log::info!("Deleted parent collection: {}", parent_subject),
        Err(e) => log::warn!(
            "Failed to delete parent collection {}: {}",
            parent_subject,
            e
        ),
    }

    log::info!("✅ Atomic haystack Graph Embeddings role test completed successfully");
}

/// Test that compares the behavior difference between Title Scorer and Graph Embeddings roles
#[tokio::test]
async fn test_atomic_haystack_role_comparison() {
    // Initialize logging for test debugging
    let _ = env_logger::builder()
        .filter_level(log::LevelFilter::Info)
        .is_test(true)
        .try_init();

    // Load atomic server configuration from environment
    dotenvy::dotenv().ok();
    let server_url =
        std::env::var("ATOMIC_SERVER_URL").unwrap_or_else(|_| "http://localhost:9883".to_string());
    let atomic_secret = std::env::var("ATOMIC_SERVER_SECRET").ok();

    if atomic_secret.is_none() {
        log::warn!("ATOMIC_SERVER_SECRET not set, test may fail with authentication");
    }

    // Create atomic store for setup and cleanup
    let atomic_config = terraphim_atomic_client::Config {
        server_url: server_url.clone(),
        agent: atomic_secret
            .as_ref()
            .and_then(|secret| terraphim_atomic_client::Agent::from_base64(secret).ok()),
    };
    let store = Store::new(atomic_config).expect("Failed to create atomic store");

    // 1. Create test documents in the atomic server
    let test_id = Uuid::new_v4();
    let server_base = server_url.trim_end_matches('/');

    // Create parent collection for test documents
    let parent_subject = format!("{}/test-role-comparison-{}", server_base, test_id);
    let mut parent_properties = HashMap::new();
    parent_properties.insert(
        "https://atomicdata.dev/properties/isA".to_string(),
        json!(["https://atomicdata.dev/classes/Collection"]),
    );
    parent_properties.insert(
        "https://atomicdata.dev/properties/name".to_string(),
        json!("Role Comparison Test Documents"),
    );
    parent_properties.insert(
        "https://atomicdata.dev/properties/description".to_string(),
        json!("Collection of test documents for role comparison"),
    );
    parent_properties.insert(
        "https://atomicdata.dev/properties/parent".to_string(),
        json!(server_base),
    );

    store
        .create_with_commit(&parent_subject, parent_properties)
        .await
        .expect("Failed to create parent collection");

    let mut created_documents = Vec::new();

    // Create test documents that can be scored differently by title vs graph
    let documents = vec![
        ("rust-programming", "Rust Programming Guide", "A comprehensive guide to Rust programming language. This document covers ownership, borrowing, and concurrency patterns in Rust."),
        ("graph-algorithms", "Graph Algorithms and Data Structures", "Implementation of graph algorithms including depth-first search, breadth-first search, and shortest path algorithms."),
        ("machine-learning", "Machine Learning with Graph Embeddings", "Using graph embeddings for machine learning tasks and knowledge representation."),
        ("terraphim-architecture", "Terraphim System Architecture", "Detailed architecture of the Terraphim system including knowledge graphs, search algorithms, and atomic server integration."),
    ];

    for (shortname, title, content) in documents {
        let doc_subject = format!("{}/{}", parent_subject, shortname);
        let mut doc_properties = HashMap::new();
        doc_properties.insert(
            "https://atomicdata.dev/properties/isA".to_string(),
            json!(["https://atomicdata.dev/classes/Article"]),
        );
        doc_properties.insert(
            "https://atomicdata.dev/properties/name".to_string(),
            json!(title),
        );
        doc_properties.insert(
            "https://atomicdata.dev/properties/description".to_string(),
            json!(content),
        );
        doc_properties.insert(
            "https://atomicdata.dev/properties/parent".to_string(),
            json!(&parent_subject),
        );
        doc_properties.insert(
            "https://atomicdata.dev/properties/shortname".to_string(),
            json!(shortname),
        );

        // Add Terraphim-specific body property for better content extraction
        doc_properties.insert(
            "http://localhost:9883/terraphim-drive/terraphim/property/body".to_string(),
            json!(content),
        );

        store
            .create_with_commit(&doc_subject, doc_properties)
            .await
            .unwrap_or_else(|_| panic!("Failed to create document {}", shortname));

        created_documents.push(doc_subject);
        log::info!("Created test document: {} - {}", shortname, title);
    }

    // Wait for indexing - reduced for faster tests
    tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;

    // 2. Create both role configurations
    let title_scorer_config = ConfigBuilder::new()
        .global_shortcut("Ctrl+T")
        .add_role(
            "TitleScorer",
            Role {
                shortname: Some("title-scorer".to_string()),
                name: "Title Scorer".into(),
                relevance_function: RelevanceFunction::TitleScorer,
                terraphim_it: false,
                theme: "cerulean".to_string(),
                kg: None,
                haystacks: vec![Haystack {
                    location: server_url.clone(),
                    service: ServiceType::Atomic,
                    read_only: true,
                    atomic_server_secret: atomic_secret.clone(),
                    extra_parameters: std::collections::HashMap::new(),
                    fetch_content: false,
                }],
                extra: ahash::AHashMap::new(),
                ..Default::default()
            },
        )
        .build()
        .expect("Failed to build title scorer config");

    let graph_embeddings_config = ConfigBuilder::new()
        .global_shortcut("Ctrl+G")
        .add_role(
            "GraphEmbeddings",
            Role {
                shortname: Some("graph-embeddings".to_string()),
                name: "Graph Embeddings".into(),
                relevance_function: RelevanceFunction::TerraphimGraph,
                terraphim_it: true,
                theme: "superhero".to_string(),
                kg: Some(terraphim_config::KnowledgeGraph {
                    automata_path: None,
                    knowledge_graph_local: Some(terraphim_config::KnowledgeGraphLocal {
                        input_type: terraphim_types::KnowledgeGraphInputType::Markdown,
                        path: PathBuf::from("docs/src"),
                    }),
                    public: true,
                    publish: true,
                }),
                haystacks: vec![Haystack {
                    location: server_url.clone(),
                    service: ServiceType::Atomic,
                    read_only: true,
                    atomic_server_secret: atomic_secret.clone(),
                    extra_parameters: std::collections::HashMap::new(),
                    fetch_content: false,
                }],
                extra: ahash::AHashMap::new(),
                ..Default::default()
            },
        )
        .build()
        .expect("Failed to build graph embeddings config");

    // 3. Test search with both roles and compare results
    let indexer = AtomicHaystackIndexer::default();
    let title_haystack = &title_scorer_config
        .roles
        .get(&"TitleScorer".into())
        .unwrap()
        .haystacks[0];
    let graph_haystack = &graph_embeddings_config
        .roles
        .get(&"GraphEmbeddings".into())
        .unwrap()
        .haystacks[0];

    // Test search terms that should show different behavior
    let search_terms = vec!["graph", "programming", "algorithms", "machine", "terraphim"];

    for search_term in search_terms {
        log::info!("Comparing search results for: '{}'", search_term);

        // Search with title scorer
        let title_start_time = std::time::Instant::now();
        let title_index = indexer
            .index(search_term, title_haystack)
            .await
            .unwrap_or_else(|_| panic!("Title scorer search failed for term: {}", search_term));
        let title_duration = title_start_time.elapsed();

        // Search with graph embeddings
        let graph_start_time = std::time::Instant::now();
        let graph_index = indexer
            .index(search_term, graph_haystack)
            .await
            .unwrap_or_else(|_| panic!("Graph embeddings search failed for term: {}", search_term));
        let graph_duration = graph_start_time.elapsed();

        log::info!(
            "  Title Scorer took {:?} and found: {} documents",
            title_duration,
            title_index.len()
        );
        log::info!(
            "  Graph Embeddings took {:?} and found: {} documents",
            graph_duration,
            graph_index.len()
        );

        // Log document titles for comparison
        log::info!("  Title Scorer results:");
        for doc in title_index.values() {
            log::info!("    - {}", doc.title);
        }

        log::info!("  Graph Embeddings results:");
        for doc in graph_index.values() {
            log::info!("    - {}", doc.title);
        }

        // Both should find some results for valid terms
        if search_term != "nonexistent" {
            assert!(
                !title_index.is_empty() || !graph_index.is_empty(),
                "At least one role should find results for '{}'",
                search_term
            );
        }
    }

    // 4. Test integration with terraphim search pipeline for both roles
    log::info!("Testing search pipeline integration for both roles");

    let title_config_state = terraphim_config::ConfigState::new(&mut title_scorer_config.clone())
        .await
        .expect("Failed to create title scorer config state");

    let graph_config_state =
        terraphim_config::ConfigState::new(&mut graph_embeddings_config.clone())
            .await
            .expect("Failed to create graph embeddings config state");

    let search_query = SearchQuery {
        search_term: "graph".to_string().into(),
        skip: Some(0),
        limit: Some(10),
        role: None, // Will use default role
        operator: None,
        search_terms: None,
    };

    // Test with title scorer
    let title_pipeline_start = std::time::Instant::now();
    let title_results = search_haystacks(title_config_state, search_query.clone())
        .await
        .expect("Failed to search with title scorer");
    let title_pipeline_duration = title_pipeline_start.elapsed();

    // Test with graph embeddings
    let graph_pipeline_start = std::time::Instant::now();
    let graph_results = search_haystacks(graph_config_state, search_query)
        .await
        .expect("Failed to search with graph embeddings");
    let graph_pipeline_duration = graph_pipeline_start.elapsed();

    log::info!(
        "Title Scorer pipeline took {:?} and returned {} results",
        title_pipeline_duration,
        title_results.len()
    );
    log::info!(
        "Graph Embeddings pipeline took {:?} and returned {} results",
        graph_pipeline_duration,
        graph_results.len()
    );

    // Both should return results
    assert!(
        !title_results.is_empty() || !graph_results.is_empty(),
        "At least one role should return results from search pipeline"
    );

    // 5. Cleanup - delete test documents
    log::info!("Cleaning up test documents");
    for doc_subject in &created_documents {
        match store.delete_with_commit(doc_subject).await {
            Ok(_) => log::debug!("Deleted test document: {}", doc_subject),
            Err(e) => log::warn!("Failed to delete test document {}: {}", doc_subject, e),
        }
    }

    // Delete parent collection
    match store.delete_with_commit(&parent_subject).await {
        Ok(_) => log::info!("Deleted parent collection: {}", parent_subject),
        Err(e) => log::warn!(
            "Failed to delete parent collection {}: {}",
            parent_subject,
            e
        ),
    }

    log::info!("✅ Atomic haystack role comparison test completed successfully");
}

/// Test configuration validation for both roles
#[tokio::test]
async fn test_atomic_roles_config_validation() {
    // Test Title Scorer role configuration
    let title_scorer_config = ConfigBuilder::new()
        .global_shortcut("Ctrl+T")
        .add_role(
            "TitleScorer",
            Role {
                shortname: Some("title-scorer".to_string()),
                name: "Title Scorer".into(),
                relevance_function: RelevanceFunction::TitleScorer,
                terraphim_it: false,
                theme: "cerulean".to_string(),
                kg: None, // Title scorer doesn't need knowledge graph
                haystacks: vec![Haystack {
                    location: "http://localhost:9883".to_string(),
                    service: ServiceType::Atomic,
                    read_only: true,
                    atomic_server_secret: None,
                    extra_parameters: std::collections::HashMap::new(),
                    fetch_content: false,
                }],
                extra: ahash::AHashMap::new(),
                ..Default::default()
            },
        )
        .build()
        .expect("Failed to build title scorer config");

    // Verify Title Scorer role configuration
    let title_role = title_scorer_config
        .roles
        .get(&"TitleScorer".into())
        .unwrap();
    assert_eq!(
        title_role.relevance_function,
        RelevanceFunction::TitleScorer
    );
    assert!(
        title_role.kg.is_none(),
        "Title scorer should not have knowledge graph"
    );
    assert_eq!(title_role.haystacks.len(), 1);
    assert_eq!(title_role.haystacks[0].service, ServiceType::Atomic);

    // Test Graph Embeddings role configuration
    let graph_embeddings_config = ConfigBuilder::new()
        .global_shortcut("Ctrl+G")
        .add_role(
            "GraphEmbeddings",
            Role {
                shortname: Some("graph-embeddings".to_string()),
                name: "Graph Embeddings".into(),
                relevance_function: RelevanceFunction::TerraphimGraph,
                terraphim_it: true,
                theme: "superhero".to_string(),
                kg: Some(terraphim_config::KnowledgeGraph {
                    automata_path: None,
                    knowledge_graph_local: Some(terraphim_config::KnowledgeGraphLocal {
                        input_type: terraphim_types::KnowledgeGraphInputType::Markdown,
                        path: PathBuf::from("docs/src"),
                    }),
                    public: true,
                    publish: true,
                }),
                haystacks: vec![Haystack {
                    location: "http://localhost:9883".to_string(),
                    service: ServiceType::Atomic,
                    read_only: true,
                    atomic_server_secret: None,
                    extra_parameters: std::collections::HashMap::new(),
                    fetch_content: false,
                }],
                extra: ahash::AHashMap::new(),
                ..Default::default()
            },
        )
        .build()
        .expect("Failed to build graph embeddings config");

    // Verify Graph Embeddings role configuration
    let graph_role = graph_embeddings_config
        .roles
        .get(&"GraphEmbeddings".into())
        .unwrap();
    assert_eq!(
        graph_role.relevance_function,
        RelevanceFunction::TerraphimGraph
    );
    assert!(
        graph_role.kg.is_some(),
        "Graph embeddings should have knowledge graph"
    );
    assert_eq!(graph_role.haystacks.len(), 1);
    assert_eq!(graph_role.haystacks[0].service, ServiceType::Atomic);

    log::info!("✅ Atomic roles configuration validation test completed successfully");
}

/// Test comprehensive atomic server haystack role configurations including:
/// 1. Pure atomic roles (TitleScorer and TerraphimGraph)
/// 2. Hybrid roles (Atomic + Ripgrep haystacks)
/// 3. Role switching and comparison
/// 4. Configuration validation
#[tokio::test]
async fn test_comprehensive_atomic_haystack_roles() {
    // Initialize logging for test debugging
    let _ = env_logger::builder()
        .filter_level(log::LevelFilter::Info)
        .is_test(true)
        .try_init();

    // Load atomic server configuration from environment
    dotenvy::dotenv().ok();
    let server_url =
        std::env::var("ATOMIC_SERVER_URL").unwrap_or_else(|_| "http://localhost:9883".to_string());
    let atomic_secret = std::env::var("ATOMIC_SERVER_SECRET").ok();

    if atomic_secret.is_none() {
        log::warn!("ATOMIC_SERVER_SECRET not set, test may fail with authentication");
    }

    // Create atomic store for setup and cleanup
    let atomic_config = terraphim_atomic_client::Config {
        server_url: server_url.clone(),
        agent: atomic_secret
            .as_ref()
            .and_then(|secret| terraphim_atomic_client::Agent::from_base64(secret).ok()),
    };
    let store = Store::new(atomic_config).expect("Failed to create atomic store");

    // 1. Create test documents in the atomic server
    let test_id = Uuid::new_v4();
    let server_base = server_url.trim_end_matches('/');

    // Create parent collection for test documents
    let parent_subject = format!("{}/test-comprehensive-roles-{}", server_base, test_id);
    let mut parent_properties = HashMap::new();
    parent_properties.insert(
        "https://atomicdata.dev/properties/name".to_string(),
        json!("Comprehensive Roles Test Collection"),
    );
    parent_properties.insert(
        "https://atomicdata.dev/properties/description".to_string(),
        json!("Test collection for comprehensive atomic haystack role testing"),
    );
    parent_properties.insert(
        "https://atomicdata.dev/properties/isA".to_string(),
        json!(["https://atomicdata.dev/classes/Collection"]),
    );
    parent_properties.insert(
        "https://atomicdata.dev/properties/parent".to_string(),
        json!(server_base),
    );

    store
        .create_with_commit(&parent_subject, parent_properties)
        .await
        .expect("Failed to create parent collection");

    // Create diverse test documents for different search scenarios
    let test_documents = vec![
        (
            format!("{}/atomic-integration-guide", parent_subject),
            "ATOMIC: Integration Guide",
            "Complete guide for integrating Terraphim with atomic server. Covers authentication, configuration, and advanced search features."
        ),
        (
            format!("{}/semantic-search-algorithms", parent_subject),
            "ATOMIC: Semantic Search Algorithms",
            "Advanced semantic search algorithms using graph embeddings, vector spaces, and knowledge graphs for improved relevance."
        ),
        (
            format!("{}/hybrid-haystack-configuration", parent_subject),
            "ATOMIC: Hybrid Haystack Configuration",
            "Configuration guide for setting up hybrid haystacks combining atomic server and ripgrep for comprehensive document search."
        ),
        (
            format!("{}/role-based-search", parent_subject),
            "ATOMIC: Role-Based Search",
            "Role-based search functionality allowing different user roles to access different search capabilities and document sets."
        ),
        (
            format!("{}/performance-optimization", parent_subject),
            "ATOMIC: Performance Optimization",
            "Performance optimization techniques for atomic server integration including caching, indexing, and query optimization."
        ),
    ];

    let mut created_documents = Vec::new();
    for (subject, title, description) in &test_documents {
        let mut properties = HashMap::new();
        properties.insert(
            "https://atomicdata.dev/properties/name".to_string(),
            json!(title),
        );
        properties.insert(
            "https://atomicdata.dev/properties/description".to_string(),
            json!(description),
        );
        properties.insert(
            "https://atomicdata.dev/properties/isA".to_string(),
            json!(["https://atomicdata.dev/classes/Article"]),
        );
        properties.insert(
            "https://atomicdata.dev/properties/parent".to_string(),
            json!(parent_subject),
        );

        store
            .create_with_commit(subject, properties)
            .await
            .expect("Failed to create test document");
        created_documents.push(subject.clone());
        log::debug!("Created test document: {}", title);
    }

    log::info!(
        "Created {} test documents in atomic server",
        created_documents.len()
    );

    // 2. Create comprehensive role configurations

    // Pure Atomic Title Scorer Role
    let pure_atomic_title_config = ConfigBuilder::new()
        .global_shortcut("Ctrl+1")
        .add_role(
            "PureAtomicTitle",
            Role {
                shortname: Some("pure-atomic-title".to_string()),
                name: "Pure Atomic Title".into(),
                relevance_function: RelevanceFunction::TitleScorer,
                terraphim_it: false,
                theme: "cerulean".to_string(),
                kg: None,
                haystacks: vec![Haystack {
                    location: server_url.clone(),
                    service: ServiceType::Atomic,
                    read_only: true,
                    atomic_server_secret: atomic_secret.clone(),
                    extra_parameters: std::collections::HashMap::new(),
                    fetch_content: false,
                }],
                extra: ahash::AHashMap::new(),
                ..Default::default()
            },
        )
        .build()
        .expect("Failed to build pure atomic title config");

    // Pure Atomic Graph Embeddings Role
    let pure_atomic_graph_config = ConfigBuilder::new()
        .global_shortcut("Ctrl+2")
        .add_role(
            "PureAtomicGraph",
            Role {
                shortname: Some("pure-atomic-graph".to_string()),
                name: "Pure Atomic Graph".into(),
                relevance_function: RelevanceFunction::TerraphimGraph,
                terraphim_it: true,
                theme: "superhero".to_string(),
                kg: Some(terraphim_config::KnowledgeGraph {
                    automata_path: None,
                    knowledge_graph_local: Some(terraphim_config::KnowledgeGraphLocal {
                        input_type: terraphim_types::KnowledgeGraphInputType::Markdown,
                        path: PathBuf::from("docs/src"),
                    }),
                    public: true,
                    publish: true,
                }),
                haystacks: vec![Haystack {
                    location: server_url.clone(),
                    service: ServiceType::Atomic,
                    read_only: true,
                    atomic_server_secret: atomic_secret.clone(),
                    extra_parameters: std::collections::HashMap::new(),
                    fetch_content: false,
                }],
                extra: ahash::AHashMap::new(),
                ..Default::default()
            },
        )
        .build()
        .expect("Failed to build pure atomic graph config");

    // Hybrid Role: Atomic + Ripgrep with Title Scorer
    let hybrid_title_config = ConfigBuilder::new()
        .global_shortcut("Ctrl+3")
        .add_role(
            "HybridTitle",
            Role {
                shortname: Some("hybrid-title".to_string()),
                name: "Hybrid Title".into(),
                relevance_function: RelevanceFunction::TitleScorer,
                terraphim_it: false,
                theme: "lumen".to_string(),
                kg: None,
                haystacks: vec![
                    Haystack {
                        location: server_url.clone(),
                        service: ServiceType::Atomic,
                        read_only: true,
                        atomic_server_secret: atomic_secret.clone(),
                        extra_parameters: std::collections::HashMap::new(),
                        fetch_content: false,
                    },
                    Haystack {
                        location: "docs/src".to_string(),
                        service: ServiceType::Ripgrep,
                        read_only: true,
                        atomic_server_secret: None,
                        extra_parameters: std::collections::HashMap::new(),
                        fetch_content: false,
                    },
                ],
                extra: ahash::AHashMap::new(),
                ..Default::default()
            },
        )
        .build()
        .expect("Failed to build hybrid title config");

    // Hybrid Role: Atomic + Ripgrep with Graph Embeddings
    let hybrid_graph_config = ConfigBuilder::new()
        .global_shortcut("Ctrl+4")
        .add_role(
            "HybridGraph",
            Role {
                shortname: Some("hybrid-graph".to_string()),
                name: "Hybrid Graph".into(),
                relevance_function: RelevanceFunction::TerraphimGraph,
                terraphim_it: true,
                theme: "darkly".to_string(),
                kg: Some(terraphim_config::KnowledgeGraph {
                    automata_path: None,
                    knowledge_graph_local: Some(terraphim_config::KnowledgeGraphLocal {
                        input_type: terraphim_types::KnowledgeGraphInputType::Markdown,
                        path: PathBuf::from("docs/src"),
                    }),
                    public: true,
                    publish: true,
                }),
                haystacks: vec![
                    Haystack {
                        location: server_url.clone(),
                        service: ServiceType::Atomic,
                        read_only: true,
                        atomic_server_secret: atomic_secret.clone(),
                        extra_parameters: std::collections::HashMap::new(),
                        fetch_content: false,
                    },
                    Haystack {
                        location: "docs/src".to_string(),
                        service: ServiceType::Ripgrep,
                        read_only: true,
                        atomic_server_secret: None,
                        extra_parameters: std::collections::HashMap::new(),
                        fetch_content: false,
                    },
                ],
                extra: ahash::AHashMap::new(),
                ..Default::default()
            },
        )
        .build()
        .expect("Failed to build hybrid graph config");

    // 3. Test each role configuration
    let configs = vec![
        ("PureAtomicTitle", pure_atomic_title_config),
        ("PureAtomicGraph", pure_atomic_graph_config),
        ("HybridTitle", hybrid_title_config),
        ("HybridGraph", hybrid_graph_config),
    ];

    let search_terms = vec!["integration", "semantic", "configuration", "performance"];
    let mut all_results = HashMap::new();

    for (role_name, config) in &configs {
        log::info!("Testing role: {}", role_name);

        // Validate configuration structure
        let role = config.roles.values().next().unwrap();
        match *role_name {
            "PureAtomicTitle" | "PureAtomicGraph" => {
                assert_eq!(
                    role.haystacks.len(),
                    1,
                    "Pure atomic roles should have 1 haystack"
                );
                assert_eq!(role.haystacks[0].service, ServiceType::Atomic);
            }
            "HybridTitle" | "HybridGraph" => {
                assert_eq!(
                    role.haystacks.len(),
                    2,
                    "Hybrid roles should have 2 haystacks"
                );
                assert!(role
                    .haystacks
                    .iter()
                    .any(|h| h.service == ServiceType::Atomic));
                assert!(role
                    .haystacks
                    .iter()
                    .any(|h| h.service == ServiceType::Ripgrep));
            }
            _ => panic!("Unknown role name: {}", role_name),
        }

        // Test search functionality for each role
        let indexer = AtomicHaystackIndexer::default();
        let role_results = &mut all_results
            .entry(role_name.to_string())
            .or_insert_with(HashMap::new);

        for search_term in &search_terms {
            let search_start = std::time::Instant::now();

            // Test search across all haystacks for this role
            let mut total_results = 0;
            for haystack in &role.haystacks {
                if haystack.service == ServiceType::Atomic {
                    match indexer.index(search_term, haystack).await {
                        Ok(results) => {
                            total_results += results.len();
                            log::debug!(
                                "Role {}, haystack {:?}, term '{}': {} results",
                                role_name,
                                haystack.service,
                                search_term,
                                results.len()
                            );
                        }
                        Err(e) => {
                            log::warn!(
                                "Search failed for role {}, term '{}': {}",
                                role_name,
                                search_term,
                                e
                            );
                        }
                    }
                }
            }

            let search_duration = search_start.elapsed();
            role_results.insert(search_term.to_string(), (total_results, search_duration));
            log::info!(
                "Role {}, term '{}': {} total results in {:?}",
                role_name,
                search_term,
                total_results,
                search_duration
            );
        }
    }

    // 4. Validate search results and performance
    for (role_name, results) in &all_results {
        log::info!("=== Results Summary for {} ===", role_name);
        for (term, (count, duration)) in results {
            log::info!("  '{}': {} results in {:?}", term, count, duration);

            // Validate that we get reasonable results
            if atomic_secret.is_some() {
                assert!(
                    *count > 0,
                    "Role {} should find results for term '{}'",
                    role_name,
                    term
                );
            }

            // Validate reasonable performance (less than 5 seconds per search)
            assert!(
                duration.as_secs() < 5,
                "Search should complete within 5 seconds"
            );
        }
    }

    // 5. Test role comparison - hybrid roles should generally find more results
    if atomic_secret.is_some() {
        for search_term in &search_terms {
            let pure_title_count = all_results
                .get("PureAtomicTitle")
                .and_then(|r| r.get(*search_term))
                .map(|(count, _)| *count)
                .unwrap_or(0);

            let hybrid_title_count = all_results
                .get("HybridTitle")
                .and_then(|r| r.get(*search_term))
                .map(|(count, _)| *count)
                .unwrap_or(0);

            log::info!(
                "Term '{}': Pure={}, Hybrid={}",
                search_term,
                pure_title_count,
                hybrid_title_count
            );

            // Hybrid should generally find more or equal results (has additional ripgrep haystack)
            // Note: This is not always guaranteed depending on document overlap
            if hybrid_title_count < pure_title_count {
                log::warn!("Hybrid role found fewer results than pure atomic for '{}' - this may indicate an issue", search_term);
            }
        }
    }

    // 6. Test configuration serialization and deserialization
    for (role_name, config) in &configs {
        let json_str = serde_json::to_string_pretty(config).expect("Failed to serialize config");

        let deserialized_config: terraphim_config::Config =
            serde_json::from_str(&json_str).expect("Failed to deserialize config");

        assert_eq!(
            config.roles.len(),
            deserialized_config.roles.len(),
            "Serialized config should maintain role count for {}",
            role_name
        );

        log::debug!("Role {} config serialization validated", role_name);
    }

    // 7. Cleanup - delete test documents
    log::info!("Cleaning up test documents");
    for doc_subject in &created_documents {
        match store.delete_with_commit(doc_subject).await {
            Ok(_) => log::debug!("Deleted test document: {}", doc_subject),
            Err(e) => log::warn!("Failed to delete test document {}: {}", doc_subject, e),
        }
    }

    // Delete parent collection
    match store.delete_with_commit(&parent_subject).await {
        Ok(_) => log::info!("Deleted parent collection: {}", parent_subject),
        Err(e) => log::warn!(
            "Failed to delete parent collection {}: {}",
            parent_subject,
            e
        ),
    }

    log::info!("✅ Comprehensive atomic haystack roles test completed successfully");
}

/// Test atomic server error handling and graceful degradation
#[tokio::test]
async fn test_atomic_haystack_error_handling() {
    // Initialize logging for test debugging
    let _ = env_logger::builder()
        .filter_level(log::LevelFilter::Info)
        .is_test(true)
        .try_init();

    // Test with invalid atomic server URL
    let invalid_config = ConfigBuilder::new()
        .global_shortcut("Ctrl+E")
        .add_role(
            "InvalidAtomic",
            Role {
                shortname: Some("invalid-atomic".to_string()),
                name: "Invalid Atomic".into(),
                relevance_function: RelevanceFunction::TitleScorer,
                terraphim_it: false,
                theme: "cerulean".to_string(),
                kg: None,
                haystacks: vec![Haystack {
                    location: "http://localhost:9999".to_string(), // Non-existent server
                    service: ServiceType::Atomic,
                    read_only: true,
                    atomic_server_secret: Some("invalid_secret".to_string()),
                    extra_parameters: std::collections::HashMap::new(),
                    fetch_content: false,
                }],
                extra: ahash::AHashMap::new(),
                ..Default::default()
            },
        )
        .build()
        .expect("Failed to build invalid config");

    // Test search with invalid configuration - should handle errors gracefully
    let indexer = AtomicHaystackIndexer::default();
    let role = invalid_config.roles.values().next().unwrap();
    let haystack = &role.haystacks[0];

    let search_result = indexer.index("test", haystack).await;

    // Should return an error, not panic
    assert!(
        search_result.is_err(),
        "Search with invalid atomic server should return error"
    );
    log::info!(
        "✅ Error handling test: Got expected error - {}",
        search_result.unwrap_err()
    );

    // Test with missing secret
    let no_secret_config = ConfigBuilder::new()
        .global_shortcut("Ctrl+N")
        .add_role(
            "NoSecretAtomic",
            Role {
                shortname: Some("no-secret-atomic".to_string()),
                name: "No Secret Atomic".into(),
                relevance_function: RelevanceFunction::TitleScorer,
                terraphim_it: false,
                theme: "cerulean".to_string(),
                kg: None,
                haystacks: vec![Haystack {
                    location: "http://localhost:9883".to_string(),
                    service: ServiceType::Atomic,
                    read_only: true,
                    atomic_server_secret: None, // No authentication secret
                    extra_parameters: std::collections::HashMap::new(),
                    fetch_content: false,
                }],
                extra: ahash::AHashMap::new(),
                ..Default::default()
            },
        )
        .build()
        .expect("Failed to build no-secret config");

    let no_secret_role = no_secret_config.roles.values().next().unwrap();
    let no_secret_haystack = &no_secret_role.haystacks[0];

    let no_secret_result = indexer.index("test", no_secret_haystack).await;

    // May succeed (anonymous access) or fail (authentication required) - both are valid
    match no_secret_result {
        Ok(results) => {
            log::info!("✅ Anonymous access test: Found {} results", results.len());
        }
        Err(e) => {
            log::info!(
                "✅ Authentication required test: Got expected error - {}",
                e
            );
        }
    }

    log::info!("✅ Atomic haystack error handling test completed successfully");
}