switchy_web_server 0.3.0

Switchy Web Server package
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
//! Simulator backend for deterministic testing.
//!
//! This module provides a lightweight, in-memory HTTP server simulator that can be used
//! for testing without starting an actual HTTP server. It implements the same interfaces
//! as the Actix backend but runs entirely in-process.
//!
//! # Overview
//!
//! The simulator backend includes:
//!
//! * [`SimulatorWebServer`] - In-memory web server for testing
//! * [`SimulationRequest`] / [`SimulationResponse`] - Request/response types
//! * [`SimulationStub`] - Enhanced request stub with state support
//! * Path pattern matching with parameter extraction
//! * Application state management
//!
//! # Example
//!
//! ```rust
//! use switchy_web_server::simulator::{SimulatorWebServer, SimulationRequest};
//! use switchy_web_server::{Scope, Route, Method, HttpResponse};
//!
//! # async fn example() {
//! // Create a simulator server with routes
//! let server = SimulatorWebServer::with_test_routes();
//!
//! // Process a simulated request
//! let request = SimulationRequest::new(Method::Get, "/test");
//! let response = server.process_request(request).await;
//!
//! assert_eq!(response.status, 200);
//! # }
//! ```
//!
//! # Path Patterns
//!
//! The simulator supports parameterized routes using `{param}` syntax:
//!
//! ```rust
//! use switchy_web_server::simulator::{parse_path_pattern, match_path};
//!
//! let pattern = parse_path_pattern("/users/{id}/posts/{post_id}");
//! let params = match_path(&pattern, "/users/123/posts/456").unwrap();
//!
//! assert_eq!(params.get("id"), Some(&"123".to_string()));
//! assert_eq!(params.get("post_id"), Some(&"456".to_string()));
//! ```

use std::{
    collections::BTreeMap,
    future::Future,
    pin::Pin,
    sync::{Arc, RwLock},
};

use bytes::Bytes;
use switchy_http_models::Method;
use switchy_web_server_core::WebServer;

use crate::{PathParams, RouteHandler, StaticFiles, WebServerBuilder};

/// Simulation-specific implementation of HTTP response data
#[derive(Debug, Clone)]
pub struct SimulationResponse {
    /// HTTP status code (e.g., 200, 404, 500)
    pub status: u16,
    /// Response headers as key-value pairs
    pub headers: BTreeMap<String, String>,
    /// Optional response body as bytes
    pub body: Option<Bytes>,
}

impl SimulationResponse {
    /// Create a new response with the specified status code
    #[must_use]
    pub const fn new(status: u16) -> Self {
        Self {
            status,
            headers: BTreeMap::new(),
            body: None,
        }
    }

    /// Create a new 200 OK response
    #[must_use]
    pub const fn ok() -> Self {
        Self::new(200)
    }

    /// Create a new 404 Not Found response
    #[must_use]
    pub const fn not_found() -> Self {
        Self::new(404)
    }

    /// Create a new 500 Internal Server Error response
    #[must_use]
    pub const fn internal_server_error() -> Self {
        Self::new(500)
    }

    /// Add a header to the response
    #[must_use]
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.insert(name.into(), value.into());
        self
    }

    /// Set the response body
    #[must_use]
    pub fn with_body(mut self, body: impl Into<Bytes>) -> Self {
        self.body = Some(body.into());
        self
    }

    /// Returns the body as a UTF-8 string, if present and valid UTF-8.
    #[must_use]
    pub fn body_str(&self) -> Option<&str> {
        self.body.as_ref().and_then(|b| std::str::from_utf8(b).ok())
    }
}

/// Represents a segment in a URL path pattern
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum PathSegment {
    /// A literal path segment (e.g., "users" in "/users/profile")
    Literal(String),
    /// A parameter segment (e.g., "id" in "/users/{id}")
    Parameter(String),
}

/// Represents a parsed path pattern for route matching
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PathPattern {
    segments: Vec<PathSegment>,
}

impl PathPattern {
    /// Create a new path pattern from the given segments
    #[must_use]
    pub const fn new(segments: Vec<PathSegment>) -> Self {
        Self { segments }
    }

    /// Get the segments of this path pattern
    #[must_use]
    pub fn segments(&self) -> &[PathSegment] {
        &self.segments
    }
}

/// Parses a path pattern string into a `PathPattern`
///
/// Supports both literal segments and parameter segments using `{param}` syntax.
///
/// # Examples
///
/// ```
/// use switchy_web_server::simulator::{parse_path_pattern, PathSegment};
///
/// let pattern = parse_path_pattern("/users/{id}/profile");
/// assert_eq!(pattern.segments().len(), 3);
/// assert_eq!(pattern.segments()[0], PathSegment::Literal("users".to_string()));
/// assert_eq!(pattern.segments()[1], PathSegment::Parameter("id".to_string()));
/// assert_eq!(pattern.segments()[2], PathSegment::Literal("profile".to_string()));
/// ```
#[must_use]
pub fn parse_path_pattern(path: &str) -> PathPattern {
    let path = path.strip_prefix('/').unwrap_or(path);

    if path.is_empty() {
        return PathPattern::new(Vec::new());
    }

    let segments = path
        .split('/')
        .filter(|segment| !segment.is_empty())
        .map(|segment| {
            if segment.starts_with('{') && segment.ends_with('}') {
                let param_name = &segment[1..segment.len() - 1];
                PathSegment::Parameter(param_name.to_string())
            } else {
                PathSegment::Literal(segment.to_string())
            }
        })
        .collect();

    PathPattern::new(segments)
}

/// Matches a path pattern against an actual request path
///
/// Returns `Some(PathParams)` if the path matches the pattern, with any extracted parameters.
/// Returns `None` if the path does not match the pattern.
///
/// # Examples
///
/// ```
/// use switchy_web_server::simulator::{parse_path_pattern, match_path};
///
/// // Exact match
/// let pattern = parse_path_pattern("/users/profile");
/// let params = match_path(&pattern, "/users/profile").unwrap();
/// assert!(params.is_empty());
///
/// // Parameter extraction
/// let pattern = parse_path_pattern("/users/{id}");
/// let params = match_path(&pattern, "/users/123").unwrap();
/// assert_eq!(params.get("id"), Some(&"123".to_string()));
/// ```
#[must_use]
pub fn match_path(pattern: &PathPattern, actual_path: &str) -> Option<PathParams> {
    let actual_pattern = parse_path_pattern(actual_path);
    let actual_segments = actual_pattern.segments();
    let pattern_segments = pattern.segments();

    // Must have same number of segments
    if actual_segments.len() != pattern_segments.len() {
        return None;
    }

    let mut params = PathParams::new();

    for (pattern_segment, actual_segment) in pattern_segments.iter().zip(actual_segments.iter()) {
        match (pattern_segment, actual_segment) {
            // Both are literals - must match exactly
            (PathSegment::Literal(pattern_lit), PathSegment::Literal(actual_lit)) => {
                if pattern_lit != actual_lit {
                    return None;
                }
            }
            // Pattern has parameter, actual has literal - extract parameter
            (PathSegment::Parameter(param_name), PathSegment::Literal(actual_value)) => {
                params.insert(param_name.clone(), actual_value.clone());
            }
            // Pattern has literal, actual has parameter - no match
            // Both are parameters - this shouldn't happen in normal usage
            (PathSegment::Literal(_) | PathSegment::Parameter(_), PathSegment::Parameter(_)) => {
                return None;
            }
        }
    }

    Some(params)
}

/// Converts an `HttpResponse` to a `SimulationResponse`
///
/// Enhanced conversion that preserves all headers and handles different body types.
/// Implemented as part of Section 5.1.5.2.
fn convert_http_response_to_simulation_response(
    http_response: crate::HttpResponse,
) -> SimulationResponse {
    // Map status code to u16
    let status = status_code_to_u16(http_response.status_code);

    // Create response with direct header copy (no inference needed!)
    let mut response = SimulationResponse {
        status,
        headers: http_response.headers, // Direct BTreeMap copy
        body: None,
    };

    // Handle body conversion
    if let Some(body) = http_response.body {
        let crate::HttpResponseBody::Bytes(body_bytes) = body;
        response.body = Some(body_bytes);
    }

    // Keep backwards compatibility with location field
    if let Some(location) = http_response.location {
        response.headers.insert("Location".to_string(), location);
    }

    response
}

/// Maps `StatusCode` enum to u16 for `SimulationResponse`
const fn status_code_to_u16(status_code: switchy_http_models::StatusCode) -> u16 {
    match status_code {
        switchy_http_models::StatusCode::Ok => 200,
        switchy_http_models::StatusCode::Created => 201,
        switchy_http_models::StatusCode::Accepted => 202,
        switchy_http_models::StatusCode::NoContent => 204,
        switchy_http_models::StatusCode::MovedPermanently => 301,
        switchy_http_models::StatusCode::Found => 302,
        switchy_http_models::StatusCode::SeeOther => 303,
        switchy_http_models::StatusCode::NotModified => 304,
        switchy_http_models::StatusCode::TemporaryRedirect => 307,
        switchy_http_models::StatusCode::PermanentRedirect => 308,
        switchy_http_models::StatusCode::BadRequest => 400,
        switchy_http_models::StatusCode::Unauthorized => 401,
        switchy_http_models::StatusCode::PaymentRequired => 402,
        switchy_http_models::StatusCode::Forbidden => 403,
        switchy_http_models::StatusCode::NotFound => 404,
        switchy_http_models::StatusCode::MethodNotAllowed => 405,
        switchy_http_models::StatusCode::NotAcceptable => 406,
        switchy_http_models::StatusCode::ProxyAuthenticationRequired => 407,
        switchy_http_models::StatusCode::RequestTimeout => 408,
        switchy_http_models::StatusCode::Conflict => 409,
        switchy_http_models::StatusCode::Gone => 410,
        switchy_http_models::StatusCode::LengthRequired => 411,
        switchy_http_models::StatusCode::PreconditionFailed => 412,
        switchy_http_models::StatusCode::ContentTooLarge => 413,
        switchy_http_models::StatusCode::URITooLong => 414,
        switchy_http_models::StatusCode::UnsupportedMediaType => 415,
        switchy_http_models::StatusCode::RangeNotSatisfiable => 416,
        switchy_http_models::StatusCode::ExpectationFailed => 417,
        switchy_http_models::StatusCode::ImATeapot => 418,
        switchy_http_models::StatusCode::MisdirectedRequest => 421,
        switchy_http_models::StatusCode::UncompressableContent => 422,
        switchy_http_models::StatusCode::Locked => 423,
        switchy_http_models::StatusCode::FailedDependency => 424,
        switchy_http_models::StatusCode::UpgradeRequired => 426,
        switchy_http_models::StatusCode::PreconditionRequired => 428,
        switchy_http_models::StatusCode::TooManyRequests => 429,
        switchy_http_models::StatusCode::RequestHeaderFieldsTooLarge => 431,
        switchy_http_models::StatusCode::UnavailableForLegalReasons => 451,
        switchy_http_models::StatusCode::NotImplemented => 501,
        switchy_http_models::StatusCode::BadGateway => 502,
        switchy_http_models::StatusCode::ServiceUnavailable => 503,
        switchy_http_models::StatusCode::GatewayTimeout => 504,
        switchy_http_models::StatusCode::HTTPVersionNotSupported => 505,
        switchy_http_models::StatusCode::VariantAlsoNegotiates => 506,
        switchy_http_models::StatusCode::InsufficientStorage => 507,
        switchy_http_models::StatusCode::LoopDetected => 508,
        switchy_http_models::StatusCode::NotExtended => 510,
        switchy_http_models::StatusCode::NetworkAuthenticationRequired => 511,
        // Handle any other status codes (including InternalServerError)
        _ => 500, // Default to Internal Server Error
    }
}

/// Simulation-specific implementation of HTTP request data
#[derive(Debug, Clone)]
pub struct SimulationRequest {
    /// HTTP method (GET, POST, etc.)
    pub method: Method,
    /// Request path (e.g., `/api/users`)
    pub path: String,
    /// Query string (e.g., `?page=1&limit=20`)
    pub query_string: String,
    /// Request headers as key-value pairs
    pub headers: BTreeMap<String, String>,
    /// Optional request body
    pub body: Option<Bytes>,
    /// Cookies as key-value pairs
    pub cookies: BTreeMap<String, String>,
    /// Optional remote address of the client
    pub remote_addr: Option<String>,
    /// Path parameters extracted from the route pattern
    pub path_params: PathParams,
}

impl SimulationRequest {
    /// Create a new simulation request with the given method and path
    #[must_use]
    pub fn new(method: Method, path: impl Into<String>) -> Self {
        Self {
            method,
            path: path.into(),
            query_string: String::new(),
            headers: BTreeMap::new(),
            body: None,
            cookies: BTreeMap::new(),
            remote_addr: None,
            path_params: PathParams::new(),
        }
    }

    /// Set the query string for this request
    #[must_use]
    pub fn with_query_string(mut self, query: impl Into<String>) -> Self {
        self.query_string = query.into();
        self
    }

    /// Add a header to this request
    #[must_use]
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.insert(name.into(), value.into());
        self
    }

    /// Set the body for this request
    #[must_use]
    pub fn with_body(mut self, body: impl Into<Bytes>) -> Self {
        self.body = Some(body.into());
        self
    }

    /// Add multiple cookies to this request
    #[must_use]
    pub fn with_cookies(mut self, cookies: impl IntoIterator<Item = (String, String)>) -> Self {
        self.cookies.extend(cookies);
        self
    }

    /// Add a single cookie to this request
    #[must_use]
    pub fn with_cookie(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.cookies.insert(name.into(), value.into());
        self
    }

    /// Set the remote address for this request
    #[must_use]
    pub fn with_remote_addr(mut self, addr: impl Into<String>) -> Self {
        self.remote_addr = Some(addr.into());
        self
    }

    /// Set the path parameters for this request
    #[must_use]
    pub fn with_path_params(mut self, params: PathParams) -> Self {
        self.path_params = params;
        self
    }
}

/// Enhanced Stub that can hold simulation data
#[derive(Debug, Clone)]
pub struct SimulationStub {
    /// The simulation request being processed
    pub request: SimulationRequest,
    /// State container for the simulation
    pub state_container: Option<Arc<RwLock<crate::extractors::state::StateContainer>>>,
}

impl SimulationStub {
    /// Create a new simulation stub from the given request
    #[must_use]
    pub const fn new(request: SimulationRequest) -> Self {
        Self {
            request,
            state_container: None,
        }
    }

    /// Attach a state container to this stub
    #[must_use]
    pub fn with_state_container(
        mut self,
        container: Arc<RwLock<crate::extractors::state::StateContainer>>,
    ) -> Self {
        self.state_container = Some(container);
        self
    }

    /// Get a header value by name
    #[must_use]
    pub fn header(&self, name: &str) -> Option<&str> {
        self.request.headers.get(name).map(String::as_str)
    }

    /// Get the request path
    #[must_use]
    pub fn path(&self) -> &str {
        &self.request.path
    }

    /// Get the query string
    #[must_use]
    pub fn query_string(&self) -> &str {
        &self.request.query_string
    }

    /// Get the HTTP method
    #[must_use]
    pub const fn method(&self) -> &Method {
        &self.request.method
    }

    /// Get the request body
    #[must_use]
    pub const fn body(&self) -> Option<&Bytes> {
        self.request.body.as_ref()
    }

    /// Get a cookie value by name
    #[must_use]
    pub fn cookie(&self, name: &str) -> Option<&str> {
        self.request.cookies.get(name).map(String::as_str)
    }

    /// Get all cookies
    #[must_use]
    pub const fn cookies(&self) -> &BTreeMap<String, String> {
        &self.request.cookies
    }

    /// Get the remote address of the client
    #[must_use]
    pub fn remote_addr(&self) -> Option<&str> {
        self.request.remote_addr.as_deref()
    }

    /// Get state of type T from the state container
    #[must_use]
    pub fn state<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
        self.state_container.as_ref().and_then(|container| {
            container
                .read()
                .map_or_else(|_| None, |state| state.get::<T>())
        })
    }

    /// Get a path parameter by name
    #[must_use]
    pub fn path_param(&self, name: &str) -> Option<&str> {
        self.request.path_params.get(name).map(String::as_str)
    }

    /// Access application state from the server
    ///
    /// This method provides access to the server's state container, which can be used
    /// by extractors like `State<T>` to retrieve typed state values.
    ///
    /// Returns `None` if no state container has been set on this stub.
    #[must_use]
    pub const fn app_state(
        &self,
    ) -> Option<&Arc<RwLock<crate::extractors::state::StateContainer>>> {
        self.state_container.as_ref()
    }
}

impl From<SimulationRequest> for SimulationStub {
    fn from(request: SimulationRequest) -> Self {
        Self::new(request)
    }
}

impl crate::request::HttpRequestTrait for SimulationStub {
    fn path(&self) -> &str {
        &self.request.path
    }

    fn query_string(&self) -> &str {
        &self.request.query_string
    }

    fn method(&self) -> Method {
        self.request.method
    }

    fn header(&self, name: &str) -> Option<&str> {
        self.request.headers.get(name).map(String::as_str)
    }

    fn headers(&self) -> BTreeMap<String, String> {
        self.request.headers.clone()
    }

    fn body(&self) -> Option<&Bytes> {
        self.request.body.as_ref()
    }

    fn cookie(&self, name: &str) -> Option<String> {
        self.request.cookies.get(name).cloned()
    }

    fn cookies(&self) -> BTreeMap<String, String> {
        self.request.cookies.clone()
    }

    fn remote_addr(&self) -> Option<String> {
        self.request.remote_addr.clone()
    }

    fn path_params(&self) -> &PathParams {
        &self.request.path_params
    }

    fn app_state_any(&self, type_id: std::any::TypeId) -> Option<crate::request::ErasedState> {
        self.state_container.as_ref().and_then(|container| {
            container
                .read()
                .map_or_else(|_| None, |state| state.get_any(type_id))
        })
    }
}

/// In-memory web server for deterministic testing and simulation.
///
/// This struct provides a lightweight, in-process HTTP server simulator that can be used
/// for testing without starting an actual HTTP server. It implements the [`WebServer`]
/// trait and stores routes, scopes, and application state for request processing.
///
/// # Structure
///
/// * `scopes` - All registered scopes with their routes
/// * `routes` - Flattened route map for efficient lookup
/// * `state` - Shared application state accessible via extractors
///
/// # Example
///
/// ```rust
/// use switchy_web_server::simulator::SimulatorWebServer;
/// use switchy_web_server::{Scope, Method, HttpResponse};
///
/// # async fn example() {
/// let server = SimulatorWebServer::with_test_routes();
/// // Use server for testing
/// # }
/// ```
pub struct SimulatorWebServer {
    /// Registered scopes containing routes and nested scopes
    pub scopes: Vec<crate::Scope>,
    /// Flat map of registered routes with their handlers
    pub routes: BTreeMap<(Method, String), RouteHandler>,
    /// Application state container for extractors
    pub state: Arc<RwLock<crate::extractors::state::StateContainer>>,
    /// Static files configuration for serving files from disk
    pub static_files: Option<StaticFiles>,
}

impl SimulatorWebServer {
    /// Register a single route with the simulator
    #[allow(dead_code)] // Used in tests and scope processing
    pub fn register_route(&mut self, method: Method, path: &str, handler: RouteHandler) {
        self.routes.insert((method, path.to_string()), handler);
    }

    /// Register a scope and all its routes and nested scopes
    ///
    /// This method processes a scope recursively, registering all routes with their
    /// full paths (including scope prefixes) and handling nested scopes.
    ///
    /// # Arguments
    ///
    /// * `scope` - The scope to register
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let mut server = SimulatorWebServer::new();
    /// let scope = Scope::new("/api")
    ///     .route(Method::Get, "/users", handler);
    /// server.register_scope(scope);
    /// // This registers a route at "/api/users"
    /// ```
    #[allow(dead_code)] // Used in tests
    pub fn register_scope(&mut self, scope: &crate::Scope) {
        self.process_scope_recursive(scope, "");
    }

    /// Recursively process a scope and register all its routes
    ///
    /// This helper method handles the recursive processing of scopes, building
    /// the full path by combining parent prefixes with the current scope path.
    ///
    /// # Arguments
    ///
    /// * `scope` - The scope to process
    /// * `parent_prefix` - The accumulated path prefix from parent scopes
    fn process_scope_recursive(&mut self, scope: &crate::Scope, parent_prefix: &str) {
        // Build the full prefix for this scope
        let full_prefix = if parent_prefix.is_empty() {
            scope.path.clone()
        } else {
            format!("{}{}", parent_prefix, scope.path)
        };

        // Register all routes in this scope with the full prefix
        for route in &scope.routes {
            let full_path = if full_prefix.is_empty() {
                route.path.clone()
            } else {
                format!("{}{}", full_prefix, route.path)
            };

            // Clone the Arc<RouteHandler> and extract the inner RouteHandler
            let handler_arc = Arc::clone(&route.handler);
            // We need to create a new Box that wraps the Arc-ed handler
            let handler: RouteHandler = Box::new(move |req| {
                let handler_arc = Arc::clone(&handler_arc);
                handler_arc(req)
            });

            self.register_route(route.method, &full_path, handler);
        }

        // Recursively process nested scopes
        for nested_scope in &scope.scopes {
            self.process_scope_recursive(nested_scope, &full_prefix);
        }
    }

    /// Finds a route that matches the given method and path
    ///
    /// Returns the handler and extracted path parameters if a match is found.
    /// Implements route precedence: exact matches are preferred over parameterized matches.
    #[allow(unused)] // TODO: Remove in 5.1.4 when process_request() uses this method
    #[must_use]
    pub fn find_route(&self, method: Method, path: &str) -> Option<(&RouteHandler, PathParams)> {
        let mut exact_matches = Vec::new();
        let mut parameterized_matches = Vec::new();

        // Collect all potential matches
        for ((route_method, route_path), handler) in &self.routes {
            if *route_method != method {
                continue;
            }

            let route_pattern = parse_path_pattern(route_path);
            if let Some(params) = match_path(&route_pattern, path) {
                // Check if this is an exact match (no parameters extracted)
                if params.is_empty() {
                    exact_matches.push((handler, params));
                } else {
                    parameterized_matches.push((handler, params));
                }
            }
        }

        // Prefer exact matches over parameterized matches
        if let Some((handler, params)) = exact_matches.into_iter().next() {
            Some((handler, params))
        } else {
            parameterized_matches.into_iter().next()
        }
    }

    /// Processes a simulation request and returns a simulation response
    ///
    /// This method implements the complete request processing pipeline:
    /// 1. Find matching route using `find_route()`
    /// 2. Inject path parameters into request
    /// 3. Create `HttpRequest` from enhanced request
    /// 4. Execute matched handler with request
    /// 5. Convert `HttpResponse` to `SimulationResponse`
    /// 6. Return 404 response if no route matches
    #[allow(unused)] // TODO: Remove in 5.1.4 integration tests when this method is called
    pub async fn process_request(&self, mut request: SimulationRequest) -> SimulationResponse {
        // Find matching route using find_route()
        let route_result = self.find_route(request.method, &request.path);

        let Some((handler, path_params)) = route_result else {
            // Return 404 response if no route matches
            return SimulationResponse::not_found().with_body("Not Found");
        };

        // Inject path params into request
        request.path_params = path_params;

        // Create HttpRequest from enhanced request with state container
        let simulation_stub =
            SimulationStub::new(request).with_state_container(Arc::clone(&self.state));

        let http_request = crate::HttpRequest::new(simulation_stub);

        // Execute matched handler with request
        handler(http_request).await.map_or_else(
            |_| {
                // Return 500 response on handler error
                SimulationResponse::internal_server_error().with_body("Internal Server Error")
            },
            |http_response| {
                // Convert HttpResponse to SimulationResponse
                convert_http_response_to_simulation_response(http_response)
            },
        )
    }

    /// Insert state of type T into the server's state container
    ///
    /// This state can later be retrieved by handlers using the `State<T>` extractor.
    /// The state is stored in a thread-safe manner and can be accessed concurrently.
    ///
    /// # Arguments
    ///
    /// * `state` - The state value to store
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // SimulatorWebServer is an internal implementation detail
    /// let mut server = SimulatorWebServer::new();
    /// server.insert_state("Hello, World!".to_string());
    /// ```
    #[allow(dead_code)] // Used in tests
    pub fn insert_state<T: Send + Sync + 'static>(&self, state: T) {
        if let Ok(mut state_container) = self.state.write() {
            state_container.insert(state);
        }
    }

    /// Retrieve state of type T from the server's state container
    ///
    /// Returns `Some(Arc<T>)` if state of the requested type exists,
    /// or `None` if no state of that type has been inserted.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // SimulatorWebServer is an internal implementation detail
    /// let mut server = SimulatorWebServer::new();
    /// server.insert_state("Hello, World!".to_string());
    ///
    /// let state: Option<std::sync::Arc<String>> = server.get_state();
    /// assert!(state.is_some());
    /// ```
    #[must_use]
    #[allow(dead_code)] // Used in tests
    pub fn get_state<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
        self.state
            .read()
            .map_or_else(|_| None, |state_container| state_container.get::<T>())
    }

    /// Create a new simulator web server with the given scopes
    #[must_use]
    pub fn new(scopes: Vec<crate::Scope>) -> Self {
        Self {
            scopes,
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
            static_files: None,
        }
    }

    /// Creates a new simulator web server with static files configuration.
    #[must_use]
    pub fn with_static_files(scopes: Vec<crate::Scope>, static_files: StaticFiles) -> Self {
        Self {
            scopes,
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
            static_files: Some(static_files),
        }
    }

    /// Returns the static files configuration, if set.
    #[must_use]
    pub const fn static_files(&self) -> Option<&StaticFiles> {
        self.static_files.as_ref()
    }

    /// Returns the MIME type for a file based on its extension.
    ///
    /// This is a simple lookup table covering common web file types.
    /// Unknown extensions return `application/octet-stream`.
    #[cfg(feature = "simulator")]
    fn get_mime_type(path: &str) -> &'static str {
        let extension = path.rsplit('.').next().unwrap_or("");
        match extension.to_lowercase().as_str() {
            "html" | "htm" => "text/html; charset=utf-8",
            "css" => "text/css; charset=utf-8",
            "js" | "mjs" => "application/javascript; charset=utf-8",
            "json" => "application/json; charset=utf-8",
            "png" => "image/png",
            "jpg" | "jpeg" => "image/jpeg",
            "gif" => "image/gif",
            "svg" => "image/svg+xml",
            "webp" => "image/webp",
            "ico" => "image/x-icon",
            "woff" => "font/woff",
            "woff2" => "font/woff2",
            "ttf" => "font/ttf",
            "eot" => "application/vnd.ms-fontobject",
            "otf" => "font/otf",
            "txt" => "text/plain; charset=utf-8",
            "xml" => "application/xml; charset=utf-8",
            "pdf" => "application/pdf",
            "map" => "application/json",
            "wasm" => "application/wasm",
            _ => "application/octet-stream",
        }
    }

    /// Serves a static file from the configured static files directory.
    ///
    /// Returns `None` if:
    /// - No static files configuration is set
    /// - The requested path doesn't match the mount path
    /// - The file doesn't exist or cannot be read
    ///
    /// This method provides a primitive for serving static files. It does NOT
    /// handle index files or SPA fallback - consumers should implement those
    /// behaviors using this primitive combined with the config accessors.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use switchy_web_server::simulator::SimulatorWebServer;
    /// use switchy_web_server::StaticFiles;
    ///
    /// let server = SimulatorWebServer::with_static_files(
    ///     Vec::new(),
    ///     StaticFiles::new("/static", "./public"),
    /// );
    ///
    /// // Serve a file
    /// if let Some(response) = server.serve_static_file("/static/style.css").await {
    ///     // File found and served
    /// }
    /// ```
    #[cfg(feature = "simulator")]
    pub async fn serve_static_file(&self, request_path: &str) -> Option<SimulationResponse> {
        let config = self.static_files.as_ref()?;

        // Strip mount path prefix
        let mount_path = config.mount_path();
        let relative_path = if mount_path == "/" {
            request_path.strip_prefix('/').unwrap_or(request_path)
        } else {
            request_path
                .strip_prefix(mount_path)?
                .strip_prefix('/')
                .unwrap_or("")
        };

        // Prevent path traversal
        if relative_path.contains("..") {
            return None;
        }

        // Construct file path
        let file_path = config.directory().join(relative_path);

        // Read file using switchy async fs
        let contents = switchy_fs::unsync::read(&file_path).await.ok()?;

        // Determine MIME type
        let mime_type = Self::get_mime_type(request_path);

        Some(
            SimulationResponse::ok()
                .with_header("Content-Type", mime_type)
                .with_body(contents),
        )
    }

    /// Create a server with test routes
    #[must_use]
    pub fn with_test_routes() -> Self {
        let mut server = Self::new(Vec::new());

        // Register test routes similar to Actix implementation
        server.register_route(
            Method::Get,
            "/test",
            Box::new(|_req| {
                Box::pin(async {
                    Ok(crate::HttpResponse::ok()
                        .with_header("content-type", "application/json")
                        .with_body(r#"{"message":"Hello from test route!"}"#))
                })
            }),
        );

        server.register_route(
            Method::Get,
            "/health",
            Box::new(|_req| {
                Box::pin(async {
                    Ok(crate::HttpResponse::ok()
                        .with_header("content-type", "application/json")
                        .with_body(r#"{"status":"ok"}"#))
                })
            }),
        );

        server
    }

    /// Create a server with API routes
    #[must_use]
    pub fn with_api_routes() -> Self {
        let mut server = Self::new(Vec::new());

        // Register API routes similar to Actix implementation
        server.register_route(
            Method::Get,
            "/api/status",
            Box::new(|_req| {
                Box::pin(async {
                    Ok(crate::HttpResponse::ok()
                        .with_header("content-type", "application/json")
                        .with_body(r#"{"service":"running"}"#))
                })
            }),
        );

        server.register_route(
            Method::Post,
            "/api/echo",
            Box::new(|_req| {
                Box::pin(async {
                    Ok(crate::HttpResponse::ok()
                        .with_header("content-type", "application/json")
                        .with_body(r#"{"echoed":"data"}"#))
                })
            }),
        );

        server
    }
}

/// Error type for simulator web server operations
#[derive(Debug, thiserror::Error)]
pub enum SimulatorWebServerError {
    /// Server startup error
    #[error("Server startup failed: {0}")]
    Startup(String),
    /// Server shutdown error
    #[error("Server shutdown failed: {0}")]
    Shutdown(String),
}

impl crate::test_client::GenericTestServer for SimulatorWebServer {
    type Error = SimulatorWebServerError;

    fn url(&self) -> String {
        // Simulator doesn't have a real URL, so return a placeholder
        "http://simulator".to_string()
    }

    fn port(&self) -> u16 {
        // Simulator doesn't use a real port, so return a placeholder
        8080
    }

    fn start(&mut self) -> Result<(), Self::Error> {
        // Simulator doesn't need to start, so this is a no-op
        Ok(())
    }

    fn stop(&mut self) -> Result<(), Self::Error> {
        // Simulator doesn't need to stop, so this is a no-op
        Ok(())
    }
}

impl WebServer for SimulatorWebServer {
    fn start(&self) -> Pin<Box<dyn Future<Output = ()>>> {
        let scopes = self.scopes.clone();
        Box::pin(async move {
            log::info!("Simulator web server started with {} scopes", scopes.len());
            for scope in &scopes {
                log::debug!("Scope '{}' has {} routes", scope.path, scope.routes.len());
                for route in &scope.routes {
                    log::debug!("  {:?} {}{}", route.method, scope.path, route.path);
                }
            }
        })
    }

    fn stop(&self) -> Pin<Box<dyn Future<Output = ()>>> {
        Box::pin(async {
            log::info!("Simulator web server stopped");
        })
    }
}

impl WebServerBuilder {
    /// Build a simulator web server instance
    #[must_use]
    pub fn build_simulator(self) -> Box<dyn WebServer> {
        Box::new(SimulatorWebServer {
            scopes: self.scopes,
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
            static_files: self.static_files,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{HttpRequest, HttpResponse};

    fn create_test_handler() -> RouteHandler {
        Box::new(|_req: HttpRequest| {
            Box::pin(async move { Ok(HttpResponse::ok().with_body("test response")) })
        })
    }

    #[test]
    fn test_route_registration_stores_handler_correctly() {
        let mut server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        let handler = create_test_handler();
        server.register_route(Method::Get, "/test", handler);

        assert!(
            server
                .routes
                .contains_key(&(Method::Get, "/test".to_string()))
        );
        assert_eq!(server.routes.len(), 1);
    }

    #[test]
    fn test_multiple_routes_can_be_registered_without_conflict() {
        let mut server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        let handler1 = create_test_handler();
        let handler2 = create_test_handler();
        let handler3 = create_test_handler();

        server.register_route(Method::Get, "/users", handler1);
        server.register_route(Method::Post, "/users", handler2);
        server.register_route(Method::Get, "/posts", handler3);

        assert!(
            server
                .routes
                .contains_key(&(Method::Get, "/users".to_string()))
        );
        assert!(
            server
                .routes
                .contains_key(&(Method::Post, "/users".to_string()))
        );
        assert!(
            server
                .routes
                .contains_key(&(Method::Get, "/posts".to_string()))
        );
        assert_eq!(server.routes.len(), 3);
    }

    #[test]
    fn test_parse_literal_path_pattern() {
        let pattern = parse_path_pattern("/users/profile");

        assert_eq!(pattern.segments().len(), 2);
        assert_eq!(
            pattern.segments()[0],
            PathSegment::Literal("users".to_string())
        );
        assert_eq!(
            pattern.segments()[1],
            PathSegment::Literal("profile".to_string())
        );
    }

    #[test]
    fn test_parse_parameterized_path_pattern() {
        let pattern = parse_path_pattern("/{id}");

        assert_eq!(pattern.segments().len(), 1);
        assert_eq!(
            pattern.segments()[0],
            PathSegment::Parameter("id".to_string())
        );
    }

    #[test]
    fn test_parse_mixed_literal_and_parameter_path_pattern() {
        let pattern = parse_path_pattern("/users/{id}/posts/{post_id}");

        assert_eq!(pattern.segments().len(), 4);
        assert_eq!(
            pattern.segments()[0],
            PathSegment::Literal("users".to_string())
        );
        assert_eq!(
            pattern.segments()[1],
            PathSegment::Parameter("id".to_string())
        );
        assert_eq!(
            pattern.segments()[2],
            PathSegment::Literal("posts".to_string())
        );
        assert_eq!(
            pattern.segments()[3],
            PathSegment::Parameter("post_id".to_string())
        );
    }

    #[test]
    fn test_parse_empty_path_pattern() {
        let pattern = parse_path_pattern("");
        assert_eq!(pattern.segments().len(), 0);

        let pattern = parse_path_pattern("/");
        assert_eq!(pattern.segments().len(), 0);
    }

    #[test]
    fn test_parse_path_pattern_without_leading_slash() {
        let pattern = parse_path_pattern("users/{id}");

        assert_eq!(pattern.segments().len(), 2);
        assert_eq!(
            pattern.segments()[0],
            PathSegment::Literal("users".to_string())
        );
        assert_eq!(
            pattern.segments()[1],
            PathSegment::Parameter("id".to_string())
        );
    }

    #[test]
    fn test_match_path_exact_route() {
        let pattern = parse_path_pattern("/api/users");
        let params = match_path(&pattern, "/api/users").unwrap();

        assert!(params.is_empty());
    }

    #[test]
    fn test_match_path_parameterized_route() {
        let pattern = parse_path_pattern("/users/{id}");
        let params = match_path(&pattern, "/users/123").unwrap();

        assert_eq!(params.len(), 1);
        assert_eq!(params.get("id"), Some(&"123".to_string()));
    }

    #[test]
    fn test_match_path_multiple_parameters() {
        let pattern = parse_path_pattern("/users/{id}/posts/{post_id}");
        let params = match_path(&pattern, "/users/123/posts/456").unwrap();

        assert_eq!(params.len(), 2);
        assert_eq!(params.get("id"), Some(&"123".to_string()));
        assert_eq!(params.get("post_id"), Some(&"456".to_string()));
    }

    #[test]
    fn test_match_path_no_match_different_segments() {
        let pattern = parse_path_pattern("/users/{id}");
        let result = match_path(&pattern, "/posts/123");

        assert!(result.is_none());
    }

    #[test]
    fn test_match_path_no_match_different_length() {
        let pattern = parse_path_pattern("/users/{id}");
        let result = match_path(&pattern, "/users/123/extra");

        assert!(result.is_none());
    }

    #[test]
    fn test_find_route_exact_match() {
        let mut server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        let handler = create_test_handler();
        server.register_route(Method::Get, "/api/users", handler);

        let result = server.find_route(Method::Get, "/api/users");
        assert!(result.is_some());

        let (_, params) = result.unwrap();
        assert!(params.is_empty());
    }

    #[test]
    fn test_find_route_parameterized_match() {
        let mut server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        let handler = create_test_handler();
        server.register_route(Method::Get, "/users/{id}", handler);

        let result = server.find_route(Method::Get, "/users/123");
        assert!(result.is_some());

        let (_, params) = result.unwrap();
        assert_eq!(params.len(), 1);
        assert_eq!(params.get("id"), Some(&"123".to_string()));
    }

    #[test]
    fn test_find_route_method_discrimination() {
        let mut server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        let get_handler = create_test_handler();
        let post_handler = create_test_handler();
        server.register_route(Method::Get, "/users", get_handler);
        server.register_route(Method::Post, "/users", post_handler);

        // GET request should match GET route
        let get_result = server.find_route(Method::Get, "/users");
        assert!(get_result.is_some());

        // POST request should match POST route
        let post_result = server.find_route(Method::Post, "/users");
        assert!(post_result.is_some());

        // PUT request should not match any route
        let put_result = server.find_route(Method::Put, "/users");
        assert!(put_result.is_none());
    }

    #[test]
    fn test_find_route_no_match_404() {
        let mut server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        let handler = create_test_handler();
        server.register_route(Method::Get, "/users", handler);

        // Different path should not match
        let result = server.find_route(Method::Get, "/posts");
        assert!(result.is_none());

        // Different method should not match
        let result = server.find_route(Method::Post, "/users");
        assert!(result.is_none());
    }

    #[test]
    fn test_find_route_precedence_exact_over_parameterized() {
        let mut server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        let exact_handler = create_test_handler();
        let param_handler = create_test_handler();

        // Register parameterized route first
        server.register_route(Method::Get, "/users/{id}", param_handler);
        // Register exact route second
        server.register_route(Method::Get, "/users/profile", exact_handler);

        // Request for "/users/profile" should match exact route (empty params)
        let result = server.find_route(Method::Get, "/users/profile");
        assert!(result.is_some());

        let (_, params) = result.unwrap();
        assert!(params.is_empty()); // Exact match should have no parameters
    }

    #[test]
    fn test_process_request_integration_setup() {
        // This test validates that the process_request method can be set up correctly
        // Full async integration tests will be added when tokio dependency is available
        let mut server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        let handler = create_test_handler();
        server.register_route(Method::Get, "/hello", handler);

        // Verify the route was registered
        let route_result = server.find_route(Method::Get, "/hello");
        assert!(route_result.is_some());

        // Verify 404 case
        let not_found_result = server.find_route(Method::Get, "/nonexistent");
        assert!(not_found_result.is_none());
    }

    #[test]
    fn test_simulation_response_builders() {
        let response = SimulationResponse::ok()
            .with_header("Content-Type", "application/json")
            .with_body("{}");

        assert_eq!(response.status, 200);
        assert_eq!(
            response.headers.get("Content-Type"),
            Some(&"application/json".to_string())
        );
        assert_eq!(response.body_str(), Some("{}"));
    }

    #[test]
    fn test_simulation_request_with_path_params() {
        let mut params = PathParams::new();
        params.insert("id".to_string(), "123".to_string());

        let request = SimulationRequest::new(Method::Get, "/users/123").with_path_params(params);

        assert_eq!(request.path_params.get("id"), Some(&"123".to_string()));
    }

    #[test]
    fn test_simulation_stub_path_param() {
        let mut params = PathParams::new();
        params.insert("id".to_string(), "456".to_string());
        params.insert("name".to_string(), "john".to_string());

        let request = SimulationRequest::new(Method::Get, "/users/456").with_path_params(params);
        let stub = SimulationStub::new(request);

        assert_eq!(stub.path_param("id"), Some("456"));
        assert_eq!(stub.path_param("name"), Some("john"));
        assert_eq!(stub.path_param("nonexistent"), None);
    }

    // Response Generation Tests (Section 5.1.5.2)

    #[test]
    #[cfg(feature = "serde")]
    fn test_json_response_conversion_preserves_content_type() {
        use serde_json::json;

        let test_data = json!({"message": "Hello, World!", "status": "success"});
        let http_response = HttpResponse::json(&test_data).unwrap();

        let simulation_response = convert_http_response_to_simulation_response(http_response);

        assert_eq!(simulation_response.status, 200);
        assert_eq!(
            simulation_response.headers.get("Content-Type"),
            Some(&"application/json".to_string())
        );
        assert!(simulation_response.body.is_some());

        // Verify the JSON content is preserved
        let body = simulation_response.body_str().unwrap();
        let parsed: serde_json::Value = serde_json::from_str(body).unwrap();
        assert_eq!(parsed["message"], "Hello, World!");
        assert_eq!(parsed["status"], "success");
    }

    #[test]
    fn test_status_codes_are_preserved() {
        // Test 200 OK
        let ok_response = HttpResponse::ok();
        let sim_response = convert_http_response_to_simulation_response(ok_response);
        assert_eq!(sim_response.status, 200);

        // Test 404 Not Found
        let not_found_response = HttpResponse::not_found();
        let sim_response = convert_http_response_to_simulation_response(not_found_response);
        assert_eq!(sim_response.status, 404);

        // Test 500 Internal Server Error
        let error_response =
            HttpResponse::from_status_code(switchy_http_models::StatusCode::InternalServerError);
        let sim_response = convert_http_response_to_simulation_response(error_response);
        assert_eq!(sim_response.status, 500);

        // Test 201 Created
        let created_response =
            HttpResponse::from_status_code(switchy_http_models::StatusCode::Created);
        let sim_response = convert_http_response_to_simulation_response(created_response);
        assert_eq!(sim_response.status, 201);

        // Test 401 Unauthorized
        let unauthorized_response =
            HttpResponse::from_status_code(switchy_http_models::StatusCode::Unauthorized);
        let sim_response = convert_http_response_to_simulation_response(unauthorized_response);
        assert_eq!(sim_response.status, 401);
    }

    #[test]
    fn test_custom_headers_are_preserved() {
        let http_response = HttpResponse::ok()
            .with_header("X-Custom-Header", "custom-value")
            .with_header("X-Another-Header", "another-value")
            .with_content_type("text/plain")
            .with_body("Hello, World!");

        let simulation_response = convert_http_response_to_simulation_response(http_response);

        assert_eq!(simulation_response.status, 200);
        assert_eq!(
            simulation_response.headers.get("X-Custom-Header"),
            Some(&"custom-value".to_string())
        );
        assert_eq!(
            simulation_response.headers.get("X-Another-Header"),
            Some(&"another-value".to_string())
        );
        assert_eq!(
            simulation_response.headers.get("Content-Type"),
            Some(&"text/plain".to_string())
        );
        assert_eq!(simulation_response.body_str(), Some("Hello, World!"));
    }

    #[test]
    fn test_html_response_conversion() {
        let html_content = "<h1>Hello, World!</h1><p>This is a test.</p>";
        let http_response = HttpResponse::html(html_content);

        let simulation_response = convert_http_response_to_simulation_response(http_response);

        assert_eq!(simulation_response.status, 200);
        assert_eq!(
            simulation_response.headers.get("Content-Type"),
            Some(&"text/html; charset=utf-8".to_string())
        );
        assert_eq!(simulation_response.body_str(), Some(html_content));
    }

    #[test]
    fn test_text_response_conversion() {
        let text_content = "This is plain text content.";
        let http_response = HttpResponse::text(text_content);

        let simulation_response = convert_http_response_to_simulation_response(http_response);

        assert_eq!(simulation_response.status, 200);
        assert_eq!(
            simulation_response.headers.get("Content-Type"),
            Some(&"text/plain; charset=utf-8".to_string())
        );
        assert_eq!(simulation_response.body_str(), Some(text_content));
    }

    #[test]
    fn test_location_header_backwards_compatibility() {
        let redirect_response =
            HttpResponse::temporary_redirect().with_location("https://example.com/new-location");

        let simulation_response = convert_http_response_to_simulation_response(redirect_response);

        assert_eq!(simulation_response.status, 307);
        assert_eq!(
            simulation_response.headers.get("Location"),
            Some(&"https://example.com/new-location".to_string())
        );
    }

    // State Management Tests (Section 5.1.6)

    #[test]
    fn test_simulator_state_management_string_state() {
        let server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        // Insert string state
        let test_string = "Hello, World!".to_string();
        server.insert_state(test_string.clone());

        // Retrieve string state
        let retrieved_state: Option<Arc<String>> = server.get_state();
        assert!(retrieved_state.is_some());
        assert_eq!(*retrieved_state.unwrap(), test_string);
    }

    #[test]
    fn test_simulator_state_management_custom_struct_state() {
        #[derive(Debug, Clone, PartialEq)]
        struct AppConfig {
            name: String,
            version: u32,
            debug: bool,
        }

        let server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        // Insert custom struct state
        let config = AppConfig {
            name: "TestApp".to_string(),
            version: 42,
            debug: true,
        };
        server.insert_state(config.clone());

        // Retrieve custom struct state
        let retrieved_config: Option<Arc<AppConfig>> = server.get_state();
        assert!(retrieved_config.is_some());
        assert_eq!(*retrieved_config.unwrap(), config);
    }

    #[test]
    fn test_simulator_state_management_multiple_types() {
        let server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        // Insert multiple different types
        server.insert_state("Hello".to_string());
        server.insert_state(42u32);
        server.insert_state(true);

        // Retrieve each type independently
        let string_state: Option<Arc<String>> = server.get_state();
        let u32_state: Option<Arc<u32>> = server.get_state();
        let bool_state: Option<Arc<bool>> = server.get_state();

        assert!(string_state.is_some());
        assert!(u32_state.is_some());
        assert!(bool_state.is_some());

        assert_eq!(*string_state.unwrap(), "Hello");
        assert_eq!(*u32_state.unwrap(), 42);
        assert!(*bool_state.unwrap());
    }

    #[test]
    fn test_simulator_state_management_shared_across_requests() {
        let server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        // Insert shared state
        let shared_data = "Shared across requests".to_string();
        server.insert_state(shared_data.clone());

        // Create multiple requests
        let request1 = SimulationRequest::new(Method::Get, "/test1");
        let request2 = SimulationRequest::new(Method::Get, "/test2");

        // Create simulation stubs with state container
        let stub1 = SimulationStub::new(request1).with_state_container(Arc::clone(&server.state));
        let stub2 = SimulationStub::new(request2).with_state_container(Arc::clone(&server.state));

        // Both stubs should access the same state
        let state1: Option<Arc<String>> = stub1.state();
        let state2: Option<Arc<String>> = stub2.state();

        assert!(state1.is_some());
        assert!(state2.is_some());
        assert_eq!(*state1.unwrap(), shared_data);
        assert_eq!(*state2.unwrap(), shared_data);

        // Verify they're actually the same Arc (same memory location)
        let state1_again: Option<Arc<String>> = stub1.state();
        let state2_again: Option<Arc<String>> = stub2.state();
        assert!(Arc::ptr_eq(&state1_again.unwrap(), &state2_again.unwrap()));
    }

    #[test]
    fn test_simulator_state_management_handler_extraction() {
        use crate::{extractors::state::State, from_request::FromRequest};

        let server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        // Insert state that will be extracted by handler
        let app_name = "TestApplication".to_string();
        server.insert_state(app_name.clone());

        // Create a request and simulation stub with state
        let request = SimulationRequest::new(Method::Get, "/app-info");
        let simulation_stub =
            SimulationStub::new(request).with_state_container(Arc::clone(&server.state));
        let http_request = crate::HttpRequest::new(simulation_stub);

        // Test that State<T> extractor works with the simulator backend
        let state_result: Result<State<String>, _> = State::from_request_sync(&http_request);

        assert!(state_result.is_ok());
        let State(extracted_name) = state_result.unwrap();
        assert_eq!(*extracted_name, app_name);
    }

    // Scope Processing Tests (Section 5.1.7)

    #[test]
    fn test_register_scope_with_single_route() {
        let mut server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        let scope = crate::Scope::new("/api").with_route(crate::Route::new(
            Method::Get,
            "/users",
            |_req: crate::HttpRequest| {
                Box::pin(async move { Ok(crate::HttpResponse::ok().with_body("test response")) })
            },
        ));

        server.register_scope(&scope);

        // Verify the route was registered with the full path
        assert!(
            server
                .routes
                .contains_key(&(Method::Get, "/api/users".to_string()))
        );
        assert_eq!(server.routes.len(), 1);
    }

    #[test]
    fn test_register_scope_with_multiple_routes() {
        let mut server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        let scope = crate::Scope::new("/api")
            .with_route(crate::Route::new(
                Method::Get,
                "/users",
                |_req: crate::HttpRequest| {
                    Box::pin(async move { Ok(crate::HttpResponse::ok().with_body("get users")) })
                },
            ))
            .with_route(crate::Route::new(
                Method::Post,
                "/users",
                |_req: crate::HttpRequest| {
                    Box::pin(async move { Ok(crate::HttpResponse::ok().with_body("create user")) })
                },
            ));

        server.register_scope(&scope);

        // Verify both routes were registered with the full path
        assert!(
            server
                .routes
                .contains_key(&(Method::Get, "/api/users".to_string()))
        );
        assert!(
            server
                .routes
                .contains_key(&(Method::Post, "/api/users".to_string()))
        );
        assert_eq!(server.routes.len(), 2);
    }

    #[test]
    fn test_register_scope_with_nested_scopes() {
        let mut server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        let nested_scope = crate::Scope::new("/v1").with_route(crate::Route::new(
            Method::Get,
            "/users",
            |_req: crate::HttpRequest| {
                Box::pin(async move { Ok(crate::HttpResponse::ok().with_body("v1 users")) })
            },
        ));

        let scope = crate::Scope::new("/api")
            .with_route(crate::Route::new(
                Method::Get,
                "/health",
                |_req: crate::HttpRequest| {
                    Box::pin(async move { Ok(crate::HttpResponse::ok().with_body("healthy")) })
                },
            ))
            .with_scope(nested_scope)
            .with_route(crate::Route::new(
                Method::Post,
                "/auth",
                |_req: crate::HttpRequest| {
                    Box::pin(
                        async move { Ok(crate::HttpResponse::ok().with_body("authenticated")) },
                    )
                },
            ));

        server.register_scope(&scope);

        // Verify all routes were registered with correct full paths
        assert!(
            server
                .routes
                .contains_key(&(Method::Get, "/api/health".to_string()))
        );
        assert!(
            server
                .routes
                .contains_key(&(Method::Get, "/api/v1/users".to_string()))
        );
        assert!(
            server
                .routes
                .contains_key(&(Method::Post, "/api/auth".to_string()))
        );
        assert_eq!(server.routes.len(), 3);
    }

    #[test]
    fn test_register_scope_with_empty_prefix() {
        let mut server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        let scope = crate::Scope::new("").with_route(crate::Route::new(
            Method::Get,
            "/users",
            |_req: crate::HttpRequest| {
                Box::pin(async move { Ok(crate::HttpResponse::ok().with_body("users")) })
            },
        ));

        server.register_scope(&scope);

        // Verify the route was registered without prefix
        assert!(
            server
                .routes
                .contains_key(&(Method::Get, "/users".to_string()))
        );
        assert_eq!(server.routes.len(), 1);
    }

    #[test]
    fn test_register_scope_with_deeply_nested_scopes() {
        let mut server = SimulatorWebServer {
            static_files: None,
            scopes: Vec::new(),
            routes: BTreeMap::new(),
            state: Arc::new(RwLock::new(crate::extractors::state::StateContainer::new())),
        };

        // Create deeply nested scopes: /api/v1/admin/users
        let admin_scope = crate::Scope::new("/admin").with_route(crate::Route::new(
            Method::Delete,
            "/users/{id}",
            |_req: crate::HttpRequest| {
                Box::pin(async move { Ok(crate::HttpResponse::ok().with_body("user deleted")) })
            },
        ));

        let v1_scope = crate::Scope::new("/v1").with_scope(admin_scope);
        let api_scope = crate::Scope::new("/api").with_scope(v1_scope);

        server.register_scope(&api_scope);

        // Verify the deeply nested route was registered correctly
        assert!(
            server
                .routes
                .contains_key(&(Method::Delete, "/api/v1/admin/users/{id}".to_string()))
        );
        assert_eq!(server.routes.len(), 1);
    }

    // ==================== SimulationRequest Builder Tests ====================

    #[test]
    fn test_simulation_request_with_single_cookie() {
        let req = SimulationRequest::new(Method::Get, "/test").with_cookie("session_id", "abc123");

        assert_eq!(req.cookies.len(), 1);
        assert_eq!(req.cookies.get("session_id"), Some(&"abc123".to_string()));
    }

    #[test]
    fn test_simulation_request_with_multiple_cookies() {
        let cookies = vec![
            ("session_id".to_string(), "abc123".to_string()),
            ("user_pref".to_string(), "dark_mode".to_string()),
            ("tracking".to_string(), "opt_out".to_string()),
        ];

        let req = SimulationRequest::new(Method::Get, "/test").with_cookies(cookies);

        assert_eq!(req.cookies.len(), 3);
        assert_eq!(req.cookies.get("session_id"), Some(&"abc123".to_string()));
        assert_eq!(req.cookies.get("user_pref"), Some(&"dark_mode".to_string()));
        assert_eq!(req.cookies.get("tracking"), Some(&"opt_out".to_string()));
    }

    #[test]
    fn test_simulation_request_with_remote_addr() {
        let req =
            SimulationRequest::new(Method::Get, "/test").with_remote_addr("192.168.1.100:8080");

        assert_eq!(req.remote_addr, Some("192.168.1.100:8080".to_string()));
    }

    #[test]
    fn test_simulation_request_with_multiple_path_params() {
        let mut params = PathParams::new();
        params.insert("user_id".to_string(), "123".to_string());
        params.insert("post_id".to_string(), "456".to_string());

        let req = SimulationRequest::new(Method::Get, "/users/{user_id}/posts/{post_id}")
            .with_path_params(params);

        assert_eq!(req.path_params.len(), 2);
        assert_eq!(req.path_params.get("user_id"), Some(&"123".to_string()));
        assert_eq!(req.path_params.get("post_id"), Some(&"456".to_string()));
    }

    #[test]
    fn test_simulation_request_chained_builder() {
        let mut path_params = PathParams::new();
        path_params.insert("id".to_string(), "42".to_string());

        let req = SimulationRequest::new(Method::Post, "/api/resource")
            .with_query_string("format=json&pretty=true")
            .with_header("Content-Type", "application/json")
            .with_header("Authorization", "Bearer token123")
            .with_cookie("session", "xyz789")
            .with_remote_addr("10.0.0.1:12345")
            .with_path_params(path_params)
            .with_body(r#"{"name": "test"}"#);

        assert_eq!(req.method, Method::Post);
        assert_eq!(req.path, "/api/resource");
        assert_eq!(req.query_string, "format=json&pretty=true");
        assert_eq!(
            req.headers.get("Content-Type"),
            Some(&"application/json".to_string())
        );
        assert_eq!(
            req.headers.get("Authorization"),
            Some(&"Bearer token123".to_string())
        );
        assert_eq!(req.cookies.get("session"), Some(&"xyz789".to_string()));
        assert_eq!(req.remote_addr, Some("10.0.0.1:12345".to_string()));
        assert_eq!(req.path_params.get("id"), Some(&"42".to_string()));
        assert!(req.body.is_some());
    }

    // ==================== SimulationStub Access Tests ====================

    #[test]
    fn test_simulation_stub_cookie_access() {
        let req = SimulationRequest::new(Method::Get, "/test")
            .with_cookie("auth_token", "secret123")
            .with_cookie("user_id", "user_42");

        let stub = SimulationStub::new(req);

        assert_eq!(stub.cookie("auth_token"), Some("secret123"));
        assert_eq!(stub.cookie("user_id"), Some("user_42"));
        assert_eq!(stub.cookie("nonexistent"), None);
    }

    #[test]
    fn test_simulation_stub_cookies_returns_all() {
        let req = SimulationRequest::new(Method::Get, "/test")
            .with_cookie("a", "1")
            .with_cookie("b", "2")
            .with_cookie("c", "3");

        let stub = SimulationStub::new(req);
        let cookies = stub.cookies();

        assert_eq!(cookies.len(), 3);
        assert_eq!(cookies.get("a"), Some(&"1".to_string()));
        assert_eq!(cookies.get("b"), Some(&"2".to_string()));
        assert_eq!(cookies.get("c"), Some(&"3".to_string()));
    }

    #[test]
    fn test_simulation_stub_remote_addr_access() {
        let req = SimulationRequest::new(Method::Get, "/test").with_remote_addr("127.0.0.1:55555");

        let stub = SimulationStub::new(req);

        assert_eq!(stub.remote_addr(), Some("127.0.0.1:55555"));
    }

    #[test]
    fn test_simulation_stub_remote_addr_none() {
        let req = SimulationRequest::new(Method::Get, "/test");
        let stub = SimulationStub::new(req);

        assert_eq!(stub.remote_addr(), None);
    }

    #[test]
    fn test_simulation_stub_path_param_access() {
        let mut params = PathParams::new();
        params.insert("id".to_string(), "999".to_string());
        params.insert("action".to_string(), "edit".to_string());

        let req =
            SimulationRequest::new(Method::Get, "/resource/{id}/{action}").with_path_params(params);

        let stub = SimulationStub::new(req);

        assert_eq!(stub.path_param("id"), Some("999"));
        assert_eq!(stub.path_param("action"), Some("edit"));
        assert_eq!(stub.path_param("nonexistent"), None);
    }

    #[test]
    fn test_simulation_stub_with_state_container() {
        use crate::extractors::state::StateContainer;

        #[derive(Debug, Clone, PartialEq)]
        struct TestState {
            value: i32,
        }

        let req = SimulationRequest::new(Method::Get, "/test");
        let mut container = StateContainer::new();
        container.insert(TestState { value: 42 });

        let stub = SimulationStub::new(req).with_state_container(Arc::new(RwLock::new(container)));

        let retrieved_state = stub.state::<TestState>();
        assert!(retrieved_state.is_some());
        assert_eq!(retrieved_state.unwrap().value, 42);
    }

    #[test]
    fn test_simulation_stub_state_not_found() {
        use crate::extractors::state::StateContainer;

        #[derive(Debug, Clone)]
        struct UnregisteredState;

        let req = SimulationRequest::new(Method::Get, "/test");
        let container = StateContainer::new();

        let stub = SimulationStub::new(req).with_state_container(Arc::new(RwLock::new(container)));

        let result = stub.state::<UnregisteredState>();
        assert!(result.is_none());
    }

    #[test]
    fn test_simulation_stub_app_state_access() {
        use crate::extractors::state::StateContainer;

        let req = SimulationRequest::new(Method::Get, "/test");
        let container = Arc::new(RwLock::new(StateContainer::new()));

        let stub = SimulationStub::new(req).with_state_container(Arc::clone(&container));

        assert!(stub.app_state().is_some());
    }

    #[test]
    fn test_simulation_stub_app_state_none_when_not_set() {
        let req = SimulationRequest::new(Method::Get, "/test");
        let stub = SimulationStub::new(req);

        assert!(stub.app_state().is_none());
    }

    #[test]
    fn test_simulation_stub_from_simulation_request() {
        let req =
            SimulationRequest::new(Method::Post, "/api/data").with_header("X-Custom", "value");

        let stub: SimulationStub = req.into();

        assert_eq!(stub.method(), &Method::Post);
        assert_eq!(stub.path(), "/api/data");
        assert_eq!(stub.header("X-Custom"), Some("value"));
    }

    // ==================== Path Pattern Matching Edge Cases ====================

    #[test]
    fn test_match_path_with_multiple_parameters() {
        let pattern = parse_path_pattern("/users/{user_id}/posts/{post_id}/comments/{comment_id}");

        let result = match_path(&pattern, "/users/123/posts/456/comments/789");

        assert!(result.is_some());
        let params = result.unwrap();
        assert_eq!(params.get("user_id"), Some(&"123".to_string()));
        assert_eq!(params.get("post_id"), Some(&"456".to_string()));
        assert_eq!(params.get("comment_id"), Some(&"789".to_string()));
    }

    #[test]
    fn test_match_path_parameter_with_special_characters() {
        let pattern = parse_path_pattern("/files/{filename}");

        let result = match_path(&pattern, "/files/my-document_v2.pdf");

        assert!(result.is_some());
        let params = result.unwrap();
        assert_eq!(
            params.get("filename"),
            Some(&"my-document_v2.pdf".to_string())
        );
    }

    #[test]
    fn test_match_path_empty_parameter_value() {
        // This tests edge case where path segment is empty
        let pattern = parse_path_pattern("/api/{version}/resource");

        // Note: URL path /api//resource has empty segment which won't match
        let result = match_path(&pattern, "/api//resource");
        // Empty segments are filtered out, so this should not match
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_path_pattern_root_only() {
        let pattern = parse_path_pattern("/");

        assert!(pattern.segments().is_empty());
    }

    #[test]
    fn test_parse_path_pattern_single_parameter() {
        let pattern = parse_path_pattern("/{id}");

        assert_eq!(pattern.segments().len(), 1);
        assert_eq!(
            pattern.segments()[0],
            PathSegment::Parameter("id".to_string())
        );
    }

    #[test]
    fn test_parse_path_pattern_consecutive_literals() {
        let pattern = parse_path_pattern("/api/v1/users/list");

        assert_eq!(pattern.segments().len(), 4);
        assert!(
            pattern
                .segments()
                .iter()
                .all(|s| matches!(s, PathSegment::Literal(_)))
        );
    }

    // ==================== Static Files Tests ====================

    #[test]
    #[cfg(feature = "simulator")]
    fn test_get_mime_type_html() {
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.html"),
            "text/html; charset=utf-8"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.htm"),
            "text/html; charset=utf-8"
        );
    }

    #[test]
    #[cfg(feature = "simulator")]
    fn test_get_mime_type_css() {
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.css"),
            "text/css; charset=utf-8"
        );
    }

    #[test]
    #[cfg(feature = "simulator")]
    fn test_get_mime_type_javascript() {
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.js"),
            "application/javascript; charset=utf-8"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.mjs"),
            "application/javascript; charset=utf-8"
        );
    }

    #[test]
    #[cfg(feature = "simulator")]
    fn test_get_mime_type_json() {
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.json"),
            "application/json; charset=utf-8"
        );
    }

    #[test]
    #[cfg(feature = "simulator")]
    fn test_get_mime_type_images() {
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.png"),
            "image/png"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.jpg"),
            "image/jpeg"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.jpeg"),
            "image/jpeg"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.gif"),
            "image/gif"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.svg"),
            "image/svg+xml"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.webp"),
            "image/webp"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.ico"),
            "image/x-icon"
        );
    }

    #[test]
    #[cfg(feature = "simulator")]
    fn test_get_mime_type_fonts() {
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.woff"),
            "font/woff"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.woff2"),
            "font/woff2"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.ttf"),
            "font/ttf"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.otf"),
            "font/otf"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.eot"),
            "application/vnd.ms-fontobject"
        );
    }

    #[test]
    #[cfg(feature = "simulator")]
    fn test_get_mime_type_other() {
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.txt"),
            "text/plain; charset=utf-8"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.xml"),
            "application/xml; charset=utf-8"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.pdf"),
            "application/pdf"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.map"),
            "application/json"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.wasm"),
            "application/wasm"
        );
    }

    #[test]
    #[cfg(feature = "simulator")]
    fn test_get_mime_type_unknown() {
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.unknown"),
            "application/octet-stream"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file"),
            "application/octet-stream"
        );
    }

    #[test]
    #[cfg(feature = "simulator")]
    fn test_get_mime_type_case_insensitive() {
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.HTML"),
            "text/html; charset=utf-8"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.CSS"),
            "text/css; charset=utf-8"
        );
        assert_eq!(
            SimulatorWebServer::get_mime_type("/path/file.PNG"),
            "image/png"
        );
    }

    #[test]
    fn test_simulator_static_files_none_by_default() {
        let server = SimulatorWebServer::new(Vec::new());
        assert!(server.static_files().is_none());
    }

    #[test]
    fn test_simulator_with_static_files_constructor() {
        let config = crate::StaticFiles::new("/static", "./public");
        let server = SimulatorWebServer::with_static_files(Vec::new(), config);

        let sf = server.static_files().unwrap();
        assert_eq!(sf.mount_path(), "/static");
        assert_eq!(sf.directory(), &std::path::PathBuf::from("./public"));
    }

    #[test]
    fn test_web_server_builder_static_files() {
        let builder = crate::WebServerBuilder::new()
            .with_static_files(crate::StaticFiles::new("/assets", "./dist"));

        let sf = builder.static_files().unwrap();
        assert_eq!(sf.mount_path(), "/assets");
        assert_eq!(sf.directory(), &std::path::PathBuf::from("./dist"));
    }

    #[test]
    fn test_web_server_builder_static_files_none_by_default() {
        let builder = crate::WebServerBuilder::new();
        assert!(builder.static_files().is_none());
    }
}