rustf 1.0.0

A simple MVC web framework inspired by Total.js
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
use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::Path;

/// Environment type for configuration
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum Environment {
    #[default]
    Development,
    Production,
}

/// The one environment variable that selects the environment.
pub const ENVIRONMENT_VARIABLE: &str = "RUSTF_ENV";

impl Environment {
    /// Parse an environment name: `development` / `dev` or `production` /
    /// `prod`, case-insensitive. Anything else is an error — a typo or an
    /// unsupported name (`staging`) must not silently run as development.
    pub fn parse(env: &str) -> Result<Self> {
        Self::parse_named(env).map_err(Error::internal)
    }

    /// `parse` with the reason as plain text, for callers that add context.
    fn parse_named(env: &str) -> std::result::Result<Self, String> {
        match env.trim().to_ascii_lowercase().as_str() {
            "production" | "prod" => Ok(Environment::Production),
            "development" | "dev" => Ok(Environment::Development),
            other => Err(format!(
                "unknown environment '{}': use development (dev) or production (prod)",
                other
            )),
        }
    }

    /// The environment named by `RUSTF_ENV`, if it is set.
    pub fn from_process_env() -> Result<Option<Self>> {
        match env::var(ENVIRONMENT_VARIABLE) {
            Ok(value) => Self::parse_named(&value)
                .map(Some)
                .map_err(|reason| Error::internal(format!("{}: {}", ENVIRONMENT_VARIABLE, reason))),
            Err(env::VarError::NotPresent) => Ok(None),
            Err(env::VarError::NotUnicode(_)) => Err(Error::internal(format!(
                "{}: not valid UTF-8; use development (dev) or production (prod)",
                ENVIRONMENT_VARIABLE
            ))),
        }
    }

    /// The environment for code that runs without a loaded configuration
    /// (`RustF::new()`, a standalone `WorkerManager`): `RUSTF_ENV`, or
    /// development when it is not set. An invalid `RUSTF_ENV` cannot be
    /// returned as an error there, so it is logged and production is used —
    /// secure cookies and no detailed error pages.
    pub fn from_process_env_or_production_on_error() -> Self {
        match Self::from_process_env() {
            Ok(Some(env)) => env,
            Ok(None) => Environment::Development,
            Err(e) => {
                log::error!("{}; running as production", e);
                Environment::Production
            }
        }
    }

    /// Get environment from string. Unknown names become `Development`.
    #[deprecated(note = "use Environment::parse, which rejects unknown names")]
    pub fn from_str(env: &str) -> Self {
        Self::parse(env).unwrap_or(Environment::Development)
    }

    /// Full name: `development` or `production`.
    pub fn name(&self) -> &'static str {
        match self {
            Environment::Development => "development",
            Environment::Production => "production",
        }
    }

    /// Get environment name as string
    pub fn as_str(&self) -> &'static str {
        match self {
            Environment::Development => "dev",
            Environment::Production => "prod",
        }
    }

    /// Check if this is a production environment
    pub fn is_production(&self) -> bool {
        matches!(self, Environment::Production)
    }

    /// Check if this is a development environment
    pub fn is_development(&self) -> bool {
        matches!(self, Environment::Development)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AppConfig {
    #[serde(default)]
    pub environment: Environment,

    #[serde(default)]
    pub server: ServerConfig,

    #[serde(default)]
    pub views: ViewConfig,

    #[serde(default)]
    pub session: SessionConfig,

    #[serde(default)]
    pub static_files: StaticConfig,

    #[serde(default)]
    pub database: DatabaseConfig,

    #[serde(default)]
    pub cors: CorsConfig,

    #[serde(default)]
    pub logging: LoggingConfig,

    #[serde(default)]
    pub uploads: UploadConfig,

    #[serde(default, rename = "private")]
    pub r#private: PrivateConfig,

    #[serde(default)]
    pub websocket: WebSocketSettings,

    // All other sections - user-defined configuration sections
    // These sections are stored as TOML values and can be deserialized on-demand
    #[serde(flatten)]
    pub sections: HashMap<String, toml::Value>,

    /// Values that came from `"(env) ..."` / `"(file) ..."` references, kept
    /// so that `section()` errors raised after loading can mask them.
    ///
    /// Public only so that `AppConfig { server, ..AppConfig::default() }`
    /// keeps compiling outside the crate; its content is not accessible.
    #[doc(hidden)]
    #[serde(skip)]
    pub resolved_values: ResolvedValues,
}

/// Resolved reference values, opaque outside the crate. `Debug` shows only
/// how many there are.
#[doc(hidden)]
#[derive(Clone, Default)]
pub struct ResolvedValues(Vec<String>);

impl std::fmt::Debug for ResolvedValues {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ResolvedValues({} masked)", self.0.len())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
    #[serde(default = "default_host")]
    pub host: String,

    #[serde(default = "default_port")]
    pub port: u16,

    #[serde(default = "default_timeout")]
    pub timeout: u64,

    #[serde(default)]
    pub ssl_enabled: bool,

    #[serde(default)]
    pub ssl_cert: Option<String>,

    #[serde(default)]
    pub ssl_key: Option<String>,

    #[serde(default)]
    pub public_url: Option<String>,

    #[serde(default = "default_max_connections")]
    pub max_connections: usize,

    #[serde(default = "default_shutdown_timeout")]
    pub shutdown_timeout: u64,

    #[serde(default)]
    pub trusted_proxies: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ViewConfig {
    #[serde(default = "default_views_dir")]
    pub directory: String,

    #[serde(default = "default_layout")]
    pub default_layout: String,

    #[serde(default)]
    pub cache_enabled: bool,

    #[serde(default = "default_extension")]
    pub extension: String,

    #[serde(default)]
    pub engine: TemplateEngine,

    #[serde(default)]
    pub storage: TemplateStorage,

    #[serde(default = "default_root")]
    pub default_root: String,

    #[serde(default)]
    pub minify: bool,
}

/// Template engine - Total.js is the only supported engine
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum TemplateEngine {
    /// Total.js template engine (the only supported engine)
    #[default]
    TotalJs,
}

/// Template storage method - runtime configurable
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum TemplateStorage {
    /// Load templates from filesystem at runtime (supports --views CLI flag)
    Filesystem,
    /// Templates embedded at compile time (ignores --views CLI flag)
    #[default]
    Embedded,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionConfig {
    #[serde(default = "default_session_enabled")]
    pub enabled: bool,

    #[serde(default = "default_cookie_name")]
    pub cookie_name: String,

    #[serde(default = "default_idle_timeout")]
    pub idle_timeout: u64,

    #[serde(default = "default_absolute_timeout")]
    pub absolute_timeout: u64,

    #[serde(default = "default_same_site")]
    pub same_site: String,

    #[serde(default = "default_fingerprint_mode")]
    pub fingerprint_mode: String,

    #[serde(default)]
    pub storage: SessionStorageConfig,

    #[serde(default)]
    pub exempt_routes: Vec<String>,
}

/// Session storage backend configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum SessionStorageConfig {
    /// In-memory session storage (default)
    Memory {
        #[serde(default = "default_cleanup_interval")]
        cleanup_interval: u64,
    },
    /// Redis-based session storage
    Redis {
        url: String,
        #[serde(default = "default_redis_prefix")]
        prefix: String,
        #[serde(default = "default_redis_pool_size")]
        pool_size: usize,
        #[serde(default = "default_redis_connection_timeout")]
        connection_timeout: u64,
        #[serde(default = "default_redis_command_timeout")]
        command_timeout: u64,
    },
    /// Database-based session storage
    Database {
        #[serde(default = "default_sessions_table")]
        table: String,
        connection_url: Option<String>,
        #[serde(default = "default_cleanup_interval")]
        cleanup_interval: u64,
    },
}

impl Default for SessionStorageConfig {
    fn default() -> Self {
        Self::Memory {
            cleanup_interval: default_cleanup_interval(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StaticConfig {
    #[serde(default = "default_static_dir")]
    pub directory: String,

    #[serde(default = "default_static_prefix")]
    pub url_prefix: String,

    #[serde(default)]
    pub cache_enabled: bool,

    #[serde(default = "default_cache_max_age")]
    pub cache_max_age: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DatabaseConfig {
    #[serde(default)]
    pub url: Option<String>,

    #[serde(default)]
    pub max_connections: Option<u32>,

    #[serde(default)]
    pub timeout: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CorsConfig {
    #[serde(default)]
    pub enabled: bool,

    #[serde(default)]
    pub allowed_origins: Vec<String>,

    #[serde(default)]
    pub allowed_methods: Vec<String>,

    #[serde(default)]
    pub allowed_headers: Vec<String>,
}

/// `[websocket]` — limits and policy for WebSocket connections.
///
/// ```toml
/// [websocket]
/// max_message_size = 1048576
/// max_frame_size   = 262144
/// ping_interval    = 30
/// allowed_origins  = []
/// accept_subprotocols = []
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebSocketSettings {
    /// Largest message accepted, in bytes. Oversize closes with `1009`.
    ///
    /// Defaults to 1 MiB. tungstenite's own default is 64 MiB, which is a
    /// memory-exhaustion vector on a public endpoint.
    #[serde(default = "default_ws_max_message_size")]
    pub max_message_size: usize,

    /// Largest single frame accepted, in bytes. Defaults to 256 KiB.
    #[serde(default = "default_ws_max_frame_size")]
    pub max_frame_size: usize,

    /// Seconds between server-sent pings. `0` disables the keepalive.
    ///
    /// Pings detect peers that vanished without a close frame — the half-open
    /// connections that otherwise accumulate behind NATs and load balancers.
    #[serde(default = "default_ws_ping_interval")]
    pub ping_interval: u64,

    /// Origins allowed *in addition to* the request's own origin.
    ///
    /// Empty (the default) means same-origin only. A single `"*"` disables
    /// the check, which re-opens Cross-Site WebSocket Hijacking: a page on any
    /// site could then open an authenticated socket with the visitor's
    /// cookies. Only appropriate for endpoints that carry no ambient
    /// authority.
    #[serde(default)]
    pub allowed_origins: Vec<String>,

    /// Subprotocols the server understands, most preferred first.
    ///
    /// The first entry the client also offered is echoed back in
    /// `Sec-WebSocket-Protocol`. Matching is case-sensitive, as RFC 7230
    /// tokens require. Empty means none is negotiated.
    #[serde(default)]
    pub accept_subprotocols: Vec<String>,

    /// Refuse a handshake that carries no `Origin` header at all.
    ///
    /// Off by default: an absent `Origin` normally means a non-browser client,
    /// which attaches no cookies of its own, and refusing those would break
    /// every service-to-service socket. Turn it on for an endpoint only ever
    /// opened by a browser, where a missing `Origin` more likely means a proxy
    /// stripped it while still forwarding `Cookie`.
    #[serde(default)]
    pub require_origin: bool,

    /// Largest number of WebSocket connections served at once. `0` is no limit.
    ///
    /// The handshake is cheap and a connection is long-lived, so without a cap
    /// an unauthenticated client can hold open as many tasks and outbound
    /// queues as it likes. Over the limit, the handshake gets
    /// `503 Service Unavailable`.
    #[serde(default)]
    pub max_connections: usize,
}

impl Default for WebSocketSettings {
    fn default() -> Self {
        Self {
            max_message_size: default_ws_max_message_size(),
            max_frame_size: default_ws_max_frame_size(),
            ping_interval: default_ws_ping_interval(),
            allowed_origins: Vec::new(),
            accept_subprotocols: Vec::new(),
            require_origin: false,
            max_connections: 0,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    #[serde(default = "default_log_level")]
    pub level: String,

    #[serde(default)]
    pub file: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UploadConfig {
    #[serde(default = "default_upload_dir")]
    pub directory: String,

    #[serde(default = "default_max_file_size")]
    pub max_file_size: u64,

    #[serde(default = "default_max_files")]
    pub max_files: usize,

    #[serde(default)]
    pub allowed_extensions: Vec<String>,

    #[serde(default)]
    pub blocked_extensions: Vec<String>,

    #[serde(default)]
    pub create_directories: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrivateConfig {
    #[serde(default = "default_private_dir")]
    pub directory: String,
}

// Default value functions
fn default_host() -> String {
    "127.0.0.1".to_string()
}
fn default_port() -> u16 {
    8000
}
fn default_timeout() -> u64 {
    30
}
fn default_shutdown_timeout() -> u64 {
    30
}
fn default_ws_max_message_size() -> usize {
    1024 * 1024
}
fn default_ws_max_frame_size() -> usize {
    256 * 1024
}
fn default_ws_ping_interval() -> u64 {
    30
}
fn default_max_connections() -> usize {
    1000
}
fn default_views_dir() -> String {
    "views".to_string()
}
fn default_layout() -> String {
    "layouts/default".to_string()
}
fn default_extension() -> String {
    "html".to_string()
}
fn default_root() -> String {
    "".to_string()
}
fn default_session_enabled() -> bool {
    true
}
fn default_idle_timeout() -> u64 {
    900
} // 15 minutes
fn default_absolute_timeout() -> u64 {
    28800
} // 8 hours
fn default_same_site() -> String {
    "Lax".to_string()
}
fn default_fingerprint_mode() -> String {
    "soft".to_string()
}
fn default_cookie_name() -> String {
    "rustf_session".to_string()
}
fn default_static_dir() -> String {
    "public".to_string()
}
fn default_static_prefix() -> String {
    "/static".to_string()
}
fn default_cache_max_age() -> u64 {
    86400
}
fn default_log_level() -> String {
    "info".to_string()
}
fn default_upload_dir() -> String {
    "uploads".to_string()
}
fn default_private_dir() -> String {
    "private".to_string()
}
fn default_max_file_size() -> u64 {
    10 * 1024 * 1024
} // 10MB
fn default_max_files() -> usize {
    5
}

// Session storage defaults
fn default_cleanup_interval() -> u64 {
    300
} // 5 minutes
fn default_redis_prefix() -> String {
    "rustf:session:".to_string()
}
fn default_redis_pool_size() -> usize {
    10
}
fn default_redis_connection_timeout() -> u64 {
    5000
} // 5 seconds
fn default_redis_command_timeout() -> u64 {
    3000
} // 3 seconds
fn default_sessions_table() -> String {
    "sessions".to_string()
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            host: default_host(),
            port: default_port(),
            timeout: default_timeout(),
            ssl_enabled: false,
            ssl_cert: None,
            ssl_key: None,
            public_url: None,
            max_connections: default_max_connections(),
            shutdown_timeout: default_shutdown_timeout(),
            trusted_proxies: Vec::new(),
        }
    }
}

impl Default for ViewConfig {
    fn default() -> Self {
        Self {
            directory: default_views_dir(),
            default_layout: default_layout(),
            cache_enabled: false,
            extension: default_extension(),
            engine: TemplateEngine::default(),
            storage: TemplateStorage::default(),
            default_root: default_root(),
            minify: false,
        }
    }
}

impl Default for SessionConfig {
    fn default() -> Self {
        Self {
            enabled: default_session_enabled(),
            cookie_name: default_cookie_name(),
            idle_timeout: default_idle_timeout(),
            absolute_timeout: default_absolute_timeout(),
            same_site: default_same_site(),
            fingerprint_mode: default_fingerprint_mode(),
            storage: SessionStorageConfig::default(),
            exempt_routes: Vec::new(),
        }
    }
}

impl Default for StaticConfig {
    fn default() -> Self {
        Self {
            directory: default_static_dir(),
            url_prefix: default_static_prefix(),
            cache_enabled: true,
            cache_max_age: default_cache_max_age(),
        }
    }
}

impl Default for CorsConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            allowed_origins: vec!["*".to_string()],
            allowed_methods: vec!["GET".to_string(), "POST".to_string()],
            allowed_headers: vec!["Content-Type".to_string()],
        }
    }
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: default_log_level(),
            file: None,
        }
    }
}

impl Default for UploadConfig {
    fn default() -> Self {
        Self {
            directory: default_upload_dir(),
            max_file_size: default_max_file_size(),
            max_files: default_max_files(),
            allowed_extensions: vec![],
            blocked_extensions: vec![
                "exe".to_string(),
                "bat".to_string(),
                "sh".to_string(),
                "cmd".to_string(),
            ],
            create_directories: true,
        }
    }
}

impl Default for PrivateConfig {
    fn default() -> Self {
        Self {
            directory: default_private_dir(),
        }
    }
}

impl AppConfig {
    /// Load configuration with environment-specific overrides
    pub fn load() -> Result<Self> {
        Self::load_with_base_dir(".")
    }

    /// Load configuration with development-time auto-detection
    pub fn load_with_dev_detection() -> Result<Self> {
        let base_dir: std::path::PathBuf = if cfg!(debug_assertions) {
            // Debug builds: look relative to CWD (project root when using cargo run)
            if Path::new("target/debug").exists() && Path::new("../../config.toml").exists() {
                std::path::PathBuf::from("../..")
            } else {
                std::path::PathBuf::from(".")
            }
        } else {
            // Release builds: look next to the binary, not the CWD.
            // Resolves symlinks so /usr/local/bin/myapp -> /opt/myapp/myapp
            // correctly uses /opt/myapp/ as the config directory.
            std::env::current_exe()
                .ok()
                .and_then(|p| p.canonicalize().ok())
                .and_then(|p| p.parent().map(|p| p.to_path_buf()))
                .unwrap_or_else(|| std::path::PathBuf::from("."))
        };

        Self::load_with_base_dir(base_dir)
    }

    /// Load configuration from a specific base directory
    pub fn load_with_base_dir<P: AsRef<Path>>(base_dir: P) -> Result<Self> {
        let base_dir = base_dir.as_ref();

        // Load base configuration as TOML Value first
        let base_config_path = base_dir.join("config.toml");
        let mut secrets = Vec::new();
        let mut merged_value = if base_config_path.exists() {
            Self::load_resolved_toml_value(&base_config_path, base_dir, None, &mut secrets)?
        } else if !cfg!(debug_assertions) {
            // In release builds, a missing config.toml is a hard error.
            // The binary must be launched from the directory containing config.toml,
            // or --config <path> must be used to specify its location.
            return Err(Error::internal(format!(
                "Configuration file not found: '{}'. \
                 Launch the binary from the directory containing config.toml, \
                 or use --config <path> to specify its location.",
                base_config_path.display()
            )));
        } else {
            // In debug builds, fall back to defaults for dev convenience
            let default_config = AppConfig::default();
            toml::to_string(&default_config)
                .ok()
                .and_then(|s| toml::from_str(&s).ok())
                .unwrap_or(toml::Value::Table(toml::map::Map::new()))
        };

        // Resolve environment AFTER reading config.toml so we can honour the
        // `environment` field declared there. Env vars still override if set.
        let env = Self::resolve_environment(&merged_value)?;

        // Load and merge environment-specific configuration if it exists
        let env_config_path = base_dir.join(format!("config.{}.toml", env.as_str()));
        if env_config_path.exists() {
            let env_value = Self::load_resolved_toml_value(
                &env_config_path,
                base_dir,
                Some(&merged_value),
                &mut secrets,
            )?;
            merged_value = Self::merge_overlay(merged_value, env_value, &secrets)?;
        }

        let config = Self::finish_loading(merged_value, env, base_dir, &secrets)?;

        log::info!(
            "Configuration loaded and merged successfully (environment: {})",
            config.environment.as_str()
        );

        Ok(config)
    }

    /// Load configuration from TOML file
    ///
    /// Mirrors `load_with_base_dir()`: resolves the environment, merges the
    /// environment overlay (`config.prod.toml` / `config.dev.toml`) from the
    /// same directory as the specified file, applies env-var overrides, and
    /// runs production security/performance defaults.
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path_ref = path.as_ref();

        // Base directory for overlay lookup = directory containing the config file
        let base_dir = path_ref
            .parent()
            .map(|p| p.to_path_buf())
            .unwrap_or_else(|| std::path::PathBuf::from("."));

        // Load specified file as raw TOML value
        let mut secrets = Vec::new();
        let mut merged_value =
            Self::load_resolved_toml_value(path_ref, &base_dir, None, &mut secrets)?;

        // Resolve environment (env vars > [app].environment in file > Development)
        let env = Self::resolve_environment(&merged_value)?;

        // Merge environment overlay if present (config.prod.toml / config.dev.toml)
        let env_config_path = base_dir.join(format!("config.{}.toml", env.as_str()));
        if env_config_path.exists() {
            let env_value = Self::load_resolved_toml_value(
                &env_config_path,
                &base_dir,
                Some(&merged_value),
                &mut secrets,
            )?;
            merged_value = Self::merge_overlay(merged_value, env_value, &secrets)?;
        }

        let config = Self::finish_loading(merged_value, env, &base_dir, &secrets)?;

        log::info!(
            "Configuration loaded from '{}' (environment: {})",
            path_ref.display(),
            config.environment.as_str()
        );

        Ok(config)
    }

    /// Read one configuration file and resolve its `"(env) NAME"` /
    /// `"(file) PATH"` values (see `config_refs`), adding the resolved values
    /// to `secrets` so that later errors can mask them.
    ///
    /// Each file is resolved before the files are merged: the merge refuses
    /// to put a string (`"(env) PORT"`) over an integer (`port = 8000`). For
    /// the same reason an overlay's references also take the type of the value
    /// the base file already holds (`retries = 3` in `config.toml`,
    /// `retries = "(env) RETRIES"` in `config.prod.toml`): pass the resolved
    /// base as `base`.
    fn load_resolved_toml_value(
        path: &Path,
        base_dir: &Path,
        base: Option<&toml::Value>,
        secrets: &mut Vec<String>,
    ) -> Result<toml::Value> {
        let mut value = Self::load_toml_value(path)?;
        let framework = Self::reference_template()?;
        let template = match base {
            // A base value whose type conflicts with the framework's would
            // fail deserialization anyway; type by the framework then.
            Some(base) => {
                serde_toml_merge::merge(framework.clone(), base.clone()).unwrap_or(framework)
            }
            None => framework,
        };
        let resolved = crate::config_refs::resolve(&mut value, &template, base_dir)
            .map_err(|reason| Error::internal(format!("{}: {}", path.display(), reason)))?;
        secrets.extend(resolved);
        Ok(value)
    }

    /// The types a resolved reference takes: the framework defaults as TOML,
    /// plus the framework keys that have no default value to read a type from
    /// (`Option` numbers, and the fields of the non-default session storage
    /// variants). Any key not found here stays a string.
    fn reference_template() -> Result<toml::Value> {
        let mut template = toml::Value::try_from(AppConfig::default()).map_err(|e| {
            Error::internal(format!("Failed to build the configuration template: {}", e))
        })?;
        let hints: toml::Value = toml::from_str(
            r#"
            [database]
            max_connections = 0
            timeout = 0

            [session.storage]
            pool_size = 0
            connection_timeout = 0
            command_timeout = 0
            cleanup_interval = 0
            "#,
        )
        .map_err(|e| Error::internal(format!("Invalid configuration type hints: {}", e)))?;
        template = serde_toml_merge::merge(template, hints)
            .map_err(|e| Error::internal(format!("Invalid configuration type hints: {}", e)))?;
        Ok(template)
    }

    /// Merge an environment overlay into the base configuration.
    fn merge_overlay(
        base: toml::Value,
        overlay: toml::Value,
        secrets: &[String],
    ) -> Result<toml::Value> {
        serde_toml_merge::merge(base, overlay).map_err(|e| {
            Error::internal(crate::config_refs::mask(
                &format!("Failed to merge configuration files: {}", e),
                secrets,
            ))
        })
    }

    /// Everything after the merge: deserialize, apply the environment, the
    /// `RUSTF_*` overrides, relative paths, production defaults, and validate.
    ///
    /// Errors here can quote values (serde's `invalid type: integer 123456`),
    /// so every resolved reference is masked out of them.
    fn finish_loading(
        merged_value: toml::Value,
        env: Environment,
        base_dir: &Path,
        secrets: &[String],
    ) -> Result<Self> {
        let load = || -> Result<Self> {
            let json_value = serde_json::to_value(&merged_value).map_err(|e| {
                Error::internal(format!("Failed to convert merged configuration: {}", e))
            })?;
            let mut config: AppConfig = serde_json::from_value(json_value).map_err(|e| {
                Error::internal(format!("Failed to deserialize merged configuration: {}", e))
            })?;

            config.environment = env;
            config.apply_env_overrides()?;
            config.resolve_relative_paths(base_dir)?;
            if config.environment.is_production() {
                config.apply_security_defaults();
                config.apply_performance_defaults();
            }
            config.validate()?;
            config.resolved_values = ResolvedValues(secrets.to_vec());
            Ok(config)
        };

        load().map_err(|e| {
            if secrets.is_empty() {
                e
            } else {
                // Mask the inner message, so the result is not prefixed twice.
                let message = match &e {
                    Error::Internal(message) => message.clone(),
                    other => other.to_string(),
                };
                Error::internal(crate::config_refs::mask(&message, secrets))
            }
        })
    }

    /// Check the `"(tag) ..."` references of a configuration file without
    /// resolving them: every tag must be known and have an argument. For
    /// validating a production configuration on a machine that does not have
    /// its variables or secret files (`rustf-cli validate`).
    pub fn check_references<P: AsRef<Path>>(path: P) -> Result<()> {
        let path = path.as_ref();
        let value = Self::load_toml_value(path)?;
        crate::config_refs::check(&value)
            .map_err(|reason| Error::internal(format!("{}: {}", path.display(), reason)))
    }

    /// Load TOML file as a Value (for merging before deserialization)
    ///
    /// This is used when merging multiple config files at the TOML level
    /// rather than at the AppConfig struct level.
    fn load_toml_value<P: AsRef<Path>>(path: P) -> Result<toml::Value> {
        let path_ref = path.as_ref();

        let content = fs::read_to_string(path_ref).map_err(|e| {
            Error::internal(format!(
                "Failed to read config file '{}': {}. Make sure the file exists and is readable.",
                path_ref.display(),
                e
            ))
        })?;

        let value: toml::Value = toml::from_str(&content).map_err(|e| {
            Error::internal(format!(
                "Failed to parse config file '{}': {}. Check TOML syntax.",
                path_ref.display(),
                e
            ))
        })?;

        log::debug!(
            "Successfully loaded TOML value from: {}",
            path_ref.display()
        );
        Ok(value)
    }

    /// Create configuration with environment variable overrides
    pub fn from_env() -> Result<Self> {
        let mut config = AppConfig::default();
        config.apply_env_overrides()?;
        Ok(config)
    }

    /// Detect the current environment from `RUSTF_ENV` (development when it
    /// is not set). An unknown value is an error.
    pub fn detect_environment() -> Result<Environment> {
        Ok(Environment::from_process_env()?.unwrap_or_default())
    }

    /// Resolve the active environment from the loaded base config TOML and env vars.
    ///
    /// Priority order:
    /// 1. `RUSTF_ENV` (deployment override)
    /// 2. `[app] environment` in `config.toml` (per-app declaration)
    /// 3. `Development` (fallback)
    ///
    /// An unknown name in either place is an error.
    fn resolve_environment(base_toml: &toml::Value) -> Result<Environment> {
        if let Some(env) = Environment::from_process_env()? {
            return Ok(env);
        }

        if let Some(declared) = base_toml.get("app").and_then(|app| app.get("environment")) {
            return match declared {
                toml::Value::String(name) => Environment::parse_named(name)
                    .map_err(|reason| Error::internal(format!("[app] environment: {}", reason))),
                _ => Err(Error::internal(
                    "[app] environment must be a string: \"development\" or \"production\"",
                )),
            };
        }

        Ok(Environment::Development)
    }

    /// Apply security defaults for production environments
    pub fn apply_security_defaults(&mut self) {
        // Sessions are configured via new secure middleware
        // No longer need to override session settings here

        // Disable CORS by default in production (must be explicitly enabled)
        if !self.cors.enabled {
            self.cors.allowed_origins = vec![];
        }

        // Force SSL in production if not explicitly disabled
        if self.environment.is_production() && !self.server.ssl_enabled {
            eprintln!("WARNING: SSL is not enabled in production environment");
        }
    }

    /// Apply performance defaults for production environments
    pub fn apply_performance_defaults(&mut self) {
        // Enable view caching in production
        self.views.cache_enabled = true;

        // Enable HTML minification in production
        self.views.minify = true;

        // Enable static file caching
        self.static_files.cache_enabled = true;

        // Increase connection limits for production
        if self.server.max_connections == default_max_connections() {
            self.server.max_connections = 2000; // Higher default for production
        }

        // Set reasonable timeout for production
        if self.server.timeout == default_timeout() {
            self.server.timeout = 60; // 60 seconds for production
        }
    }

    /// Validate configuration for the current environment
    pub fn validate(&self) -> Result<()> {
        // Validate template engine configuration against enabled features
        self.validate_template_engine()?;

        // Validate server configuration
        if self.server.port == 0 {
            return Err(Error::internal("Server port cannot be 0"));
        }

        if self.server.ssl_enabled {
            if self.server.ssl_cert.is_none() {
                return Err(Error::internal(
                    "SSL certificate path required when SSL is enabled",
                ));
            }
            if self.server.ssl_key.is_none() {
                return Err(Error::internal(
                    "SSL private key path required when SSL is enabled",
                ));
            }
        }

        // Validate production-specific requirements
        if self.environment.is_production() && self.database.url.is_none() {
            eprintln!("WARNING: No database configured in production environment");
        }

        // Validate paths exist
        // Note: For views directory, we only validate for filesystem storage
        // and only warn if it doesn't exist (might be overridden by CLI)
        if matches!(self.views.storage, TemplateStorage::Filesystem)
            && !Path::new(&self.views.directory).exists()
        {
            // Only warn, don't error - might be overridden by CLI --views flag
            log::warn!(
                "Views directory does not exist: {} (can be overridden with --views flag)",
                self.views.directory
            );
        }

        if !Path::new(&self.static_files.directory).exists() {
            // Static files directory is more critical, so we still error
            return Err(Error::internal(format!(
                "Static files directory does not exist: {}",
                self.static_files.directory
            )));
        }

        Ok(())
    }

    /// Apply environment variable overrides
    fn apply_env_overrides(&mut self) -> Result<()> {
        // Environment override (highest priority)
        if let Some(env) = Environment::from_process_env()? {
            self.environment = env;
        }

        // Server overrides
        if let Ok(host) = env::var("RUSTF_HOST") {
            self.server.host = host;
        }
        if let Ok(port) = env::var("RUSTF_PORT") {
            self.server.port = port
                .parse()
                .map_err(|_| Error::internal("Invalid RUSTF_PORT value"))?;
        }
        if let Ok(timeout) = env::var("RUSTF_TIMEOUT") {
            self.server.timeout = timeout
                .parse()
                .map_err(|_| Error::internal("Invalid RUSTF_TIMEOUT value"))?;
        }
        if let Ok(ssl) = env::var("RUSTF_SSL_ENABLED") {
            self.server.ssl_enabled = ssl
                .parse()
                .map_err(|_| Error::internal("Invalid RUSTF_SSL_ENABLED value"))?;
        }
        if let Ok(ssl_cert) = env::var("RUSTF_SSL_CERT") {
            self.server.ssl_cert = Some(ssl_cert);
        }
        if let Ok(ssl_key) = env::var("RUSTF_SSL_KEY") {
            self.server.ssl_key = Some(ssl_key);
        }
        if let Ok(max_conn) = env::var("RUSTF_MAX_CONNECTIONS") {
            self.server.max_connections = max_conn
                .parse()
                .map_err(|_| Error::internal("Invalid RUSTF_MAX_CONNECTIONS value"))?;
        }

        // View overrides
        if let Ok(views_dir) = env::var("RUSTF_VIEWS_DIR") {
            self.views.directory = views_dir;
        }
        if let Ok(layout) = env::var("RUSTF_DEFAULT_LAYOUT") {
            self.views.default_layout = layout;
        }
        if let Ok(cache) = env::var("RUSTF_VIEW_CACHE") {
            self.views.cache_enabled = cache
                .parse()
                .map_err(|_| Error::internal("Invalid RUSTF_VIEW_CACHE value"))?;
        }
        if let Ok(minify) = env::var("RUSTF_VIEW_MINIFY") {
            self.views.minify = minify
                .parse()
                .map_err(|_| Error::internal("Invalid RUSTF_VIEW_MINIFY value"))?;
        }

        // New storage configuration
        if let Ok(storage) = env::var("RUSTF_TEMPLATE_STORAGE") {
            self.views.storage = match storage.to_lowercase().as_str() {
                "filesystem" => TemplateStorage::Filesystem,
                "embedded" => TemplateStorage::Embedded,
                _ => {
                    return Err(Error::internal(
                        "Invalid RUSTF_TEMPLATE_STORAGE value. Use 'filesystem' or 'embedded'.",
                    ))
                }
            };
        }

        // Legacy engine override for backward compatibility - DEPRECATED
        if let Ok(engine) = env::var("RUSTF_VIEW_ENGINE") {
            // Map legacy engine values to storage method
            self.views.storage =
                match engine.to_lowercase().as_str() {
                    "filesystem" | "totaljs" | "tera" | "auto" => TemplateStorage::Filesystem,
                    "embedded" => TemplateStorage::Embedded,
                    _ => return Err(Error::internal(
                        "Invalid RUSTF_VIEW_ENGINE value (DEPRECATED - use RUSTF_TEMPLATE_STORAGE)",
                    )),
                };

            log::warn!("RUSTF_VIEW_ENGINE is deprecated. Use RUSTF_TEMPLATE_STORAGE instead.");
        }

        // Session configuration is now handled via config file only
        // No environment variable overrides for sessions

        // Database overrides
        if let Ok(db_url) = env::var("DATABASE_URL") {
            self.database.url = Some(db_url);
        }
        if let Ok(db_url) = env::var("RUSTF_DATABASE_URL") {
            self.database.url = Some(db_url);
        }
        if let Ok(max_conn) = env::var("RUSTF_DB_MAX_CONNECTIONS") {
            self.database.max_connections = Some(
                max_conn
                    .parse()
                    .map_err(|_| Error::internal("Invalid RUSTF_DB_MAX_CONNECTIONS value"))?,
            );
        }
        if let Ok(timeout) = env::var("RUSTF_DB_TIMEOUT") {
            self.database.timeout = Some(
                timeout
                    .parse()
                    .map_err(|_| Error::internal("Invalid RUSTF_DB_TIMEOUT value"))?,
            );
        }

        // Static files overrides
        if let Ok(static_dir) = env::var("RUSTF_STATIC_DIR") {
            self.static_files.directory = static_dir;
        }
        if let Ok(url_prefix) = env::var("RUSTF_STATIC_PREFIX") {
            self.static_files.url_prefix = url_prefix;
        }
        if let Ok(cache) = env::var("RUSTF_STATIC_CACHE") {
            self.static_files.cache_enabled = cache
                .parse()
                .map_err(|_| Error::internal("Invalid RUSTF_STATIC_CACHE value"))?;
        }
        if let Ok(max_age) = env::var("RUSTF_STATIC_MAX_AGE") {
            self.static_files.cache_max_age = max_age
                .parse()
                .map_err(|_| Error::internal("Invalid RUSTF_STATIC_MAX_AGE value"))?;
        }

        // CORS overrides
        if let Ok(cors) = env::var("RUSTF_CORS_ENABLED") {
            self.cors.enabled = cors
                .parse()
                .map_err(|_| Error::internal("Invalid RUSTF_CORS_ENABLED value"))?;
        }
        if let Ok(origins) = env::var("RUSTF_CORS_ORIGINS") {
            self.cors.allowed_origins = origins.split(',').map(|s| s.trim().to_string()).collect();
        }
        if let Ok(methods) = env::var("RUSTF_CORS_METHODS") {
            self.cors.allowed_methods = methods
                .split(',')
                .map(|s| s.trim().to_uppercase())
                .collect();
        }
        if let Ok(headers) = env::var("RUSTF_CORS_HEADERS") {
            self.cors.allowed_headers = headers.split(',').map(|s| s.trim().to_string()).collect();
        }

        // Logging overrides
        if let Ok(level) = env::var("RUSTF_LOG_LEVEL") {
            self.logging.level = level;
        }
        if let Ok(log_file) = env::var("RUSTF_LOG_FILE") {
            self.logging.file = Some(log_file);
        }
        if let Ok(trusted_proxies) = env::var("RUSTF_TRUSTED_PROXIES") {
            self.server.trusted_proxies = trusted_proxies
                .split(',')
                .map(|s| s.trim())
                .filter(|s| !s.is_empty())
                .map(|s| s.to_string())
                .collect();
        }
        if let Ok(public_url) = env::var("RUSTF_PUBLIC_URL") {
            self.server.public_url = Some(public_url);
        }

        // Upload overrides
        if let Ok(upload_dir) = env::var("RUSTF_UPLOAD_DIR") {
            self.uploads.directory = upload_dir;
        }
        if let Ok(private_dir) = env::var("RUSTF_PRIVATE_DIR") {
            self.r#private.directory = private_dir;
        }
        if let Ok(max_size) = env::var("RUSTF_MAX_FILE_SIZE") {
            self.uploads.max_file_size = max_size
                .parse()
                .map_err(|_| Error::internal("Invalid RUSTF_MAX_FILE_SIZE value"))?;
        }
        if let Ok(max_files) = env::var("RUSTF_MAX_FILES") {
            self.uploads.max_files = max_files
                .parse()
                .map_err(|_| Error::internal("Invalid RUSTF_MAX_FILES value"))?;
        }

        Ok(())
    }

    /// Validate template configuration matches enabled features
    fn validate_template_engine(&self) -> Result<()> {
        // Total.js is always available, no validation needed for it

        // Validate embedded storage requires embedded-views feature when used
        match self.views.storage {
            TemplateStorage::Embedded => {
                #[cfg(not(feature = "embedded-views"))]
                {
                    return Err(Error::internal(
                        "Embedded template storage selected but 'embedded-views' feature not enabled. Enable the feature or change storage to 'filesystem'."
                    ));
                }
            }
            TemplateStorage::Filesystem => {
                // Filesystem storage works with any engine feature
            }
        }

        Ok(())
    }

    /// Resolve all directory paths (views, static, private, uploads) relative to the config base dir.
    ///
    /// Relative paths like `"public"` or `"views"` are joined to `base_dir` so they
    /// resolve correctly regardless of the process CWD. Absolute paths are kept as-is.
    fn resolve_relative_paths<P: AsRef<Path>>(&mut self, base_dir: P) -> Result<()> {
        let base = base_dir.as_ref();

        // Views directory — only meaningful for filesystem storage
        if matches!(self.views.storage, TemplateStorage::Filesystem) {
            self.views.directory = Self::resolve_dir(&self.views.directory, base);
        }

        // Static files and the private root are always path-sensitive
        self.static_files.directory = Self::resolve_dir(&self.static_files.directory, base);
        self.r#private.directory = Self::resolve_dir(&self.r#private.directory, base);

        // Uploads live under the private root unless configured as an absolute path.
        let private_root = Path::new(&self.r#private.directory);
        self.uploads.directory = Self::resolve_dir(&self.uploads.directory, private_root);

        Ok(())
    }

    /// Join a relative path to `base`, canonicalizing if it already exists.
    /// Absolute paths are returned unchanged.
    fn resolve_dir(dir: &str, base: &Path) -> String {
        let p = Path::new(dir);
        if p.is_absolute() {
            return dir.to_string();
        }
        let joined = base.join(p);
        if joined.exists() {
            joined
                .canonicalize()
                .unwrap_or(joined)
                .to_string_lossy()
                .into_owned()
        } else {
            joined.to_string_lossy().into_owned()
        }
    }

    /// Get server address string
    pub fn server_address(&self) -> String {
        format!("{}:{}", self.server.host, self.server.port)
    }

    /// Check if running in debug mode
    pub fn is_debug(&self) -> bool {
        cfg!(debug_assertions) || env::var("RUSTF_DEBUG").is_ok()
    }

    /// Get a custom configuration section by name
    ///
    /// Deserializes a custom section from the configuration into the specified type.
    /// This allows type-safe access to application-defined configuration sections.
    ///
    /// # Arguments
    /// * `name` - The name of the configuration section
    ///
    /// # Returns
    /// * `Ok(T)` - The deserialized configuration section
    /// * `Err` - If the section doesn't exist or deserialization fails
    ///
    /// # Example
    /// ```ignore
    /// #[derive(serde::Deserialize)]
    /// struct AppSettings {
    ///     api_key: String,
    ///     max_connections: usize,
    /// }
    ///
    /// let settings = config.section::<AppSettings>("app")?;
    /// println!("API Key: {}", settings.api_key);
    /// ```
    pub fn section<T: serde::de::DeserializeOwned>(&self, name: &str) -> Result<T> {
        self.sections
            .get(name)
            .ok_or_else(|| {
                Error::internal(format!(
                    "Configuration section '{}' not found. Check your config.toml.",
                    name
                ))
            })
            .and_then(|value| {
                let json = serde_json::to_value(value).map_err(|e| {
                    Error::internal(format!(
                        "Failed to serialize section '{}' to JSON: {}",
                        name, e
                    ))
                })?;
                // Lenient: "(env) NAME" values in a custom section are strings;
                // they still read as numbers or booleans where T asks for one.
                crate::config_lenient::from_value(&json).map_err(|e| {
                    Error::internal(crate::config_refs::mask(
                        &format!("Failed to deserialize section '{}': {}", name, e),
                        &self.resolved_values.0,
                    ))
                })
            })
    }

    /// Get a raw configuration value from a custom section
    ///
    /// Returns the TOML value at the specified section, or None if not found.
    /// This allows access to configuration values without requiring full deserialization.
    ///
    /// # Arguments
    /// * `section_name` - The name of the configuration section
    ///
    /// # Returns
    /// * `Some(&toml::Value)` - The configuration value
    /// * `None` - If the section doesn't exist
    ///
    /// # Example
    /// ```ignore
    /// if let Some(value) = config.get_value("app.name") {
    ///     println!("App name: {:?}", value);
    /// }
    /// ```
    pub fn get_value(&self, section_name: &str) -> Option<&toml::Value> {
        self.sections.get(section_name)
    }

    /// Check if a custom configuration section exists
    ///
    /// Returns true if the specified section is defined in the configuration.
    ///
    /// # Arguments
    /// * `name` - The name of the configuration section
    ///
    /// # Example
    /// ```ignore
    /// if config.has_section("payment") {
    ///     let payment = config.section::<PaymentConfig>("payment")?;
    /// }
    /// ```
    pub fn has_section(&self, name: &str) -> bool {
        self.sections.contains_key(name)
    }
}

// TOML support (always available — config loading is core to the framework)
use toml;

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

    // Note: merge_with() tests removed - configuration merging is now handled
    // at the TOML file level via serde_toml_merge, not at the AppConfig struct level

    #[test]
    fn test_toml_level_merging_simple() {
        // Test simple TOML value merging
        use serde_toml_merge::merge;

        let base_toml = r#"
[server]
port = 8000
host = "127.0.0.1"
"#;

        let dev_toml = r#"
[server]
port = 3000
"#;

        let base_value: toml::Value = toml::from_str(base_toml).unwrap();
        let dev_value: toml::Value = toml::from_str(dev_toml).unwrap();

        let merged = merge(base_value, dev_value).unwrap();

        // Verify port was overridden
        assert_eq!(merged["server"]["port"].as_integer().unwrap(), 3000);
        // Verify host was preserved from base
        assert_eq!(merged["server"]["host"].as_str().unwrap(), "127.0.0.1");
    }

    #[test]
    fn test_toml_level_merging_nested_tables() {
        // Test that nested tables are properly merged
        use serde_toml_merge::merge;

        let base_toml = r#"
[session.storage]
type = "memory"
cleanup_interval = 300

[session]
enabled = true
cookie_name = "base_session"
"#;

        let dev_toml = r#"
[session.storage]
type = "redis"
url = "redis://localhost:6379"
"#;

        let base_value: toml::Value = toml::from_str(base_toml).unwrap();
        let dev_value: toml::Value = toml::from_str(dev_toml).unwrap();

        let merged = merge(base_value, dev_value).unwrap();

        // Verify session.storage was merged properly
        assert_eq!(
            merged["session"]["storage"]["type"].as_str().unwrap(),
            "redis"
        );
        assert_eq!(
            merged["session"]["storage"]["url"].as_str().unwrap(),
            "redis://localhost:6379"
        );
        // Verify session.enabled was preserved
        assert_eq!(merged["session"]["enabled"].as_bool().unwrap(), true);
    }

    #[test]
    fn test_toml_level_merging_custom_sections() {
        // Test that custom config sections merge properly
        use serde_toml_merge::merge;

        let base_toml = r#"
[custom.email]
smtp_host = "smtp.example.com"
smtp_port = 587

[custom.app]
name = "MyApp"
"#;

        let dev_toml = r#"
[custom.email]
smtp_port = 2525

[custom.logging]
debug = true
"#;

        let base_value: toml::Value = toml::from_str(base_toml).unwrap();
        let dev_value: toml::Value = toml::from_str(dev_toml).unwrap();

        let merged = merge(base_value, dev_value).unwrap();

        // Verify email port was overridden
        assert_eq!(
            merged["custom"]["email"]["smtp_port"].as_integer().unwrap(),
            2525
        );
        // Verify email host was preserved
        assert_eq!(
            merged["custom"]["email"]["smtp_host"].as_str().unwrap(),
            "smtp.example.com"
        );
        // Verify app section was preserved
        assert_eq!(merged["custom"]["app"]["name"].as_str().unwrap(), "MyApp");
        // Verify logging section was added
        assert_eq!(
            merged["custom"]["logging"]["debug"].as_bool().unwrap(),
            true
        );
    }

    #[test]
    fn test_custom_section_access() {
        // Test that custom sections are properly accessible
        use serde::{Deserialize, Serialize};

        #[derive(Debug, Deserialize, Serialize, PartialEq)]
        struct AppSettings {
            name: String,
            version: String,
            debug: bool,
        }

        let mut config = AppConfig::default();

        // Add a custom section to the config
        let app_value = toml::Value::Table(toml::map::Map::from_iter(vec![
            (
                "name".to_string(),
                toml::Value::String("TestApp".to_string()),
            ),
            (
                "version".to_string(),
                toml::Value::String("1.0.0".to_string()),
            ),
            ("debug".to_string(), toml::Value::Boolean(true)),
        ]));

        config.sections.insert("app".to_string(), app_value);

        // Test has_section
        assert!(config.has_section("app"));
        assert!(!config.has_section("nonexistent"));

        // Test get_value
        assert!(config.get_value("app").is_some());
        assert!(config.get_value("nonexistent").is_none());

        // Test section() deserialization
        let app_settings: AppSettings = config.section("app").unwrap();
        assert_eq!(app_settings.name, "TestApp");
        assert_eq!(app_settings.version, "1.0.0");
        assert_eq!(app_settings.debug, true);
    }

    #[test]
    fn test_custom_section_error_handling() {
        // Test error handling when section is missing
        use serde::Deserialize;

        #[derive(Debug, Deserialize)]
        struct PaymentConfig {
            #[allow(dead_code)]
            stripe_key: String,
        }

        let config = AppConfig::default();

        // Should return error for missing section
        let result: Result<PaymentConfig> = config.section("payment");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[test]
    fn test_custom_sections_with_toml_loading() {
        // Test that custom sections are properly loaded and accessible
        let config_toml = r#"
[server]
port = 8000

[app]
name = "TestApp"
version = "2.0.0"

[payment]
stripe_key = "sk_test_123"
enabled = true
"#;

        let config: AppConfig = toml::from_str(config_toml).unwrap();

        // Verify framework section is typed
        assert_eq!(config.server.port, 8000);

        // Verify custom sections are in sections
        assert!(config.has_section("app"));
        assert!(config.has_section("payment"));
        assert!(!config.has_section("nonexistent"));

        // Verify can access values
        assert!(config.get_value("app").is_some());
        assert!(config.get_value("payment").is_some());

        // Verify can access specific values within sections
        let app_name = config
            .get_value("app")
            .and_then(|v| v.get("name"))
            .and_then(|v| v.as_str());
        assert_eq!(app_name, Some("TestApp"));

        let stripe_key = config
            .get_value("payment")
            .and_then(|v| v.get("stripe_key"))
            .and_then(|v| v.as_str());
        assert_eq!(stripe_key, Some("sk_test_123"));
    }

    #[test]
    fn test_resolve_environment_from_config_toml() {
        // [app] environment = "production" in config.toml → Production, no env vars needed
        let toml_str = r#"[app]
environment = "production"
"#;
        let toml_value: toml::Value = toml::from_str(toml_str).unwrap();
        let env = AppConfig::resolve_environment(&toml_value).unwrap();
        assert_eq!(env, Environment::Production);
    }

    #[test]
    fn test_resolve_environment_rejects_unknown_names() {
        let staging: toml::Value = toml::from_str("[app]\nenvironment = \"staging\"\n").unwrap();
        let error = AppConfig::resolve_environment(&staging)
            .unwrap_err()
            .to_string();
        assert!(error.contains("[app] environment"), "{error}");
        assert!(error.contains("staging"), "{error}");

        let not_a_string: toml::Value = toml::from_str("[app]\nenvironment = 1\n").unwrap();
        assert!(AppConfig::resolve_environment(&not_a_string).is_err());
    }

    #[test]
    fn test_environment_parse_is_strict() {
        assert_eq!(Environment::parse("prod").unwrap(), Environment::Production);
        assert_eq!(
            Environment::parse(" Production ").unwrap(),
            Environment::Production
        );
        assert_eq!(Environment::parse("DEV").unwrap(), Environment::Development);
        assert!(Environment::parse("staging").is_err());
        assert!(Environment::parse("prodution").is_err());
        assert!(Environment::parse("").is_err());
    }

    #[test]
    fn test_resolve_environment_default() {
        // No environment field, no env vars → Development
        let toml_value = toml::Value::Table(toml::map::Map::new());
        let env = AppConfig::resolve_environment(&toml_value).unwrap();
        assert_eq!(env, Environment::Development);
    }

    #[test]
    fn test_private_and_upload_defaults() {
        let config = AppConfig::default();
        assert_eq!(config.r#private.directory, "private");
        assert_eq!(config.uploads.directory, "uploads");
        assert!(config.server.trusted_proxies.is_empty());
    }

    #[test]
    fn test_trusted_proxies_toml_loading() {
        let config_toml = r#"
[server]
trusted_proxies = ["127.0.0.1/32", "10.0.0.0/8"]
"#;

        let config: AppConfig = toml::from_str(config_toml).unwrap();
        assert_eq!(
            config.server.trusted_proxies,
            vec!["127.0.0.1/32".to_string(), "10.0.0.0/8".to_string()]
        );
    }

    #[test]
    fn test_upload_directory_resolves_under_private_root() {
        let base_dir = std::env::temp_dir().join(format!(
            "rustf-config-private-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&base_dir).unwrap();

        let mut config = AppConfig::default();
        config.resolve_relative_paths(&base_dir).unwrap();

        let expected_private = base_dir.join("private");
        let expected_uploads = expected_private.join("uploads");

        assert_eq!(
            std::path::Path::new(&config.r#private.directory),
            expected_private
        );
        assert_eq!(
            std::path::Path::new(&config.uploads.directory),
            expected_uploads
        );

        std::fs::remove_dir_all(&base_dir).unwrap();
    }

    #[test]
    fn test_absolute_upload_directory_stays_absolute() {
        let base_dir = std::env::temp_dir().join(format!(
            "rustf-config-absolute-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let absolute_uploads = std::env::temp_dir().join(format!(
            "rustf-absolute-uploads-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&base_dir).unwrap();

        let mut config = AppConfig::default();
        config.uploads.directory = absolute_uploads.to_string_lossy().into_owned();
        config.resolve_relative_paths(&base_dir).unwrap();

        assert_eq!(
            std::path::Path::new(&config.uploads.directory),
            absolute_uploads
        );

        std::fs::remove_dir_all(&base_dir).unwrap();
    }
}