graphrag-core 0.2.0

Core portable library for GraphRAG - works on native and WASM
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
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
//! TOML Configuration System for GraphRAG
//! Complete configuration management with extensive TOML support

use crate::Result;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;

/// Complete GraphRAG configuration loaded from TOML
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SetConfig {
    /// Pipeline mode/approach configuration
    #[serde(default)]
    pub mode: ModeConfig,

    /// Semantic/Neural pipeline configuration
    #[serde(default)]
    pub semantic: Option<SemanticPipelineConfig>,

    /// Algorithmic/Classic NLP pipeline configuration
    #[serde(default)]
    pub algorithmic: Option<AlgorithmicPipelineConfig>,

    /// Hybrid pipeline configuration
    #[serde(default)]
    pub hybrid: Option<HybridPipelineConfig>,

    /// General system settings
    #[serde(default)]
    pub general: GeneralConfig,

    /// Pipeline configuration
    #[serde(default)]
    pub pipeline: PipelineConfig,

    /// Storage configuration
    #[serde(default)]
    pub storage: StorageConfig,

    /// Model configuration
    #[serde(default)]
    pub models: ModelsConfig,

    /// Performance tuning
    #[serde(default)]
    pub performance: PerformanceConfig,

    /// Ollama-specific configuration
    #[serde(default)]
    pub ollama: OllamaSetConfig,

    /// GLiNER-Relex extractor configuration
    #[serde(default)]
    pub gliner: GlinerSetConfig,

    /// Experimental features
    #[serde(default)]
    pub experimental: ExperimentalConfig,

    /// Top-level entity extraction configuration (for gleaning)
    #[serde(default)]
    pub entity_extraction: EntityExtractionTopLevelConfig,

    /// Auto-save configuration for workspace persistence
    #[serde(default)]
    pub auto_save: AutoSaveSetConfig,
}

/// Auto-save / storage configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutoSaveSetConfig {
    /// Enable persistent storage.
    /// `false` (default) → graph lives in memory only.
    /// `true` → graph is saved to disk after `build_graph()` and reloaded on the next run.
    #[serde(default)]
    pub enabled: bool,

    /// Base directory for workspace storage. Required when `enabled = true`.
    /// Example: `"./output"` or `"/data/graphrag"`.
    /// The workspace folder is created at `<base_dir>/<workspace_name>/`.
    #[serde(default)]
    pub base_dir: Option<String>,

    /// Auto-save interval in seconds (0 = save after every graph build)
    #[serde(default = "default_auto_save_interval")]
    pub interval_seconds: u64,

    /// Workspace name — sub-folder inside `base_dir` (default: "default").
    #[serde(default)]
    pub workspace_name: Option<String>,

    /// Maximum number of auto-save versions to keep (0 = unlimited)
    #[serde(default = "default_max_auto_save_versions")]
    pub max_versions: usize,
}

impl Default for AutoSaveSetConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            base_dir: None,
            interval_seconds: default_auto_save_interval(),
            workspace_name: None,
            max_versions: default_max_auto_save_versions(),
        }
    }
}

/// General system configuration settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeneralConfig {
    /// Logging level (error, warn, info, debug, trace)
    #[serde(default = "default_log_level")]
    pub log_level: String,

    /// Output directory for results
    #[serde(default = "default_output_dir")]
    pub output_dir: String,

    /// Path to the input document to process
    #[serde(default)]
    pub input_document_path: Option<String>,

    /// Maximum threads (0 = auto-detect)
    #[serde(default)]
    pub max_threads: Option<usize>,

    /// Enable performance profiling
    #[serde(default)]
    pub enable_profiling: bool,
}

/// Pipeline execution configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PipelineConfig {
    /// Workflows to execute in sequence
    #[serde(default = "default_workflows")]
    pub workflows: Vec<String>,

    /// Enable parallel execution
    #[serde(default = "default_true")]
    pub parallel_execution: bool,

    /// Text extraction configuration
    #[serde(default)]
    pub text_extraction: TextExtractionConfig,

    /// Entity extraction configuration
    #[serde(default)]
    pub entity_extraction: EntityExtractionConfig,

    /// Graph building configuration
    #[serde(default)]
    pub graph_building: GraphBuildingConfig,

    /// Community detection configuration
    #[serde(default)]
    pub community_detection: CommunityDetectionConfig,
}

/// Text extraction and chunking configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextExtractionConfig {
    /// Chunk size for text splitting
    #[serde(default = "default_chunk_size")]
    pub chunk_size: usize,

    /// Overlap between chunks
    #[serde(default = "default_chunk_overlap")]
    pub chunk_overlap: usize,

    /// Clean control characters
    #[serde(default = "default_true")]
    pub clean_control_chars: bool,

    /// Minimum chunk size to keep
    #[serde(default = "default_min_chunk_size")]
    pub min_chunk_size: usize,

    /// Text cleaning options
    #[serde(default)]
    pub cleaning: Option<CleaningConfig>,
}

/// Text cleaning options configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CleaningConfig {
    /// Remove URLs from text
    #[serde(default)]
    pub remove_urls: bool,

    /// Remove email addresses
    #[serde(default)]
    pub remove_emails: bool,

    /// Normalize whitespace
    #[serde(default = "default_true")]
    pub normalize_whitespace: bool,

    /// Remove special characters
    #[serde(default)]
    pub remove_special_chars: bool,
}

/// Entity extraction configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntityExtractionConfig {
    /// Model name for NER
    #[serde(default = "default_ner_model")]
    pub model_name: String,

    /// Temperature for entity extraction (0.0 = fully deterministic JSON output)
    #[serde(default = "default_extraction_temperature")]
    pub temperature: f32,

    /// Maximum tokens for extraction
    #[serde(default = "default_max_tokens")]
    pub max_tokens: usize,

    /// Entity types to extract (dynamic configuration)
    pub entity_types: Option<Vec<String>>,

    /// Confidence threshold for entity extraction (top-level)
    #[serde(default = "default_confidence_threshold")]
    pub confidence_threshold: f32,

    /// Custom extraction prompt
    pub custom_prompt: Option<String>,

    /// Entity filtering options
    #[serde(default)]
    pub filters: Option<EntityFiltersConfig>,
}

/// Entity filtering configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntityFiltersConfig {
    /// Minimum entity length
    #[serde(default = "default_min_entity_length")]
    pub min_entity_length: usize,

    /// Maximum entity length
    #[serde(default = "default_max_entity_length")]
    pub max_entity_length: usize,

    /// Allowed entity types
    pub allowed_entity_types: Option<Vec<String>>,

    /// Confidence threshold
    #[serde(default = "default_confidence_threshold")]
    pub confidence_threshold: f32,

    /// Allowed regex patterns for entity matching
    pub allowed_patterns: Option<Vec<String>>,

    /// Excluded regex patterns for entity filtering
    pub excluded_patterns: Option<Vec<String>>,

    /// Enable fuzzy matching for entity resolution
    #[serde(default)]
    pub enable_fuzzy_matching: bool,
}

/// Graph building configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphBuildingConfig {
    /// Relation scoring algorithm
    #[serde(default = "default_relation_scorer")]
    pub relation_scorer: String,

    /// Minimum relation score threshold
    #[serde(default = "default_min_relation_score")]
    pub min_relation_score: f32,

    /// Maximum connections per node
    #[serde(default = "default_max_connections")]
    pub max_connections_per_node: usize,

    /// Use bidirectional relationships
    #[serde(default = "default_true")]
    pub bidirectional_relations: bool,
}

/// Community detection configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommunityDetectionConfig {
    /// Algorithm for community detection
    #[serde(default = "default_community_algorithm")]
    pub algorithm: String,

    /// Resolution parameter
    #[serde(default = "default_resolution")]
    pub resolution: f32,

    /// Minimum community size
    #[serde(default = "default_min_community_size")]
    pub min_community_size: usize,

    /// Maximum community size (0 = unlimited)
    #[serde(default)]
    pub max_community_size: usize,
}

/// Storage backend configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageConfig {
    /// Database type
    #[serde(default = "default_database_type")]
    pub database_type: String,

    /// Database path for SQLite
    #[serde(default = "default_database_path")]
    pub database_path: String,

    /// Enable WAL for SQLite
    #[serde(default = "default_true")]
    pub enable_wal: bool,

    /// PostgreSQL configuration
    pub postgresql: Option<PostgreSQLConfig>,

    /// Neo4j configuration
    pub neo4j: Option<Neo4jConfig>,
}

/// PostgreSQL database configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PostgreSQLConfig {
    /// PostgreSQL server host
    pub host: String,
    /// PostgreSQL server port
    pub port: u16,
    /// Database name
    pub database: String,
    /// Username for authentication
    pub username: String,
    /// Password for authentication
    pub password: String,
    /// Connection pool size
    #[serde(default = "default_pool_size")]
    pub pool_size: usize,
}

/// Neo4j graph database configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Neo4jConfig {
    /// Neo4j server URI
    pub uri: String,
    /// Username for authentication
    pub username: String,
    /// Password for authentication
    pub password: String,
    /// Enable encrypted connections
    #[serde(default)]
    pub encrypted: bool,
}

/// Model configuration for LLM and embeddings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelsConfig {
    /// Primary LLM for generation
    #[serde(default = "default_primary_llm")]
    pub primary_llm: String,

    /// Embedding model
    #[serde(default = "default_embedding_model")]
    pub embedding_model: String,

    /// Maximum context length
    #[serde(default = "default_max_context")]
    pub max_context_length: usize,

    /// LLM parameters
    #[serde(default)]
    pub llm_params: Option<LLMParamsConfig>,

    /// Local model configuration
    #[serde(default)]
    pub local: Option<LocalModelsConfig>,
}

/// LLM generation parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LLMParamsConfig {
    /// Sampling temperature (0.0-2.0)
    #[serde(default = "default_temperature")]
    pub temperature: f32,

    /// Nucleus sampling parameter (0.0-1.0)
    #[serde(default = "default_top_p")]
    pub top_p: f32,

    /// Frequency penalty (-2.0-2.0)
    #[serde(default)]
    pub frequency_penalty: f32,

    /// Presence penalty (-2.0-2.0)
    #[serde(default)]
    pub presence_penalty: f32,

    /// Sequences where the model will stop generating
    pub stop_sequences: Option<Vec<String>>,
}

/// Local model configuration (Ollama)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LocalModelsConfig {
    /// Ollama API base URL
    #[serde(default = "default_ollama_url")]
    pub ollama_base_url: String,

    /// Local model name for generation
    #[serde(default = "default_ollama_model")]
    pub model_name: String,

    /// Local embedding model name
    #[serde(default = "default_ollama_embedding")]
    pub embedding_model: String,
}

/// Performance tuning configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceConfig {
    /// Enable batch processing
    #[serde(default = "default_true")]
    pub batch_processing: bool,

    /// Batch size
    #[serde(default = "default_batch_size")]
    pub batch_size: usize,

    /// Worker threads
    #[serde(default = "default_worker_threads")]
    pub worker_threads: usize,

    /// Memory limit per worker (MB)
    #[serde(default = "default_memory_limit")]
    pub memory_limit_mb: usize,
}

/// Ollama-specific configuration for local LLM and embeddings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OllamaSetConfig {
    /// Enable Ollama integration
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// Ollama host
    #[serde(default = "default_ollama_host")]
    pub host: String,

    /// Ollama port
    #[serde(default = "default_ollama_port")]
    pub port: u16,

    /// Chat model name
    #[serde(default = "default_chat_model")]
    pub chat_model: String,

    /// Embedding model name
    #[serde(default = "default_embedding_model_ollama")]
    pub embedding_model: String,

    /// Timeout in seconds
    #[serde(default = "default_timeout")]
    pub timeout_seconds: u64,

    /// Maximum retries
    #[serde(default = "default_max_retries")]
    pub max_retries: u32,

    /// Fallback to hash-based embeddings
    #[serde(default)]
    pub fallback_to_hash: bool,

    /// Maximum tokens
    pub max_tokens: Option<u32>,

    /// Temperature
    pub temperature: Option<f32>,

    /// How long to keep the model loaded in memory (e.g. "1h", "30m", "0")
    ///
    /// Critical for KV Cache efficiency when processing multiple chunks from the same document.
    pub keep_alive: Option<String>,

    /// Context window size in tokens (overrides Ollama model default)
    ///
    /// Ollama silently truncates prompts exceeding the context window.
    /// Set this when processing long documents to avoid silent truncation.
    pub num_ctx: Option<u32>,
}

/// GLiNER-Relex extractor configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GlinerSetConfig {
    /// Enable GLiNER-Relex extraction
    #[serde(default)]
    pub enabled: bool,
    /// Path to the ONNX model file
    #[serde(default)]
    pub model_path: String,
    /// Path to tokenizer.json (defaults to same dir as model_path)
    #[serde(default)]
    pub tokenizer_path: String,
    /// "span" (default) or "token"
    #[serde(default = "default_gliner_mode")]
    pub mode: String,
    /// Entity labels to extract
    #[serde(default = "default_gliner_entity_labels")]
    pub entity_labels: Vec<String>,
    /// Relation labels to extract
    #[serde(default = "default_gliner_relation_labels")]
    pub relation_labels: Vec<String>,
    /// Minimum entity confidence threshold
    #[serde(default = "default_entity_threshold")]
    pub entity_threshold: f32,
    /// Minimum relation confidence threshold
    #[serde(default = "default_relation_threshold")]
    pub relation_threshold: f32,
    /// Use GPU (CUDA) for inference
    #[serde(default)]
    pub use_gpu: bool,
    /// Max concurrent chunk inferences (None → 4)
    #[serde(default)]
    pub max_concurrent_chunks: Option<usize>,
}

fn default_gliner_mode() -> String {
    "span".to_string()
}
// Kept in sync with `GlinerConfig::default()` in config/mod.rs (canonical runtime
// defaults). The drift-guard test `gliner_setconfig_default_matches_runtime` enforces it.
fn default_gliner_entity_labels() -> Vec<String> {
    vec![
        "person".into(),
        "organization".into(),
        "location".into(),
        "concept".into(),
    ]
}
fn default_gliner_relation_labels() -> Vec<String> {
    vec!["related to".into(), "part of".into(), "causes".into()]
}
fn default_entity_threshold() -> f32 {
    0.4
}
fn default_relation_threshold() -> f32 {
    0.5
}

impl Default for GlinerSetConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            model_path: String::new(),
            tokenizer_path: String::new(),
            mode: default_gliner_mode(),
            entity_labels: default_gliner_entity_labels(),
            relation_labels: default_gliner_relation_labels(),
            entity_threshold: default_entity_threshold(),
            relation_threshold: default_relation_threshold(),
            use_gpu: false,
            max_concurrent_chunks: None,
        }
    }
}

/// Experimental features configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ExperimentalConfig {
    /// Enable neural reranking
    #[serde(default)]
    pub neural_reranking: bool,

    /// Enable federated learning
    #[serde(default)]
    pub federated_learning: bool,

    /// Enable real-time updates
    #[serde(default)]
    pub real_time_updates: bool,

    /// Enable distributed processing
    #[serde(default)]
    pub distributed_processing: bool,

    /// Enable LazyGraphRAG mode (no prior summarization, 0.1% indexing cost)
    #[serde(default)]
    pub lazy_graphrag: bool,

    /// Enable E2GraphRAG mode (efficient entity extraction without LLM)
    #[serde(default)]
    pub e2_graphrag: bool,

    /// LazyGraphRAG configuration
    #[serde(default)]
    pub lazy_graphrag_config: Option<LazyGraphRAGConfig>,

    /// E2GraphRAG configuration
    #[serde(default)]
    pub e2_graphrag_config: Option<E2GraphRAGConfig>,
}

/// LazyGraphRAG configuration
/// Concept-based retrieval without prior summarization (Microsoft Research, 2025)
/// Achieves 0.1% of full GraphRAG indexing cost and 700x cheaper query costs
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LazyGraphRAGConfig {
    /// Enable concept extraction (noun phrases without LLM)
    #[serde(default = "default_true")]
    pub use_concept_extraction: bool,

    /// Minimum concept length in characters
    #[serde(default = "default_min_concept_length")]
    pub min_concept_length: usize,

    /// Maximum concept length in words
    #[serde(default = "default_max_concept_words")]
    pub max_concept_words: usize,

    /// Co-occurrence threshold (minimum shared chunks for relationship)
    #[serde(default = "default_co_occurrence_threshold")]
    pub co_occurrence_threshold: usize,

    /// Enable query refinement with iterative deepening
    #[serde(default = "default_true")]
    pub use_query_refinement: bool,

    /// Maximum refinement iterations
    #[serde(default = "default_max_refinement_iterations")]
    pub max_refinement_iterations: usize,

    /// Enable bidirectional entity-chunk indexing for fast lookups
    #[serde(default = "default_true")]
    pub use_bidirectional_index: bool,
}

impl Default for LazyGraphRAGConfig {
    fn default() -> Self {
        Self {
            use_concept_extraction: true,
            min_concept_length: 3,
            max_concept_words: 5,
            co_occurrence_threshold: 1,
            use_query_refinement: true,
            max_refinement_iterations: 3,
            use_bidirectional_index: true,
        }
    }
}

/// E2GraphRAG configuration
/// Efficient entity extraction using SpaCy-like approach without LLM
/// Achieves 10x faster indexing and 100x faster retrieval
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct E2GraphRAGConfig {
    /// Enable lightweight NER (no LLM required)
    #[serde(default = "default_true")]
    pub use_lightweight_ner: bool,

    /// Entity types to extract (using pattern matching)
    #[serde(default = "default_e2_entity_types")]
    pub entity_types: Vec<String>,

    /// Minimum entity confidence for pattern-based extraction
    #[serde(default = "default_e2_min_confidence")]
    pub min_confidence: f32,

    /// Enable capitalization-based named entity detection
    #[serde(default = "default_true")]
    pub use_capitalization_detection: bool,

    /// Enable noun phrase extraction
    #[serde(default = "default_true")]
    pub use_noun_phrase_extraction: bool,

    /// Minimum entity frequency (entities must appear at least N times)
    #[serde(default = "default_min_entity_frequency")]
    pub min_entity_frequency: usize,

    /// Use fast co-occurrence for relationships (no LLM)
    #[serde(default = "default_true")]
    pub use_fast_cooccurrence: bool,

    /// Enable bidirectional entity-chunk indexing
    #[serde(default = "default_true")]
    pub use_bidirectional_index: bool,
}

impl Default for E2GraphRAGConfig {
    fn default() -> Self {
        Self {
            use_lightweight_ner: true,
            entity_types: default_e2_entity_types(),
            min_confidence: 0.6,
            use_capitalization_detection: true,
            use_noun_phrase_extraction: true,
            min_entity_frequency: 1,
            use_fast_cooccurrence: true,
            use_bidirectional_index: true,
        }
    }
}

// =============================================================================
// PIPELINE APPROACH CONFIGURATION (Semantic vs Algorithmic vs Hybrid)
// =============================================================================

/// Pipeline mode/approach configuration
/// Determines which pipeline implementation to use
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModeConfig {
    /// Pipeline approach: "semantic", "algorithmic", or "hybrid"
    /// - semantic: Neural embeddings + LLM extraction + vector search
    /// - algorithmic: Pattern matching + TF-IDF + BM25 keyword search
    /// - hybrid: Combines both with weighted fusion
    #[serde(default = "default_approach")]
    pub approach: String,
}

impl Default for ModeConfig {
    fn default() -> Self {
        Self {
            approach: default_approach(),
        }
    }
}

/// Semantic/Neural pipeline configuration
/// Uses deep learning models for embeddings, entity extraction, and retrieval
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SemanticPipelineConfig {
    /// Enable semantic pipeline
    #[serde(default)]
    pub enabled: bool,

    /// Embeddings configuration for semantic approach
    pub embeddings: SemanticEmbeddingsConfig,

    /// Entity extraction configuration for semantic approach
    pub entity_extraction: SemanticEntityConfig,

    /// Retrieval configuration for semantic approach
    pub retrieval: SemanticRetrievalConfig,

    /// Graph construction configuration for semantic approach
    pub graph_construction: SemanticGraphConfig,
}

/// Semantic embeddings configuration (neural models)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SemanticEmbeddingsConfig {
    /// Backend: "huggingface", "openai", "voyage", "cohere", "jina", "mistral", "together", "ollama"
    #[serde(default = "default_semantic_embedding_backend")]
    pub backend: String,

    /// Model identifier (provider-specific)
    #[serde(default = "default_semantic_embedding_model")]
    pub model: String,

    /// Embedding dimension
    #[serde(default = "default_semantic_embedding_dim")]
    pub dimension: usize,

    /// Use GPU acceleration if available
    #[serde(default = "default_true")]
    pub use_gpu: bool,

    /// Similarity metric (cosine, euclidean, dot_product)
    #[serde(default = "default_similarity_metric")]
    pub similarity_metric: String,

    /// Batch size for embeddings generation
    #[serde(default = "default_batch_size")]
    pub batch_size: usize,
}

/// Semantic entity extraction configuration (LLM-based)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SemanticEntityConfig {
    /// Extraction method (always "llm" for semantic)
    #[serde(default = "default_semantic_entity_method")]
    pub method: String,

    /// Enable gleaning (iterative refinement)
    #[serde(default = "default_true")]
    pub use_gleaning: bool,

    /// Maximum gleaning rounds
    #[serde(default = "default_max_gleaning_rounds")]
    pub max_gleaning_rounds: usize,

    /// LLM model for extraction
    #[serde(default = "default_chat_model")]
    pub model: String,

    /// Temperature for LLM
    #[serde(default = "default_semantic_temperature")]
    pub temperature: f32,

    /// Confidence threshold
    #[serde(default = "default_semantic_confidence")]
    pub confidence_threshold: f32,
}

/// Semantic retrieval configuration (vector search)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SemanticRetrievalConfig {
    /// Retrieval strategy (always "vector" for semantic)
    #[serde(default = "default_semantic_retrieval_strategy")]
    pub strategy: String,

    /// Use HNSW index for fast approximate search
    #[serde(default = "default_true")]
    pub use_hnsw: bool,

    /// HNSW ef_construction parameter
    #[serde(default = "default_hnsw_ef_construction")]
    pub hnsw_ef_construction: usize,

    /// HNSW M parameter (connections per node)
    #[serde(default = "default_hnsw_m")]
    pub hnsw_m: usize,

    /// Top-k results
    #[serde(default = "default_top_k")]
    pub top_k: usize,

    /// Similarity threshold
    #[serde(default = "default_semantic_similarity_threshold")]
    pub similarity_threshold: f32,
}

/// Semantic graph construction configuration (embedding-based)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SemanticGraphConfig {
    /// Relation scorer (always "embedding_similarity" for semantic)
    #[serde(default = "default_semantic_relation_scorer")]
    pub relation_scorer: String,

    /// Use transformer embeddings for relationships
    #[serde(default = "default_true")]
    pub use_transformer_embeddings: bool,

    /// Minimum relation score
    #[serde(default = "default_min_relation_score")]
    pub min_relation_score: f32,
}

/// Algorithmic/Classic NLP pipeline configuration
/// Uses pattern matching, TF-IDF, and keyword-based methods
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AlgorithmicPipelineConfig {
    /// Enable algorithmic pipeline
    #[serde(default)]
    pub enabled: bool,

    /// Embeddings configuration for algorithmic approach
    pub embeddings: AlgorithmicEmbeddingsConfig,

    /// Entity extraction configuration for algorithmic approach
    pub entity_extraction: AlgorithmicEntityConfig,

    /// Retrieval configuration for algorithmic approach
    pub retrieval: AlgorithmicRetrievalConfig,

    /// Graph construction configuration for algorithmic approach
    pub graph_construction: AlgorithmicGraphConfig,
}

/// Algorithmic embeddings configuration (hash-based, TF-IDF)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlgorithmicEmbeddingsConfig {
    /// Backend (always "hash" for algorithmic)
    #[serde(default = "default_algorithmic_embedding_backend")]
    pub backend: String,

    /// Embedding dimension
    #[serde(default = "default_algorithmic_embedding_dim")]
    pub dimension: usize,

    /// Use TF-IDF weighting
    #[serde(default = "default_true")]
    pub use_tfidf: bool,

    /// Vocabulary size
    #[serde(default = "default_vocabulary_size")]
    pub vocabulary_size: usize,

    /// Minimum term frequency
    #[serde(default = "default_min_term_frequency")]
    pub min_term_frequency: usize,

    /// Maximum document frequency (0.0-1.0)
    #[serde(default = "default_max_document_frequency")]
    pub max_document_frequency: f32,
}

/// Algorithmic entity extraction configuration (pattern-based)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlgorithmicEntityConfig {
    /// Extraction method (always "pattern" for algorithmic)
    #[serde(default = "default_algorithmic_entity_method")]
    pub method: String,

    /// Use NER rules
    #[serde(default = "default_true")]
    pub use_ner_rules: bool,

    /// Use POS tagging
    #[serde(default)]
    pub use_pos_tagging: bool,

    /// Minimum entity length
    #[serde(default = "default_min_entity_length")]
    pub min_entity_length: usize,

    /// Confidence threshold
    #[serde(default = "default_algorithmic_confidence")]
    pub confidence_threshold: f32,

    /// Regex patterns for entity matching
    pub patterns: Option<Vec<String>>,
}

/// Algorithmic retrieval configuration (BM25 keyword search)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlgorithmicRetrievalConfig {
    /// Retrieval strategy (always "bm25" for algorithmic)
    #[serde(default = "default_algorithmic_retrieval_strategy")]
    pub strategy: String,

    /// BM25 k1 parameter (term frequency saturation)
    #[serde(default = "default_bm25_k1")]
    pub k1: f32,

    /// BM25 b parameter (length normalization)
    #[serde(default = "default_bm25_b")]
    pub b: f32,

    /// Use stemming
    #[serde(default = "default_true")]
    pub use_stemming: bool,

    /// Language for stemming
    #[serde(default = "default_language")]
    pub language: String,

    /// Top-k results
    #[serde(default = "default_top_k")]
    pub top_k: usize,
}

/// Algorithmic graph construction configuration (token overlap)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlgorithmicGraphConfig {
    /// Relation scorer (jaccard, cosine on token vectors)
    #[serde(default = "default_algorithmic_relation_scorer")]
    pub relation_scorer: String,

    /// Use co-occurrence for relationship detection
    #[serde(default = "default_true")]
    pub use_cooccurrence: bool,

    /// Co-occurrence window size
    #[serde(default = "default_cooccurrence_window")]
    pub window_size: usize,

    /// Minimum relation score
    #[serde(default = "default_algorithmic_min_relation_score")]
    pub min_relation_score: f32,
}

/// Hybrid pipeline configuration
/// Combines semantic and algorithmic approaches with weighted fusion
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HybridPipelineConfig {
    /// Enable hybrid pipeline
    #[serde(default)]
    pub enabled: bool,

    /// Weight configuration for combining approaches
    pub weights: HybridWeightsConfig,

    /// Embeddings configuration for hybrid
    pub embeddings: HybridEmbeddingsConfig,

    /// Entity extraction configuration for hybrid
    pub entity_extraction: HybridEntityConfig,

    /// Retrieval configuration for hybrid
    pub retrieval: HybridRetrievalConfig,

    /// Graph construction configuration for hybrid
    pub graph_construction: HybridGraphConfig,

    /// Fallback strategy when primary fails
    #[serde(default = "default_hybrid_fallback_strategy")]
    pub fallback_strategy: String,

    /// Enable cross-validation between approaches
    #[serde(default = "default_true")]
    pub cross_validation: bool,
}

/// Hybrid weight configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HybridWeightsConfig {
    /// Weight for semantic approach (0.0-1.0)
    #[serde(default = "default_hybrid_semantic_weight")]
    pub semantic_weight: f32,

    /// Weight for algorithmic approach (0.0-1.0)
    #[serde(default = "default_hybrid_algorithmic_weight")]
    pub algorithmic_weight: f32,
}

/// Hybrid embeddings configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HybridEmbeddingsConfig {
    /// Primary backend (neural)
    #[serde(default = "default_semantic_embedding_backend")]
    pub primary: String,

    /// Fallback backend (hash-based)
    #[serde(default = "default_algorithmic_embedding_backend")]
    pub fallback: String,

    /// Combine scores from both
    #[serde(default = "default_true")]
    pub combine_scores: bool,

    /// Auto-fallback when primary unavailable
    #[serde(default = "default_true")]
    pub auto_fallback: bool,
}

/// Hybrid entity extraction configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HybridEntityConfig {
    /// Use both LLM and pattern extraction
    #[serde(default = "default_true")]
    pub use_both: bool,

    /// Weight for LLM extraction (0.0-1.0)
    #[serde(default = "default_hybrid_llm_weight")]
    pub llm_weight: f32,

    /// Weight for pattern extraction (0.0-1.0)
    #[serde(default = "default_hybrid_pattern_weight")]
    pub pattern_weight: f32,

    /// Cross-validate LLM results with patterns
    #[serde(default = "default_true")]
    pub cross_validate: bool,

    /// Confidence boost when both agree
    #[serde(default = "default_hybrid_confidence_boost")]
    pub confidence_boost: f32,
}

/// Hybrid retrieval configuration (RRF fusion)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HybridRetrievalConfig {
    /// Retrieval strategy (always "fusion" for hybrid)
    #[serde(default = "default_hybrid_retrieval_strategy")]
    pub strategy: String,

    /// Combine vector and BM25
    #[serde(default = "default_true")]
    pub combine_vector_bm25: bool,

    /// Weight for vector search
    #[serde(default = "default_hybrid_vector_weight")]
    pub vector_weight: f32,

    /// Weight for BM25 search
    #[serde(default = "default_hybrid_bm25_weight")]
    pub bm25_weight: f32,

    /// RRF constant (typically 60)
    #[serde(default = "default_rrf_constant")]
    pub rrf_constant: usize,
}

/// Hybrid graph construction configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HybridGraphConfig {
    /// Primary relation scorer (embedding-based)
    #[serde(default = "default_semantic_relation_scorer")]
    pub primary_scorer: String,

    /// Fallback relation scorer (token-based)
    #[serde(default = "default_algorithmic_relation_scorer")]
    pub fallback_scorer: String,

    /// Combine scores from both scorers
    #[serde(default = "default_true")]
    pub combine_scores: bool,
}

/// Top-level entity extraction configuration (gleaning settings)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntityExtractionTopLevelConfig {
    /// Enable entity extraction
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// Minimum confidence threshold
    #[serde(default = "default_confidence_threshold")]
    pub min_confidence: f32,

    /// Use LLM-based gleaning
    #[serde(default)]
    pub use_gleaning: bool,

    /// Maximum gleaning rounds
    #[serde(default = "default_gleaning_rounds")]
    pub max_gleaning_rounds: usize,

    /// Gleaning improvement threshold
    #[serde(default = "default_gleaning_improvement")]
    pub gleaning_improvement_threshold: f32,

    /// Enable semantic merging
    #[serde(default)]
    pub semantic_merging: bool,

    /// Merge similarity threshold
    #[serde(default = "default_merge_threshold")]
    pub merge_similarity_threshold: f32,

    /// Enable automatic linking
    #[serde(default)]
    pub automatic_linking: bool,

    /// Linking confidence threshold
    #[serde(default = "default_confidence_threshold")]
    pub linking_confidence_threshold: f32,
}

impl Default for EntityExtractionTopLevelConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            min_confidence: default_confidence_threshold(),
            use_gleaning: false,
            max_gleaning_rounds: default_gleaning_rounds(),
            gleaning_improvement_threshold: default_gleaning_improvement(),
            semantic_merging: false,
            merge_similarity_threshold: default_merge_threshold(),
            automatic_linking: false,
            linking_confidence_threshold: default_confidence_threshold(),
        }
    }
}

// Default value functions
fn default_log_level() -> String {
    "info".to_string()
}
fn default_output_dir() -> String {
    "./output".to_string()
}
fn default_true() -> bool {
    true
}
fn default_workflows() -> Vec<String> {
    vec![
        "extract_text".to_string(),
        "extract_entities".to_string(),
        "build_graph".to_string(),
        "detect_communities".to_string(),
    ]
}
fn default_chunk_size() -> usize {
    512
}
fn default_chunk_overlap() -> usize {
    64
}
fn default_min_chunk_size() -> usize {
    50
}
fn default_ner_model() -> String {
    "microsoft/DialoGPT-medium".to_string()
}
fn default_temperature() -> f32 {
    0.1
}
fn default_extraction_temperature() -> f32 {
    0.0
}
fn default_max_tokens() -> usize {
    2048
}
fn default_min_entity_length() -> usize {
    3
}
fn default_max_entity_length() -> usize {
    100
}
fn default_confidence_threshold() -> f32 {
    0.8
}
fn default_relation_scorer() -> String {
    "cosine_similarity".to_string()
}
fn default_min_relation_score() -> f32 {
    0.7
}
fn default_max_connections() -> usize {
    10
}
fn default_community_algorithm() -> String {
    "leiden".to_string()
}
fn default_resolution() -> f32 {
    1.0
}
fn default_min_community_size() -> usize {
    3
}
fn default_database_type() -> String {
    "sqlite".to_string()
}
fn default_database_path() -> String {
    "./graphrag.db".to_string()
}
fn default_pool_size() -> usize {
    10
}
fn default_primary_llm() -> String {
    "gpt-4".to_string()
}
fn default_embedding_model() -> String {
    "text-embedding-ada-002".to_string()
}
fn default_max_context() -> usize {
    4096
}
fn default_top_p() -> f32 {
    0.9
}
fn default_ollama_url() -> String {
    "http://localhost:11434".to_string()
}
fn default_ollama_model() -> String {
    "llama2:7b".to_string()
}
fn default_ollama_embedding() -> String {
    "nomic-embed-text".to_string()
}
fn default_batch_size() -> usize {
    100
}
fn default_worker_threads() -> usize {
    4
}
fn default_memory_limit() -> usize {
    1024
}
fn default_ollama_host() -> String {
    "http://localhost".to_string()
}
fn default_ollama_port() -> u16 {
    11434
}
fn default_chat_model() -> String {
    "llama3.1:8b".to_string()
}
fn default_embedding_model_ollama() -> String {
    "nomic-embed-text".to_string()
}
fn default_timeout() -> u64 {
    60
}
fn default_max_retries() -> u32 {
    3
}
fn default_gleaning_rounds() -> usize {
    3
}
fn default_gleaning_improvement() -> f32 {
    0.1
}
fn default_merge_threshold() -> f32 {
    0.85
}

// =============================================================================
// Default functions for Pipeline Approach Configuration
// =============================================================================

// Mode defaults
fn default_approach() -> String {
    "semantic".to_string() // Default to semantic pipeline
}

// Semantic pipeline defaults
fn default_semantic_embedding_backend() -> String {
    "huggingface".to_string()
}
fn default_semantic_embedding_model() -> String {
    "sentence-transformers/all-MiniLM-L6-v2".to_string()
}
fn default_semantic_embedding_dim() -> usize {
    384 // MiniLM-L6-v2 dimension
}
fn default_similarity_metric() -> String {
    "cosine".to_string()
}
fn default_semantic_entity_method() -> String {
    "llm".to_string()
}
fn default_max_gleaning_rounds() -> usize {
    3
}
fn default_semantic_temperature() -> f32 {
    0.1
}
fn default_semantic_confidence() -> f32 {
    0.7
}
fn default_semantic_retrieval_strategy() -> String {
    "vector".to_string()
}
fn default_hnsw_ef_construction() -> usize {
    200
}
fn default_hnsw_m() -> usize {
    16
}
fn default_top_k() -> usize {
    10
}
fn default_semantic_similarity_threshold() -> f32 {
    0.7
}
fn default_semantic_relation_scorer() -> String {
    "embedding_similarity".to_string()
}

// Algorithmic pipeline defaults
fn default_algorithmic_embedding_backend() -> String {
    "hash".to_string()
}
fn default_algorithmic_embedding_dim() -> usize {
    128
}
fn default_vocabulary_size() -> usize {
    10000
}
fn default_min_term_frequency() -> usize {
    2
}
fn default_max_document_frequency() -> f32 {
    0.8
}
fn default_algorithmic_entity_method() -> String {
    "pattern".to_string()
}
fn default_algorithmic_confidence() -> f32 {
    0.75
}
fn default_algorithmic_retrieval_strategy() -> String {
    "bm25".to_string()
}
fn default_bm25_k1() -> f32 {
    1.5
}
fn default_bm25_b() -> f32 {
    0.75
}
fn default_language() -> String {
    "english".to_string()
}
fn default_algorithmic_relation_scorer() -> String {
    "jaccard".to_string()
}
fn default_cooccurrence_window() -> usize {
    10
}
fn default_algorithmic_min_relation_score() -> f32 {
    0.6
}

// Hybrid pipeline defaults
fn default_hybrid_semantic_weight() -> f32 {
    0.6
}
fn default_hybrid_algorithmic_weight() -> f32 {
    0.4
}
fn default_hybrid_llm_weight() -> f32 {
    0.7
}
fn default_hybrid_pattern_weight() -> f32 {
    0.3
}
fn default_hybrid_confidence_boost() -> f32 {
    0.15
}
fn default_hybrid_retrieval_strategy() -> String {
    "fusion".to_string()
}
fn default_hybrid_vector_weight() -> f32 {
    0.6
}
fn default_hybrid_bm25_weight() -> f32 {
    0.4
}
fn default_rrf_constant() -> usize {
    60
}
fn default_hybrid_fallback_strategy() -> String {
    "semantic_first".to_string()
}
fn default_auto_save_interval() -> u64 {
    300 // 5 minutes
}
fn default_max_auto_save_versions() -> usize {
    5 // Keep 5 versions by default
}

// LazyGraphRAG default functions
fn default_min_concept_length() -> usize {
    3 // Minimum 3 characters for concepts
}
fn default_max_concept_words() -> usize {
    5 // Maximum 5 words per concept
}
fn default_co_occurrence_threshold() -> usize {
    1 // Minimum 1 shared chunk for relationship
}
fn default_max_refinement_iterations() -> usize {
    3 // Up to 3 query refinement iterations
}

// E2GraphRAG default functions
fn default_e2_entity_types() -> Vec<String> {
    vec![
        "PERSON".to_string(),
        "ORGANIZATION".to_string(),
        "LOCATION".to_string(),
        "CONCEPT".to_string(),
    ]
}
fn default_e2_min_confidence() -> f32 {
    0.6 // 60% minimum confidence for pattern-based extraction
}
fn default_min_entity_frequency() -> usize {
    1 // Entities must appear at least once
}

impl Default for GeneralConfig {
    fn default() -> Self {
        Self {
            log_level: default_log_level(),
            output_dir: default_output_dir(),
            input_document_path: None,
            max_threads: None,
            enable_profiling: false,
        }
    }
}

impl Default for PipelineConfig {
    fn default() -> Self {
        Self {
            workflows: default_workflows(),
            parallel_execution: default_true(),
            text_extraction: TextExtractionConfig::default(),
            entity_extraction: EntityExtractionConfig::default(),
            graph_building: GraphBuildingConfig::default(),
            community_detection: CommunityDetectionConfig::default(),
        }
    }
}

impl Default for TextExtractionConfig {
    fn default() -> Self {
        Self {
            chunk_size: default_chunk_size(),
            chunk_overlap: default_chunk_overlap(),
            clean_control_chars: default_true(),
            min_chunk_size: default_min_chunk_size(),
            cleaning: None,
        }
    }
}

impl Default for EntityExtractionConfig {
    fn default() -> Self {
        Self {
            model_name: default_ner_model(),
            temperature: default_temperature(),
            max_tokens: default_max_tokens(),
            entity_types: None,
            confidence_threshold: default_confidence_threshold(),
            custom_prompt: None,
            filters: None,
        }
    }
}

impl Default for GraphBuildingConfig {
    fn default() -> Self {
        Self {
            relation_scorer: default_relation_scorer(),
            min_relation_score: default_min_relation_score(),
            max_connections_per_node: default_max_connections(),
            bidirectional_relations: default_true(),
        }
    }
}

impl Default for CommunityDetectionConfig {
    fn default() -> Self {
        Self {
            algorithm: default_community_algorithm(),
            resolution: default_resolution(),
            min_community_size: default_min_community_size(),
            max_community_size: 0,
        }
    }
}

impl Default for StorageConfig {
    fn default() -> Self {
        Self {
            database_type: default_database_type(),
            database_path: default_database_path(),
            enable_wal: default_true(),
            postgresql: None,
            neo4j: None,
        }
    }
}

impl Default for ModelsConfig {
    fn default() -> Self {
        Self {
            primary_llm: default_primary_llm(),
            embedding_model: default_embedding_model(),
            max_context_length: default_max_context(),
            llm_params: None,
            local: None,
        }
    }
}

impl Default for PerformanceConfig {
    fn default() -> Self {
        Self {
            batch_processing: default_true(),
            batch_size: default_batch_size(),
            worker_threads: default_worker_threads(),
            memory_limit_mb: default_memory_limit(),
        }
    }
}

impl Default for OllamaSetConfig {
    fn default() -> Self {
        Self {
            enabled: default_true(),
            host: default_ollama_host(),
            port: default_ollama_port(),
            chat_model: default_chat_model(),
            embedding_model: default_embedding_model_ollama(),
            timeout_seconds: default_timeout(),
            max_retries: default_max_retries(),
            fallback_to_hash: false,
            max_tokens: Some(800),
            temperature: Some(0.3),
            keep_alive: None,
            num_ctx: None,
        }
    }
}

// =============================================================================
// Default implementations for Pipeline Approach Configuration
// =============================================================================

impl Default for SemanticPipelineConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            embeddings: SemanticEmbeddingsConfig::default(),
            entity_extraction: SemanticEntityConfig::default(),
            retrieval: SemanticRetrievalConfig::default(),
            graph_construction: SemanticGraphConfig::default(),
        }
    }
}

impl Default for SemanticEmbeddingsConfig {
    fn default() -> Self {
        Self {
            backend: default_semantic_embedding_backend(),
            model: default_semantic_embedding_model(),
            dimension: default_semantic_embedding_dim(),
            use_gpu: default_true(),
            similarity_metric: default_similarity_metric(),
            batch_size: default_batch_size(),
        }
    }
}

impl Default for SemanticEntityConfig {
    fn default() -> Self {
        Self {
            method: default_semantic_entity_method(),
            use_gleaning: default_true(),
            max_gleaning_rounds: default_max_gleaning_rounds(),
            model: default_chat_model(),
            temperature: default_semantic_temperature(),
            confidence_threshold: default_semantic_confidence(),
        }
    }
}

impl Default for SemanticRetrievalConfig {
    fn default() -> Self {
        Self {
            strategy: default_semantic_retrieval_strategy(),
            use_hnsw: default_true(),
            hnsw_ef_construction: default_hnsw_ef_construction(),
            hnsw_m: default_hnsw_m(),
            top_k: default_top_k(),
            similarity_threshold: default_semantic_similarity_threshold(),
        }
    }
}

impl Default for SemanticGraphConfig {
    fn default() -> Self {
        Self {
            relation_scorer: default_semantic_relation_scorer(),
            use_transformer_embeddings: default_true(),
            min_relation_score: default_min_relation_score(),
        }
    }
}

impl Default for AlgorithmicEmbeddingsConfig {
    fn default() -> Self {
        Self {
            backend: default_algorithmic_embedding_backend(),
            dimension: default_algorithmic_embedding_dim(),
            use_tfidf: default_true(),
            vocabulary_size: default_vocabulary_size(),
            min_term_frequency: default_min_term_frequency(),
            max_document_frequency: default_max_document_frequency(),
        }
    }
}

impl Default for AlgorithmicEntityConfig {
    fn default() -> Self {
        Self {
            method: default_algorithmic_entity_method(),
            use_ner_rules: default_true(),
            use_pos_tagging: false,
            min_entity_length: default_min_entity_length(),
            confidence_threshold: default_algorithmic_confidence(),
            patterns: None,
        }
    }
}

impl Default for AlgorithmicRetrievalConfig {
    fn default() -> Self {
        Self {
            strategy: default_algorithmic_retrieval_strategy(),
            k1: default_bm25_k1(),
            b: default_bm25_b(),
            use_stemming: default_true(),
            language: default_language(),
            top_k: default_top_k(),
        }
    }
}

impl Default for AlgorithmicGraphConfig {
    fn default() -> Self {
        Self {
            relation_scorer: default_algorithmic_relation_scorer(),
            use_cooccurrence: default_true(),
            window_size: default_cooccurrence_window(),
            min_relation_score: default_algorithmic_min_relation_score(),
        }
    }
}

impl Default for HybridPipelineConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            weights: HybridWeightsConfig::default(),
            embeddings: HybridEmbeddingsConfig::default(),
            entity_extraction: HybridEntityConfig::default(),
            retrieval: HybridRetrievalConfig::default(),
            graph_construction: HybridGraphConfig::default(),
            fallback_strategy: default_hybrid_fallback_strategy(),
            cross_validation: default_true(),
        }
    }
}

impl Default for HybridWeightsConfig {
    fn default() -> Self {
        Self {
            semantic_weight: default_hybrid_semantic_weight(),
            algorithmic_weight: default_hybrid_algorithmic_weight(),
        }
    }
}

impl Default for HybridEmbeddingsConfig {
    fn default() -> Self {
        Self {
            primary: default_semantic_embedding_backend(),
            fallback: default_algorithmic_embedding_backend(),
            combine_scores: default_true(),
            auto_fallback: default_true(),
        }
    }
}

impl Default for HybridEntityConfig {
    fn default() -> Self {
        Self {
            use_both: default_true(),
            llm_weight: default_hybrid_llm_weight(),
            pattern_weight: default_hybrid_pattern_weight(),
            cross_validate: default_true(),
            confidence_boost: default_hybrid_confidence_boost(),
        }
    }
}

impl Default for HybridRetrievalConfig {
    fn default() -> Self {
        Self {
            strategy: default_hybrid_retrieval_strategy(),
            combine_vector_bm25: default_true(),
            vector_weight: default_hybrid_vector_weight(),
            bm25_weight: default_hybrid_bm25_weight(),
            rrf_constant: default_rrf_constant(),
        }
    }
}

impl Default for HybridGraphConfig {
    fn default() -> Self {
        Self {
            primary_scorer: default_semantic_relation_scorer(),
            fallback_scorer: default_algorithmic_relation_scorer(),
            combine_scores: default_true(),
        }
    }
}

impl SetConfig {
    /// Load configuration from TOML or JSON5 file (auto-detects format by extension)
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path_ref = path.as_ref();
        let content = fs::read_to_string(path_ref)?;

        // Detect format by file extension
        let extension = path_ref.extension().and_then(|e| e.to_str()).unwrap_or("");

        let config: SetConfig = match extension {
            #[cfg(feature = "json5-support")]
            "json5" | "json" => {
                json5::from_str(&content).map_err(|e| crate::core::GraphRAGError::Config {
                    message: format!("JSON5 parse error: {e}"),
                })?
            },
            #[cfg(not(feature = "json5-support"))]
            "json5" | "json" => {
                return Err(crate::core::GraphRAGError::Config {
                    message: "JSON5 support not enabled. Rebuild with --features json5-support"
                        .to_string(),
                });
            },
            _ => toml::from_str(&content).map_err(|e| crate::core::GraphRAGError::Config {
                message: format!("TOML parse error: {e}"),
            })?,
        };

        Ok(config)
    }

    /// Save configuration to TOML file with comments
    pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let toml_string =
            toml::to_string_pretty(&self).map_err(|e| crate::core::GraphRAGError::Config {
                message: format!("TOML serialize error: {e}"),
            })?;

        // Add header comment
        let commented_toml = format!(
            "# =============================================================================\n\
             # GraphRAG Configuration File\n\
             # Complete configuration with extensive parameters for easy customization\n\
             # =============================================================================\n\n{toml_string}"
        );

        fs::write(path, commented_toml)?;
        Ok(())
    }

    /// Convert to the existing Config format for compatibility
    pub fn to_graphrag_config(&self) -> crate::Config {
        let mut config = crate::Config {
            approach: self.mode.approach.clone(),
            ..Default::default()
        };

        // Map text processing
        config.text.chunk_size = self.pipeline.text_extraction.chunk_size;
        config.text.chunk_overlap = self.pipeline.text_extraction.chunk_overlap;

        // Map entity extraction based on approach
        config.entities.min_confidence = self.entity_extraction.min_confidence;

        // Map entity types from pipeline.entity_extraction
        if let Some(ref types) = self.pipeline.entity_extraction.entity_types {
            config.entities.entity_types = types.clone();
        }

        // Configure gleaning based on approach:
        // - semantic: use LLM-based gleaning
        // - algorithmic: use pattern-based extraction
        // - hybrid: use both (for compatibility, map to gleaning)
        match self.mode.approach.as_str() {
            "semantic" => {
                if let Some(ref semantic) = self.semantic {
                    config.entities.use_gleaning = semantic.entity_extraction.use_gleaning;
                    config.entities.max_gleaning_rounds =
                        semantic.entity_extraction.max_gleaning_rounds;
                    config.entities.min_confidence =
                        semantic.entity_extraction.confidence_threshold;
                } else {
                    // No semantic sub-section: use top-level entity_extraction settings directly
                    config.entities.use_gleaning = self.entity_extraction.use_gleaning;
                    config.entities.max_gleaning_rounds =
                        self.entity_extraction.max_gleaning_rounds;
                    config.entities.min_confidence = self.entity_extraction.min_confidence;
                }
            },
            "algorithmic" => {
                // Algorithmic uses pattern-based extraction, no gleaning
                config.entities.use_gleaning = false;
                if let Some(ref algorithmic) = self.algorithmic {
                    config.entities.min_confidence =
                        algorithmic.entity_extraction.confidence_threshold;
                }
            },
            "hybrid" => {
                // Hybrid can use both, enable gleaning for LLM component
                config.entities.use_gleaning = true;
                if self.hybrid.is_some() {
                    // Use hybrid configuration if available
                    config.entities.max_gleaning_rounds = 2; // Reduced for hybrid efficiency
                }
            },
            _ => {
                // Unknown approach, use top-level config as fallback
                config.entities.use_gleaning = self.entity_extraction.use_gleaning;
                config.entities.max_gleaning_rounds = self.entity_extraction.max_gleaning_rounds;
            },
        }

        // Map graph building
        config.graph.similarity_threshold = self.pipeline.graph_building.min_relation_score;
        config.graph.max_connections = self.pipeline.graph_building.max_connections_per_node;
        config.graph.extract_relationships = true; // Enable by default for TOML configs
        config.graph.relationship_confidence_threshold = 0.5; // Default threshold

        // Map retrieval
        config.retrieval.top_k = 10; // Default

        // Map embeddings
        config.embeddings.dimension = 768; // Default for nomic-embed-text
        config.embeddings.backend = "ollama".to_string();
        config.embeddings.fallback_to_hash = self.ollama.fallback_to_hash;

        // Map parallel processing
        config.parallel.enabled = self.pipeline.parallel_execution;
        config.parallel.num_threads = self.performance.worker_threads;

        // Map Ollama configuration
        config.ollama = crate::ollama::OllamaConfig {
            enabled: self.ollama.enabled,
            host: self.ollama.host.clone(),
            port: self.ollama.port,
            chat_model: self.ollama.chat_model.clone(),
            embedding_model: self.ollama.embedding_model.clone(),
            timeout_seconds: self.ollama.timeout_seconds,
            max_retries: self.ollama.max_retries,
            fallback_to_hash: self.ollama.fallback_to_hash,
            max_tokens: self.ollama.max_tokens,
            temperature: self.ollama.temperature,
            enable_caching: true,
            keep_alive: self.ollama.keep_alive.clone(),
            num_ctx: self.ollama.num_ctx,
        };

        // Map GLiNER configuration
        config.gliner = crate::config::GlinerConfig {
            enabled: self.gliner.enabled,
            model_path: self.gliner.model_path.clone(),
            tokenizer_path: self.gliner.tokenizer_path.clone(),
            mode: self.gliner.mode.clone(),
            entity_labels: self.gliner.entity_labels.clone(),
            relation_labels: self.gliner.relation_labels.clone(),
            entity_threshold: self.gliner.entity_threshold,
            relation_threshold: self.gliner.relation_threshold,
            use_gpu: self.gliner.use_gpu,
            max_concurrent_chunks: self.gliner.max_concurrent_chunks,
        };

        // Map auto-save configuration
        config.auto_save = crate::config::AutoSaveConfig {
            enabled: self.auto_save.enabled,
            base_dir: self.auto_save.base_dir.clone(),
            interval_seconds: self.auto_save.interval_seconds,
            workspace_name: self.auto_save.workspace_name.clone(),
            max_versions: self.auto_save.max_versions,
        };

        config
    }
}

#[cfg(test)]
mod drift_guard_tests {
    //! Guards against silent drift between the serde-facing `*SetConfig` leaf
    //! structs and their canonical runtime counterparts in `config/mod.rs` /
    //! `ollama/mod.rs`. These structs are mechanical mirrors kept in sync by hand
    //! (the "5-point-sync" documented in CLAUDE.md); these tests fail loudly when
    //! a field's default diverges so the drift is caught at build time.
    //!
    //! NOTE: `OllamaConfig` is *intentionally* excluded — its runtime default is
    //! offline-first (`enabled = false`, `fallback_to_hash = true`) while
    //! `OllamaSetConfig` is the user-facing "I want Ollama" schema
    //! (`enabled = true`). That divergence is by design, not drift.

    use super::*;
    use crate::config::{AutoSaveConfig, GlinerConfig};

    #[test]
    fn gliner_setconfig_default_matches_runtime() {
        let set = GlinerSetConfig::default();
        let runtime = GlinerConfig::default();
        assert_eq!(set.mode, runtime.mode, "gliner.mode drifted");
        assert_eq!(
            set.entity_labels, runtime.entity_labels,
            "gliner.entity_labels drifted"
        );
        assert_eq!(
            set.relation_labels, runtime.relation_labels,
            "gliner.relation_labels drifted"
        );
        assert_eq!(
            set.entity_threshold, runtime.entity_threshold,
            "gliner.entity_threshold drifted"
        );
        assert_eq!(
            set.relation_threshold, runtime.relation_threshold,
            "gliner.relation_threshold drifted"
        );
        assert_eq!(set.use_gpu, runtime.use_gpu, "gliner.use_gpu drifted");
    }

    #[test]
    fn autosave_setconfig_default_matches_runtime() {
        let set = AutoSaveSetConfig::default();
        let runtime = AutoSaveConfig::default();
        assert_eq!(set.enabled, runtime.enabled, "auto_save.enabled drifted");
        assert_eq!(
            set.interval_seconds, runtime.interval_seconds,
            "auto_save.interval_seconds drifted"
        );
        assert_eq!(
            set.max_versions, runtime.max_versions,
            "auto_save.max_versions drifted"
        );
    }
}