lonkero 3.7.0

Web scanner built for actual pentests. Fast, modular, Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
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
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
// Copyright (c) 2026 Bountyy Oy. All rights reserved.
// This software is proprietary and confidential.

//! Session Recording Module for Browser Session Capture and Replay
//!
//! This module provides comprehensive session recording capabilities for the
//! headless browser crawler, enabling:
//! - Full network request/response capture in HAR format
//! - DOM interaction recording (clicks, form submissions, scrolls)
//! - Console message and error capture
//! - Screenshot capture at key points
//! - Session replay for debugging vulnerabilities
//!
//! # Example
//!
//! ```rust,ignore
//! use lonkero_scanner::session_recording::{SessionRecorder, SessionExporter, ExportFormat};
//!
//! // Create a recorder
//! let recorder = SessionRecorder::new();
//! recorder.start();
//!
//! // Record events during crawl...
//! recorder.record_navigation("https://example.com".to_string());
//! recorder.record_network_request(request_event);
//!
//! // Export the recording
//! let recording = recorder.stop();
//! let exporter = SessionExporter::new(&recording);
//! let har = exporter.export(ExportFormat::Har)?;
//! ```

use anyhow::{Context, Result};
use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
use chrono::{DateTime, Utc};
use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use flate2::Compression;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{Read, Write};
use std::sync::{Arc, Mutex, RwLock};
use std::time::Instant;
use tracing::{debug, info, warn};

// ============================================================================
// Core Types
// ============================================================================

/// Type of session event captured during recording
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum SessionEventType {
    /// Page navigation (URL change)
    Navigation,
    /// Network request initiated
    NetworkRequest,
    /// Network response received
    NetworkResponse,
    /// Network request failed
    NetworkError,
    /// DOM click event
    Click,
    /// Form field input
    Input,
    /// Form submission
    FormSubmit,
    /// Page scroll
    Scroll,
    /// Console message
    ConsoleMessage,
    /// JavaScript error
    JsError,
    /// Screenshot captured
    Screenshot,
    /// Cookie set/modified
    CookieChange,
    /// Local/session storage change
    StorageChange,
    /// WebSocket message
    WebSocketMessage,
    /// Custom marker event (for debugging)
    Marker,
}

/// Severity level for console messages and errors
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ConsoleSeverity {
    Log,
    Info,
    Warning,
    Error,
    Debug,
}

/// HTTP method for network requests
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum HttpMethod {
    Get,
    Post,
    Put,
    Patch,
    Delete,
    Head,
    Options,
    Connect,
    Trace,
    /// Unknown HTTP method - preserves the original method string
    #[serde(other)]
    Unknown,
}

impl std::fmt::Display for HttpMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HttpMethod::Get => write!(f, "GET"),
            HttpMethod::Post => write!(f, "POST"),
            HttpMethod::Put => write!(f, "PUT"),
            HttpMethod::Patch => write!(f, "PATCH"),
            HttpMethod::Delete => write!(f, "DELETE"),
            HttpMethod::Head => write!(f, "HEAD"),
            HttpMethod::Options => write!(f, "OPTIONS"),
            HttpMethod::Connect => write!(f, "CONNECT"),
            HttpMethod::Trace => write!(f, "TRACE"),
            HttpMethod::Unknown => write!(f, "UNKNOWN"),
        }
    }
}

impl From<&str> for HttpMethod {
    fn from(s: &str) -> Self {
        match s.to_uppercase().as_str() {
            "GET" => HttpMethod::Get,
            "POST" => HttpMethod::Post,
            "PUT" => HttpMethod::Put,
            "PATCH" => HttpMethod::Patch,
            "DELETE" => HttpMethod::Delete,
            "HEAD" => HttpMethod::Head,
            "OPTIONS" => HttpMethod::Options,
            "CONNECT" => HttpMethod::Connect,
            "TRACE" => HttpMethod::Trace,
            other => {
                debug!("Unknown HTTP method encountered: {}", other);
                HttpMethod::Unknown
            }
        }
    }
}

/// Network request details captured during recording
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkRequest {
    /// Unique request ID for correlation with response
    pub request_id: String,
    /// Request URL
    pub url: String,
    /// HTTP method
    pub method: HttpMethod,
    /// Request headers
    pub headers: HashMap<String, String>,
    /// Request body (if applicable)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    /// Content-Type of request body
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,
    /// Size of request in bytes
    pub size: usize,
    /// Timestamp when request was initiated
    pub timestamp: DateTime<Utc>,
    /// Initiator type (script, link, fetch, etc.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub initiator: Option<String>,
    /// Stack trace of request origin (for debugging)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stack_trace: Option<String>,
}

/// Network response details captured during recording
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkResponse {
    /// Request ID for correlation
    pub request_id: String,
    /// HTTP status code
    pub status_code: u16,
    /// Status text (e.g., "OK", "Not Found")
    pub status_text: String,
    /// Response headers
    pub headers: HashMap<String, String>,
    /// Response body (may be truncated for large responses)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    /// Whether body was truncated
    pub body_truncated: bool,
    /// Content-Type of response
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,
    /// Size of response in bytes
    pub size: usize,
    /// Time to first byte (ms)
    pub ttfb_ms: u64,
    /// Total response time (ms)
    pub duration_ms: u64,
    /// Timestamp when response was received
    pub timestamp: DateTime<Utc>,
    /// Whether response came from cache
    pub from_cache: bool,
}

/// Network error details
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkError {
    /// Request ID for correlation
    pub request_id: String,
    /// Error type (dns, connection, timeout, etc.)
    pub error_type: String,
    /// Error message
    pub message: String,
    /// Timestamp
    pub timestamp: DateTime<Utc>,
}

/// DOM interaction details
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DomInteraction {
    /// Type of interaction
    pub interaction_type: DomInteractionType,
    /// CSS selector of target element
    pub selector: String,
    /// XPath of target element (for precise replay)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub xpath: Option<String>,
    /// Element tag name
    pub tag_name: String,
    /// Element ID (if any)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub element_id: Option<String>,
    /// Element classes
    #[serde(default)]
    pub classes: Vec<String>,
    /// Element text content (truncated)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_content: Option<String>,
    /// Input value (for input events)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_value: Option<String>,
    /// Scroll position (for scroll events)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scroll_position: Option<ScrollPosition>,
    /// Click coordinates (for click events)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coordinates: Option<ClickCoordinates>,
    /// Timestamp
    pub timestamp: DateTime<Utc>,
}

/// Type of DOM interaction
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum DomInteractionType {
    Click,
    DoubleClick,
    RightClick,
    Input,
    Focus,
    Blur,
    Submit,
    Scroll,
    Hover,
    KeyPress,
}

/// Scroll position details
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScrollPosition {
    pub x: i32,
    pub y: i32,
    pub max_x: i32,
    pub max_y: i32,
}

/// Click coordinates
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClickCoordinates {
    pub x: i32,
    pub y: i32,
    pub viewport_x: i32,
    pub viewport_y: i32,
}

/// Console message details
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConsoleMessage {
    /// Message severity level
    pub severity: ConsoleSeverity,
    /// Message text
    pub text: String,
    /// Source URL where message originated
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_url: Option<String>,
    /// Line number in source
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line_number: Option<u32>,
    /// Column number in source
    #[serde(skip_serializing_if = "Option::is_none")]
    pub column_number: Option<u32>,
    /// Stack trace (for errors)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stack_trace: Option<String>,
    /// Timestamp
    pub timestamp: DateTime<Utc>,
}

/// Screenshot captured during recording
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Screenshot {
    /// Unique screenshot ID
    pub id: String,
    /// Base64-encoded PNG image data
    pub data: String,
    /// Image format (always "png")
    pub format: String,
    /// Image width
    pub width: u32,
    /// Image height
    pub height: u32,
    /// Description/context for the screenshot
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// URL at time of capture
    pub url: String,
    /// Timestamp
    pub timestamp: DateTime<Utc>,
}

/// Navigation event details
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NavigationEvent {
    /// Navigation URL
    pub url: String,
    /// Previous URL (if any)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_url: Option<String>,
    /// Navigation type (link, typed, back_forward, reload)
    pub navigation_type: NavigationType,
    /// HTTP status code of navigation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_code: Option<u16>,
    /// Page title after navigation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Time to load page (ms)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub load_time_ms: Option<u64>,
    /// Timestamp
    pub timestamp: DateTime<Utc>,
}

/// Type of navigation
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum NavigationType {
    Link,
    Typed,
    FormSubmit,
    BackForward,
    Reload,
    Redirect,
    Script,
    Other,
}

/// Cookie change event
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CookieChange {
    /// Cookie name
    pub name: String,
    /// Cookie value (may be redacted for security)
    pub value: String,
    /// Cookie domain
    pub domain: String,
    /// Cookie path
    pub path: String,
    /// Whether cookie is secure
    pub secure: bool,
    /// Whether cookie is HTTP-only
    pub http_only: bool,
    /// Cookie expiry (if set)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires: Option<DateTime<Utc>>,
    /// Whether this is a deletion
    pub deleted: bool,
    /// Timestamp
    pub timestamp: DateTime<Utc>,
}

/// Storage change event (localStorage/sessionStorage)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StorageChange {
    /// Storage type
    pub storage_type: StorageType,
    /// Key that changed
    pub key: String,
    /// New value (None if deleted)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_value: Option<String>,
    /// Old value (None if new key)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub old_value: Option<String>,
    /// URL where change occurred
    pub url: String,
    /// Timestamp
    pub timestamp: DateTime<Utc>,
}

/// Type of web storage
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum StorageType {
    LocalStorage,
    SessionStorage,
}

/// WebSocket message event
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WebSocketEvent {
    /// WebSocket URL
    pub url: String,
    /// Message direction
    pub direction: WebSocketDirection,
    /// Message data (may be truncated)
    pub data: String,
    /// Whether data was truncated
    pub truncated: bool,
    /// Whether data is binary (base64-encoded if so)
    pub is_binary: bool,
    /// Message size in bytes
    pub size: usize,
    /// Timestamp
    pub timestamp: DateTime<Utc>,
}

/// WebSocket message direction
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum WebSocketDirection {
    Sent,
    Received,
}

/// Single session event with all possible data
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionEvent {
    /// Unique event ID
    pub id: String,
    /// Event type
    pub event_type: SessionEventType,
    /// Timestamp when event occurred
    pub timestamp: DateTime<Utc>,
    /// Milliseconds since recording started
    pub offset_ms: u64,
    /// Current page URL at time of event
    pub current_url: String,

    // Event-specific data (only one will be present based on event_type)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub navigation: Option<NavigationEvent>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub network_request: Option<NetworkRequest>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub network_response: Option<NetworkResponse>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub network_error: Option<NetworkError>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dom_interaction: Option<DomInteraction>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub console_message: Option<ConsoleMessage>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub screenshot: Option<Screenshot>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cookie_change: Option<CookieChange>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub storage_change: Option<StorageChange>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub websocket_event: Option<WebSocketEvent>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub marker_label: Option<String>,
}

impl SessionEvent {
    /// Create a new navigation event
    pub fn navigation(
        id: String,
        offset_ms: u64,
        current_url: String,
        navigation: NavigationEvent,
    ) -> Self {
        Self {
            id,
            event_type: SessionEventType::Navigation,
            timestamp: Utc::now(),
            offset_ms,
            current_url,
            navigation: Some(navigation),
            network_request: None,
            network_response: None,
            network_error: None,
            dom_interaction: None,
            console_message: None,
            screenshot: None,
            cookie_change: None,
            storage_change: None,
            websocket_event: None,
            marker_label: None,
        }
    }

    /// Create a new network request event
    pub fn network_request(
        id: String,
        offset_ms: u64,
        current_url: String,
        request: NetworkRequest,
    ) -> Self {
        Self {
            id,
            event_type: SessionEventType::NetworkRequest,
            timestamp: Utc::now(),
            offset_ms,
            current_url,
            navigation: None,
            network_request: Some(request),
            network_response: None,
            network_error: None,
            dom_interaction: None,
            console_message: None,
            screenshot: None,
            cookie_change: None,
            storage_change: None,
            websocket_event: None,
            marker_label: None,
        }
    }

    /// Create a new network response event
    pub fn network_response(
        id: String,
        offset_ms: u64,
        current_url: String,
        response: NetworkResponse,
    ) -> Self {
        Self {
            id,
            event_type: SessionEventType::NetworkResponse,
            timestamp: Utc::now(),
            offset_ms,
            current_url,
            navigation: None,
            network_request: None,
            network_response: Some(response),
            network_error: None,
            dom_interaction: None,
            console_message: None,
            screenshot: None,
            cookie_change: None,
            storage_change: None,
            websocket_event: None,
            marker_label: None,
        }
    }

    /// Create a new DOM interaction event
    pub fn dom_interaction(
        id: String,
        offset_ms: u64,
        current_url: String,
        interaction: DomInteraction,
    ) -> Self {
        let event_type = match interaction.interaction_type {
            DomInteractionType::Click
            | DomInteractionType::DoubleClick
            | DomInteractionType::RightClick => SessionEventType::Click,
            DomInteractionType::Input | DomInteractionType::KeyPress => SessionEventType::Input,
            DomInteractionType::Submit => SessionEventType::FormSubmit,
            DomInteractionType::Scroll => SessionEventType::Scroll,
            _ => SessionEventType::Click,
        };

        Self {
            id,
            event_type,
            timestamp: Utc::now(),
            offset_ms,
            current_url,
            navigation: None,
            network_request: None,
            network_response: None,
            network_error: None,
            dom_interaction: Some(interaction),
            console_message: None,
            screenshot: None,
            cookie_change: None,
            storage_change: None,
            websocket_event: None,
            marker_label: None,
        }
    }

    /// Create a new console message event
    pub fn console_message(
        id: String,
        offset_ms: u64,
        current_url: String,
        message: ConsoleMessage,
    ) -> Self {
        let event_type = if message.severity == ConsoleSeverity::Error {
            SessionEventType::JsError
        } else {
            SessionEventType::ConsoleMessage
        };

        Self {
            id,
            event_type,
            timestamp: Utc::now(),
            offset_ms,
            current_url,
            navigation: None,
            network_request: None,
            network_response: None,
            network_error: None,
            dom_interaction: None,
            console_message: Some(message),
            screenshot: None,
            cookie_change: None,
            storage_change: None,
            websocket_event: None,
            marker_label: None,
        }
    }

    /// Create a new screenshot event
    pub fn screenshot(
        id: String,
        offset_ms: u64,
        current_url: String,
        screenshot: Screenshot,
    ) -> Self {
        Self {
            id,
            event_type: SessionEventType::Screenshot,
            timestamp: Utc::now(),
            offset_ms,
            current_url,
            navigation: None,
            network_request: None,
            network_response: None,
            network_error: None,
            dom_interaction: None,
            console_message: None,
            screenshot: Some(screenshot),
            cookie_change: None,
            storage_change: None,
            websocket_event: None,
            marker_label: None,
        }
    }

    /// Create a marker event for debugging
    pub fn marker(id: String, offset_ms: u64, current_url: String, label: String) -> Self {
        Self {
            id,
            event_type: SessionEventType::Marker,
            timestamp: Utc::now(),
            offset_ms,
            current_url,
            navigation: None,
            network_request: None,
            network_response: None,
            network_error: None,
            dom_interaction: None,
            console_message: None,
            screenshot: None,
            cookie_change: None,
            storage_change: None,
            websocket_event: None,
            marker_label: Some(label),
        }
    }
}

/// Full session recording containing all events
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionRecording {
    /// Unique recording ID
    pub id: String,
    /// Session name/description
    pub name: String,
    /// Start URL of the recording
    pub start_url: String,
    /// Recording start time
    pub started_at: DateTime<Utc>,
    /// Recording end time (None if still recording)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ended_at: Option<DateTime<Utc>>,
    /// Total duration in milliseconds
    pub duration_ms: u64,
    /// All recorded events
    pub events: Vec<SessionEvent>,
    /// Total number of events
    pub event_count: usize,
    /// Recording metadata
    pub metadata: RecordingMetadata,
    /// Recording statistics
    pub stats: RecordingStats,
}

/// Metadata about the recording
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecordingMetadata {
    /// Scanner version
    pub scanner_version: String,
    /// Browser user agent
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_agent: Option<String>,
    /// Viewport width
    pub viewport_width: u32,
    /// Viewport height
    pub viewport_height: u32,
    /// Recording settings
    pub settings: RecordingSettings,
    /// Custom tags/labels
    #[serde(default)]
    pub tags: Vec<String>,
}

/// Recording settings
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecordingSettings {
    /// Whether to capture request/response bodies
    pub capture_bodies: bool,
    /// Maximum body size to capture (bytes)
    pub max_body_size: usize,
    /// Whether to capture screenshots
    pub capture_screenshots: bool,
    /// Screenshot capture frequency (key events only, interval, etc.)
    pub screenshot_mode: ScreenshotMode,
    /// Whether to capture console messages
    pub capture_console: bool,
    /// Whether to redact sensitive data (passwords, tokens)
    pub redact_sensitive: bool,
    /// Whether to capture DOM interactions
    pub capture_dom_interactions: bool,
    /// Whether to capture storage changes
    pub capture_storage: bool,
}

impl Default for RecordingSettings {
    fn default() -> Self {
        Self {
            capture_bodies: true,
            max_body_size: 1024 * 1024, // 1MB
            capture_screenshots: true,
            screenshot_mode: ScreenshotMode::KeyEvents,
            capture_console: true,
            redact_sensitive: true,
            capture_dom_interactions: true,
            capture_storage: true,
        }
    }
}

/// Screenshot capture mode
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ScreenshotMode {
    /// Capture only on navigation and errors
    KeyEvents,
    /// Capture at fixed intervals (ms)
    Interval(u64),
    /// Capture on every DOM interaction
    AllInteractions,
    /// Disabled
    None,
}

/// Statistics about the recording
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecordingStats {
    /// Total number of navigations
    pub navigations: usize,
    /// Total number of network requests
    pub network_requests: usize,
    /// Total number of network errors
    pub network_errors: usize,
    /// Total number of DOM interactions
    pub dom_interactions: usize,
    /// Total number of console messages
    pub console_messages: usize,
    /// Total number of errors/warnings
    pub errors: usize,
    /// Total number of screenshots
    pub screenshots: usize,
    /// Total data transferred (bytes)
    pub bytes_transferred: usize,
    /// Number of unique URLs visited
    pub unique_urls: usize,
}

// ============================================================================
// Session Recorder
// ============================================================================

/// State of the session recorder
#[derive(Debug, Clone, PartialEq)]
pub enum RecorderState {
    Idle,
    Recording,
    Paused,
    Stopped,
}

/// Session recorder that captures browser events during a scan
pub struct SessionRecorder {
    /// Current state
    state: Arc<RwLock<RecorderState>>,
    /// Recording settings
    settings: RecordingSettings,
    /// Start time of recording
    start_time: Arc<RwLock<Option<Instant>>>,
    /// Start URL
    start_url: Arc<RwLock<String>>,
    /// Current URL (updated during recording)
    current_url: Arc<RwLock<String>>,
    /// Recorded events
    events: Arc<Mutex<Vec<SessionEvent>>>,
    /// Event counter for ID generation
    event_counter: Arc<std::sync::atomic::AtomicU64>,
    /// Pending network requests (for correlating with responses)
    pending_requests: Arc<Mutex<HashMap<String, Instant>>>,
    /// Statistics
    stats: Arc<Mutex<RecordingStats>>,
    /// Unique URLs seen
    unique_urls: Arc<Mutex<std::collections::HashSet<String>>>,
}

impl SessionRecorder {
    // ========================================================================
    // Lock Recovery Helpers - Handle poisoned locks gracefully
    // ========================================================================

    /// Access events with lock poisoning recovery
    fn with_events<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&mut Vec<SessionEvent>) -> R,
    {
        match self.events.lock() {
            Ok(mut guard) => f(&mut guard),
            Err(poisoned) => {
                warn!("[SessionRecorder] Events mutex poisoned, recovering");
                f(&mut poisoned.into_inner())
            }
        }
    }

    /// Access stats with lock poisoning recovery
    fn with_stats<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&mut RecordingStats) -> R,
    {
        match self.stats.lock() {
            Ok(mut guard) => f(&mut guard),
            Err(poisoned) => {
                warn!("[SessionRecorder] Stats mutex poisoned, recovering");
                f(&mut poisoned.into_inner())
            }
        }
    }

    /// Access pending_requests with lock poisoning recovery
    fn with_pending_requests<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&mut HashMap<String, Instant>) -> R,
    {
        match self.pending_requests.lock() {
            Ok(mut guard) => f(&mut guard),
            Err(poisoned) => {
                warn!("[SessionRecorder] Pending requests mutex poisoned, recovering");
                f(&mut poisoned.into_inner())
            }
        }
    }

    /// Access unique_urls with lock poisoning recovery
    fn with_unique_urls<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&mut std::collections::HashSet<String>) -> R,
    {
        match self.unique_urls.lock() {
            Ok(mut guard) => f(&mut guard),
            Err(poisoned) => {
                warn!("[SessionRecorder] Unique URLs mutex poisoned, recovering");
                f(&mut poisoned.into_inner())
            }
        }
    }

    /// Read state with lock poisoning recovery
    fn read_state(&self) -> RecorderState {
        match self.state.read() {
            Ok(guard) => guard.clone(),
            Err(poisoned) => {
                warn!("[SessionRecorder] State RwLock poisoned, recovering");
                poisoned.into_inner().clone()
            }
        }
    }

    /// Write state with lock poisoning recovery
    fn with_state_write<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&mut RecorderState) -> R,
    {
        match self.state.write() {
            Ok(mut guard) => f(&mut guard),
            Err(poisoned) => {
                warn!("[SessionRecorder] State RwLock poisoned, recovering");
                f(&mut poisoned.into_inner())
            }
        }
    }

    /// Read start_time with lock poisoning recovery
    fn read_start_time(&self) -> Option<Instant> {
        match self.start_time.read() {
            Ok(guard) => *guard,
            Err(poisoned) => {
                warn!("[SessionRecorder] Start time RwLock poisoned, recovering");
                *poisoned.into_inner()
            }
        }
    }

    /// Write start_time with lock poisoning recovery
    fn write_start_time(&self, value: Option<Instant>) {
        match self.start_time.write() {
            Ok(mut guard) => *guard = value,
            Err(poisoned) => {
                warn!("[SessionRecorder] Start time RwLock poisoned, recovering");
                *poisoned.into_inner() = value;
            }
        }
    }

    /// Read start_url with lock poisoning recovery
    fn read_start_url(&self) -> String {
        match self.start_url.read() {
            Ok(guard) => guard.clone(),
            Err(poisoned) => {
                warn!("[SessionRecorder] Start URL RwLock poisoned, recovering");
                poisoned.into_inner().clone()
            }
        }
    }

    /// Write start_url with lock poisoning recovery
    fn write_start_url(&self, value: String) {
        match self.start_url.write() {
            Ok(mut guard) => *guard = value,
            Err(poisoned) => {
                warn!("[SessionRecorder] Start URL RwLock poisoned, recovering");
                *poisoned.into_inner() = value;
            }
        }
    }

    /// Read current_url with lock poisoning recovery
    fn read_current_url(&self) -> String {
        match self.current_url.read() {
            Ok(guard) => guard.clone(),
            Err(poisoned) => {
                warn!("[SessionRecorder] Current URL RwLock poisoned, recovering");
                poisoned.into_inner().clone()
            }
        }
    }

    /// Write current_url with lock poisoning recovery
    fn write_current_url(&self, value: String) {
        match self.current_url.write() {
            Ok(mut guard) => *guard = value,
            Err(poisoned) => {
                warn!("[SessionRecorder] Current URL RwLock poisoned, recovering");
                *poisoned.into_inner() = value;
            }
        }
    }

    // ========================================================================
    // Public API
    // ========================================================================

    /// Create a new session recorder with default settings
    pub fn new() -> Self {
        Self::with_settings(RecordingSettings::default())
    }

    /// Create a new session recorder with custom settings
    pub fn with_settings(settings: RecordingSettings) -> Self {
        Self {
            state: Arc::new(RwLock::new(RecorderState::Idle)),
            settings,
            start_time: Arc::new(RwLock::new(None)),
            start_url: Arc::new(RwLock::new(String::new())),
            current_url: Arc::new(RwLock::new(String::new())),
            events: Arc::new(Mutex::new(Vec::new())),
            event_counter: Arc::new(std::sync::atomic::AtomicU64::new(0)),
            pending_requests: Arc::new(Mutex::new(HashMap::new())),
            stats: Arc::new(Mutex::new(RecordingStats::default())),
            unique_urls: Arc::new(Mutex::new(std::collections::HashSet::new())),
        }
    }

    /// Get the current recorder state
    pub fn state(&self) -> RecorderState {
        self.read_state()
    }

    /// Check if currently recording
    pub fn is_recording(&self) -> bool {
        matches!(self.read_state(), RecorderState::Recording)
    }

    /// Start recording
    pub fn start(&self, start_url: &str) {
        let current_state = self.read_state();
        if current_state != RecorderState::Idle && current_state != RecorderState::Stopped {
            warn!(
                "[SessionRecorder] Cannot start recording, current state: {:?}",
                current_state
            );
            return;
        }

        self.with_state_write(|state| *state = RecorderState::Recording);
        self.write_start_time(Some(Instant::now()));
        self.write_start_url(start_url.to_string());
        self.write_current_url(start_url.to_string());
        self.with_events(|events| events.clear());
        self.with_stats(|stats| *stats = RecordingStats::default());
        self.with_unique_urls(|urls| {
            urls.clear();
            urls.insert(start_url.to_string());
        });
        self.event_counter
            .store(0, std::sync::atomic::Ordering::SeqCst);

        info!("[SessionRecorder] Started recording: {}", start_url);
    }

    /// Pause recording
    pub fn pause(&self) {
        self.with_state_write(|state| {
            if *state == RecorderState::Recording {
                *state = RecorderState::Paused;
                debug!("[SessionRecorder] Recording paused");
            }
        });
    }

    /// Resume recording
    pub fn resume(&self) {
        self.with_state_write(|state| {
            if *state == RecorderState::Paused {
                *state = RecorderState::Recording;
                debug!("[SessionRecorder] Recording resumed");
            }
        });
    }

    /// Stop recording and return the session recording
    pub fn stop(&self) -> SessionRecording {
        self.with_state_write(|state| *state = RecorderState::Stopped);

        let start_time = self.read_start_time();
        let duration_ms = start_time
            .map(|t| t.elapsed().as_millis() as u64)
            .unwrap_or(0);

        let events = self.with_events(|events| events.clone());
        let stats = self.with_stats(|stats| stats.clone());
        let unique_urls_count = self.with_unique_urls(|urls| urls.len());

        let mut final_stats = stats;
        final_stats.unique_urls = unique_urls_count;

        let recording = SessionRecording {
            id: uuid::Uuid::new_v4().to_string(),
            name: format!(
                "Recording {}",
                chrono::Utc::now().format("%Y-%m-%d %H:%M:%S")
            ),
            start_url: self.read_start_url(),
            started_at: chrono::Utc::now() - chrono::Duration::milliseconds(duration_ms as i64),
            ended_at: Some(chrono::Utc::now()),
            duration_ms,
            event_count: events.len(),
            events,
            metadata: RecordingMetadata {
                scanner_version: env!("CARGO_PKG_VERSION").to_string(),
                user_agent: None,
                viewport_width: 1920,
                viewport_height: 1080,
                settings: self.settings.clone(),
                tags: Vec::new(),
            },
            stats: final_stats,
        };

        info!(
            "[SessionRecorder] Recording stopped: {} events, {} ms",
            recording.event_count, recording.duration_ms
        );

        recording
    }

    /// Get the offset in milliseconds since recording started
    fn offset_ms(&self) -> u64 {
        self.read_start_time()
            .map(|t| t.elapsed().as_millis() as u64)
            .unwrap_or(0)
    }

    /// Generate a unique event ID
    fn next_event_id(&self) -> String {
        let counter = self
            .event_counter
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        format!("evt_{}", counter)
    }

    /// Get current URL
    fn get_current_url(&self) -> String {
        self.read_current_url()
    }

    /// Update current URL
    fn set_current_url(&self, url: &str) {
        self.write_current_url(url.to_string());
        self.with_unique_urls(|urls| {
            urls.insert(url.to_string());
        });
    }

    /// Record a navigation event
    pub fn record_navigation(&self, nav: NavigationEvent) {
        if !self.is_recording() {
            return;
        }

        self.set_current_url(&nav.url);

        let event =
            SessionEvent::navigation(self.next_event_id(), self.offset_ms(), nav.url.clone(), nav);

        self.with_events(|events| events.push(event));
        self.with_stats(|stats| stats.navigations += 1);
        debug!("[SessionRecorder] Recorded navigation");
    }

    /// Record a network request
    pub fn record_network_request(&self, request: NetworkRequest) {
        if !self.is_recording() {
            return;
        }

        // Track pending request for response correlation
        self.with_pending_requests(|pending| {
            pending.insert(request.request_id.clone(), Instant::now());
        });

        let current_url = self.get_current_url();
        let event = SessionEvent::network_request(
            self.next_event_id(),
            self.offset_ms(),
            current_url,
            request,
        );

        self.with_events(|events| events.push(event));
        self.with_stats(|stats| stats.network_requests += 1);
    }

    /// Record a network response
    pub fn record_network_response(&self, mut response: NetworkResponse) {
        if !self.is_recording() {
            return;
        }

        // Calculate duration from pending request
        if let Some(start) = self.with_pending_requests(|pending| pending.remove(&response.request_id)) {
            response.duration_ms = start.elapsed().as_millis() as u64;
        }

        // Update bytes transferred
        self.with_stats(|stats| stats.bytes_transferred += response.size);

        let current_url = self.get_current_url();
        let event = SessionEvent::network_response(
            self.next_event_id(),
            self.offset_ms(),
            current_url,
            response,
        );

        self.with_events(|events| events.push(event));
    }

    /// Record a network error
    pub fn record_network_error(&self, error: NetworkError) {
        if !self.is_recording() {
            return;
        }

        self.with_pending_requests(|pending| pending.remove(&error.request_id));

        let current_url = self.get_current_url();
        let event = SessionEvent {
            id: self.next_event_id(),
            event_type: SessionEventType::NetworkError,
            timestamp: Utc::now(),
            offset_ms: self.offset_ms(),
            current_url,
            network_error: Some(error),
            navigation: None,
            network_request: None,
            network_response: None,
            dom_interaction: None,
            console_message: None,
            screenshot: None,
            cookie_change: None,
            storage_change: None,
            websocket_event: None,
            marker_label: None,
        };

        self.with_events(|events| events.push(event));
        self.with_stats(|stats| stats.network_errors += 1);
    }

    /// Record a DOM interaction
    pub fn record_dom_interaction(&self, interaction: DomInteraction) {
        if !self.is_recording() || !self.settings.capture_dom_interactions {
            return;
        }

        let current_url = self.get_current_url();
        let event = SessionEvent::dom_interaction(
            self.next_event_id(),
            self.offset_ms(),
            current_url,
            interaction,
        );

        self.with_events(|events| events.push(event));
        self.with_stats(|stats| stats.dom_interactions += 1);
    }

    /// Record a console message
    pub fn record_console_message(&self, message: ConsoleMessage) {
        if !self.is_recording() || !self.settings.capture_console {
            return;
        }

        if message.severity == ConsoleSeverity::Error
            || message.severity == ConsoleSeverity::Warning
        {
            self.with_stats(|stats| stats.errors += 1);
        }

        let current_url = self.get_current_url();
        let event = SessionEvent::console_message(
            self.next_event_id(),
            self.offset_ms(),
            current_url,
            message,
        );

        self.with_events(|events| events.push(event));
        self.with_stats(|stats| stats.console_messages += 1);
    }

    /// Record a screenshot
    pub fn record_screenshot(&self, data: Vec<u8>, description: Option<String>) {
        if !self.is_recording() || !self.settings.capture_screenshots {
            return;
        }

        let current_url = self.get_current_url();
        let screenshot = Screenshot {
            id: uuid::Uuid::new_v4().to_string(),
            data: BASE64.encode(&data),
            format: "png".to_string(),
            width: 0, // Would be set from actual image dimensions
            height: 0,
            description,
            url: current_url.clone(),
            timestamp: Utc::now(),
        };

        let event = SessionEvent::screenshot(
            self.next_event_id(),
            self.offset_ms(),
            current_url,
            screenshot,
        );

        self.with_events(|events| events.push(event));
        self.with_stats(|stats| stats.screenshots += 1);
    }

    /// Record a cookie change
    pub fn record_cookie_change(&self, cookie: CookieChange) {
        if !self.is_recording() {
            return;
        }

        let current_url = self.get_current_url();
        let event = SessionEvent {
            id: self.next_event_id(),
            event_type: SessionEventType::CookieChange,
            timestamp: Utc::now(),
            offset_ms: self.offset_ms(),
            current_url,
            cookie_change: Some(cookie),
            navigation: None,
            network_request: None,
            network_response: None,
            network_error: None,
            dom_interaction: None,
            console_message: None,
            screenshot: None,
            storage_change: None,
            websocket_event: None,
            marker_label: None,
        };

        self.with_events(|events| events.push(event));
    }

    /// Record a storage change
    pub fn record_storage_change(&self, change: StorageChange) {
        if !self.is_recording() || !self.settings.capture_storage {
            return;
        }

        let current_url = self.get_current_url();
        let event = SessionEvent {
            id: self.next_event_id(),
            event_type: SessionEventType::StorageChange,
            timestamp: Utc::now(),
            offset_ms: self.offset_ms(),
            current_url,
            storage_change: Some(change),
            navigation: None,
            network_request: None,
            network_response: None,
            network_error: None,
            dom_interaction: None,
            console_message: None,
            screenshot: None,
            cookie_change: None,
            websocket_event: None,
            marker_label: None,
        };

        self.with_events(|events| events.push(event));
    }

    /// Record a WebSocket message
    pub fn record_websocket_message(&self, ws_event: WebSocketEvent) {
        if !self.is_recording() {
            return;
        }

        let current_url = self.get_current_url();
        let event = SessionEvent {
            id: self.next_event_id(),
            event_type: SessionEventType::WebSocketMessage,
            timestamp: Utc::now(),
            offset_ms: self.offset_ms(),
            current_url,
            websocket_event: Some(ws_event),
            navigation: None,
            network_request: None,
            network_response: None,
            network_error: None,
            dom_interaction: None,
            console_message: None,
            screenshot: None,
            cookie_change: None,
            storage_change: None,
            marker_label: None,
        };

        self.with_events(|events| events.push(event));
    }

    /// Add a marker event for debugging
    pub fn add_marker(&self, label: &str) {
        if !self.is_recording() {
            return;
        }

        let current_url = self.get_current_url();
        let event = SessionEvent::marker(
            self.next_event_id(),
            self.offset_ms(),
            current_url,
            label.to_string(),
        );

        self.with_events(|events| events.push(event));
        debug!("[SessionRecorder] Marker added: {}", label);
    }

    /// Get current event count
    pub fn event_count(&self) -> usize {
        self.with_events(|events| events.len())
    }

    /// Get current statistics
    pub fn stats(&self) -> RecordingStats {
        self.with_stats(|stats| stats.clone())
    }
}

impl Default for SessionRecorder {
    fn default() -> Self {
        Self::new()
    }
}

impl Clone for SessionRecorder {
    fn clone(&self) -> Self {
        Self {
            state: Arc::clone(&self.state),
            settings: self.settings.clone(),
            start_time: Arc::clone(&self.start_time),
            start_url: Arc::clone(&self.start_url),
            current_url: Arc::clone(&self.current_url),
            events: Arc::clone(&self.events),
            event_counter: Arc::clone(&self.event_counter),
            pending_requests: Arc::clone(&self.pending_requests),
            stats: Arc::clone(&self.stats),
            unique_urls: Arc::clone(&self.unique_urls),
        }
    }
}

// ============================================================================
// Session Exporter
// ============================================================================

/// Export format for session recordings
#[derive(Debug, Clone, PartialEq)]
pub enum ExportFormat {
    /// HAR (HTTP Archive) format - compatible with browser dev tools
    Har,
    /// JSON timeline format - custom format with all events
    Json,
    /// Compressed JSON (gzip)
    JsonCompressed,
    /// HTML report with embedded screenshots
    Html,
}

/// Session exporter for converting recordings to various formats
pub struct SessionExporter<'a> {
    recording: &'a SessionRecording,
}

impl<'a> SessionExporter<'a> {
    /// Create a new exporter for a recording
    pub fn new(recording: &'a SessionRecording) -> Self {
        Self { recording }
    }

    /// Render placeholder HTML for events with missing data
    fn render_missing_event_data(&self, event_type_class: &str, event_type_label: &str) -> String {
        warn!(
            "[SessionExporter] Event missing expected data for type: {}",
            event_type_label
        );
        format!(
            r#"
            <div class="event" data-type="{}">
                <div class="event-header">
                    <span class="event-type {}">{}</span>
                    <span class="event-time">?ms</span>
                </div>
                <div class="event-details"><em>Event data missing</em></div>
            </div>
"#,
            event_type_class, event_type_class, event_type_label
        )
    }

    /// Export to the specified format
    pub fn export(&self, format: ExportFormat) -> Result<Vec<u8>> {
        match format {
            ExportFormat::Har => self.export_har(),
            ExportFormat::Json => self.export_json(),
            ExportFormat::JsonCompressed => self.export_json_compressed(),
            ExportFormat::Html => self.export_html(),
        }
    }

    /// Export to HAR (HTTP Archive) format
    pub fn export_har(&self) -> Result<Vec<u8>> {
        let har = self.build_har()?;
        let json = serde_json::to_string_pretty(&har).context("Failed to serialize HAR")?;
        Ok(json.into_bytes())
    }

    /// Build HAR structure from recording
    fn build_har(&self) -> Result<HarRoot> {
        let mut entries: Vec<HarEntry> = Vec::new();

        // Collect request/response pairs
        let mut requests: HashMap<String, &NetworkRequest> = HashMap::new();

        for event in &self.recording.events {
            if let Some(ref req) = event.network_request {
                requests.insert(req.request_id.clone(), req);
            }

            if let Some(ref resp) = event.network_response {
                if let Some(req) = requests.remove(&resp.request_id) {
                    entries.push(self.create_har_entry(req, resp));
                }
            }
        }

        Ok(HarRoot {
            log: HarLog {
                version: "1.2".to_string(),
                creator: HarCreator {
                    name: "Lonkero Security Scanner".to_string(),
                    version: env!("CARGO_PKG_VERSION").to_string(),
                },
                browser: Some(HarBrowser {
                    name: "Chrome/Chromium (Headless)".to_string(),
                    version: "latest".to_string(),
                }),
                pages: vec![HarPage {
                    started_date_time: self.recording.started_at.to_rfc3339(),
                    id: "page_0".to_string(),
                    title: self.recording.start_url.clone(),
                    page_timings: HarPageTimings {
                        on_content_load: None,
                        on_load: Some(self.recording.duration_ms as i64),
                    },
                }],
                entries,
            },
        })
    }

    /// Create a HAR entry from request/response pair
    fn create_har_entry(&self, req: &NetworkRequest, resp: &NetworkResponse) -> HarEntry {
        HarEntry {
            started_date_time: req.timestamp.to_rfc3339(),
            time: resp.duration_ms as f64,
            request: HarRequest {
                method: req.method.to_string(),
                url: req.url.clone(),
                http_version: "HTTP/1.1".to_string(),
                cookies: Vec::new(),
                headers: req
                    .headers
                    .iter()
                    .map(|(k, v)| HarHeader {
                        name: k.clone(),
                        value: v.clone(),
                    })
                    .collect(),
                query_string: Vec::new(),
                post_data: req.body.as_ref().map(|body| HarPostData {
                    mime_type: req.content_type.clone().unwrap_or_default(),
                    text: Some(body.clone()),
                    params: Vec::new(),
                }),
                headers_size: -1,
                body_size: req.size as i64,
            },
            response: HarResponse {
                status: resp.status_code as i32,
                status_text: resp.status_text.clone(),
                http_version: "HTTP/1.1".to_string(),
                cookies: Vec::new(),
                headers: resp
                    .headers
                    .iter()
                    .map(|(k, v)| HarHeader {
                        name: k.clone(),
                        value: v.clone(),
                    })
                    .collect(),
                content: HarContent {
                    size: resp.size as i64,
                    compression: None,
                    mime_type: resp.content_type.clone().unwrap_or_default(),
                    text: resp.body.clone(),
                    encoding: None,
                },
                redirect_url: String::new(),
                headers_size: -1,
                body_size: resp.size as i64,
            },
            cache: HarCache {},
            timings: HarTimings {
                blocked: -1.0,
                dns: -1.0,
                connect: -1.0,
                send: 0.0,
                wait: resp.ttfb_ms as f64,
                receive: (resp.duration_ms - resp.ttfb_ms) as f64,
                ssl: Some(-1.0),
            },
            server_ip_address: None,
            connection: None,
            pageref: Some("page_0".to_string()),
        }
    }

    /// Export to JSON timeline format
    pub fn export_json(&self) -> Result<Vec<u8>> {
        let json = serde_json::to_string_pretty(&self.recording)
            .context("Failed to serialize recording to JSON")?;
        Ok(json.into_bytes())
    }

    /// Export to compressed JSON (gzip)
    pub fn export_json_compressed(&self) -> Result<Vec<u8>> {
        let json = serde_json::to_string(&self.recording)
            .context("Failed to serialize recording to JSON")?;

        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
        encoder
            .write_all(json.as_bytes())
            .context("Failed to compress JSON")?;
        encoder.finish().context("Failed to finish compression")
    }

    /// Export to HTML report with embedded screenshots
    pub fn export_html(&self) -> Result<Vec<u8>> {
        let mut html = String::new();

        // HTML header
        html.push_str(&format!(
            r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Session Recording - {}</title>
    <style>
        :root {{
            --bg-primary: #1a1a2e;
            --bg-secondary: #16213e;
            --bg-tertiary: #0f3460;
            --text-primary: #e8e8e8;
            --text-secondary: #a0a0a0;
            --accent: #e94560;
            --success: #00d4aa;
            --warning: #ffc107;
            --error: #dc3545;
            --border: #2a2a4a;
        }}
        * {{ box-sizing: border-box; margin: 0; padding: 0; }}
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: var(--bg-primary);
            color: var(--text-primary);
            line-height: 1.6;
        }}
        .container {{ max-width: 1400px; margin: 0 auto; padding: 20px; }}
        header {{
            background: var(--bg-secondary);
            padding: 20px;
            border-bottom: 1px solid var(--border);
            margin-bottom: 20px;
        }}
        h1 {{ color: var(--accent); font-size: 1.5rem; margin-bottom: 10px; }}
        .meta {{ display: flex; gap: 30px; flex-wrap: wrap; color: var(--text-secondary); font-size: 0.9rem; }}
        .stats {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }}
        .stat {{
            background: var(--bg-secondary);
            padding: 15px;
            border-radius: 8px;
            border: 1px solid var(--border);
        }}
        .stat-value {{ font-size: 1.5rem; font-weight: bold; color: var(--accent); }}
        .stat-label {{ font-size: 0.85rem; color: var(--text-secondary); }}
        .timeline {{ position: relative; padding-left: 30px; }}
        .timeline::before {{
            content: '';
            position: absolute;
            left: 10px;
            top: 0;
            bottom: 0;
            width: 2px;
            background: var(--border);
        }}
        .event {{
            background: var(--bg-secondary);
            border: 1px solid var(--border);
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            position: relative;
        }}
        .event::before {{
            content: '';
            position: absolute;
            left: -24px;
            top: 20px;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: var(--accent);
        }}
        .event-header {{
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }}
        .event-type {{
            display: inline-block;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: bold;
            text-transform: uppercase;
        }}
        .event-type.navigation {{ background: #3498db; }}
        .event-type.network {{ background: #2ecc71; }}
        .event-type.interaction {{ background: #9b59b6; }}
        .event-type.console {{ background: #f39c12; }}
        .event-type.error {{ background: var(--error); }}
        .event-type.screenshot {{ background: #1abc9c; }}
        .event-time {{ font-size: 0.8rem; color: var(--text-secondary); }}
        .event-url {{ font-family: monospace; font-size: 0.85rem; color: var(--text-secondary); word-break: break-all; }}
        .event-details {{ font-size: 0.9rem; margin-top: 10px; }}
        .screenshot-container {{ margin-top: 10px; }}
        .screenshot-container img {{
            max-width: 100%;
            border: 1px solid var(--border);
            border-radius: 4px;
        }}
        pre {{
            background: var(--bg-tertiary);
            padding: 10px;
            border-radius: 4px;
            overflow-x: auto;
            font-size: 0.85rem;
        }}
        .network-status {{ font-weight: bold; }}
        .network-status.success {{ color: var(--success); }}
        .network-status.redirect {{ color: var(--warning); }}
        .network-status.error {{ color: var(--error); }}
        .filter-bar {{
            background: var(--bg-secondary);
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }}
        .filter-btn {{
            padding: 6px 12px;
            border: 1px solid var(--border);
            border-radius: 4px;
            background: var(--bg-tertiary);
            color: var(--text-primary);
            cursor: pointer;
            font-size: 0.85rem;
        }}
        .filter-btn:hover {{ background: var(--accent); }}
        .filter-btn.active {{ background: var(--accent); border-color: var(--accent); }}
    </style>
</head>
<body>
    <header>
        <h1>Session Recording Report</h1>
        <div class="meta">
            <span><strong>URL:</strong> {}</span>
            <span><strong>Duration:</strong> {}ms</span>
            <span><strong>Events:</strong> {}</span>
            <span><strong>Started:</strong> {}</span>
        </div>
    </header>
    <div class="container">
"#,
            self.recording.id,
            self.recording.start_url,
            self.recording.duration_ms,
            self.recording.event_count,
            self.recording.started_at.format("%Y-%m-%d %H:%M:%S UTC")
        ));

        // Statistics
        html.push_str(&format!(
            r#"
        <div class="stats">
            <div class="stat">
                <div class="stat-value">{}</div>
                <div class="stat-label">Navigations</div>
            </div>
            <div class="stat">
                <div class="stat-value">{}</div>
                <div class="stat-label">Network Requests</div>
            </div>
            <div class="stat">
                <div class="stat-value">{}</div>
                <div class="stat-label">DOM Interactions</div>
            </div>
            <div class="stat">
                <div class="stat-value">{}</div>
                <div class="stat-label">Console Messages</div>
            </div>
            <div class="stat">
                <div class="stat-value">{}</div>
                <div class="stat-label">Errors</div>
            </div>
            <div class="stat">
                <div class="stat-value">{}</div>
                <div class="stat-label">Screenshots</div>
            </div>
        </div>
"#,
            self.recording.stats.navigations,
            self.recording.stats.network_requests,
            self.recording.stats.dom_interactions,
            self.recording.stats.console_messages,
            self.recording.stats.errors,
            self.recording.stats.screenshots,
        ));

        // Filter bar
        html.push_str(
            r#"
        <div class="filter-bar">
            <button class="filter-btn active" onclick="filterEvents('all')">All</button>
            <button class="filter-btn" onclick="filterEvents('navigation')">Navigation</button>
            <button class="filter-btn" onclick="filterEvents('network')">Network</button>
            <button class="filter-btn" onclick="filterEvents('interaction')">Interactions</button>
            <button class="filter-btn" onclick="filterEvents('console')">Console</button>
            <button class="filter-btn" onclick="filterEvents('error')">Errors</button>
            <button class="filter-btn" onclick="filterEvents('screenshot')">Screenshots</button>
        </div>
        <div class="timeline">
"#,
        );

        // Events
        for event in &self.recording.events {
            html.push_str(&self.render_event_html(event));
        }

        // Footer and scripts
        html.push_str(
            r#"
        </div>
    </div>
    <script>
        function filterEvents(type) {
            document.querySelectorAll('.filter-btn').forEach(btn => btn.classList.remove('active'));
            event.target.classList.add('active');

            document.querySelectorAll('.event').forEach(el => {
                if (type === 'all' || el.dataset.type === type) {
                    el.style.display = 'block';
                } else {
                    el.style.display = 'none';
                }
            });
        }
    </script>
</body>
</html>
"#,
        );

        Ok(html.into_bytes())
    }

    /// Render a single event as HTML
    fn render_event_html(&self, event: &SessionEvent) -> String {
        let (event_type_class, event_type_label, details) = match event.event_type {
            SessionEventType::Navigation => {
                let Some(nav) = event.navigation.as_ref() else {
                    return self.render_missing_event_data("navigation", "Navigation");
                };
                (
                    "navigation",
                    "Navigation",
                    format!(
                        "<div class='event-url'>{}</div>",
                        html_escape::encode_text(&nav.url)
                    ),
                )
            }
            SessionEventType::NetworkRequest => {
                let Some(req) = event.network_request.as_ref() else {
                    return self.render_missing_event_data("network", "Request");
                };
                (
                    "network",
                    "Request",
                    format!(
                        "<div><strong>{}</strong> <span class='event-url'>{}</span></div>",
                        req.method,
                        html_escape::encode_text(&req.url)
                    ),
                )
            }
            SessionEventType::NetworkResponse => {
                let Some(resp) = event.network_response.as_ref() else {
                    return self.render_missing_event_data("network", "Response");
                };
                let status_class = if resp.status_code < 300 {
                    "success"
                } else if resp.status_code < 400 {
                    "redirect"
                } else {
                    "error"
                };
                (
                    "network",
                    "Response",
                    format!(
                        "<div><span class='network-status {}'>{} {}</span> - {} bytes in {}ms</div>",
                        status_class, resp.status_code, resp.status_text, resp.size, resp.duration_ms
                    ),
                )
            }
            SessionEventType::NetworkError => {
                let Some(err) = event.network_error.as_ref() else {
                    return self.render_missing_event_data("error", "Network Error");
                };
                (
                    "error",
                    "Network Error",
                    format!("<div>{}</div>", html_escape::encode_text(&err.message)),
                )
            }
            SessionEventType::Click
            | SessionEventType::Input
            | SessionEventType::FormSubmit
            | SessionEventType::Scroll => {
                let Some(dom) = event.dom_interaction.as_ref() else {
                    return self.render_missing_event_data("interaction", "Interaction");
                };
                (
                    "interaction",
                    match event.event_type {
                        SessionEventType::Click => "Click",
                        SessionEventType::Input => "Input",
                        SessionEventType::FormSubmit => "Form Submit",
                        SessionEventType::Scroll => "Scroll",
                        _ => "Interaction",
                    },
                    format!(
                        "<div>&lt;{}&gt; {}</div>",
                        html_escape::encode_text(&dom.tag_name),
                        html_escape::encode_text(&dom.selector)
                    ),
                )
            }
            SessionEventType::ConsoleMessage => {
                let Some(msg) = event.console_message.as_ref() else {
                    return self.render_missing_event_data("console", "Console");
                };
                (
                    "console",
                    match msg.severity {
                        ConsoleSeverity::Error => "Console Error",
                        ConsoleSeverity::Warning => "Console Warning",
                        _ => "Console",
                    },
                    format!("<pre>{}</pre>", html_escape::encode_text(&msg.text)),
                )
            }
            SessionEventType::JsError => {
                let Some(msg) = event.console_message.as_ref() else {
                    return self.render_missing_event_data("error", "JS Error");
                };
                (
                    "error",
                    "JS Error",
                    format!("<pre>{}</pre>", html_escape::encode_text(&msg.text)),
                )
            }
            SessionEventType::Screenshot => {
                let Some(ss) = event.screenshot.as_ref() else {
                    return self.render_missing_event_data("screenshot", "Screenshot");
                };
                (
                    "screenshot",
                    "Screenshot",
                    format!(
                        "<div class='screenshot-container'><img src='data:image/png;base64,{}' alt='Screenshot'/></div>",
                        ss.data
                    ),
                )
            }
            SessionEventType::CookieChange => ("network", "Cookie", String::new()),
            SessionEventType::StorageChange => ("network", "Storage", String::new()),
            SessionEventType::WebSocketMessage => ("network", "WebSocket", String::new()),
            SessionEventType::Marker => {
                let Some(label) = event.marker_label.as_ref() else {
                    return self.render_missing_event_data("navigation", "Marker");
                };
                (
                    "navigation",
                    "Marker",
                    format!("<div>{}</div>", html_escape::encode_text(label)),
                )
            }
        };

        format!(
            r#"
            <div class="event" data-type="{}">
                <div class="event-header">
                    <span class="event-type {}">{}</span>
                    <span class="event-time">+{}ms</span>
                </div>
                <div class="event-details">{}</div>
            </div>
"#,
            event_type_class, event_type_class, event_type_label, event.offset_ms, details
        )
    }
}

// ============================================================================
// HAR Format Types (HTTP Archive 1.2)
// ============================================================================

#[derive(Debug, Serialize, Deserialize)]
pub struct HarRoot {
    pub log: HarLog,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct HarLog {
    pub version: String,
    pub creator: HarCreator,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub browser: Option<HarBrowser>,
    pub pages: Vec<HarPage>,
    pub entries: Vec<HarEntry>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct HarCreator {
    pub name: String,
    pub version: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct HarBrowser {
    pub name: String,
    pub version: String,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HarPage {
    pub started_date_time: String,
    pub id: String,
    pub title: String,
    pub page_timings: HarPageTimings,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HarPageTimings {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub on_content_load: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub on_load: Option<i64>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HarEntry {
    pub started_date_time: String,
    pub time: f64,
    pub request: HarRequest,
    pub response: HarResponse,
    pub cache: HarCache,
    pub timings: HarTimings,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub server_ip_address: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pageref: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HarRequest {
    pub method: String,
    pub url: String,
    pub http_version: String,
    pub cookies: Vec<HarCookie>,
    pub headers: Vec<HarHeader>,
    pub query_string: Vec<HarQueryParam>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub post_data: Option<HarPostData>,
    pub headers_size: i64,
    pub body_size: i64,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HarResponse {
    pub status: i32,
    pub status_text: String,
    pub http_version: String,
    pub cookies: Vec<HarCookie>,
    pub headers: Vec<HarHeader>,
    pub content: HarContent,
    pub redirect_url: String,
    pub headers_size: i64,
    pub body_size: i64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct HarCookie {
    pub name: String,
    pub value: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_only: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub secure: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct HarHeader {
    pub name: String,
    pub value: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct HarQueryParam {
    pub name: String,
    pub value: String,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HarPostData {
    pub mime_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    pub params: Vec<HarParam>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HarParam {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HarContent {
    pub size: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compression: Option<i64>,
    pub mime_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub encoding: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct HarCache {}

#[derive(Debug, Serialize, Deserialize)]
pub struct HarTimings {
    pub blocked: f64,
    pub dns: f64,
    pub connect: f64,
    pub send: f64,
    pub wait: f64,
    pub receive: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ssl: Option<f64>,
}

// ============================================================================
// Compression Utilities
// ============================================================================

/// Compression utilities for session recordings
pub struct RecordingCompression;

impl RecordingCompression {
    /// Compress a recording to gzip format
    pub fn compress(recording: &SessionRecording) -> Result<Vec<u8>> {
        let json = serde_json::to_string(recording).context("Failed to serialize recording")?;

        let mut encoder = GzEncoder::new(Vec::new(), Compression::best());
        encoder
            .write_all(json.as_bytes())
            .context("Failed to compress")?;
        encoder.finish().context("Failed to finish compression")
    }

    /// Decompress a gzip-compressed recording
    pub fn decompress(data: &[u8]) -> Result<SessionRecording> {
        let mut decoder = GzDecoder::new(data);
        let mut json = String::new();
        decoder
            .read_to_string(&mut json)
            .context("Failed to decompress")?;

        serde_json::from_str(&json).context("Failed to parse recording")
    }

    /// Calculate compression ratio
    pub fn compression_ratio(original: &SessionRecording, compressed: &[u8]) -> f64 {
        let original_size = serde_json::to_string(original)
            .map(|s| s.len())
            .unwrap_or(0);

        if original_size == 0 {
            return 0.0;
        }

        1.0 - (compressed.len() as f64 / original_size as f64)
    }
}

// ============================================================================
// Vulnerability Attachment
// ============================================================================

/// Attachment information for linking recordings to vulnerabilities
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecordingAttachment {
    /// Recording ID
    pub recording_id: String,
    /// Start offset in recording (ms) - where the relevant action begins
    pub start_offset_ms: u64,
    /// End offset in recording (ms) - where the relevant action ends
    pub end_offset_ms: u64,
    /// Specific event IDs that are relevant to this vulnerability
    pub relevant_event_ids: Vec<String>,
    /// Description of what the recording shows
    pub description: String,
}

impl SessionRecording {
    /// Create an attachment reference for a vulnerability report
    pub fn create_attachment(
        &self,
        start_offset_ms: u64,
        end_offset_ms: u64,
        description: &str,
    ) -> RecordingAttachment {
        // Find events within the time range
        let relevant_event_ids: Vec<String> = self
            .events
            .iter()
            .filter(|e| e.offset_ms >= start_offset_ms && e.offset_ms <= end_offset_ms)
            .map(|e| e.id.clone())
            .collect();

        RecordingAttachment {
            recording_id: self.id.clone(),
            start_offset_ms,
            end_offset_ms,
            relevant_event_ids,
            description: description.to_string(),
        }
    }

    /// Extract a sub-recording containing only events within a time range
    pub fn extract_segment(&self, start_offset_ms: u64, end_offset_ms: u64) -> SessionRecording {
        let events: Vec<SessionEvent> = self
            .events
            .iter()
            .filter(|e| e.offset_ms >= start_offset_ms && e.offset_ms <= end_offset_ms)
            .cloned()
            .collect();

        let mut stats = RecordingStats::default();
        for event in &events {
            match event.event_type {
                SessionEventType::Navigation => stats.navigations += 1,
                SessionEventType::NetworkRequest => stats.network_requests += 1,
                SessionEventType::NetworkError => stats.network_errors += 1,
                SessionEventType::Click
                | SessionEventType::Input
                | SessionEventType::FormSubmit
                | SessionEventType::Scroll => stats.dom_interactions += 1,
                SessionEventType::ConsoleMessage | SessionEventType::JsError => {
                    stats.console_messages += 1;
                    if event.event_type == SessionEventType::JsError {
                        stats.errors += 1;
                    }
                }
                SessionEventType::Screenshot => stats.screenshots += 1,
                _ => {}
            }
        }

        SessionRecording {
            id: format!("{}-segment", self.id),
            name: format!(
                "{} ({}ms - {}ms)",
                self.name, start_offset_ms, end_offset_ms
            ),
            start_url: self.start_url.clone(),
            started_at: self.started_at + chrono::Duration::milliseconds(start_offset_ms as i64),
            ended_at: Some(self.started_at + chrono::Duration::milliseconds(end_offset_ms as i64)),
            duration_ms: end_offset_ms - start_offset_ms,
            event_count: events.len(),
            events,
            metadata: self.metadata.clone(),
            stats,
        }
    }
}

// Note: flate2 crate is used for compression (added to Cargo.toml)

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

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

    #[test]
    fn test_session_recorder_lifecycle() {
        let recorder = SessionRecorder::new();
        assert_eq!(recorder.state(), RecorderState::Idle);

        recorder.start("https://example.com");
        assert_eq!(recorder.state(), RecorderState::Recording);
        assert!(recorder.is_recording());

        recorder.pause();
        assert_eq!(recorder.state(), RecorderState::Paused);
        assert!(!recorder.is_recording());

        recorder.resume();
        assert_eq!(recorder.state(), RecorderState::Recording);

        let recording = recorder.stop();
        assert_eq!(recorder.state(), RecorderState::Stopped);
        assert_eq!(recording.start_url, "https://example.com");
    }

    #[test]
    fn test_record_navigation() {
        let recorder = SessionRecorder::new();
        recorder.start("https://example.com");

        recorder.record_navigation(NavigationEvent {
            url: "https://example.com/page".to_string(),
            from_url: Some("https://example.com".to_string()),
            navigation_type: NavigationType::Link,
            status_code: Some(200),
            title: Some("Test Page".to_string()),
            load_time_ms: Some(150),
            timestamp: Utc::now(),
        });

        let recording = recorder.stop();
        assert_eq!(recording.stats.navigations, 1);
        assert_eq!(recording.events.len(), 1);
        assert_eq!(recording.events[0].event_type, SessionEventType::Navigation);
    }

    #[test]
    fn test_record_network_request_response() {
        let recorder = SessionRecorder::new();
        recorder.start("https://example.com");

        let request_id = "req_123".to_string();

        recorder.record_network_request(NetworkRequest {
            request_id: request_id.clone(),
            url: "https://api.example.com/data".to_string(),
            method: HttpMethod::Get,
            headers: HashMap::new(),
            body: None,
            content_type: None,
            size: 0,
            timestamp: Utc::now(),
            initiator: Some("fetch".to_string()),
            stack_trace: None,
        });

        std::thread::sleep(std::time::Duration::from_millis(10));

        recorder.record_network_response(NetworkResponse {
            request_id: request_id.clone(),
            status_code: 200,
            status_text: "OK".to_string(),
            headers: HashMap::new(),
            body: Some("{\"data\": \"test\"}".to_string()),
            body_truncated: false,
            content_type: Some("application/json".to_string()),
            size: 16,
            ttfb_ms: 5,
            duration_ms: 0, // Will be calculated
            timestamp: Utc::now(),
            from_cache: false,
        });

        let recording = recorder.stop();
        assert_eq!(recording.stats.network_requests, 1);
        assert_eq!(recording.events.len(), 2);
    }

    #[test]
    fn test_record_dom_interaction() {
        let recorder = SessionRecorder::new();
        recorder.start("https://example.com");

        recorder.record_dom_interaction(DomInteraction {
            interaction_type: DomInteractionType::Click,
            selector: "button#submit".to_string(),
            xpath: Some("/html/body/form/button".to_string()),
            tag_name: "BUTTON".to_string(),
            element_id: Some("submit".to_string()),
            classes: vec!["btn".to_string(), "btn-primary".to_string()],
            text_content: Some("Submit".to_string()),
            input_value: None,
            scroll_position: None,
            coordinates: Some(ClickCoordinates {
                x: 100,
                y: 200,
                viewport_x: 100,
                viewport_y: 200,
            }),
            timestamp: Utc::now(),
        });

        let recording = recorder.stop();
        assert_eq!(recording.stats.dom_interactions, 1);
        assert_eq!(recording.events[0].event_type, SessionEventType::Click);
    }

    #[test]
    fn test_record_console_message() {
        let recorder = SessionRecorder::new();
        recorder.start("https://example.com");

        recorder.record_console_message(ConsoleMessage {
            severity: ConsoleSeverity::Error,
            text: "Uncaught TypeError: Cannot read property 'foo' of undefined".to_string(),
            source_url: Some("https://example.com/app.js".to_string()),
            line_number: Some(42),
            column_number: Some(10),
            stack_trace: None,
            timestamp: Utc::now(),
        });

        let recording = recorder.stop();
        assert_eq!(recording.stats.console_messages, 1);
        assert_eq!(recording.stats.errors, 1);
        assert_eq!(recording.events[0].event_type, SessionEventType::JsError);
    }

    #[test]
    fn test_add_marker() {
        let recorder = SessionRecorder::new();
        recorder.start("https://example.com");

        recorder.add_marker("vulnerability_detected");

        let recording = recorder.stop();
        assert_eq!(recording.events.len(), 1);
        assert_eq!(recording.events[0].event_type, SessionEventType::Marker);
        assert_eq!(
            recording.events[0].marker_label.as_ref().unwrap(),
            "vulnerability_detected"
        );
    }

    #[test]
    fn test_export_json() {
        let recorder = SessionRecorder::new();
        recorder.start("https://example.com");
        recorder.add_marker("test");
        let recording = recorder.stop();

        let exporter = SessionExporter::new(&recording);
        let json = exporter.export(ExportFormat::Json).unwrap();

        assert!(!json.is_empty());
        let parsed: SessionRecording = serde_json::from_slice(&json).unwrap();
        assert_eq!(parsed.start_url, "https://example.com");
    }

    #[test]
    fn test_export_har() {
        let recorder = SessionRecorder::new();
        recorder.start("https://example.com");

        recorder.record_network_request(NetworkRequest {
            request_id: "req_1".to_string(),
            url: "https://example.com/api".to_string(),
            method: HttpMethod::Get,
            headers: HashMap::new(),
            body: None,
            content_type: None,
            size: 0,
            timestamp: Utc::now(),
            initiator: None,
            stack_trace: None,
        });

        recorder.record_network_response(NetworkResponse {
            request_id: "req_1".to_string(),
            status_code: 200,
            status_text: "OK".to_string(),
            headers: HashMap::new(),
            body: Some("{}".to_string()),
            body_truncated: false,
            content_type: Some("application/json".to_string()),
            size: 2,
            ttfb_ms: 10,
            duration_ms: 50,
            timestamp: Utc::now(),
            from_cache: false,
        });

        let recording = recorder.stop();

        let exporter = SessionExporter::new(&recording);
        let har = exporter.export(ExportFormat::Har).unwrap();

        assert!(!har.is_empty());
        let parsed: HarRoot = serde_json::from_slice(&har).unwrap();
        assert_eq!(parsed.log.version, "1.2");
        assert_eq!(parsed.log.entries.len(), 1);
    }

    #[test]
    fn test_export_html() {
        let recorder = SessionRecorder::new();
        recorder.start("https://example.com");
        recorder.add_marker("test");
        let recording = recorder.stop();

        let exporter = SessionExporter::new(&recording);
        let html = exporter.export(ExportFormat::Html).unwrap();

        let html_str = String::from_utf8(html).unwrap();
        assert!(html_str.contains("<!DOCTYPE html>"));
        assert!(html_str.contains("Session Recording Report"));
        assert!(html_str.contains("https://example.com"));
    }

    #[test]
    fn test_extract_segment() {
        let recorder = SessionRecorder::new();
        recorder.start("https://example.com");

        // Add events at different times
        recorder.add_marker("start");
        std::thread::sleep(std::time::Duration::from_millis(50));
        recorder.add_marker("middle");
        std::thread::sleep(std::time::Duration::from_millis(50));
        recorder.add_marker("end");

        let recording = recorder.stop();

        // Extract middle segment
        let segment = recording.extract_segment(25, 75);
        assert!(segment.events.len() >= 1);
    }

    #[test]
    fn test_create_attachment() {
        let recorder = SessionRecorder::new();
        recorder.start("https://example.com");
        recorder.add_marker("vuln_trigger");
        let recording = recorder.stop();

        let attachment = recording.create_attachment(0, 1000, "XSS vulnerability triggered");

        assert_eq!(attachment.recording_id, recording.id);
        assert!(!attachment.relevant_event_ids.is_empty());
        assert_eq!(attachment.description, "XSS vulnerability triggered");
    }

    #[test]
    fn test_http_method_from_string() {
        assert_eq!(HttpMethod::from("GET"), HttpMethod::Get);
        assert_eq!(HttpMethod::from("post"), HttpMethod::Post);
        assert_eq!(HttpMethod::from("DELETE"), HttpMethod::Delete);
        assert_eq!(HttpMethod::from("unknown"), HttpMethod::Get);
    }

    #[test]
    fn test_recording_settings_default() {
        let settings = RecordingSettings::default();
        assert!(settings.capture_bodies);
        assert!(settings.capture_screenshots);
        assert!(settings.capture_console);
        assert!(settings.redact_sensitive);
        assert_eq!(settings.max_body_size, 1024 * 1024);
    }

    #[test]
    fn test_recorder_clone() {
        let recorder = SessionRecorder::new();
        recorder.start("https://example.com");
        recorder.add_marker("test");

        let cloned = recorder.clone();
        assert!(cloned.is_recording());
        assert_eq!(cloned.event_count(), 1);
    }
}