jflow-core 0.1.0

Shared types, configuration, and application state for the JANUS trading engine (signals, config, unified metrics, inter-module channels).
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
//! Unified configuration for all JANUS modules
//!
//! Supports loading from TOML files with environment variable overrides.
//! Configuration can be loaded from:
//! 1. TOML file (specified by JANUS_CONFIG_PATH or default locations)
//! 2. Environment variables (override file settings)
//!
//! Environment variable naming convention: JANUS_<SECTION>_<KEY>
//! Example: JANUS_PORTS_HTTP=8080, JANUS_MODULES_FORWARD=true

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use tracing::{debug, info, warn};

/// Default config file search paths
const CONFIG_PATHS: &[&str] = &[
    "config/janus.toml",
    "/etc/janus/janus.toml",
    "janus.toml",
    "infrastructure/config/janus/janus.toml",
];

// ============================================================================
// Main Configuration Structure
// ============================================================================

/// Main configuration for the unified JANUS service
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
    /// Service metadata
    pub service: ServiceConfig,

    /// Network ports configuration
    pub ports: PortsConfig,

    /// Host/bind configuration
    pub host: HostConfig,

    /// Module toggles
    pub modules: ModulesConfig,

    /// Redis configuration
    pub redis: RedisConfig,

    /// Database configuration
    pub database: DatabaseConfig,

    /// QuestDB configuration
    pub questdb: QuestDbConfig,

    /// Forward module settings
    pub forward: ForwardConfig,

    /// Risk management settings
    pub risk: RiskConfig,

    /// Backward module settings
    pub backward: BackwardConfig,

    /// CNS module settings
    pub cns: CnsConfig,

    /// Market data configuration
    pub market: MarketConfig,

    /// Assets configuration
    pub assets: AssetsConfig,

    /// Trading configuration
    pub trading: TradingConfig,

    /// Logging configuration
    pub logging: LoggingConfig,

    /// Tracing configuration
    pub tracing: TracingConfig,

    /// Metrics configuration
    pub metrics: MetricsConfig,

    /// Alerting configuration
    pub alerting: AlertingConfig,

    /// Parameter hot-reload configuration
    pub param_reload: ParamReloadConfig,

    /// Feature engineering configuration
    pub features: FeaturesConfig,

    /// Security configuration
    pub security: SecurityConfig,

    /// Advanced settings
    pub advanced: AdvancedConfig,
}

// ============================================================================
// Configuration Sections
// ============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ServiceConfig {
    /// Service name
    pub name: String,
    /// Service version
    pub version: String,
    /// Environment: development | staging | production
    pub environment: String,
}

impl Default for ServiceConfig {
    fn default() -> Self {
        Self {
            name: "janus".to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
            environment: "development".to_string(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PortsConfig {
    /// HTTP/REST API port
    pub http: u16,
    /// gRPC API port
    pub grpc: u16,
    /// WebSocket port
    pub websocket: u16,
    /// Prometheus metrics port
    pub metrics: u16,
}

impl Default for PortsConfig {
    fn default() -> Self {
        Self {
            http: 8080,
            grpc: 50051,
            websocket: 8081,
            metrics: 9090,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct HostConfig {
    /// Bind address for all services
    pub bind: String,
    /// Public hostname
    pub public: String,
}

impl Default for HostConfig {
    fn default() -> Self {
        Self {
            bind: "0.0.0.0".to_string(),
            public: "localhost".to_string(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ModulesConfig {
    /// Enable forward module
    pub forward: bool,
    /// Enable backward module
    pub backward: bool,
    /// Enable CNS module
    pub cns: bool,
    /// Enable API module
    pub api: bool,
    /// Enable Data module
    pub data: bool,
    /// Enable WebSocket streaming
    pub websocket: bool,
    /// Enable gRPC API
    pub grpc: bool,
    /// Enable Prometheus metrics
    pub metrics: bool,
}

impl Default for ModulesConfig {
    fn default() -> Self {
        Self {
            forward: true,
            backward: true,
            cns: true,
            api: true,
            data: true,
            websocket: true,
            grpc: true,
            metrics: true,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RedisConfig {
    /// Redis connection URL
    pub url: String,
    /// Maximum connections in pool
    pub max_connections: u32,
    /// Minimum connections in pool
    pub min_connections: u32,
    /// Connection timeout in seconds
    pub connect_timeout_secs: u64,
    /// Pub/Sub channel for parameters
    pub param_channel: String,
    /// Pub/Sub channel for signals
    pub signal_channel: String,
}

impl Default for RedisConfig {
    fn default() -> Self {
        Self {
            url: "redis://localhost:6379/0".to_string(),
            max_connections: 10,
            min_connections: 2,
            connect_timeout_secs: 10,
            param_channel: "fks:params".to_string(),
            signal_channel: "fks:signals".to_string(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DatabaseConfig {
    /// PostgreSQL connection URL
    pub url: String,
    /// Maximum connections in pool
    pub max_connections: u32,
    /// Minimum connections in pool
    pub min_connections: u32,
    /// Connection timeout in seconds
    pub connect_timeout_secs: u64,
    /// Idle timeout in seconds
    pub idle_timeout_secs: u64,
    /// Maximum connection lifetime in seconds
    pub max_lifetime_secs: u64,
    /// Enable SQL query logging
    pub enable_logging: bool,
}

impl Default for DatabaseConfig {
    fn default() -> Self {
        Self {
            url: "postgresql://postgres:postgres@localhost:5432/janus".to_string(),
            max_connections: 10,
            min_connections: 2,
            connect_timeout_secs: 30,
            idle_timeout_secs: 600,
            max_lifetime_secs: 1800,
            enable_logging: false,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct QuestDbConfig {
    /// QuestDB host
    pub host: String,
    /// ILP port for line protocol
    pub ilp_port: u16,
    /// HTTP API port
    pub http_port: u16,
    /// PostgreSQL wire protocol port
    pub pg_port: u16,
}

impl Default for QuestDbConfig {
    fn default() -> Self {
        Self {
            host: "localhost".to_string(),
            ilp_port: 9009,
            http_port: 9000,
            pg_port: 8812,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ForwardConfig {
    /// Signal generation interval in seconds
    pub signal_interval_secs: u64,
    /// Path to ML models
    pub ml_model_path: String,
    /// Enable ML inference
    pub enable_ml_inference: bool,
    /// Signal configuration
    pub signals: SignalConfig,
    /// Execution configuration
    pub execution: ExecutionConfig,
    /// Indicators configuration
    pub indicators: IndicatorsConfig,
    /// Strategies configuration
    pub strategies: StrategiesConfig,
}

impl Default for ForwardConfig {
    fn default() -> Self {
        Self {
            signal_interval_secs: 5,
            ml_model_path: "/models".to_string(),
            enable_ml_inference: false,
            signals: SignalConfig::default(),
            execution: ExecutionConfig::default(),
            indicators: IndicatorsConfig::default(),
            strategies: StrategiesConfig::default(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SignalConfig {
    /// Minimum confidence threshold
    pub min_confidence: f64,
    /// Minimum signal strength
    pub min_strength: f64,
    /// Maximum signal age in seconds
    pub max_age_secs: u64,
    /// Enable quality filtering
    pub enable_quality_filter: bool,
    /// Batch size for processing
    pub batch_size: usize,
}

impl Default for SignalConfig {
    fn default() -> Self {
        Self {
            min_confidence: 0.6,
            min_strength: 0.5,
            max_age_secs: 300,
            enable_quality_filter: true,
            batch_size: 100,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ExecutionConfig {
    /// Enable execution
    pub enabled: bool,
    /// Execution service endpoint
    pub endpoint: String,
    /// Connection timeout in seconds
    pub connect_timeout_secs: u64,
    /// Request timeout in seconds
    pub request_timeout_secs: u64,
    /// Enable TLS
    pub enable_tls: bool,
    /// Maximum retries
    pub max_retries: u32,
    /// Retry backoff in milliseconds
    pub retry_backoff_ms: u64,
}

impl Default for ExecutionConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            endpoint: "http://execution:50052".to_string(),
            connect_timeout_secs: 10,
            request_timeout_secs: 30,
            enable_tls: false,
            max_retries: 3,
            retry_backoff_ms: 100,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct IndicatorsConfig {
    /// EMA periods
    pub ema_periods: Vec<u32>,
    /// RSI period
    pub rsi_period: u32,
    /// RSI overbought threshold
    pub rsi_overbought: f64,
    /// RSI oversold threshold
    pub rsi_oversold: f64,
    /// MACD fast period
    pub macd_fast_period: u32,
    /// MACD slow period
    pub macd_slow_period: u32,
    /// MACD signal period
    pub macd_signal_period: u32,
    /// Bollinger period
    pub bollinger_period: u32,
    /// Bollinger standard deviation
    pub bollinger_std_dev: f64,
    /// ATR period
    pub atr_period: u32,
    /// Volume MA period
    pub volume_ma_period: u32,
}

impl Default for IndicatorsConfig {
    fn default() -> Self {
        Self {
            ema_periods: vec![9, 21, 50, 200],
            rsi_period: 14,
            rsi_overbought: 70.0,
            rsi_oversold: 30.0,
            macd_fast_period: 12,
            macd_slow_period: 26,
            macd_signal_period: 9,
            bollinger_period: 20,
            bollinger_std_dev: 2.0,
            atr_period: 14,
            volume_ma_period: 20,
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct StrategiesConfig {
    /// Strategy weights
    pub weights: StrategyWeights,
    /// Consensus settings
    pub consensus: ConsensusConfig,
    /// EMA crossover strategy
    pub ema_crossover: EmaCrossoverConfig,
    /// RSI reversal strategy
    pub rsi_reversal: RsiReversalConfig,
    /// MACD momentum strategy
    pub macd_momentum: MacdMomentumConfig,
    /// Bollinger breakout strategy
    pub bollinger_breakout: BollingerBreakoutConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct StrategyWeights {
    pub ema_crossover: f64,
    pub rsi_reversal: f64,
    pub macd_momentum: f64,
    pub bollinger_breakout: f64,
}

impl Default for StrategyWeights {
    fn default() -> Self {
        Self {
            ema_crossover: 1.0,
            rsi_reversal: 1.0,
            macd_momentum: 1.0,
            bollinger_breakout: 1.0,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ConsensusConfig {
    pub min_agreement: f64,
    pub min_strategies: u32,
}

impl Default for ConsensusConfig {
    fn default() -> Self {
        Self {
            min_agreement: 0.6,
            min_strategies: 2,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct EmaCrossoverConfig {
    pub enabled: bool,
    pub fast_period: u32,
    pub slow_period: u32,
    pub min_spread_pct: f64,
}

impl Default for EmaCrossoverConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            fast_period: 9,
            slow_period: 21,
            min_spread_pct: 0.1,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RsiReversalConfig {
    pub enabled: bool,
    pub period: u32,
    pub overbought_threshold: f64,
    pub oversold_threshold: f64,
    pub confirmation_candles: u32,
}

impl Default for RsiReversalConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            period: 14,
            overbought_threshold: 70.0,
            oversold_threshold: 30.0,
            confirmation_candles: 1,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MacdMomentumConfig {
    pub enabled: bool,
    pub fast_period: u32,
    pub slow_period: u32,
    pub signal_period: u32,
    pub histogram_threshold: f64,
}

impl Default for MacdMomentumConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            fast_period: 12,
            slow_period: 26,
            signal_period: 9,
            histogram_threshold: 0.0,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct BollingerBreakoutConfig {
    pub enabled: bool,
    pub period: u32,
    pub std_dev: f64,
    pub require_close_outside: bool,
}

impl Default for BollingerBreakoutConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            period: 20,
            std_dev: 2.0,
            require_close_outside: true,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RiskConfig {
    /// Account balance for position sizing
    pub account_balance: f64,
    /// Maximum position size percentage
    pub max_position_size_pct: f64,
    /// Maximum portfolio risk percentage
    pub max_portfolio_risk_pct: f64,
    /// Maximum open positions
    pub max_open_positions: u32,
    /// Maximum daily loss
    pub max_daily_loss: f64,
    /// Maximum position hold time in hours
    pub max_position_hold_hours: u32,
    /// Stop loss configuration
    pub stop_loss: StopLossConfig,
    /// Take profit configuration
    pub take_profit: TakeProfitConfig,
    /// Position sizing configuration
    pub position_sizing: PositionSizingConfig,
}

impl Default for RiskConfig {
    fn default() -> Self {
        Self {
            account_balance: 100000.0,
            max_position_size_pct: 0.02,
            max_portfolio_risk_pct: 0.10,
            max_open_positions: 10,
            max_daily_loss: 1000.0,
            max_position_hold_hours: 24,
            stop_loss: StopLossConfig::default(),
            take_profit: TakeProfitConfig::default(),
            position_sizing: PositionSizingConfig::default(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct StopLossConfig {
    pub default_pct: f64,
    pub use_atr: bool,
    pub atr_multiplier: f64,
    pub min_distance_pct: f64,
    pub max_distance_pct: f64,
}

impl Default for StopLossConfig {
    fn default() -> Self {
        Self {
            default_pct: 0.02,
            use_atr: true,
            atr_multiplier: 2.0,
            min_distance_pct: 0.005,
            max_distance_pct: 0.10,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct TakeProfitConfig {
    pub risk_reward_ratio: f64,
    pub enable_trailing: bool,
    pub trailing_distance_pct: f64,
}

impl Default for TakeProfitConfig {
    fn default() -> Self {
        Self {
            risk_reward_ratio: 2.0,
            enable_trailing: false,
            trailing_distance_pct: 0.01,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PositionSizingConfig {
    /// Method: fixed | risk_based | kelly | volatility
    pub method: String,
    pub fixed_size_usd: f64,
    pub risk_per_trade_pct: f64,
    pub kelly_fraction: f64,
}

impl Default for PositionSizingConfig {
    fn default() -> Self {
        Self {
            method: "risk_based".to_string(),
            fixed_size_usd: 1000.0,
            risk_per_trade_pct: 0.01,
            kelly_fraction: 0.25,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct BackwardConfig {
    /// Number of worker threads
    pub worker_threads: usize,
    /// Enable scheduled jobs
    pub enable_scheduler: bool,
    /// Persistence configuration
    pub persistence: PersistenceConfig,
    /// Analytics configuration
    pub analytics: AnalyticsConfig,
    /// Data retention configuration
    pub retention: RetentionConfig,
}

impl Default for BackwardConfig {
    fn default() -> Self {
        Self {
            worker_threads: 4,
            enable_scheduler: true,
            persistence: PersistenceConfig::default(),
            analytics: AnalyticsConfig::default(),
            retention: RetentionConfig::default(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PersistenceConfig {
    pub batch_size: usize,
    pub flush_interval_secs: u64,
    pub enable_wal: bool,
}

impl Default for PersistenceConfig {
    fn default() -> Self {
        Self {
            batch_size: 100,
            flush_interval_secs: 5,
            enable_wal: true,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AnalyticsConfig {
    pub update_interval_secs: u64,
    pub performance_window_hours: u32,
    pub enable_trade_analysis: bool,
}

impl Default for AnalyticsConfig {
    fn default() -> Self {
        Self {
            update_interval_secs: 60,
            performance_window_hours: 24,
            enable_trade_analysis: true,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RetentionConfig {
    pub signals_days: u32,
    pub trades_days: u32,
    pub metrics_days: u32,
}

impl Default for RetentionConfig {
    fn default() -> Self {
        Self {
            signals_days: 90,
            trades_days: 365,
            metrics_days: 30,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CnsConfig {
    /// Health check interval in seconds
    pub health_check_interval_secs: u64,
    /// Enable automatic recovery reflexes
    pub enable_reflexes: bool,
    /// Verbose logging
    pub verbose_logging: bool,
    /// Startup grace period in seconds
    pub startup_grace_period_secs: u64,
    /// Maximum concurrent probes
    pub max_concurrent_probes: u32,
    /// Probe retry attempts
    pub probe_retry_attempts: u32,
    /// Endpoints configuration
    pub endpoints: CnsEndpointsConfig,
    /// Circuit breakers configuration
    pub circuit_breakers: HashMap<String, CircuitBreakerConfig>,
}

impl Default for CnsConfig {
    fn default() -> Self {
        Self {
            health_check_interval_secs: 10,
            enable_reflexes: true,
            verbose_logging: false,
            startup_grace_period_secs: 30,
            max_concurrent_probes: 10,
            probe_retry_attempts: 2,
            endpoints: CnsEndpointsConfig::default(),
            circuit_breakers: HashMap::new(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CnsEndpointsConfig {
    pub forward_service: String,
    pub backward_service: String,
    pub gateway_service: String,
    pub redis: String,
    pub qdrant: String,
    pub shared_memory_path: String,
    pub neuromorphic: NeuromorphicConfig,
}

impl Default for CnsEndpointsConfig {
    fn default() -> Self {
        Self {
            forward_service: "http://localhost:8080/api/v1".to_string(),
            backward_service: "http://localhost:8082".to_string(),
            gateway_service: "http://localhost:8000".to_string(),
            redis: "redis://localhost:6379".to_string(),
            qdrant: String::new(),
            shared_memory_path: "/dev/shm/janus_forward_backward".to_string(),
            neuromorphic: NeuromorphicConfig::default(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct NeuromorphicConfig {
    pub enabled: bool,
    pub base_url: String,
}

impl Default for NeuromorphicConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            base_url: "http://localhost:8090".to_string(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CircuitBreakerConfig {
    pub failure_threshold: u32,
    pub failure_window_secs: u64,
    pub recovery_timeout_secs: u64,
    pub success_threshold: u32,
}

impl Default for CircuitBreakerConfig {
    fn default() -> Self {
        Self {
            failure_threshold: 5,
            failure_window_secs: 60,
            recovery_timeout_secs: 30,
            success_threshold: 3,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MarketConfig {
    /// Primary exchange
    pub exchange: String,
    /// Update interval in milliseconds
    pub update_interval_ms: u64,
    /// Enable order book
    pub enable_orderbook: bool,
    /// Order book depth
    pub orderbook_depth: u32,
    /// Timeframes configuration
    pub timeframes: TimeframesConfig,
}

impl Default for MarketConfig {
    fn default() -> Self {
        Self {
            exchange: "kraken".to_string(),
            update_interval_ms: 1000,
            enable_orderbook: true,
            orderbook_depth: 10,
            timeframes: TimeframesConfig::default(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AssetsConfig {
    /// List of enabled trading assets (base currency symbols)
    pub enabled: Vec<String>,
    /// Default quote currency
    pub default_quote: String,
    /// Assets to use for optimization runs
    pub optimize_assets: Vec<String>,
    /// High priority assets (receive more frequent updates)
    pub priority_assets: Vec<String>,
    /// Per-asset configurations
    #[serde(flatten)]
    pub configs: HashMap<String, AssetConfig>,
}

impl Default for AssetsConfig {
    fn default() -> Self {
        Self {
            enabled: vec!["BTC".to_string(), "ETH".to_string(), "SOL".to_string()],
            default_quote: "USD".to_string(),
            optimize_assets: vec!["BTC".to_string(), "ETH".to_string(), "SOL".to_string()],
            priority_assets: vec!["BTC".to_string(), "ETH".to_string()],
            configs: HashMap::new(),
        }
    }
}

impl AssetsConfig {
    /// Get list of enabled trading symbols (e.g., "BTC/USD")
    pub fn enabled_symbols(&self) -> Vec<String> {
        self.enabled
            .iter()
            .map(|asset| format!("{}/{}", asset, self.default_quote))
            .collect()
    }

    /// Get config for a specific asset
    pub fn get(&self, asset: &str) -> Option<&AssetConfig> {
        self.configs.get(asset)
    }

    /// Check if an asset is enabled
    pub fn is_enabled(&self, asset: &str) -> bool {
        self.enabled.contains(&asset.to_string())
    }

    /// Check if an asset is high priority
    pub fn is_priority(&self, asset: &str) -> bool {
        self.priority_assets.contains(&asset.to_string())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AssetConfig {
    /// Full trading symbol (e.g., "BTC/USD")
    pub symbol: String,
    /// Whether this asset is enabled for trading
    pub enabled: bool,
    /// Maximum position size as percentage of account
    pub max_position_size_pct: f64,
    /// Maximum leverage allowed
    pub max_leverage: f64,
    /// Minimum order size in base currency
    pub min_order_size: f64,
    /// Maximum order size in base currency
    pub max_order_size: f64,
    /// ATR multiplier for stop loss calculation
    pub atr_multiplier: f64,
    /// RSI overbought threshold
    pub rsi_overbought: f64,
    /// RSI oversold threshold
    pub rsi_oversold: f64,
    /// Exchange-specific configurations
    pub exchanges: HashMap<String, ExchangeAssetConfig>,
}

impl Default for AssetConfig {
    fn default() -> Self {
        Self {
            symbol: String::new(),
            enabled: true,
            max_position_size_pct: 0.02,
            max_leverage: 2.0,
            min_order_size: 0.001,
            max_order_size: 100.0,
            atr_multiplier: 2.0,
            rsi_overbought: 70.0,
            rsi_oversold: 30.0,
            exchanges: HashMap::new(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ExchangeAssetConfig {
    /// Exchange-specific trading pair symbol
    pub pair: String,
    /// Minimum order size on this exchange
    pub min_order: f64,
    /// Fee tier (e.g., "maker", "taker")
    pub fee_tier: Option<String>,
    /// Category for derivatives (e.g., "linear", "inverse")
    pub category: Option<String>,
}

impl Default for ExchangeAssetConfig {
    fn default() -> Self {
        Self {
            pair: String::new(),
            min_order: 0.001,
            fee_tier: None,
            category: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct TimeframesConfig {
    pub enabled: Vec<String>,
    pub primary: String,
}

impl Default for TimeframesConfig {
    fn default() -> Self {
        Self {
            enabled: vec![
                "1m".to_string(),
                "5m".to_string(),
                "15m".to_string(),
                "1h".to_string(),
                "4h".to_string(),
                "1d".to_string(),
            ],
            primary: "5m".to_string(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct TradingConfig {
    /// Trading mode: simulation | paper | live
    pub mode: String,
    /// Enable real order execution
    pub real_orders_enabled: bool,
    /// Dry run mode
    pub dry_run: bool,
    /// Simulation settings
    pub simulation: SimulationConfig,
    /// Order settings
    pub orders: OrdersConfig,
}

impl Default for TradingConfig {
    fn default() -> Self {
        Self {
            mode: "paper".to_string(),
            real_orders_enabled: false,
            dry_run: true,
            simulation: SimulationConfig::default(),
            orders: OrdersConfig::default(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SimulationConfig {
    pub initial_balance: f64,
    pub slippage_bps: u32,
    pub fee_bps: u32,
    pub fill_delay_ms: u64,
    pub enable_slippage: bool,
}

impl Default for SimulationConfig {
    fn default() -> Self {
        Self {
            initial_balance: 100000.0,
            slippage_bps: 5,
            fee_bps: 10,
            fill_delay_ms: 200,
            enable_slippage: true,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct OrdersConfig {
    pub default_type: String,
    pub default_tif: String,
    pub min_size_usd: f64,
    pub max_size_usd: f64,
    pub max_slippage_bps: u32,
}

impl Default for OrdersConfig {
    fn default() -> Self {
        Self {
            default_type: "limit".to_string(),
            default_tif: "gtc".to_string(),
            min_size_usd: 10.0,
            max_size_usd: 100000.0,
            max_slippage_bps: 50,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LoggingConfig {
    /// Log level: trace | debug | info | warn | error
    pub level: String,
    /// Log format: json | pretty
    pub format: String,
    /// Enable console output
    pub console: bool,
    /// Enable file logging
    pub file_enabled: bool,
    /// Log file path
    pub file_path: String,
    /// Enable SQL query logging
    pub sql_logging: bool,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: "info".to_string(),
            format: "json".to_string(),
            console: true,
            file_enabled: false,
            file_path: "/var/log/janus/janus.log".to_string(),
            sql_logging: false,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct TracingConfig {
    /// Enable distributed tracing
    pub enabled: bool,
    /// Jaeger endpoint
    pub jaeger_endpoint: String,
    /// Sampling rate
    pub sampling_rate: f64,
}

impl Default for TracingConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            jaeger_endpoint: "http://jaeger:14268/api/traces".to_string(),
            sampling_rate: 0.1,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MetricsConfig {
    /// Metrics endpoint path
    pub endpoint: String,
    /// Include detailed histograms
    pub detailed_histograms: bool,
    /// Custom labels
    pub labels: HashMap<String, String>,
}

impl Default for MetricsConfig {
    fn default() -> Self {
        let mut labels = HashMap::new();
        labels.insert("service".to_string(), "janus".to_string());
        labels.insert("environment".to_string(), "development".to_string());
        Self {
            endpoint: "/metrics".to_string(),
            detailed_histograms: true,
            labels,
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct AlertingConfig {
    /// Enable alerting
    pub enabled: bool,
    /// Discord configuration
    pub discord: DiscordConfig,
    /// Slack configuration
    pub slack: SlackConfig,
    /// Email configuration
    pub email: EmailConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DiscordConfig {
    pub webhook_url: String,
    pub enabled: bool,
    pub notify_on_signal: bool,
    pub notify_on_fill: bool,
    pub notify_on_error: bool,
}

impl Default for DiscordConfig {
    fn default() -> Self {
        Self {
            webhook_url: String::new(),
            enabled: false,
            notify_on_signal: true,
            notify_on_fill: true,
            notify_on_error: true,
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct SlackConfig {
    pub webhook_url: String,
    pub enabled: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct EmailConfig {
    pub enabled: bool,
    pub smtp_host: String,
    pub smtp_port: u16,
    pub recipients: Vec<String>,
}

impl Default for EmailConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            smtp_host: "localhost".to_string(),
            smtp_port: 587,
            recipients: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ParamReloadConfig {
    /// Enable parameter hot-reload
    pub enabled: bool,
    /// Instance ID for namespacing
    pub instance_id: String,
    /// Reconnection delay in milliseconds
    pub reconnect_delay_ms: u64,
    /// Maximum reconnection attempts (0 = unlimited)
    pub max_retries: u32,
}

impl Default for ParamReloadConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            instance_id: "default".to_string(),
            reconnect_delay_ms: 5000,
            max_retries: 0,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct FeaturesConfig {
    /// Enable GAF image generation
    pub enable_gaf: bool,
    /// GAF image size
    pub gaf_image_size: u32,
    /// GAF method: summation | difference
    pub gaf_method: String,
    /// Lookback windows
    pub lookback_windows: Vec<u32>,
    /// Enable normalization
    pub normalize: bool,
    /// Normalization method: minmax | zscore | robust
    pub normalization_method: String,
}

impl Default for FeaturesConfig {
    fn default() -> Self {
        Self {
            enable_gaf: false,
            gaf_image_size: 32,
            gaf_method: "summation".to_string(),
            lookback_windows: vec![5, 10, 20, 50, 100],
            normalize: true,
            normalization_method: "zscore".to_string(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SecurityConfig {
    /// CORS allowed origins
    pub cors_origins: String,
    /// Enable rate limiting
    pub enable_rate_limit: bool,
    /// Requests per second per IP
    pub rate_limit_rps: u32,
    /// API key header name
    pub api_key_header: String,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            cors_origins: "*".to_string(),
            enable_rate_limit: true,
            rate_limit_rps: 100,
            api_key_header: "X-API-Key".to_string(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AdvancedConfig {
    /// Tokio worker thread count (0 = auto)
    pub tokio_worker_threads: usize,
    /// HTTP request timeout in seconds
    pub http_timeout_secs: u64,
    /// Database query timeout in seconds
    pub db_query_timeout_secs: u64,
    /// Signal buffer size
    pub signal_buffer_size: usize,
    /// Order buffer size
    pub order_buffer_size: usize,
    /// Enable experimental features
    pub experimental_features: bool,
}

impl Default for AdvancedConfig {
    fn default() -> Self {
        Self {
            tokio_worker_threads: 0,
            http_timeout_secs: 30,
            db_query_timeout_secs: 30,
            signal_buffer_size: 1000,
            order_buffer_size: 500,
            experimental_features: false,
        }
    }
}

// ============================================================================
// Config Implementation
// ============================================================================

impl Config {
    /// Load configuration from TOML file with environment variable overrides
    ///
    /// Priority order (highest to lowest):
    /// 1. Redis overlay at `fks:janus:config` (when `redis` feature enabled and key present)
    /// 2. Environment variables
    /// 3. TOML config file
    /// 4. Default values
    pub fn load() -> anyhow::Result<Self> {
        // Try to load from TOML file
        let mut config = Self::load_from_file()?;

        // Apply environment variable overrides
        config.apply_env_overrides();

        // Apply Redis overlay (JanusAI session-driven config from Ruby).
        // Best-effort: failures are warned and ignored so cold boot still
        // works when Redis is unavailable.
        #[cfg(feature = "redis")]
        config.apply_redis_overlay_blocking();

        Ok(config)
    }

    /// Load configuration from environment variables only
    pub fn from_env() -> anyhow::Result<Self> {
        let mut config = Self::default();
        config.apply_env_overrides();
        Ok(config)
    }

    /// Load configuration from a specific TOML file
    pub fn from_file<P: AsRef<Path>>(path: P) -> anyhow::Result<Self> {
        let contents = std::fs::read_to_string(path.as_ref())?;
        let mut config: Config = toml::from_str(&contents)?;
        config.apply_env_overrides();
        Ok(config)
    }

    /// Load from default config file locations
    fn load_from_file() -> anyhow::Result<Self> {
        // Check JANUS_CONFIG_PATH environment variable first
        if let Ok(config_path) = std::env::var("JANUS_CONFIG_PATH") {
            if Path::new(&config_path).exists() {
                info!(
                    "Loading configuration from JANUS_CONFIG_PATH: {}",
                    config_path
                );
                let contents = std::fs::read_to_string(&config_path)?;
                return Ok(toml::from_str(&contents)?);
            } else {
                warn!("JANUS_CONFIG_PATH set but file not found: {}", config_path);
            }
        }

        // Try default locations
        for path in CONFIG_PATHS {
            if Path::new(path).exists() {
                info!("Loading configuration from: {}", path);
                let contents = std::fs::read_to_string(path)?;
                return Ok(toml::from_str(&contents)?);
            }
        }

        debug!("No config file found, using defaults");
        Ok(Self::default())
    }

    /// Apply environment variable overrides
    fn apply_env_overrides(&mut self) {
        // Service
        if let Ok(v) = std::env::var("JANUS_SERVICE_NAME") {
            self.service.name = v;
        }
        if let Ok(v) = std::env::var("JANUS_ENVIRONMENT") {
            self.service.environment = v;
        }

        // Ports
        if let Ok(v) = std::env::var("JANUS_HTTP_PORT")
            && let Ok(port) = v.parse()
        {
            self.ports.http = port;
        }
        if let Ok(v) = std::env::var("JANUS_GRPC_PORT")
            && let Ok(port) = v.parse()
        {
            self.ports.grpc = port;
        }
        if let Ok(v) = std::env::var("JANUS_WS_PORT")
            && let Ok(port) = v.parse()
        {
            self.ports.websocket = port;
        }
        if let Ok(v) = std::env::var("JANUS_METRICS_PORT")
            && let Ok(port) = v.parse()
        {
            self.ports.metrics = port;
        }

        // Host
        if let Ok(v) = std::env::var("JANUS_HOST") {
            self.host.bind = v;
        }

        // Modules
        if let Ok(v) = std::env::var("JANUS_ENABLE_FORWARD") {
            self.modules.forward = parse_bool(&v);
        }
        if let Ok(v) = std::env::var("JANUS_ENABLE_BACKWARD") {
            self.modules.backward = parse_bool(&v);
        }
        if let Ok(v) = std::env::var("JANUS_ENABLE_CNS") {
            self.modules.cns = parse_bool(&v);
        }
        if let Ok(v) = std::env::var("JANUS_ENABLE_API") {
            self.modules.api = parse_bool(&v);
        }
        if let Ok(v) = std::env::var("JANUS_ENABLE_DATA") {
            self.modules.data = parse_bool(&v);
        }
        if let Ok(v) = std::env::var("JANUS_ENABLE_WEBSOCKET") {
            self.modules.websocket = parse_bool(&v);
        }
        if let Ok(v) = std::env::var("JANUS_ENABLE_GRPC") {
            self.modules.grpc = parse_bool(&v);
        }
        if let Ok(v) = std::env::var("JANUS_ENABLE_METRICS") {
            self.modules.metrics = parse_bool(&v);
        }

        // External services
        if let Ok(v) = std::env::var("REDIS_URL") {
            self.redis.url = v;
        }
        if let Ok(v) = std::env::var("DATABASE_URL") {
            self.database.url = v;
        }
        if let Ok(v) = std::env::var("QUESTDB_HOST") {
            self.questdb.host = v;
        }

        // Forward settings
        if let Ok(v) = std::env::var("JANUS_FORWARD_SIGNAL_INTERVAL")
            && let Ok(interval) = v.parse()
        {
            self.forward.signal_interval_secs = interval;
        }
        if let Ok(v) = std::env::var("JANUS_FORWARD_ML_MODEL_PATH") {
            self.forward.ml_model_path = v;
        }

        // Risk settings
        if let Ok(v) = std::env::var("RISK_ACCOUNT_BALANCE")
            && let Ok(balance) = v.parse()
        {
            self.risk.account_balance = balance;
        }
        if let Ok(v) = std::env::var("RISK_MAX_POSITION_SIZE_PCT")
            && let Ok(pct) = v.parse()
        {
            self.risk.max_position_size_pct = pct;
        }

        // Backward settings
        if let Ok(v) = std::env::var("JANUS_BACKWARD_PERSIST_BATCH_SIZE")
            && let Ok(size) = v.parse()
        {
            self.backward.persistence.batch_size = size;
        }
        if let Ok(v) = std::env::var("JANUS_BACKWARD_ANALYTICS_INTERVAL")
            && let Ok(interval) = v.parse()
        {
            self.backward.analytics.update_interval_secs = interval;
        }

        // CNS settings
        if let Ok(v) = std::env::var("JANUS_CNS_HEALTH_INTERVAL")
            && let Ok(interval) = v.parse()
        {
            self.cns.health_check_interval_secs = interval;
        }
        if let Ok(v) = std::env::var("JANUS_CNS_AUTO_RECOVERY") {
            self.cns.enable_reflexes = parse_bool(&v);
        }

        // Assets settings
        if let Ok(v) = std::env::var("OPTIMIZE_ASSETS") {
            self.assets.optimize_assets = v.split(',').map(|s| s.trim().to_string()).collect();
        }
        if let Ok(v) = std::env::var("ENABLED_ASSETS") {
            self.assets.enabled = v.split(',').map(|s| s.trim().to_string()).collect();
        }
        if let Ok(v) = std::env::var("TRADING_ASSETS") {
            // Alias for ENABLED_ASSETS
            self.assets.enabled = v.split(',').map(|s| s.trim().to_string()).collect();
        }
        if let Ok(v) = std::env::var("PRIORITY_ASSETS") {
            self.assets.priority_assets = v.split(',').map(|s| s.trim().to_string()).collect();
        }
        if let Ok(v) = std::env::var("DEFAULT_QUOTE_CURRENCY") {
            self.assets.default_quote = v;
        }

        // Market/Exchange settings
        if let Ok(v) = std::env::var("PRIMARY_EXCHANGE") {
            self.market.exchange = v;
        }

        // Trading mode
        if let Ok(v) = std::env::var("TRADING_MODE") {
            self.trading.mode = v;
        }
        if let Ok(v) = std::env::var("REAL_ORDERS_ENABLED") {
            self.trading.real_orders_enabled = parse_bool(&v);
        }

        // Security
        if let Ok(v) = std::env::var("JANUS_CORS_ORIGINS") {
            self.security.cors_origins = v;
        }

        // Logging
        if let Ok(v) = std::env::var("RUST_LOG") {
            // Extract log level from RUST_LOG
            if v.contains("debug") {
                self.logging.level = "debug".to_string();
            } else if v.contains("trace") {
                self.logging.level = "trace".to_string();
            } else if v.contains("warn") {
                self.logging.level = "warn".to_string();
            } else if v.contains("error") {
                self.logging.level = "error".to_string();
            }
        }
        if let Ok(v) = std::env::var("LOG_FORMAT") {
            self.logging.format = v;
        }
    }

    /// Apply an overlay sourced from the `fks:janus:config` Redis key.
    ///
    /// The overlay is a JSON object whose keys mirror the sections produced
    /// by `Config::to_toml()`; only fields that are present in the JSON
    /// document are touched (everything else keeps its prior value).
    ///
    /// This is the JFLOW-B handshake — Ruby writes session-specific config
    /// (currently: which assets to trade) into Redis when a JanusAI session
    /// starts; Janus picks it up on the next cold boot.
    ///
    /// Best-effort: connection or parse failures are logged and ignored so
    /// the process can still boot when Redis is unavailable or the key is
    /// malformed.
    #[cfg(feature = "redis")]
    fn apply_redis_overlay_blocking(&mut self) {
        // Skip entirely when explicitly disabled so unit tests can opt out.
        if matches!(
            std::env::var("JANUS_REDIS_OVERLAY").as_deref(),
            Ok("0" | "false" | "off" | "no")
        ) {
            return;
        }

        let url = self.redis.url.clone();
        let key = std::env::var("JANUS_REDIS_CONFIG_KEY")
            .unwrap_or_else(|_| "fks:janus:config".to_string());

        // Run the async Redis fetch on a tiny single-threaded runtime so
        // `Config::load()` stays synchronous (it's called before tokio's
        // main runtime exists).
        let fetched = std::thread::spawn(move || -> Option<String> {
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .ok()?;
            rt.block_on(async move {
                let client = redis::Client::open(url.as_str()).ok()?;
                let mut conn = client.get_multiplexed_async_connection().await.ok()?;
                redis::cmd("GET")
                    .arg(&key)
                    .query_async::<Option<String>>(&mut conn)
                    .await
                    .ok()
                    .flatten()
            })
        })
        .join()
        .ok()
        .flatten();

        let Some(json) = fetched else {
            debug!("Redis config overlay: key not present, using env/file config");
            return;
        };

        let overlay: serde_json::Value = match serde_json::from_str(&json) {
            Ok(v) => v,
            Err(e) => {
                warn!("Redis config overlay: malformed JSON at {key} — {e}", key = "fks:janus:config");
                return;
            }
        };

        // Merge overlay into a JSON view of self, then deserialize back.
        // Using JSON as the intermediate keeps the merge logic ignorant of
        // the (large) Config schema — anything serde can round-trip works.
        let mut base = match serde_json::to_value(&*self) {
            Ok(v) => v,
            Err(e) => {
                warn!("Redis config overlay: failed to serialize current config — {e}");
                return;
            }
        };
        merge_json(&mut base, overlay);

        match serde_json::from_value::<Config>(base) {
            Ok(merged) => {
                info!("Redis config overlay applied from key fks:janus:config");
                *self = merged;
            }
            Err(e) => {
                warn!("Redis config overlay: merged document failed to deserialize — {e}");
            }
        }
    }

    /// Check if running in production
    pub fn is_production(&self) -> bool {
        self.service.environment == "production"
    }

    /// Get CORS origins as a list
    pub fn cors_origins_list(&self) -> Vec<String> {
        self.security
            .cors_origins
            .split(',')
            .map(|s| s.trim().to_string())
            .collect()
    }

    /// Validate configuration
    pub fn validate(&self) -> anyhow::Result<()> {
        // Ensure at least one module is enabled
        if !self.modules.forward
            && !self.modules.backward
            && !self.modules.cns
            && !self.modules.api
            && !self.modules.data
        {
            anyhow::bail!("At least one module must be enabled");
        }

        // Validate ports are unique
        let ports = [
            self.ports.http,
            self.ports.grpc,
            self.ports.websocket,
            self.ports.metrics,
        ];
        let unique: std::collections::HashSet<_> = ports.iter().collect();
        if unique.len() != ports.len() {
            anyhow::bail!("All ports must be unique");
        }

        // Validate trading mode
        let valid_modes = ["simulation", "paper", "live"];
        if !valid_modes.contains(&self.trading.mode.as_str()) {
            anyhow::bail!(
                "Invalid trading mode '{}'. Must be one of: {:?}",
                self.trading.mode,
                valid_modes
            );
        }

        // Warn about dangerous configurations
        if self.trading.mode == "live" && self.trading.real_orders_enabled {
            warn!("⚠️  LIVE TRADING ENABLED - Real orders will be executed!");
        }

        Ok(())
    }

    /// Export configuration to TOML string
    pub fn to_toml(&self) -> anyhow::Result<String> {
        Ok(toml::to_string_pretty(self)?)
    }

    /// Save configuration to file
    pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> anyhow::Result<()> {
        let contents = self.to_toml()?;
        std::fs::write(path, contents)?;
        Ok(())
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

fn parse_bool(s: &str) -> bool {
    matches!(s.to_lowercase().as_str(), "true" | "1" | "yes" | "on")
}

/// Deep-merge `overlay` into `base`. Objects are merged recursively; any
/// other value type in `overlay` (including arrays and null) replaces the
/// corresponding entry in `base`. Used by the Redis config overlay so a
/// partial JSON document like `{"assets": {"enabled": ["BTC"]}}` only
/// touches `assets.enabled`.
#[cfg(feature = "redis")]
fn merge_json(base: &mut serde_json::Value, overlay: serde_json::Value) {
    match (base, overlay) {
        (serde_json::Value::Object(base_map), serde_json::Value::Object(overlay_map)) => {
            for (k, v) in overlay_map {
                merge_json(base_map.entry(k).or_insert(serde_json::Value::Null), v);
            }
        }
        (slot, value) => {
            *slot = value;
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert_eq!(config.ports.http, 8080);
        assert!(config.modules.forward);
    }

    #[test]
    fn test_validate_config() {
        let config = Config::default();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_cors_origins_list() {
        let mut config = Config::default();
        config.security.cors_origins = "http://localhost:3000, http://localhost:8080".to_string();
        let origins = config.cors_origins_list();
        assert_eq!(origins.len(), 2);
    }

    #[test]
    fn test_toml_serialization() {
        let config = Config::default();
        let toml_str = config.to_toml().unwrap();
        assert!(toml_str.contains("[service]"));
        assert!(toml_str.contains("[ports]"));
    }

    #[test]
    fn test_toml_deserialization() {
        let toml_str = r#"
            [service]
            name = "test-janus"
            environment = "testing"

            [ports]
            http = 9000
            grpc = 50052
        "#;

        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.service.name, "test-janus");
        assert_eq!(config.service.environment, "testing");
        assert_eq!(config.ports.http, 9000);
        assert_eq!(config.ports.grpc, 50052);
    }

    #[test]
    fn test_parse_bool() {
        assert!(parse_bool("true"));
        assert!(parse_bool("True"));
        assert!(parse_bool("1"));
        assert!(parse_bool("yes"));
        assert!(parse_bool("on"));
        assert!(!parse_bool("false"));
        assert!(!parse_bool("0"));
        assert!(!parse_bool("no"));
    }

    #[test]
    fn test_validate_unique_ports() {
        let mut config = Config::default();
        config.ports.http = 8080;
        config.ports.grpc = 8080; // Duplicate!
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_validate_trading_mode() {
        let mut config = Config::default();
        config.trading.mode = "invalid".to_string();
        assert!(config.validate().is_err());
    }

    #[cfg(feature = "redis")]
    #[test]
    fn test_merge_json_partial_overlay_only_touches_named_fields() {
        let mut base = serde_json::json!({
            "ports": { "http": 8080, "grpc": 50051 },
            "assets": { "enabled": ["BTC", "ETH"], "default_quote": "USD" }
        });
        let overlay = serde_json::json!({
            "assets": { "enabled": ["SOL"] }
        });
        merge_json(&mut base, overlay);

        // Untouched fields survive.
        assert_eq!(base["ports"]["http"], 8080);
        assert_eq!(base["assets"]["default_quote"], "USD");
        // Overlay field is replaced (array replacement, not concat).
        assert_eq!(base["assets"]["enabled"], serde_json::json!(["SOL"]));
    }

    #[cfg(feature = "redis")]
    #[test]
    fn test_merge_json_replaces_scalars_and_handles_null() {
        let mut base = serde_json::json!({ "service": { "name": "old" } });
        let overlay = serde_json::json!({ "service": { "name": "new", "extra": null } });
        merge_json(&mut base, overlay);
        assert_eq!(base["service"]["name"], "new");
        assert!(base["service"]["extra"].is_null());
    }

    #[test]
    fn test_legacy_top_level_field_rejected() {
        // Old configs sometimes set ports at the top level (e.g. `http_port = 8080`)
        // instead of inside `[ports]`. `deny_unknown_fields` should make this fail
        // loudly rather than silently dropping the value.
        let toml_str = r#"
            http_port = 9000

            [ports]
            http = 8080
        "#;
        let result: Result<Config, _> = toml::from_str(toml_str);
        assert!(result.is_err(), "legacy top-level http_port should be rejected");
    }
}