oxirs-fuseki 0.2.2

SPARQL 1.1/1.2 HTTP protocol server with Fuseki-compatible configuration
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
1997
1998
1999
//! Advanced server configuration management with validation and hot-reload
use crate::error::{FusekiError, FusekiResult};
use figment::{
    providers::{Env, Format, Toml, Yaml},
    Figment,
};
#[cfg(feature = "hot-reload")]
use notify::{Config, Event, RecommendedWatcher, RecursiveMode, Watcher};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
#[cfg(feature = "hot-reload")]
use std::sync::mpsc;
use std::time::Duration;
#[cfg(feature = "hot-reload")]
use tokio::sync::watch;
use tracing::{info, warn};
use validator::{Validate, ValidationError};
/// Main server configuration with validation
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct ServerConfig {
    #[validate(nested)]
    pub server: ServerSettings,
    #[validate(nested)]
    pub datasets: HashMap<String, DatasetConfig>,

    #[validate(nested)]
    pub security: SecurityConfig,

    #[validate(nested)]
    pub monitoring: MonitoringConfig,

    #[validate(nested)]
    pub performance: PerformanceConfig,

    #[validate(nested)]
    pub logging: LoggingConfig,

    /// Federation configuration for distributed query execution
    /// Note: Currently not serializable, uses defaults at runtime
    #[serde(skip)]
    pub federation: Option<crate::federation::FederationConfig>,

    /// Streaming configuration for event processing
    /// Note: Currently not serializable, uses defaults at runtime
    #[serde(skip)]
    pub streaming: Option<crate::streaming::StreamingConfig>,

    /// HTTP protocol configuration (HTTP/2, HTTP/3)
    #[validate(nested)]
    pub http_protocol: HttpProtocolSettings,
}

/// Server-level settings with validation
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct ServerSettings {
    #[validate(range(min = 1, max = 65535))]
    pub port: u16,

    #[validate(length(min = 1))]
    pub host: String,

    pub admin_ui: bool,
    pub cors: bool,

    #[validate(range(min = 1))]
    pub max_connections: usize,

    #[validate(range(min = 1))]
    pub request_timeout_secs: u64,

    #[validate(range(min = 1))]
    pub graceful_shutdown_timeout_secs: u64,

    pub tls: Option<TlsConfig>,

    /// Directory for storing backups
    #[serde(default)]
    pub backup_directory: Option<PathBuf>,

    /// Path to the configuration file (set at runtime)
    #[serde(skip)]
    pub config_file: Option<PathBuf>,
}

/// TLS configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct TlsConfig {
    #[validate(custom(function = "validate_path"))]
    pub cert_path: PathBuf,

    #[validate(custom(function = "validate_path"))]
    pub key_path: PathBuf,

    pub require_client_cert: bool,

    pub ca_cert_path: Option<PathBuf>,
}

/// HTTP protocol configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct HttpProtocolSettings {
    /// Enable HTTP/2
    #[serde(default = "default_true")]
    pub http2_enabled: bool,

    /// Enable HTTP/3 (QUIC) - experimental
    #[serde(default)]
    pub http3_enabled: bool,

    /// HTTP/2 initial connection window size (bytes)
    #[serde(default = "default_http2_connection_window")]
    #[validate(range(min = 65535, max = 16777216))]
    pub http2_initial_connection_window_size: u32,

    /// HTTP/2 initial stream window size (bytes)
    #[serde(default = "default_http2_stream_window")]
    #[validate(range(min = 65535, max = 16777216))]
    pub http2_initial_stream_window_size: u32,

    /// HTTP/2 max concurrent streams
    #[serde(default = "default_http2_max_streams")]
    #[validate(range(min = 1, max = 1000))]
    pub http2_max_concurrent_streams: u32,

    /// HTTP/2 max frame size (bytes)
    #[serde(default = "default_http2_frame_size")]
    #[validate(range(min = 16384, max = 16777215))]
    pub http2_max_frame_size: u32,

    /// HTTP/2 keep alive interval (seconds)
    #[serde(default = "default_http2_keepalive")]
    #[validate(range(min = 1))]
    pub http2_keep_alive_interval_secs: u64,

    /// HTTP/2 keep alive timeout (seconds)
    #[serde(default = "default_http2_keepalive_timeout")]
    #[validate(range(min = 1))]
    pub http2_keep_alive_timeout_secs: u64,

    /// Enable server push for SPARQL results
    #[serde(default)]
    pub enable_server_push: bool,

    /// Enable header compression (HPACK for HTTP/2, QPACK for HTTP/3)
    #[serde(default = "default_true")]
    pub enable_header_compression: bool,

    /// Optimize for SPARQL workloads
    #[serde(default = "default_true")]
    pub sparql_optimized: bool,
}

fn default_true() -> bool {
    true
}

fn default_http2_connection_window() -> u32 {
    1024 * 1024 // 1MB
}

fn default_http2_stream_window() -> u32 {
    256 * 1024 // 256KB
}

fn default_http2_max_streams() -> u32 {
    100
}

fn default_http2_frame_size() -> u32 {
    16384 // 16KB
}

fn default_http2_keepalive() -> u64 {
    60 // seconds
}

fn default_http2_keepalive_timeout() -> u64 {
    20 // seconds
}

impl Default for HttpProtocolSettings {
    fn default() -> Self {
        Self {
            http2_enabled: true,
            http3_enabled: false,
            http2_initial_connection_window_size: default_http2_connection_window(),
            http2_initial_stream_window_size: default_http2_stream_window(),
            http2_max_concurrent_streams: default_http2_max_streams(),
            http2_max_frame_size: default_http2_frame_size(),
            http2_keep_alive_interval_secs: default_http2_keepalive(),
            http2_keep_alive_timeout_secs: default_http2_keepalive_timeout(),
            enable_server_push: false,
            enable_header_compression: true,
            sparql_optimized: true,
        }
    }
}

/// Dataset configuration with validation
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct DatasetConfig {
    #[validate(length(min = 1))]
    pub name: String,

    #[validate(length(min = 1))]
    pub location: String,

    pub read_only: bool,

    #[validate(nested)]
    pub text_index: Option<TextIndexConfig>,

    pub shacl_shapes: Vec<PathBuf>,

    #[validate(nested)]
    pub services: Vec<ServiceConfig>,

    #[validate(nested)]
    pub access_control: Option<AccessControlConfig>,

    pub backup: Option<BackupConfig>,
}

/// Service configuration for datasets
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct ServiceConfig {
    #[validate(length(min = 1))]
    pub name: String,

    pub service_type: ServiceType,

    #[validate(length(min = 1))]
    pub endpoint: String,

    pub auth_required: bool,

    pub rate_limit: Option<RateLimitConfig>,
}

/// Types of services supported
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ServiceType {
    SparqlQuery,
    SparqlUpdate,
    GraphStore,
    GraphQL,
    Rest,
}

/// Access control configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct AccessControlConfig {
    pub read_roles: Vec<String>,
    pub write_roles: Vec<String>,
    pub admin_roles: Vec<String>,
    pub public_read: bool,
}

/// Backup configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct BackupConfig {
    pub enabled: bool,

    pub directory: PathBuf,

    #[validate(range(min = 1))]
    pub interval_hours: u64,

    #[validate(range(min = 1))]
    pub retain_count: usize,
}

/// Text indexing configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct TextIndexConfig {
    pub enabled: bool,

    #[validate(length(min = 1))]
    pub analyzer: String,

    #[validate(range(min = 1))]
    pub max_results: usize,

    pub stemming: bool,

    pub stop_words: Vec<String>,
}

/// Security configuration with validation
#[derive(Debug, Clone, Serialize, Deserialize, Validate, Default)]
pub struct SecurityConfig {
    pub auth_required: bool,

    #[validate(nested)]
    pub users: HashMap<String, UserConfig>,

    #[validate(nested)]
    pub jwt: Option<JwtConfig>,

    #[validate(nested)]
    pub oauth: Option<OAuthConfig>,

    #[validate(nested)]
    pub ldap: Option<LdapConfig>,

    #[validate(nested)]
    pub rate_limiting: Option<RateLimitConfig>,

    pub cors: CorsConfig,

    pub session: SessionConfig,

    #[validate(nested)]
    pub authentication: AuthenticationConfig,

    #[validate(nested)]
    pub api_keys: Option<ApiKeyConfig>,

    #[validate(nested)]
    pub certificate: Option<CertificateConfig>,

    #[validate(nested)]
    pub saml: Option<SamlConfig>,

    #[validate(nested)]
    pub rebac: Option<RebacConfig>,

    #[validate(nested)]
    pub mfa: Option<MfaConfig>,
}

/// Authentication configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate, Default)]
pub struct AuthenticationConfig {
    pub enabled: bool,
}

/// API Key configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct ApiKeyConfig {
    /// Enable API key authentication
    pub enabled: bool,

    /// Default key expiration in days
    #[validate(range(min = 1, max = 3650))] // 1 day to 10 years
    pub default_expiration_days: u32,

    /// Maximum number of keys per user
    #[validate(range(min = 1, max = 100))]
    pub max_keys_per_user: u32,

    /// Default rate limiting for API keys
    pub default_rate_limit: Option<ApiKeyRateLimit>,

    /// Enable usage analytics
    pub usage_analytics: bool,

    /// Storage backend configuration
    pub storage: ApiKeyStorageConfig,
}

/// API key rate limiting configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct ApiKeyRateLimit {
    #[validate(range(min = 1))]
    pub requests_per_minute: u32,

    #[validate(range(min = 1))]
    pub requests_per_hour: u32,

    #[validate(range(min = 1))]
    pub requests_per_day: u32,

    #[validate(range(min = 1))]
    pub burst_limit: u32,
}

/// API key storage configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct ApiKeyStorageConfig {
    /// Storage backend type
    pub backend: ApiKeyStorageBackend,

    /// Connection string or file path
    #[validate(length(min = 1))]
    pub connection: String,

    /// Encryption key for sensitive data
    #[validate(length(min = 32))]
    pub encryption_key: Option<String>,
}

/// API key storage backend types
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApiKeyStorageBackend {
    Memory,
    File,
    Sqlite,
    Postgres,
    Redis,
}

/// Certificate authentication configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct CertificateConfig {
    /// Enable certificate authentication
    pub enabled: bool,

    /// Require client certificates for all connections
    pub require_client_cert: bool,

    /// Trust store configuration - paths to trusted CA certificates
    pub trust_store: Vec<PathBuf>,

    /// Certificate Revocation List (CRL) URLs or file paths
    pub crl_sources: Vec<String>,

    /// Enable CRL checking
    pub check_crl: bool,

    /// Enable OCSP checking
    pub check_ocsp: bool,

    /// Allow self-signed certificates (for development only)
    pub allow_self_signed: bool,

    /// Certificate to user mapping rules
    pub user_mapping: CertificateUserMapping,

    /// Maximum certificate chain length
    #[validate(range(min = 1, max = 10))]
    pub max_chain_length: u8,

    /// Certificate validation strictness
    pub validation_level: CertificateValidationLevel,

    /// Trusted issuer DN patterns for certificate validation
    /// Certificates from these issuers will be trusted without requiring CA certificates in trust store
    pub trusted_issuers: Option<Vec<String>>,
}

/// Certificate user mapping configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct CertificateUserMapping {
    /// How to extract username from certificate
    pub username_source: CertificateUsernameSource,

    /// Subject DN to username mapping rules
    pub dn_mapping_rules: Vec<DnMappingRule>,

    /// Default roles for certificate users
    pub default_roles: Vec<String>,

    /// OU to role mapping
    pub ou_role_mapping: HashMap<String, Vec<String>>,
}

/// Source for extracting username from certificate
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CertificateUsernameSource {
    /// Use Common Name (CN) from subject DN
    CommonName,
    /// Use entire subject DN
    SubjectDn,
    /// Use email from Subject Alternative Name
    EmailSan,
    /// Use custom regex pattern
    CustomPattern(String),
}

/// Subject DN to username mapping rule
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct DnMappingRule {
    /// Regex pattern to match against subject DN
    #[validate(length(min = 1))]
    pub pattern: String,

    /// Replacement string (supports capture groups)
    #[validate(length(min = 1))]
    pub replacement: String,

    /// Roles to assign to users matching this pattern
    pub roles: Vec<String>,
}

/// Certificate validation strictness levels
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CertificateValidationLevel {
    /// Strict validation - all checks must pass
    Strict,
    /// Moderate validation - allow some minor issues
    Moderate,
    /// Permissive validation - for development/testing
    Permissive,
}

/// SAML authentication configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct SamlConfig {
    /// Enable SAML authentication
    pub enabled: bool,

    /// Service Provider (SP) entity ID
    #[validate(length(min = 1))]
    pub sp_entity_id: String,

    /// SP X.509 certificate for signing
    pub sp_cert_path: Option<PathBuf>,

    /// SP private key for signing
    pub sp_key_path: Option<PathBuf>,

    /// Identity Provider (IdP) configuration
    pub idp: SamlIdpConfig,

    /// Assertion consumer service URL
    #[validate(length(min = 1))]
    pub acs_url: String,

    /// Single logout service URL
    pub slo_url: Option<String>,

    /// SAML attribute mappings
    pub attribute_mappings: SamlAttributeMappings,

    /// Session timeout in seconds
    #[validate(range(min = 300, max = 86400))]
    pub session_timeout_secs: u64,
}

/// SAML Identity Provider configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct SamlIdpConfig {
    /// IdP entity ID
    #[validate(length(min = 1))]
    pub entity_id: String,

    /// IdP SSO URL
    #[validate(length(min = 1))]
    pub sso_url: String,

    /// IdP SLO URL
    pub slo_url: Option<String>,

    /// IdP X.509 certificate for verification
    #[validate(custom(function = "validate_path"))]
    pub cert_path: PathBuf,

    /// IdP metadata URL (alternative to manual configuration)
    pub metadata_url: Option<String>,
}

/// SAML attribute mapping configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct SamlAttributeMappings {
    /// SAML attribute name for username
    #[validate(length(min = 1))]
    pub username_attribute: String,

    /// SAML attribute name for email
    pub email_attribute: Option<String>,

    /// SAML attribute name for full name
    pub name_attribute: Option<String>,

    /// SAML attribute name for groups/roles
    pub groups_attribute: Option<String>,

    /// Group to role mapping
    pub group_role_mapping: HashMap<String, Vec<String>>,
}

/// ReBAC (Relationship-Based Access Control) configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct RebacConfig {
    /// Enable ReBAC authorization
    pub enabled: bool,

    /// Policy evaluation mode
    pub policy_mode: RebacPolicyMode,

    /// Storage backend for relationships
    pub storage: RebacStorageBackend,

    /// OpenFGA server configuration (if using OpenFGA backend)
    pub openfga: Option<OpenFgaConfig>,

    /// Initial relationship tuples to load on startup
    pub initial_relationships: Vec<RelationshipTupleConfig>,

    /// Enable audit logging for authorization decisions
    pub audit_enabled: bool,

    /// Cache authorization decisions for this many seconds
    #[validate(range(min = 0, max = 3600))]
    pub cache_ttl_secs: u64,
}

/// ReBAC policy evaluation modes
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum RebacPolicyMode {
    /// Use only traditional RBAC
    RbacOnly,

    /// Use only ReBAC (relationship-based)
    RebacOnly,

    /// Try RBAC first, fall back to ReBAC (default)
    #[default]
    Combined,

    /// Require both RBAC and ReBAC to allow
    Both,
}

/// ReBAC storage backends
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum RebacStorageBackend {
    /// In-memory storage (fast, not persistent)
    #[default]
    Memory,

    /// OpenFGA server (scalable, persistent)
    OpenFga,

    /// RDF-based storage using named graphs (future)
    Rdf,

    /// Database storage (future)
    Database,
}

/// OpenFGA server configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct OpenFgaConfig {
    /// OpenFGA API URL
    #[validate(length(min = 1))]
    pub api_url: String,

    /// Store ID
    #[validate(length(min = 1))]
    pub store_id: String,

    /// Authorization model ID (optional, uses latest if not specified)
    pub model_id: Option<String>,

    /// API token for authentication
    pub api_token: Option<String>,

    /// Enable TLS for OpenFGA connection
    pub tls_enabled: bool,

    /// Connection timeout in seconds
    #[validate(range(min = 1, max = 300))]
    pub timeout_secs: u64,
}

/// Relationship tuple configuration for initial loading
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct RelationshipTupleConfig {
    /// Subject (e.g., "user:alice", "organization:engineering")
    #[validate(length(min = 1))]
    pub subject: String,

    /// Relation (e.g., "owner", "can_read", "member")
    #[validate(length(min = 1))]
    pub relation: String,

    /// Object/resource (e.g., "dataset:public", "graph:`http://example.org/g1`")
    #[validate(length(min = 1))]
    pub object: String,

    /// Optional condition
    pub condition: Option<RelationshipConditionConfig>,
}

/// Relationship condition configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum RelationshipConditionConfig {
    /// Time-based condition
    TimeWindow {
        not_before: Option<String>, // ISO 8601 datetime
        not_after: Option<String>,  // ISO 8601 datetime
    },

    /// IP address condition
    IpAddress { allowed_ips: Vec<String> },

    /// Custom attribute-based condition
    Attribute { key: String, value: String },
}

/// Multi-Factor Authentication (MFA) configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct MfaConfig {
    /// Enable MFA globally
    pub enabled: bool,

    /// Require MFA for all users (if false, users can opt-in)
    pub required: bool,

    /// Available MFA methods
    pub methods: MfaMethods,

    /// TOTP configuration
    #[validate(nested)]
    pub totp: Option<TotpConfig>,

    /// SMS configuration
    #[validate(nested)]
    pub sms: Option<SmsConfig>,

    /// Email configuration
    #[validate(nested)]
    pub email: Option<EmailConfig>,

    /// WebAuthn configuration
    #[validate(nested)]
    pub webauthn: Option<WebAuthnConfig>,

    /// Backup codes configuration
    pub backup_codes: BackupCodesConfig,

    /// MFA session duration in seconds (how long after MFA verification before re-prompt)
    #[validate(range(min = 300, max = 86400))] // 5 min to 24 hours
    pub session_duration_secs: u64,

    /// Storage path for MFA secrets
    pub storage_path: PathBuf,
}

/// Available MFA methods
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MfaMethods {
    pub totp: bool,
    pub sms: bool,
    pub email: bool,
    pub webauthn: bool,
}

/// TOTP (Time-based One-Time Password) configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct TotpConfig {
    /// Issuer name shown in authenticator apps
    #[validate(length(min = 1))]
    pub issuer: String,

    /// Number of digits in TOTP code
    #[validate(range(min = 6, max = 8))]
    pub digits: u32,

    /// Time step in seconds
    #[validate(range(min = 15, max = 60))]
    pub time_step_secs: u32,

    /// Number of time steps to look back/forward for validation
    #[validate(range(min = 0, max = 5))]
    pub skew: u32,
}

/// SMS-based MFA configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct SmsConfig {
    /// SMS provider
    pub provider: SmsProvider,

    /// API key or credentials
    pub api_key: String,

    /// Sender phone number or ID
    pub sender: String,

    /// Code expiration in seconds
    #[validate(range(min = 60, max = 600))]
    pub code_expiration_secs: u64,
}

/// SMS providers
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SmsProvider {
    Twilio,
    Aws,
    Custom,
}

/// Email-based MFA configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct EmailConfig {
    /// SMTP server
    #[validate(length(min = 1))]
    pub smtp_server: String,

    /// SMTP port
    #[validate(range(min = 1, max = 65535))]
    pub smtp_port: u16,

    /// Sender email address
    #[validate(email)]
    pub from_address: String,

    /// SMTP username
    pub smtp_username: Option<String>,

    /// SMTP password
    pub smtp_password: Option<String>,

    /// Use TLS
    pub use_tls: bool,

    /// Code expiration in seconds
    #[validate(range(min = 60, max = 600))]
    pub code_expiration_secs: u64,
}

/// WebAuthn configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct WebAuthnConfig {
    /// Relying Party ID (usually the domain)
    #[validate(length(min = 1))]
    pub rp_id: String,

    /// Relying Party name
    #[validate(length(min = 1))]
    pub rp_name: String,

    /// Origin URL
    #[validate(url)]
    pub origin: String,

    /// Require resident keys
    pub require_resident_key: bool,

    /// User verification requirement
    pub user_verification: UserVerificationRequirement,
}

/// User verification requirements for WebAuthn
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UserVerificationRequirement {
    Required,
    Preferred,
    Discouraged,
}

/// Backup codes configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct BackupCodesConfig {
    /// Enable backup codes
    pub enabled: bool,

    /// Number of backup codes to generate
    #[validate(range(min = 5, max = 20))]
    pub count: u32,

    /// Length of each backup code
    #[validate(range(min = 8, max = 16))]
    pub length: u32,
}

/// JWT configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct JwtConfig {
    #[validate(length(min = 32))]
    pub secret: String,

    #[validate(range(min = 300, max = 86400))] // 5 min to 24 hours
    pub expiration_secs: u64,

    #[validate(length(min = 1))]
    pub issuer: String,

    #[validate(length(min = 1))]
    pub audience: String,
}

/// OAuth configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct OAuthConfig {
    #[validate(length(min = 1))]
    pub provider: String,

    #[validate(length(min = 1))]
    pub client_id: String,

    #[validate(length(min = 1))]
    pub client_secret: String,

    #[validate(url)]
    pub auth_url: String,

    #[validate(url)]
    pub token_url: String,

    #[validate(url)]
    pub user_info_url: String,

    pub scopes: Vec<String>,
}

/// LDAP configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct LdapConfig {
    #[validate(url)]
    pub server: String,

    #[validate(length(min = 1))]
    pub bind_dn: String,

    #[validate(length(min = 1))]
    pub bind_password: String,

    #[validate(length(min = 1))]
    pub user_base_dn: String,

    #[validate(length(min = 1))]
    pub user_filter: String,

    #[validate(length(min = 1))]
    pub group_base_dn: String,

    #[validate(length(min = 1))]
    pub group_filter: String,

    pub use_tls: bool,
}

/// Rate limiting configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct RateLimitConfig {
    #[validate(range(min = 1))]
    pub requests_per_minute: u32,

    #[validate(range(min = 1))]
    pub burst_size: u32,

    pub per_ip: bool,

    pub per_user: bool,

    pub whitelist: Vec<String>,
}

/// CORS configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct CorsConfig {
    pub enabled: bool,
    pub allow_origins: Vec<String>,
    pub allow_methods: Vec<String>,
    pub allow_headers: Vec<String>,
    pub expose_headers: Vec<String>,
    pub allow_credentials: bool,

    #[validate(range(min = 0, max = 86400))]
    pub max_age_secs: u64,
}

/// Session configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct SessionConfig {
    #[validate(length(min = 32))]
    pub secret: String,

    #[validate(range(min = 300, max = 86400))] // 5 min to 24 hours
    pub timeout_secs: u64,

    pub secure: bool,

    pub http_only: bool,

    pub same_site: SameSitePolicy,
}

/// SameSite cookie policy
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SameSitePolicy {
    Strict,
    Lax,
    None,
}

/// User configuration with validation
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct UserConfig {
    #[validate(length(min = 1))]
    pub password_hash: String,

    pub roles: Vec<String>,

    pub permissions: Vec<crate::auth::types::Permission>,

    pub enabled: bool,

    pub email: Option<String>,

    pub full_name: Option<String>,

    pub last_login: Option<chrono::DateTime<chrono::Utc>>,

    pub failed_login_attempts: u32,

    pub locked_until: Option<chrono::DateTime<chrono::Utc>>,
}

/// Monitoring configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate, Default)]
pub struct MonitoringConfig {
    pub metrics: MetricsConfig,
    pub health_checks: HealthCheckConfig,
    pub tracing: TracingConfig,
    pub prometheus: Option<PrometheusConfig>,
}

/// Metrics configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct MetricsConfig {
    pub enabled: bool,

    #[validate(length(min = 1))]
    pub endpoint: String,

    #[validate(range(min = 1, max = 65535))]
    pub port: Option<u16>,

    pub namespace: String,

    pub collect_system_metrics: bool,

    pub histogram_buckets: Vec<f64>,
}

/// Prometheus configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct PrometheusConfig {
    pub enabled: bool,

    #[validate(length(min = 1))]
    pub endpoint: String,

    #[validate(range(min = 1, max = 65535))]
    pub port: Option<u16>,

    pub namespace: String,

    pub job_name: String,

    pub instance: String,

    pub scrape_interval_secs: u64,

    pub timeout_secs: u64,
}

/// Health check configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct HealthCheckConfig {
    pub enabled: bool,

    #[validate(range(min = 1))]
    pub interval_secs: u64,

    #[validate(range(min = 1))]
    pub timeout_secs: u64,

    pub checks: Vec<String>,
}

/// Tracing configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct TracingConfig {
    pub enabled: bool,

    pub endpoint: Option<String>,

    pub service_name: String,

    pub sample_rate: f64,

    pub output: TracingOutput,
}

/// Tracing output options
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TracingOutput {
    Stdout,
    Stderr,
    File,
    Jaeger,
    Otlp,
}

/// Performance configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct PerformanceConfig {
    pub caching: CacheConfig,
    pub connection_pool: ConnectionPoolConfig,
    pub query_optimization: QueryOptimizationConfig,
    #[validate(nested)]
    pub rate_limiting: Option<RateLimitConfig>,
}

/// Cache configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct CacheConfig {
    pub enabled: bool,

    #[validate(range(min = 1))]
    pub max_size: usize,

    #[validate(range(min = 1))]
    pub ttl_secs: u64,

    pub query_cache_enabled: bool,

    pub result_cache_enabled: bool,

    pub plan_cache_enabled: bool,
}

/// Connection pool configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct ConnectionPoolConfig {
    #[validate(range(min = 1))]
    pub min_connections: usize,

    #[validate(range(min = 1))]
    pub max_connections: usize,

    #[validate(range(min = 1))]
    pub connection_timeout_secs: u64,

    #[validate(range(min = 1))]
    pub idle_timeout_secs: u64,

    #[validate(range(min = 1))]
    pub max_lifetime_secs: u64,
}

/// Query optimization configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct QueryOptimizationConfig {
    pub enabled: bool,

    #[validate(range(min = 1))]
    pub max_query_time_secs: u64,

    #[validate(range(min = 1))]
    pub max_result_size: usize,

    pub parallel_execution: bool,

    #[validate(range(min = 1))]
    pub thread_pool_size: usize,
}

/// Logging configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct LoggingConfig {
    #[validate(length(min = 1))]
    pub level: String,

    pub format: LogFormat,

    pub output: LogOutput,

    pub file_config: Option<FileLogConfig>,
}

/// Log format options
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LogFormat {
    Text,
    Json,
    Compact,
}

/// Log output options
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LogOutput {
    Stdout,
    Stderr,
    File,
    Both,
}

/// File logging configuration
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct FileLogConfig {
    pub path: PathBuf,

    #[validate(range(min = 1))]
    pub max_size_mb: u64,

    #[validate(range(min = 1))]
    pub max_files: usize,

    pub compress: bool,
}

impl Default for ServerConfig {
    fn default() -> Self {
        ServerConfig {
            server: ServerSettings {
                port: 3030,
                host: "localhost".to_string(),
                admin_ui: true,
                cors: true,
                max_connections: 1000,
                request_timeout_secs: 30,
                graceful_shutdown_timeout_secs: 30,
                tls: None,
                backup_directory: None,
                config_file: None,
            },
            datasets: HashMap::new(),
            security: SecurityConfig {
                auth_required: false,
                users: HashMap::new(),
                jwt: None,
                oauth: None,
                ldap: None,
                rate_limiting: None,
                cors: CorsConfig {
                    enabled: true,
                    allow_origins: vec!["*".to_string()],
                    allow_methods: vec![
                        "GET".to_string(),
                        "POST".to_string(),
                        "PUT".to_string(),
                        "DELETE".to_string(),
                    ],
                    allow_headers: vec!["*".to_string()],
                    expose_headers: vec![],
                    allow_credentials: false,
                    max_age_secs: 3600,
                },
                session: SessionConfig {
                    secret: uuid::Uuid::new_v4().to_string(),
                    timeout_secs: 3600,
                    secure: false,
                    http_only: true,
                    same_site: SameSitePolicy::Lax,
                },
                authentication: AuthenticationConfig { enabled: false },
                api_keys: None,
                certificate: None,
                saml: None,
                rebac: None,
                mfa: None,
            },
            monitoring: MonitoringConfig {
                metrics: MetricsConfig {
                    enabled: true,
                    endpoint: "/metrics".to_string(),
                    port: None,
                    namespace: "oxirs_fuseki".to_string(),
                    collect_system_metrics: true,
                    histogram_buckets: vec![
                        0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
                    ],
                },
                health_checks: HealthCheckConfig {
                    enabled: true,
                    interval_secs: 30,
                    timeout_secs: 5,
                    checks: vec!["store".to_string(), "memory".to_string()],
                },
                tracing: TracingConfig {
                    enabled: false,
                    endpoint: None,
                    service_name: "oxirs-fuseki".to_string(),
                    sample_rate: 0.1,
                    output: TracingOutput::Stdout,
                },
                prometheus: None,
            },
            performance: PerformanceConfig {
                caching: CacheConfig {
                    enabled: true,
                    max_size: 1000,
                    ttl_secs: 300,
                    query_cache_enabled: true,
                    result_cache_enabled: true,
                    plan_cache_enabled: true,
                },
                connection_pool: ConnectionPoolConfig {
                    min_connections: 1,
                    max_connections: 10,
                    connection_timeout_secs: 30,
                    idle_timeout_secs: 600,
                    max_lifetime_secs: 3600,
                },
                query_optimization: QueryOptimizationConfig {
                    enabled: true,
                    max_query_time_secs: 300,
                    max_result_size: 1_000_000,
                    parallel_execution: true,
                    thread_pool_size: get_cpu_count(),
                },
                rate_limiting: None,
            },
            logging: LoggingConfig {
                level: "info".to_string(),
                format: LogFormat::Text,
                output: LogOutput::Stdout,
                file_config: None,
            },
            federation: None,
            streaming: None,
            http_protocol: HttpProtocolSettings::default(),
        }
    }
}

impl ServerConfig {
    /// Load configuration using Figment (supports TOML, YAML, env vars)
    pub fn load() -> FusekiResult<Self> {
        let config: Self = Figment::new()
            .merge(Toml::file("oxirs-fuseki.toml"))
            .merge(Yaml::file("oxirs-fuseki.yaml"))
            .merge(Yaml::file("oxirs-fuseki.yml"))
            .merge(Env::prefixed("OXIRS_FUSEKI_"))
            .extract()
            .map_err(|e| {
                FusekiError::configuration(format!("Failed to load configuration: {e}"))
            })?;

        // Validate the configuration
        config.validate().map_err(|e| {
            FusekiError::validation(format!("Configuration validation failed: {e}"))
        })?;

        Ok(config)
    }

    /// Load configuration from a specific file
    pub fn from_file<P: AsRef<Path>>(path: P) -> FusekiResult<Self> {
        let path = path.as_ref();
        let config: Self = match path.extension().and_then(|ext| ext.to_str()) {
            Some("toml") => {
                let figment = Figment::new()
                    .merge(Toml::file(path))
                    .merge(Env::prefixed("OXIRS_FUSEKI_"));
                figment.extract()
            }
            Some("yaml") | Some("yml") => {
                let figment = Figment::new()
                    .merge(Yaml::file(path))
                    .merge(Env::prefixed("OXIRS_FUSEKI_"));
                figment.extract()
            }
            _ => {
                return Err(FusekiError::configuration(format!(
                    "Unsupported configuration file format: {path:?}"
                )));
            }
        }
        .map_err(|e| {
            FusekiError::configuration(format!("Failed to load configuration from {path:?}: {e}"))
        })?;

        // Validate the configuration
        config.validate().map_err(|e| {
            FusekiError::validation(format!("Configuration validation failed: {e}"))
        })?;

        info!("Configuration loaded from {:?}", path);
        Ok(config)
    }

    /// Save configuration to YAML file
    pub fn save_yaml<P: AsRef<Path>>(&self, path: P) -> FusekiResult<()> {
        let content = serde_yaml::to_string(self).map_err(|e| {
            FusekiError::configuration(format!("Failed to serialize configuration to YAML: {e}"))
        })?;

        std::fs::write(&path, content).map_err(|e| {
            FusekiError::configuration(format!(
                "Failed to write configuration to {:?}: {}",
                path.as_ref(),
                e
            ))
        })?;

        info!("Configuration saved to {:?}", path.as_ref());
        Ok(())
    }

    /// Save configuration to TOML file
    pub fn save_toml<P: AsRef<Path>>(&self, path: P) -> FusekiResult<()> {
        let content = toml::to_string_pretty(self).map_err(|e| {
            FusekiError::configuration(format!("Failed to serialize configuration to TOML: {e}"))
        })?;

        std::fs::write(&path, content).map_err(|e| {
            FusekiError::configuration(format!(
                "Failed to write configuration to {:?}: {}",
                path.as_ref(),
                e
            ))
        })?;

        info!("Configuration saved to {:?}", path.as_ref());
        Ok(())
    }

    /// Get the socket address for the server
    pub fn socket_addr(&self) -> FusekiResult<SocketAddr> {
        use std::net::ToSocketAddrs;

        let addr = format!("{}:{}", self.server.host, self.server.port);

        // Try to resolve the hostname to socket addresses
        let socket_addrs: Vec<SocketAddr> = addr
            .to_socket_addrs()
            .map_err(|e| {
                FusekiError::configuration(format!("Invalid host:port combination '{addr}': {e}"))
            })?
            .collect();

        // Return the first resolved address
        socket_addrs.into_iter().next().ok_or_else(|| {
            FusekiError::configuration(format!("No valid socket address found for '{addr}'"))
        })
    }

    /// Get request timeout as Duration
    pub fn request_timeout(&self) -> Duration {
        Duration::from_secs(self.server.request_timeout_secs)
    }

    /// Get graceful shutdown timeout as Duration
    pub fn graceful_shutdown_timeout(&self) -> Duration {
        Duration::from_secs(self.server.graceful_shutdown_timeout_secs)
    }

    /// Check if TLS is enabled
    pub fn is_tls_enabled(&self) -> bool {
        self.server.tls.is_some()
    }

    /// Check if authentication is required
    pub fn requires_auth(&self) -> bool {
        self.security.auth_required
    }

    /// Check if metrics are enabled
    pub fn metrics_enabled(&self) -> bool {
        self.monitoring.metrics.enabled
    }

    /// Check if tracing is enabled
    pub fn tracing_enabled(&self) -> bool {
        self.monitoring.tracing.enabled
    }

    /// Validate configuration and return detailed errors
    pub fn validate_detailed(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        // Check port availability (basic check)
        if self.server.port < 1024 && !is_privileged_user() {
            errors.push(format!(
                "Port {} requires elevated privileges. Consider using port >= 1024",
                self.server.port
            ));
        }

        // Check TLS configuration
        if let Some(ref tls) = self.server.tls {
            if !tls.cert_path.exists() {
                errors.push(format!(
                    "TLS certificate file not found: {:?}",
                    tls.cert_path
                ));
            }
            if !tls.key_path.exists() {
                errors.push(format!("TLS key file not found: {:?}", tls.key_path));
            }
        }

        // Check dataset locations
        for (name, dataset) in &self.datasets {
            if dataset.location.is_empty() {
                errors.push(format!("Dataset '{name}' has empty location"));
            }

            // Check if SHACL shape files exist
            for shape_file in &dataset.shacl_shapes {
                if !shape_file.exists() {
                    errors.push(format!(
                        "SHACL shape file not found for dataset '{name}': {shape_file:?}"
                    ));
                }
            }
        }

        // Check JWT configuration
        if let Some(ref jwt) = self.security.jwt {
            if jwt.secret.len() < 32 {
                errors.push("JWT secret must be at least 32 characters long".to_string());
            }
        }

        // Check logging configuration
        if let Some(ref file_config) = self.logging.file_config {
            if let Some(parent) = file_config.path.parent() {
                if !parent.exists() {
                    errors.push(format!("Log file directory does not exist: {parent:?}"));
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

impl Default for MetricsConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            endpoint: "/metrics".to_string(),
            port: None,
            namespace: "oxirs".to_string(),
            collect_system_metrics: true,
            histogram_buckets: vec![0.001, 0.01, 0.1, 1.0, 10.0],
        }
    }
}

impl Default for HealthCheckConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            interval_secs: 30,
            timeout_secs: 5,
            checks: vec!["database".to_string(), "memory".to_string()],
        }
    }
}

impl Default for TracingConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            endpoint: None,
            service_name: "oxirs-fuseki".to_string(),
            sample_rate: 1.0,
            output: TracingOutput::Stdout,
        }
    }
}

impl Default for CorsConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            allow_origins: vec!["*".to_string()],
            allow_methods: vec!["GET".to_string(), "POST".to_string(), "OPTIONS".to_string()],
            allow_headers: vec!["Content-Type".to_string(), "Authorization".to_string()],
            expose_headers: vec![],
            allow_credentials: false,
            max_age_secs: 3600,
        }
    }
}

impl Default for SessionConfig {
    fn default() -> Self {
        Self {
            secret: "default-session-secret-change-in-production".to_string(),
            timeout_secs: 3600,
            secure: false,
            http_only: true,
            same_site: SameSitePolicy::Lax,
        }
    }
}

/// Configuration watcher for hot-reloading
#[cfg(feature = "hot-reload")]
pub struct ConfigWatcher {
    _watcher: RecommendedWatcher,
    receiver: tokio::sync::watch::Receiver<ServerConfig>,
}

#[cfg(feature = "hot-reload")]
impl ConfigWatcher {
    /// Create a new configuration watcher
    pub fn new<P: AsRef<Path>>(
        config_path: P,
    ) -> FusekiResult<(Self, tokio::sync::watch::Receiver<ServerConfig>)> {
        let config_path = config_path.as_ref().to_path_buf();
        let initial_config = ServerConfig::from_file(&config_path)?;

        let (tx, rx) = tokio::sync::watch::channel(initial_config);
        let (file_tx, file_rx) = mpsc::channel();

        let mut watcher = notify::recommended_watcher(move |res: Result<Event, notify::Error>| {
            match res {
                Ok(event) => {
                    if let Err(e) = file_tx.send(event) {
                        warn!("Failed to send file watch event: {}", e);
                    }
                }
                Err(e) => warn!("File watch error: {}", e),
            }
        })
        .map_err(|e| FusekiError::configuration(format!("Failed to create file watcher: {}", e)))?;

        watcher
            .watch(&config_path, RecursiveMode::NonRecursive)
            .map_err(|e| {
                FusekiError::configuration(format!(
                    "Failed to watch config file {:?}: {}",
                    config_path, e
                ))
            })?;

        // Spawn background task to handle file events
        let config_path_clone = config_path.clone();
        let tx_clone = tx.clone();
        tokio::spawn(async move {
            while let Ok(event) = file_rx.recv() {
                if event.kind.is_modify() {
                    // Debounce rapid file changes
                    tokio::time::sleep(Duration::from_millis(100)).await;

                    match ServerConfig::from_file(&config_path_clone) {
                        Ok(new_config) => {
                            if let Err(e) = tx_clone.send(new_config) {
                                warn!("Failed to send updated config: {}", e);
                            } else {
                                info!("Configuration reloaded from {:?}", config_path_clone);
                            }
                        }
                        Err(e) => {
                            warn!("Failed to reload configuration: {}", e);
                        }
                    }
                }
            }
        });

        let config_watcher = ConfigWatcher {
            _watcher: watcher,
            receiver: rx.clone(),
        };

        Ok((config_watcher, rx))
    }

    /// Get the current configuration
    pub fn current_config(&self) -> ServerConfig {
        self.receiver.borrow().clone()
    }
}

/// Check if the current user has elevated privileges
fn is_privileged_user() -> bool {
    #[cfg(unix)]
    {
        // Use std::env to check USER environment variable as a safe alternative
        std::env::var("USER")
            .map(|user| user == "root")
            .unwrap_or(false)
    }
    #[cfg(not(unix))]
    {
        // On Windows, assume non-privileged for simplicity
        // In a real implementation, you'd check for administrator privileges
        false
    }
}

/// Get the number of CPU cores available
fn get_cpu_count() -> usize {
    std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(4) // Fallback to 4 cores
}

/// Custom validation function for PathBuf
fn validate_path(path: &Path) -> Result<(), ValidationError> {
    if path.as_os_str().is_empty() {
        return Err(ValidationError::new("path_empty"));
    }
    Ok(())
}

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

    #[test]
    fn test_server_config_default() {
        let config = ServerConfig::default();
        assert_eq!(config.server.port, 3030);
        assert_eq!(config.server.host, "localhost");
        assert!(config.server.admin_ui);
        assert!(config.server.cors);
        assert!(!config.security.auth_required);
        assert!(config.datasets.is_empty());
        assert!(config.security.users.is_empty());
        assert!(config.monitoring.metrics.enabled);
        assert!(config.performance.caching.enabled);
    }

    #[test]
    fn test_config_validation() {
        let mut config = ServerConfig::default();

        // Valid configuration should pass
        assert!(config.validate().is_ok());

        // Invalid port should fail
        config.server.port = 0;
        assert!(config.validate().is_err());

        // Reset to valid
        config.server.port = 3030;

        // Empty host should fail
        config.server.host = String::new();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_socket_addr() {
        let config = ServerConfig::default();
        let addr = config.socket_addr().unwrap();
        assert_eq!(addr.port(), 3030);
    }

    #[test]
    fn test_timeouts() {
        let config = ServerConfig::default();
        assert_eq!(config.request_timeout().as_secs(), 30);
        assert_eq!(config.graceful_shutdown_timeout().as_secs(), 30);
    }

    #[test]
    fn test_tls_config() {
        let mut config = ServerConfig::default();
        assert!(!config.is_tls_enabled());

        config.server.tls = Some(TlsConfig {
            cert_path: "/path/to/cert.pem".into(),
            key_path: "/path/to/key.pem".into(),
            require_client_cert: false,
            ca_cert_path: None,
        });
        assert!(config.is_tls_enabled());
    }

    #[test]
    fn test_jwt_config_validation() {
        let mut jwt_config = JwtConfig {
            secret: "short".to_string(),
            expiration_secs: 3600,
            issuer: "oxirs-fuseki".to_string(),
            audience: "oxirs-users".to_string(),
        };

        // Short secret should fail validation
        assert!(jwt_config.validate().is_err());

        // Long enough secret should pass
        jwt_config.secret = "a".repeat(32);
        assert!(jwt_config.validate().is_ok());
    }

    #[test]
    fn test_rate_limit_config() {
        let rate_limit = RateLimitConfig {
            requests_per_minute: 100,
            burst_size: 10,
            per_ip: true,
            per_user: false,
            whitelist: vec!["127.0.0.1".to_string()],
        };

        assert!(rate_limit.validate().is_ok());
    }

    #[test]
    fn test_service_types() {
        let service = ServiceConfig {
            name: "query".to_string(),
            service_type: ServiceType::SparqlQuery,
            endpoint: "sparql".to_string(),
            auth_required: false,
            rate_limit: None,
        };

        assert!(service.validate().is_ok());
    }

    #[test]
    fn test_monitoring_config() {
        let monitoring = MonitoringConfig {
            metrics: MetricsConfig {
                enabled: true,
                endpoint: "/metrics".to_string(),
                port: Some(9090),
                namespace: "test".to_string(),
                collect_system_metrics: true,
                histogram_buckets: vec![0.1, 1.0, 10.0],
            },
            health_checks: HealthCheckConfig {
                enabled: true,
                interval_secs: 30,
                timeout_secs: 5,
                checks: vec!["store".to_string()],
            },
            tracing: TracingConfig {
                enabled: false,
                endpoint: None,
                service_name: "test".to_string(),
                sample_rate: 0.1,
                output: TracingOutput::Stdout,
            },
            prometheus: None,
        };

        assert!(monitoring.validate().is_ok());
    }

    #[test]
    fn test_performance_config() {
        let performance = PerformanceConfig {
            caching: CacheConfig {
                enabled: true,
                max_size: 1000,
                ttl_secs: 300,
                query_cache_enabled: true,
                result_cache_enabled: true,
                plan_cache_enabled: true,
            },
            connection_pool: ConnectionPoolConfig {
                min_connections: 1,
                max_connections: 10,
                connection_timeout_secs: 30,
                idle_timeout_secs: 600,
                max_lifetime_secs: 3600,
            },
            query_optimization: QueryOptimizationConfig {
                enabled: true,
                max_query_time_secs: 300,
                max_result_size: 1_000_000,
                parallel_execution: true,
                thread_pool_size: 4,
            },
            rate_limiting: None,
        };

        assert!(performance.validate().is_ok());
    }

    #[test]
    fn test_logging_config() {
        let logging = LoggingConfig {
            level: "info".to_string(),
            format: LogFormat::Json,
            output: LogOutput::Stdout,
            file_config: None,
        };

        assert!(logging.validate().is_ok());
    }

    #[test]
    fn test_user_config_extended() {
        let user = UserConfig {
            password_hash: "$argon2id$v=19$m=65536,t=3,p=4$...".to_string(),
            roles: vec!["admin".to_string(), "user".to_string()],
            permissions: vec![],
            enabled: true,
            email: Some("admin@example.com".to_string()),
            full_name: Some("Administrator".to_string()),
            last_login: None,
            failed_login_attempts: 0,
            locked_until: None,
        };

        assert!(user.validate().is_ok());
        assert_eq!(user.roles.len(), 2);
        assert!(user.enabled);
        assert_eq!(user.failed_login_attempts, 0);
    }

    #[test]
    fn test_cors_config() {
        let cors = CorsConfig {
            enabled: true,
            allow_origins: vec!["http://localhost:3000".to_string()],
            allow_methods: vec!["GET".to_string(), "POST".to_string()],
            allow_headers: vec!["Content-Type".to_string()],
            expose_headers: vec![],
            allow_credentials: true,
            max_age_secs: 3600,
        };

        assert!(cors.validate().is_ok());
    }

    #[test]
    fn test_session_config() {
        let session = SessionConfig {
            secret: "a".repeat(32),
            timeout_secs: 3600,
            secure: true,
            http_only: true,
            same_site: SameSitePolicy::Strict,
        };

        assert!(session.validate().is_ok());
    }

    #[test]
    fn test_save_and_load_yaml() {
        let config = ServerConfig::default();
        let temp_file = NamedTempFile::new().unwrap();
        let temp_path = temp_file.path().with_extension("yaml");

        // Save configuration
        config.save_yaml(&temp_path).unwrap();

        // Load configuration
        let loaded_config = ServerConfig::from_file(&temp_path).unwrap();

        assert_eq!(config.server.port, loaded_config.server.port);
        assert_eq!(config.server.host, loaded_config.server.host);
    }

    #[test]
    fn test_save_and_load_toml() {
        let config = ServerConfig::default();
        let temp_file = NamedTempFile::new().unwrap();
        let temp_path = temp_file.path().with_extension("toml");

        // Save configuration
        config.save_toml(&temp_path).unwrap();

        // Load configuration
        let loaded_config = ServerConfig::from_file(&temp_path).unwrap();

        assert_eq!(config.server.port, loaded_config.server.port);
        assert_eq!(config.server.host, loaded_config.server.host);

        // Clean up
        std::fs::remove_file(temp_path).ok();
    }

    #[test]
    fn test_detailed_validation() {
        let mut config = ServerConfig::default();

        // Should pass validation for default config
        assert!(config.validate_detailed().is_ok());

        // Add invalid dataset
        let dataset = DatasetConfig {
            name: "test".to_string(),
            location: String::new(), // Empty location should fail
            read_only: false,
            text_index: None,
            shacl_shapes: vec![],
            services: vec![],
            access_control: None,
            backup: None,
        };

        config.datasets.insert("test".to_string(), dataset);

        let errors = config.validate_detailed().unwrap_err();
        assert!(!errors.is_empty());
        assert!(errors.iter().any(|e| e.contains("empty location")));
    }
}