chrome-cli 1.2.0

A CLI tool for browser automation via the Chrome DevTools Protocol
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
use std::collections::HashMap;
use std::io::Write;
use std::path::Path;
use std::time::Duration;

use serde::Serialize;

use chrome_cli::cdp::{CdpClient, CdpConfig};
use chrome_cli::connection::{ManagedSession, resolve_connection, resolve_target};
use chrome_cli::error::{AppError, ExitCode};

use crate::cli::{
    GlobalOpts, NetworkArgs, NetworkCommand, NetworkFollowArgs, NetworkGetArgs, NetworkListArgs,
};
use crate::emulate::apply_emulate_state;

// =============================================================================
// Output types
// =============================================================================

/// A network request summary for list mode.
#[derive(Clone, Debug, Serialize)]
pub struct NetworkRequestSummary {
    id: usize,
    method: String,
    url: String,
    status: Option<u16>,
    #[serde(rename = "type")]
    resource_type: String,
    size: Option<u64>,
    duration_ms: Option<f64>,
    timestamp: String,
}

/// Full detail of a single network request.
#[derive(Debug, Serialize)]
struct NetworkRequestDetail {
    id: usize,
    request: RequestInfo,
    response: ResponseInfo,
    timing: TimingInfo,
    #[serde(rename = "redirect_chain")]
    redirect_chain: Vec<RedirectEntry>,
    #[serde(rename = "type")]
    resource_type: String,
    size: Option<u64>,
    duration_ms: Option<f64>,
    timestamp: String,
}

/// Request section of a detailed network request.
#[derive(Debug, Serialize)]
struct RequestInfo {
    method: String,
    url: String,
    headers: serde_json::Value,
    body: Option<String>,
}

/// Response section of a detailed network request.
#[derive(Debug, Serialize)]
struct ResponseInfo {
    status: Option<u16>,
    status_text: String,
    headers: serde_json::Value,
    body: Option<String>,
    binary: bool,
    truncated: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    mime_type: Option<String>,
}

/// Timing breakdown for a network request.
#[allow(clippy::struct_field_names)]
#[derive(Debug, Serialize)]
struct TimingInfo {
    dns_ms: f64,
    connect_ms: f64,
    tls_ms: f64,
    ttfb_ms: f64,
    download_ms: f64,
}

/// A redirect hop entry.
#[derive(Clone, Debug, Serialize)]
struct RedirectEntry {
    url: String,
    status: u16,
}

/// A network request emitted by `network follow` (one JSON line per request).
#[derive(Debug, Serialize)]
struct NetworkStreamEvent {
    method: String,
    url: String,
    status: Option<u16>,
    #[serde(rename = "type")]
    resource_type: String,
    size: Option<u64>,
    duration_ms: Option<f64>,
    timestamp: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    request_headers: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    response_headers: Option<serde_json::Value>,
}

/// Raw collected event data before correlation.
struct RawNetworkEvent {
    params: serde_json::Value,
    event_type: NetworkEventType,
    navigation_id: u32,
}

/// Types of network events we track.
enum NetworkEventType {
    RequestWillBeSent,
    ResponseReceived,
    LoadingFinished,
    LoadingFailed,
}

/// Builder for accumulating network request data from multiple CDP events.
struct NetworkRequestBuilder {
    cdp_request_id: String,
    assigned_id: usize,
    method: String,
    url: String,
    resource_type: String,
    /// Monotonic CDP timestamp (seconds since browser startup). Used for duration calculations.
    timestamp: f64,
    /// Wall-clock epoch seconds from CDP `wallTime` field. Used for display timestamps.
    wall_time: f64,
    request_headers: serde_json::Value,
    status: Option<u16>,
    status_text: String,
    response_headers: serde_json::Value,
    mime_type: Option<String>,
    encoded_data_length: Option<u64>,
    timing: Option<serde_json::Value>,
    redirect_chain: Vec<RedirectEntry>,
    completed: bool,
    failed: bool,
    error_text: Option<String>,
    navigation_id: u32,
    loading_finished_timestamp: Option<f64>,
}

// =============================================================================
// Output formatting
// =============================================================================

fn print_output(value: &impl Serialize, output: &crate::cli::OutputFormat) -> Result<(), AppError> {
    let json = if output.pretty {
        serde_json::to_string_pretty(value)
    } else {
        serde_json::to_string(value)
    };
    let json = json.map_err(|e| AppError {
        message: format!("serialization error: {e}"),
        code: ExitCode::GeneralError,
        custom_json: None,
    })?;
    println!("{json}");
    Ok(())
}

fn print_list_plain(requests: &[NetworkRequestSummary]) {
    for req in requests {
        let status_str = req
            .status
            .map_or_else(|| "---".to_string(), |s| s.to_string());
        let size_str = req
            .size
            .map_or_else(|| "-".to_string(), |s| format!("{s}B"));
        let dur_str = req
            .duration_ms
            .map_or_else(|| "-".to_string(), |d| format!("{d:.1}ms"));
        println!(
            "{} {} {} {} {}",
            req.method, req.url, status_str, size_str, dur_str
        );
    }
}

fn print_detail_plain(detail: &NetworkRequestDetail) {
    println!("{} {}", detail.request.method, detail.request.url);
    let status_str = detail
        .response
        .status
        .map_or_else(|| "---".to_string(), |s| s.to_string());
    println!("  Status: {} {}", status_str, detail.response.status_text);
    println!("  Type: {}", detail.resource_type);
    println!("  Timestamp: {}", detail.timestamp);
    if let Some(size) = detail.size {
        println!("  Size: {size} bytes");
    }
    if let Some(dur) = detail.duration_ms {
        println!("  Duration: {dur:.1}ms");
    }
    println!(
        "  Timing: DNS={:.1}ms Connect={:.1}ms TLS={:.1}ms TTFB={:.1}ms Download={:.1}ms",
        detail.timing.dns_ms,
        detail.timing.connect_ms,
        detail.timing.tls_ms,
        detail.timing.ttfb_ms,
        detail.timing.download_ms,
    );
    if !detail.redirect_chain.is_empty() {
        println!("  Redirects:");
        for hop in &detail.redirect_chain {
            println!("    {} -> {}", hop.status, hop.url);
        }
    }
}

// =============================================================================
// Config helper
// =============================================================================

fn cdp_config(global: &GlobalOpts) -> CdpConfig {
    let mut config = CdpConfig::default();
    if let Some(timeout_ms) = global.timeout {
        config.command_timeout = Duration::from_millis(timeout_ms);
    }
    config
}

// =============================================================================
// Session setup
// =============================================================================

async fn setup_session(global: &GlobalOpts) -> Result<(CdpClient, ManagedSession), AppError> {
    let conn = resolve_connection(&global.host, global.port, global.ws_url.as_deref()).await?;
    let target = resolve_target(&conn.host, conn.port, global.tab.as_deref()).await?;

    let config = cdp_config(global);
    let client = CdpClient::connect(&conn.ws_url, config).await?;
    let session = client.create_session(&target.id).await?;
    let mut managed = ManagedSession::new(session);
    apply_emulate_state(&mut managed).await?;

    Ok((client, managed))
}

// =============================================================================
// Helpers
// =============================================================================

/// Maximum inline body size (matching MCP server limit).
const MAX_INLINE_BODY_SIZE: usize = 10_000;

/// Convert epoch seconds (floating point) to an ISO 8601 string.
///
/// Callers must supply wall-clock epoch seconds (not CDP monotonic timestamps).
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_possible_wrap,
    clippy::similar_names
)]
fn timestamp_to_iso(ts: f64) -> String {
    // Expects epoch seconds (wall-clock time), NOT CDP monotonic timestamps
    let total_ms = (ts * 1000.0) as u64;
    let secs = total_ms / 1000;
    let ms_part = total_ms % 1000;

    // Civil date/time from epoch seconds (Howard Hinnant's algorithm)
    let days_since_epoch = secs / 86400;
    let time_of_day = secs % 86400;
    let hours = time_of_day / 3600;
    let minutes = (time_of_day % 3600) / 60;
    let seconds = time_of_day % 60;

    let z = days_since_epoch as i64 + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = (z - era * 146_097) as u64;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };

    format!("{y:04}-{m:02}-{d:02}T{hours:02}:{minutes:02}:{seconds:02}.{ms_part:03}Z")
}

/// Parse a status filter string. Supports exact ("404") or wildcard ("4xx").
fn parse_status_filter(status_str: &str) -> StatusFilter {
    let lower = status_str.to_lowercase();
    if lower.len() == 3 && lower.ends_with("xx") {
        if let Some(prefix_char) = lower.chars().next() {
            if let Some(digit) = prefix_char.to_digit(10) {
                #[allow(clippy::cast_possible_truncation)]
                let base = (digit as u16) * 100;
                return StatusFilter::Range(base, base + 99);
            }
        }
    }
    if let Ok(code) = status_str.parse::<u16>() {
        StatusFilter::Exact(code)
    } else {
        // Invalid filter, match nothing
        StatusFilter::Exact(0)
    }
}

/// Status code filter variant.
enum StatusFilter {
    Exact(u16),
    Range(u16, u16),
}

impl StatusFilter {
    fn matches(&self, code: u16) -> bool {
        match self {
            Self::Exact(target) => code == *target,
            Self::Range(low, high) => code >= *low && code <= *high,
        }
    }
}

/// Resolve `--type` into an optional type filter list.
fn resolve_type_filter(type_arg: Option<&str>) -> Option<Vec<String>> {
    type_arg.map(|types| types.split(',').map(|t| t.trim().to_lowercase()).collect())
}

/// Filter requests by resource type.
fn filter_by_type(
    requests: Vec<NetworkRequestSummary>,
    types: &[String],
) -> Vec<NetworkRequestSummary> {
    requests
        .into_iter()
        .filter(|r| types.iter().any(|t| t == &r.resource_type.to_lowercase()))
        .collect()
}

/// Filter requests by URL substring.
fn filter_by_url(
    requests: Vec<NetworkRequestSummary>,
    pattern: &str,
) -> Vec<NetworkRequestSummary> {
    requests
        .into_iter()
        .filter(|r| r.url.contains(pattern))
        .collect()
}

/// Filter requests by HTTP status code.
fn filter_by_status(
    requests: Vec<NetworkRequestSummary>,
    status_filter: &StatusFilter,
) -> Vec<NetworkRequestSummary> {
    requests
        .into_iter()
        .filter(|r| r.status.is_some_and(|s| status_filter.matches(s)))
        .collect()
}

/// Filter requests by HTTP method (case-insensitive).
fn filter_by_method(
    requests: Vec<NetworkRequestSummary>,
    method: &str,
) -> Vec<NetworkRequestSummary> {
    let upper = method.to_uppercase();
    requests
        .into_iter()
        .filter(|r| r.method.to_uppercase() == upper)
        .collect()
}

/// Apply pagination (limit + page offset).
fn paginate(
    requests: Vec<NetworkRequestSummary>,
    limit: usize,
    page: usize,
) -> Vec<NetworkRequestSummary> {
    let offset = page * limit;
    requests.into_iter().skip(offset).take(limit).collect()
}

/// Extract timing info from CDP `response.timing` object.
fn extract_timing(timing: &serde_json::Value) -> TimingInfo {
    let dns_start = timing["dnsStart"].as_f64().unwrap_or(-1.0);
    let dns_end = timing["dnsEnd"].as_f64().unwrap_or(-1.0);
    let connect_start = timing["connectStart"].as_f64().unwrap_or(-1.0);
    let connect_end = timing["connectEnd"].as_f64().unwrap_or(-1.0);
    let ssl_start = timing["sslStart"].as_f64().unwrap_or(-1.0);
    let ssl_end = timing["sslEnd"].as_f64().unwrap_or(-1.0);
    let send_end = timing["sendEnd"].as_f64().unwrap_or(-1.0);
    let receive_headers_end = timing["receiveHeadersEnd"].as_f64().unwrap_or(-1.0);

    let dns_ms = if dns_start >= 0.0 && dns_end >= 0.0 {
        dns_end - dns_start
    } else {
        0.0
    };
    let connect_ms = if connect_start >= 0.0 && connect_end >= 0.0 {
        connect_end - connect_start
    } else {
        0.0
    };
    let tls_ms = if ssl_start >= 0.0 && ssl_end >= 0.0 {
        ssl_end - ssl_start
    } else {
        0.0
    };
    let ttfb_ms = if send_end >= 0.0 && receive_headers_end >= 0.0 {
        receive_headers_end - send_end
    } else {
        0.0
    };

    TimingInfo {
        dns_ms,
        connect_ms,
        tls_ms,
        ttfb_ms,
        download_ms: 0.0, // Calculated separately from loading finished
    }
}

/// Check if a MIME type represents a binary resource.
fn is_binary_mime(mime: &str) -> bool {
    let lower = mime.to_lowercase();
    lower.starts_with("image/")
        || lower.starts_with("audio/")
        || lower.starts_with("video/")
        || lower.starts_with("application/octet-stream")
        || lower.starts_with("application/zip")
        || lower.starts_with("application/gzip")
        || lower.starts_with("application/pdf")
        || lower.starts_with("font/")
        || lower.starts_with("application/wasm")
}

/// Save body content to a file.
fn save_body_to_file(path: &Path, content: &str) -> Result<(), AppError> {
    std::fs::write(path, content).map_err(|e| AppError {
        message: format!("Failed to write to {}: {e}", path.display()),
        code: ExitCode::GeneralError,
        custom_json: None,
    })
}

/// Save binary body (base64 decoded) to a file.
fn save_binary_body_to_file(path: &Path, base64_content: &str) -> Result<(), AppError> {
    use base64::Engine;
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(base64_content)
        .map_err(|e| AppError {
            message: format!("Failed to decode base64 body: {e}"),
            code: ExitCode::GeneralError,
            custom_json: None,
        })?;
    std::fs::write(path, bytes).map_err(|e| AppError {
        message: format!("Failed to write to {}: {e}", path.display()),
        code: ExitCode::GeneralError,
        custom_json: None,
    })
}

// =============================================================================
// Event collection and correlation
// =============================================================================

/// Default timeout for the reload+drain cycle in milliseconds.
const DEFAULT_RELOAD_TIMEOUT_MS: u64 = 5000;

/// Idle window after page load event to catch trailing async requests (ms).
const POST_LOAD_IDLE_MS: u64 = 200;

/// Collect network events by reloading the page and capturing the resulting traffic.
///
/// After enabling the Network and Page domains and subscribing to events, this
/// triggers a `Page.reload` and collects events until the page finishes loading
/// (signaled by `Page.loadEventFired`) plus a short idle window for trailing
/// async requests. A total timeout prevents hanging on slow or broken pages.
#[allow(clippy::too_many_lines)]
async fn collect_and_correlate(
    managed: &mut ManagedSession,
    include_preserved: bool,
    timeout_ms: Option<u64>,
) -> Result<(Vec<NetworkRequestBuilder>, u32), AppError> {
    let total_timeout = Duration::from_millis(timeout_ms.unwrap_or(DEFAULT_RELOAD_TIMEOUT_MS));

    // Enable required domains
    managed.ensure_domain("Network").await?;
    managed.ensure_domain("Page").await?;

    // Subscribe to all needed events
    let mut request_rx = managed
        .subscribe("Network.requestWillBeSent")
        .await
        .map_err(|e| AppError {
            message: format!("Failed to subscribe to Network.requestWillBeSent: {e}"),
            code: ExitCode::GeneralError,
            custom_json: None,
        })?;

    let mut response_rx = managed
        .subscribe("Network.responseReceived")
        .await
        .map_err(|e| AppError {
            message: format!("Failed to subscribe to Network.responseReceived: {e}"),
            code: ExitCode::GeneralError,
            custom_json: None,
        })?;

    let mut finished_rx = managed
        .subscribe("Network.loadingFinished")
        .await
        .map_err(|e| AppError {
            message: format!("Failed to subscribe to Network.loadingFinished: {e}"),
            code: ExitCode::GeneralError,
            custom_json: None,
        })?;

    let mut failed_rx = managed
        .subscribe("Network.loadingFailed")
        .await
        .map_err(|e| AppError {
            message: format!("Failed to subscribe to Network.loadingFailed: {e}"),
            code: ExitCode::GeneralError,
            custom_json: None,
        })?;

    let mut nav_rx = managed
        .subscribe("Page.frameNavigated")
        .await
        .map_err(|e| AppError {
            message: format!("Failed to subscribe to Page.frameNavigated: {e}"),
            code: ExitCode::GeneralError,
            custom_json: None,
        })?;

    let mut load_event_rx = managed
        .subscribe("Page.loadEventFired")
        .await
        .map_err(|e| AppError {
            message: format!("Failed to subscribe to Page.loadEventFired: {e}"),
            code: ExitCode::GeneralError,
            custom_json: None,
        })?;

    // Trigger a page reload to replay network requests
    managed
        .send_command("Page.reload", Some(serde_json::json!({})))
        .await
        .map_err(|e| AppError {
            message: format!("Failed to reload page: {e}"),
            code: ExitCode::GeneralError,
            custom_json: None,
        })?;

    // Collect events until page load completes + idle window, with total timeout
    let mut raw_events: Vec<RawNetworkEvent> = Vec::new();
    let mut current_nav_id: u32 = 0;
    let mut page_loaded = false;
    let absolute_deadline = tokio::time::Instant::now() + total_timeout;
    let mut idle_deadline: Option<tokio::time::Instant> = None;

    loop {
        // Determine the effective deadline: absolute timeout, or post-load idle, whichever is sooner
        let effective_deadline = match idle_deadline {
            Some(idle) => idle.min(absolute_deadline),
            None => absolute_deadline,
        };
        let remaining = effective_deadline.saturating_duration_since(tokio::time::Instant::now());
        if remaining.is_zero() {
            break;
        }

        tokio::select! {
            event = request_rx.recv() => {
                match event {
                    Some(ev) => raw_events.push(RawNetworkEvent {
                        params: ev.params,
                        event_type: NetworkEventType::RequestWillBeSent,
                        navigation_id: current_nav_id,
                    }),
                    None => break,
                }
            }
            event = response_rx.recv() => {
                match event {
                    Some(ev) => raw_events.push(RawNetworkEvent {
                        params: ev.params,
                        event_type: NetworkEventType::ResponseReceived,
                        navigation_id: current_nav_id,
                    }),
                    None => break,
                }
            }
            event = finished_rx.recv() => {
                match event {
                    Some(ev) => raw_events.push(RawNetworkEvent {
                        params: ev.params,
                        event_type: NetworkEventType::LoadingFinished,
                        navigation_id: current_nav_id,
                    }),
                    None => break,
                }
            }
            event = failed_rx.recv() => {
                match event {
                    Some(ev) => raw_events.push(RawNetworkEvent {
                        params: ev.params,
                        event_type: NetworkEventType::LoadingFailed,
                        navigation_id: current_nav_id,
                    }),
                    None => break,
                }
            }
            event = nav_rx.recv() => {
                match event {
                    Some(_) => current_nav_id += 1,
                    None => break,
                }
            }
            event = load_event_rx.recv() => {
                match event {
                    Some(_) => {
                        if !page_loaded {
                            page_loaded = true;
                            // Start idle window to catch trailing async requests
                            idle_deadline = Some(
                                tokio::time::Instant::now()
                                    + tokio::time::Duration::from_millis(POST_LOAD_IDLE_MS),
                            );
                        }
                    }
                    None => break,
                }
            }
            () = tokio::time::sleep(remaining) => break,
        }
    }

    // Correlate events into builders
    let mut builders: HashMap<String, NetworkRequestBuilder> = HashMap::new();
    let mut next_id: usize = 0;

    for event in &raw_events {
        let request_id = event.params["requestId"].as_str().unwrap_or("").to_string();
        if request_id.is_empty() {
            continue;
        }

        match event.event_type {
            NetworkEventType::RequestWillBeSent => {
                // Check if this is a redirect (existing entry for same requestId)
                if let Some(existing) = builders.get_mut(&request_id) {
                    // Record redirect hop
                    let redirect_status = event.params["redirectResponse"]["status"]
                        .as_u64()
                        .unwrap_or(0);
                    let redirect_url = existing.url.clone();
                    #[allow(clippy::cast_possible_truncation)]
                    existing.redirect_chain.push(RedirectEntry {
                        url: redirect_url,
                        status: redirect_status as u16,
                    });
                    // Update the builder with new URL/method
                    existing.url = event.params["request"]["url"]
                        .as_str()
                        .unwrap_or("")
                        .to_string();
                    existing.method = event.params["request"]["method"]
                        .as_str()
                        .unwrap_or("GET")
                        .to_string();
                    existing.request_headers = event.params["request"]["headers"].clone();
                } else {
                    let monotonic_ts = event.params["timestamp"].as_f64().unwrap_or(0.0);
                    let wall_time = event.params["wallTime"].as_f64().unwrap_or(0.0);
                    let builder = NetworkRequestBuilder {
                        cdp_request_id: request_id.clone(),
                        assigned_id: next_id,
                        method: event.params["request"]["method"]
                            .as_str()
                            .unwrap_or("GET")
                            .to_string(),
                        url: event.params["request"]["url"]
                            .as_str()
                            .unwrap_or("")
                            .to_string(),
                        resource_type: event.params["type"]
                            .as_str()
                            .unwrap_or("Other")
                            .to_lowercase(),
                        timestamp: monotonic_ts,
                        wall_time,
                        request_headers: event.params["request"]["headers"].clone(),
                        status: None,
                        status_text: String::new(),
                        response_headers: serde_json::Value::Null,
                        mime_type: None,
                        encoded_data_length: None,
                        timing: None,
                        redirect_chain: Vec::new(),
                        completed: false,
                        failed: false,
                        error_text: None,
                        navigation_id: event.navigation_id,
                        loading_finished_timestamp: None,
                    };
                    builders.insert(request_id, builder);
                    next_id += 1;
                }
            }
            NetworkEventType::ResponseReceived => {
                if let Some(builder) = builders.get_mut(&request_id) {
                    #[allow(clippy::cast_possible_truncation)]
                    let status = event.params["response"]["status"]
                        .as_u64()
                        .map(|s| s as u16);
                    builder.status = status;
                    builder.status_text = event.params["response"]["statusText"]
                        .as_str()
                        .unwrap_or("")
                        .to_string();
                    builder.response_headers = event.params["response"]["headers"].clone();
                    builder.mime_type = event.params["response"]["mimeType"]
                        .as_str()
                        .map(String::from);
                    builder.timing = Some(event.params["response"]["timing"].clone());
                }
            }
            NetworkEventType::LoadingFinished => {
                if let Some(builder) = builders.get_mut(&request_id) {
                    builder.completed = true;
                    builder.encoded_data_length = event.params["encodedDataLength"].as_u64();
                    builder.loading_finished_timestamp = event.params["timestamp"].as_f64();
                }
            }
            NetworkEventType::LoadingFailed => {
                if let Some(builder) = builders.get_mut(&request_id) {
                    builder.failed = true;
                    builder.error_text = event.params["errorText"].as_str().map(String::from);
                }
            }
        }
    }

    // Filter by navigation if needed
    let builders_vec: Vec<NetworkRequestBuilder> = if include_preserved {
        builders.into_values().collect()
    } else {
        builders
            .into_values()
            .filter(|b| b.navigation_id == current_nav_id)
            .collect()
    };

    Ok((builders_vec, current_nav_id))
}

/// Resolve the effective size for a network request.
///
/// Returns `encoded_data_length` when it is `Some(n)` with `n > 0`. Otherwise,
/// falls back to parsing the `content-length` response header (case-insensitive).
fn resolve_size(
    encoded_data_length: Option<u64>,
    response_headers: &serde_json::Value,
) -> Option<u64> {
    if let Some(len) = encoded_data_length {
        if len > 0 {
            return Some(len);
        }
    }
    // Fall back to content-length header (case-insensitive lookup)
    if let Some(headers) = response_headers.as_object() {
        for (key, value) in headers {
            if key.eq_ignore_ascii_case("content-length") {
                return value
                    .as_str()
                    .and_then(|s| s.parse::<u64>().ok())
                    .filter(|&v| v > 0);
            }
        }
    }
    None
}

/// Convert a builder into a summary for list output.
fn builder_to_summary(builder: &NetworkRequestBuilder) -> NetworkRequestSummary {
    let duration_ms = builder
        .loading_finished_timestamp
        .map(|end_ts| (end_ts - builder.timestamp) * 1000.0);

    NetworkRequestSummary {
        id: builder.assigned_id,
        method: builder.method.clone(),
        url: builder.url.clone(),
        status: builder.status,
        resource_type: builder.resource_type.clone(),
        size: resolve_size(builder.encoded_data_length, &builder.response_headers),
        duration_ms,
        timestamp: timestamp_to_iso(builder.wall_time),
    }
}

// =============================================================================
// Dispatcher
// =============================================================================

/// Execute the `network` subcommand group.
///
/// # Errors
///
/// Returns `AppError` if the subcommand fails.
pub async fn execute_network(global: &GlobalOpts, args: &NetworkArgs) -> Result<(), AppError> {
    match &args.command {
        NetworkCommand::List(list_args) => execute_list(global, list_args).await,
        NetworkCommand::Get(get_args) => execute_get(global, get_args).await,
        NetworkCommand::Follow(follow_args) => execute_follow(global, follow_args).await,
    }
}

// =============================================================================
// List
// =============================================================================

async fn execute_list(global: &GlobalOpts, args: &NetworkListArgs) -> Result<(), AppError> {
    let (_client, mut managed) = setup_session(global).await?;

    if global.auto_dismiss_dialogs {
        let _dismiss = managed.spawn_auto_dismiss().await?;
    }

    let (builders, _nav_id) =
        collect_and_correlate(&mut managed, args.include_preserved, global.timeout).await?;

    // Convert to summaries and sort by assigned_id
    let mut requests: Vec<NetworkRequestSummary> =
        builders.iter().map(builder_to_summary).collect();
    requests.sort_by_key(|r| r.id);

    // Apply filters
    if let Some(ref types) = resolve_type_filter(args.r#type.as_deref()) {
        requests = filter_by_type(requests, types);
    }
    if let Some(ref url_pattern) = args.url {
        requests = filter_by_url(requests, url_pattern);
    }
    if let Some(ref status_str) = args.status {
        let status_filter = parse_status_filter(status_str);
        requests = filter_by_status(requests, &status_filter);
    }
    if let Some(ref method) = args.method {
        requests = filter_by_method(requests, method);
    }

    // Paginate
    requests = paginate(requests, args.limit, args.page);

    // Output
    if global.output.plain {
        print_list_plain(&requests);
        return Ok(());
    }
    print_output(&requests, &global.output)
}

// =============================================================================
// Get
// =============================================================================

#[allow(clippy::too_many_lines)]
async fn execute_get(global: &GlobalOpts, args: &NetworkGetArgs) -> Result<(), AppError> {
    let (_client, mut managed) = setup_session(global).await?;

    if global.auto_dismiss_dialogs {
        let _dismiss = managed.spawn_auto_dismiss().await?;
    }

    let (builders, _nav_id) = collect_and_correlate(&mut managed, true, global.timeout).await?;

    // Find builder by assigned numeric ID
    #[allow(clippy::cast_possible_truncation)]
    let target_id = args.req_id as usize;
    let builder = builders
        .iter()
        .find(|b| b.assigned_id == target_id)
        .ok_or_else(|| AppError {
            message: format!("Network request {target_id} not found"),
            code: ExitCode::GeneralError,
            custom_json: None,
        })?;

    // Fetch request body for POST/PUT
    let request_body =
        if builder.method == "POST" || builder.method == "PUT" || builder.method == "PATCH" {
            match managed
                .send_command(
                    "Network.getRequestPostData",
                    Some(serde_json::json!({ "requestId": builder.cdp_request_id })),
                )
                .await
            {
                Ok(result) => result["postData"].as_str().map(String::from),
                Err(_) => None,
            }
        } else {
            None
        };

    // Fetch response body
    let (response_body, is_binary, is_truncated) = match managed
        .send_command(
            "Network.getResponseBody",
            Some(serde_json::json!({ "requestId": builder.cdp_request_id })),
        )
        .await
    {
        Ok(result) => {
            let base64_encoded = result["base64Encoded"].as_bool().unwrap_or(false);
            let body_str = result["body"].as_str().unwrap_or("");

            if base64_encoded {
                // Binary content — save to file if requested, don't inline
                if let Some(ref save_path) = args.save_response {
                    save_binary_body_to_file(save_path, body_str)?;
                }
                (None, true, false)
            } else if body_str.len() > MAX_INLINE_BODY_SIZE {
                // Save full body to file if requested
                if let Some(ref save_path) = args.save_response {
                    save_body_to_file(save_path, body_str)?;
                }
                let truncated = body_str[..MAX_INLINE_BODY_SIZE].to_string();
                (Some(truncated), false, true)
            } else {
                if let Some(ref save_path) = args.save_response {
                    save_body_to_file(save_path, body_str)?;
                }
                (Some(body_str.to_string()), false, false)
            }
        }
        Err(_) => (None, false, false),
    };

    // Save request body if requested
    if let Some(ref save_path) = args.save_request {
        if let Some(ref body) = request_body {
            save_body_to_file(save_path, body)?;
        }
    }

    // Build timing info
    let timing = builder.timing.as_ref().map_or_else(
        || TimingInfo {
            dns_ms: 0.0,
            connect_ms: 0.0,
            tls_ms: 0.0,
            ttfb_ms: 0.0,
            download_ms: 0.0,
        },
        |t| {
            let mut ti = extract_timing(t);
            // Calculate download time from timing + loading finished
            if let Some(end_ts) = builder.loading_finished_timestamp {
                let request_time = t["requestTime"].as_f64().unwrap_or(0.0);
                let receive_headers_end = t["receiveHeadersEnd"].as_f64().unwrap_or(0.0);
                if request_time > 0.0 && receive_headers_end > 0.0 {
                    let headers_done = request_time + receive_headers_end / 1000.0;
                    ti.download_ms = (end_ts - headers_done) * 1000.0;
                    if ti.download_ms < 0.0 {
                        ti.download_ms = 0.0;
                    }
                }
            }
            ti
        },
    );

    let duration_ms = builder
        .loading_finished_timestamp
        .map(|end_ts| (end_ts - builder.timestamp) * 1000.0);

    let mime_for_binary_check = builder.mime_type.as_deref().unwrap_or("");
    let binary = is_binary || is_binary_mime(mime_for_binary_check);

    let detail = NetworkRequestDetail {
        id: builder.assigned_id,
        request: RequestInfo {
            method: builder.method.clone(),
            url: builder.url.clone(),
            headers: builder.request_headers.clone(),
            body: request_body,
        },
        response: ResponseInfo {
            status: builder.status,
            status_text: builder.status_text.clone(),
            headers: builder.response_headers.clone(),
            body: if binary { None } else { response_body },
            binary,
            truncated: is_truncated,
            mime_type: builder.mime_type.clone(),
        },
        timing,
        redirect_chain: builder.redirect_chain.clone(),
        resource_type: builder.resource_type.clone(),
        size: resolve_size(builder.encoded_data_length, &builder.response_headers),
        duration_ms,
        timestamp: timestamp_to_iso(builder.wall_time),
    };

    if global.output.plain {
        print_detail_plain(&detail);
        return Ok(());
    }
    print_output(&detail, &global.output)
}

// =============================================================================
// Follow: streaming mode
// =============================================================================

#[allow(clippy::too_many_lines)]
async fn execute_follow(global: &GlobalOpts, args: &NetworkFollowArgs) -> Result<(), AppError> {
    let (_client, mut managed) = setup_session(global).await?;

    if global.auto_dismiss_dialogs {
        let _dismiss = managed.spawn_auto_dismiss().await?;
    }

    // Enable required domains
    managed.ensure_domain("Network").await?;

    // Subscribe to network events
    let mut request_rx = managed
        .subscribe("Network.requestWillBeSent")
        .await
        .map_err(|e| AppError {
            message: format!("Failed to subscribe to Network.requestWillBeSent: {e}"),
            code: ExitCode::GeneralError,
            custom_json: None,
        })?;

    let mut response_rx = managed
        .subscribe("Network.responseReceived")
        .await
        .map_err(|e| AppError {
            message: format!("Failed to subscribe to Network.responseReceived: {e}"),
            code: ExitCode::GeneralError,
            custom_json: None,
        })?;

    let mut finished_rx = managed
        .subscribe("Network.loadingFinished")
        .await
        .map_err(|e| AppError {
            message: format!("Failed to subscribe to Network.loadingFinished: {e}"),
            code: ExitCode::GeneralError,
            custom_json: None,
        })?;

    let mut failed_rx = managed
        .subscribe("Network.loadingFailed")
        .await
        .map_err(|e| AppError {
            message: format!("Failed to subscribe to Network.loadingFailed: {e}"),
            code: ExitCode::GeneralError,
            custom_json: None,
        })?;

    let type_filter = resolve_type_filter(args.r#type.as_deref());
    let url_filter = args.url.as_deref();
    let method_filter = args.method.as_deref().map(str::to_uppercase);

    let timeout_duration = args.timeout.map(Duration::from_millis);
    let deadline = timeout_duration.map(|d| tokio::time::Instant::now() + d);

    // In-flight request tracking for correlation
    let mut in_flight: HashMap<String, InFlightRequest> = HashMap::new();

    loop {
        tokio::select! {
            event = request_rx.recv() => {
                match event {
                    Some(ev) => {
                        let request_id = ev.params["requestId"]
                            .as_str()
                            .unwrap_or("")
                            .to_string();
                        if request_id.is_empty() {
                            continue;
                        }
                        in_flight.insert(request_id, InFlightRequest {
                            method: ev.params["request"]["method"]
                                .as_str()
                                .unwrap_or("GET")
                                .to_string(),
                            url: ev.params["request"]["url"]
                                .as_str()
                                .unwrap_or("")
                                .to_string(),
                            resource_type: ev.params["type"]
                                .as_str()
                                .unwrap_or("other")
                                .to_lowercase(),
                            timestamp: ev.params["timestamp"].as_f64().unwrap_or(0.0),
                            wall_time: ev.params["wallTime"].as_f64().unwrap_or(0.0),
                            request_headers: ev.params["request"]["headers"].clone(),
                            response_headers: serde_json::Value::Null,
                            status: None,
                        });
                    }
                    None => {
                        return Err(AppError {
                            message: "CDP connection closed".to_string(),
                            code: ExitCode::ConnectionError,
                            custom_json: None,
                        });
                    }
                }
            }
            event = response_rx.recv() => {
                match event {
                    Some(ev) => {
                        let request_id = ev.params["requestId"]
                            .as_str()
                            .unwrap_or("");
                        if let Some(req) = in_flight.get_mut(request_id) {
                            #[allow(clippy::cast_possible_truncation)]
                            let status = ev.params["response"]["status"]
                                .as_u64()
                                .map(|s| s as u16);
                            req.status = status;
                            req.response_headers = ev.params["response"]["headers"].clone();
                        }
                    }
                    None => {
                        return Err(AppError {
                            message: "CDP connection closed".to_string(),
                            code: ExitCode::ConnectionError,
                            custom_json: None,
                        });
                    }
                }
            }
            event = finished_rx.recv() => {
                match event {
                    Some(ev) => {
                        let request_id = ev.params["requestId"]
                            .as_str()
                            .unwrap_or("");
                        let raw_size = ev.params["encodedDataLength"].as_u64();
                        let end_timestamp = ev.params["timestamp"].as_f64();

                        if let Some(req) = in_flight.remove(request_id) {
                            let size = resolve_size(raw_size, &req.response_headers);
                            emit_stream_event(
                                &req, size, end_timestamp, type_filter.as_deref(),
                                url_filter, method_filter.as_deref(), args.verbose,
                            );
                        }
                    }
                    None => {
                        return Err(AppError {
                            message: "CDP connection closed".to_string(),
                            code: ExitCode::ConnectionError,
                            custom_json: None,
                        });
                    }
                }
            }
            event = failed_rx.recv() => {
                match event {
                    Some(ev) => {
                        let request_id = ev.params["requestId"]
                            .as_str()
                            .unwrap_or("");
                        if let Some(req) = in_flight.remove(request_id) {
                            emit_stream_event(
                                &req, None, None, type_filter.as_deref(),
                                url_filter, method_filter.as_deref(), args.verbose,
                            );
                        }
                    }
                    None => {
                        return Err(AppError {
                            message: "CDP connection closed".to_string(),
                            code: ExitCode::ConnectionError,
                            custom_json: None,
                        });
                    }
                }
            }
            () = async {
                if let Some(d) = deadline {
                    tokio::time::sleep_until(d).await;
                } else {
                    std::future::pending::<()>().await;
                }
            } => {
                // Timeout expired
                break;
            }
            _ = tokio::signal::ctrl_c() => {
                // Ctrl+C
                break;
            }
        }
    }

    Ok(())
}

/// In-flight request state for follow mode correlation.
struct InFlightRequest {
    method: String,
    url: String,
    resource_type: String,
    /// Monotonic CDP timestamp (seconds since browser startup). Used for duration calculations.
    timestamp: f64,
    /// Wall-clock epoch seconds from CDP `wallTime` field. Used for display timestamps.
    wall_time: f64,
    request_headers: serde_json::Value,
    response_headers: serde_json::Value,
    status: Option<u16>,
}

/// Emit a stream event for a completed request (if it passes filters).
fn emit_stream_event(
    req: &InFlightRequest,
    size: Option<u64>,
    end_timestamp: Option<f64>,
    type_filter: Option<&[String]>,
    url_filter: Option<&str>,
    method_filter: Option<&str>,
    verbose: bool,
) {
    // Apply filters
    if let Some(types) = type_filter {
        if !types.iter().any(|t| t == &req.resource_type.to_lowercase()) {
            return;
        }
    }
    if let Some(pattern) = url_filter {
        if !req.url.contains(pattern) {
            return;
        }
    }
    if let Some(method) = method_filter {
        if req.method.to_uppercase() != method {
            return;
        }
    }

    let duration_ms = end_timestamp.map(|end| (end - req.timestamp) * 1000.0);

    let event = NetworkStreamEvent {
        method: req.method.clone(),
        url: req.url.clone(),
        status: req.status,
        resource_type: req.resource_type.clone(),
        size,
        duration_ms,
        timestamp: timestamp_to_iso(req.wall_time),
        request_headers: if verbose {
            Some(req.request_headers.clone())
        } else {
            None
        },
        response_headers: if verbose {
            Some(req.response_headers.clone())
        } else {
            None
        },
    };

    let json = serde_json::to_string(&event).unwrap_or_default();
    println!("{json}");
    let _ = std::io::stdout().flush();
}

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

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

    // =========================================================================
    // NetworkRequestSummary serialization
    // =========================================================================

    #[test]
    fn network_request_summary_serialization() {
        let req = NetworkRequestSummary {
            id: 0,
            method: "GET".to_string(),
            url: "https://example.com/api/data".to_string(),
            status: Some(200),
            resource_type: "xhr".to_string(),
            size: Some(1234),
            duration_ms: Some(45.2),
            timestamp: "2026-02-14T12:00:00.000Z".to_string(),
        };
        let json: serde_json::Value = serde_json::to_value(&req).unwrap();
        assert_eq!(json["id"], 0);
        assert_eq!(json["method"], "GET");
        assert_eq!(json["url"], "https://example.com/api/data");
        assert_eq!(json["status"], 200);
        assert_eq!(json["type"], "xhr");
        assert_eq!(json["size"], 1234);
        assert_eq!(json["timestamp"], "2026-02-14T12:00:00.000Z");
        // Verify "type" field, not "resource_type"
        assert!(json.get("resource_type").is_none());
    }

    #[test]
    fn network_request_summary_null_fields() {
        let req = NetworkRequestSummary {
            id: 1,
            method: "GET".to_string(),
            url: "https://example.com".to_string(),
            status: None,
            resource_type: "document".to_string(),
            size: None,
            duration_ms: None,
            timestamp: String::new(),
        };
        let json: serde_json::Value = serde_json::to_value(&req).unwrap();
        assert!(json["status"].is_null());
        assert!(json["size"].is_null());
        assert!(json["duration_ms"].is_null());
    }

    // =========================================================================
    // NetworkRequestDetail serialization
    // =========================================================================

    #[test]
    fn network_request_detail_serialization() {
        let detail = NetworkRequestDetail {
            id: 1,
            request: RequestInfo {
                method: "POST".to_string(),
                url: "https://example.com/api".to_string(),
                headers: serde_json::json!({"Content-Type": "application/json"}),
                body: Some("{\"key\":\"value\"}".to_string()),
            },
            response: ResponseInfo {
                status: Some(200),
                status_text: "OK".to_string(),
                headers: serde_json::json!({"Content-Type": "application/json"}),
                body: Some("{\"result\":\"ok\"}".to_string()),
                binary: false,
                truncated: false,
                mime_type: Some("application/json".to_string()),
            },
            timing: TimingInfo {
                dns_ms: 5.0,
                connect_ms: 10.0,
                tls_ms: 15.0,
                ttfb_ms: 50.0,
                download_ms: 20.0,
            },
            redirect_chain: vec![RedirectEntry {
                url: "http://example.com/api".to_string(),
                status: 301,
            }],
            resource_type: "xhr".to_string(),
            size: Some(1234),
            duration_ms: Some(100.2),
            timestamp: "2026-02-14T12:00:00.000Z".to_string(),
        };
        let json: serde_json::Value = serde_json::to_value(&detail).unwrap();
        assert_eq!(json["id"], 1);
        assert_eq!(json["request"]["method"], "POST");
        assert_eq!(json["response"]["status"], 200);
        assert_eq!(json["response"]["binary"], false);
        assert_eq!(json["response"]["truncated"], false);
        assert_eq!(json["timing"]["dns_ms"], 5.0);
        assert_eq!(json["timing"]["ttfb_ms"], 50.0);
        assert_eq!(json["redirect_chain"][0]["status"], 301);
        assert_eq!(json["type"], "xhr");
    }

    // =========================================================================
    // NetworkStreamEvent serialization
    // =========================================================================

    #[test]
    fn stream_event_serialization() {
        let event = NetworkStreamEvent {
            method: "GET".to_string(),
            url: "https://example.com/api".to_string(),
            status: Some(200),
            resource_type: "xhr".to_string(),
            size: Some(1234),
            duration_ms: Some(45.2),
            timestamp: "2026-02-14T12:00:00.000Z".to_string(),
            request_headers: None,
            response_headers: None,
        };
        let json: serde_json::Value = serde_json::to_value(&event).unwrap();
        assert_eq!(json["method"], "GET");
        assert_eq!(json["status"], 200);
        assert_eq!(json["type"], "xhr");
        // Headers should be absent (not null) when None
        assert!(json.get("request_headers").is_none());
        assert!(json.get("response_headers").is_none());
    }

    #[test]
    fn stream_event_verbose_serialization() {
        let event = NetworkStreamEvent {
            method: "GET".to_string(),
            url: "https://example.com/api".to_string(),
            status: Some(200),
            resource_type: "xhr".to_string(),
            size: Some(1234),
            duration_ms: Some(45.2),
            timestamp: "2026-02-14T12:00:00.000Z".to_string(),
            request_headers: Some(serde_json::json!({"Accept": "*/*"})),
            response_headers: Some(serde_json::json!({"Content-Type": "application/json"})),
        };
        let json: serde_json::Value = serde_json::to_value(&event).unwrap();
        assert_eq!(json["request_headers"]["Accept"], "*/*");
        assert_eq!(json["response_headers"]["Content-Type"], "application/json");
    }

    // =========================================================================
    // filter_by_type
    // =========================================================================

    fn make_request(
        id: usize,
        method: &str,
        url: &str,
        status: Option<u16>,
        resource_type: &str,
    ) -> NetworkRequestSummary {
        NetworkRequestSummary {
            id,
            method: method.to_string(),
            url: url.to_string(),
            status,
            resource_type: resource_type.to_string(),
            size: None,
            duration_ms: None,
            timestamp: String::new(),
        }
    }

    #[test]
    fn filter_by_type_single() {
        let requests = vec![
            make_request(0, "GET", "https://a.com", Some(200), "xhr"),
            make_request(1, "GET", "https://b.com", Some(200), "document"),
            make_request(2, "GET", "https://c.com", Some(200), "xhr"),
        ];
        let filtered = filter_by_type(requests, &["xhr".to_string()]);
        assert_eq!(filtered.len(), 2);
        assert!(filtered.iter().all(|r| r.resource_type == "xhr"));
    }

    #[test]
    fn filter_by_type_multiple() {
        let requests = vec![
            make_request(0, "GET", "https://a.com", Some(200), "xhr"),
            make_request(1, "GET", "https://b.com", Some(200), "document"),
            make_request(2, "GET", "https://c.com", Some(200), "fetch"),
        ];
        let filtered = filter_by_type(requests, &["xhr".to_string(), "fetch".to_string()]);
        assert_eq!(filtered.len(), 2);
    }

    // =========================================================================
    // filter_by_url
    // =========================================================================

    #[test]
    fn filter_by_url_substring() {
        let requests = vec![
            make_request(0, "GET", "https://api.example.com/data", Some(200), "xhr"),
            make_request(
                1,
                "GET",
                "https://cdn.example.com/image.png",
                Some(200),
                "image",
            ),
        ];
        let filtered = filter_by_url(requests, "api.example.com");
        assert_eq!(filtered.len(), 1);
        assert!(filtered[0].url.contains("api.example.com"));
    }

    #[test]
    fn filter_by_url_no_match() {
        let requests = vec![make_request(
            0,
            "GET",
            "https://example.com/page",
            Some(200),
            "document",
        )];
        let filtered = filter_by_url(requests, "api.nowhere.com");
        assert!(filtered.is_empty());
    }

    // =========================================================================
    // filter_by_status
    // =========================================================================

    #[test]
    fn filter_by_status_exact() {
        let requests = vec![
            make_request(0, "GET", "https://a.com", Some(200), "document"),
            make_request(1, "GET", "https://b.com", Some(404), "document"),
            make_request(2, "GET", "https://c.com", Some(500), "document"),
        ];
        let filter = parse_status_filter("404");
        let filtered = filter_by_status(requests, &filter);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].status, Some(404));
    }

    #[test]
    fn filter_by_status_wildcard() {
        let requests = vec![
            make_request(0, "GET", "https://a.com", Some(200), "document"),
            make_request(1, "GET", "https://b.com", Some(400), "document"),
            make_request(2, "GET", "https://c.com", Some(404), "document"),
            make_request(3, "GET", "https://d.com", Some(500), "document"),
        ];
        let filter = parse_status_filter("4xx");
        let filtered = filter_by_status(requests, &filter);
        assert_eq!(filtered.len(), 2);
        assert!(filtered.iter().all(|r| {
            let s = r.status.unwrap();
            (400..500).contains(&s)
        }));
    }

    #[test]
    fn filter_by_status_none_skipped() {
        let requests = vec![
            make_request(0, "GET", "https://a.com", None, "document"),
            make_request(1, "GET", "https://b.com", Some(200), "document"),
        ];
        let filter = parse_status_filter("200");
        let filtered = filter_by_status(requests, &filter);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].status, Some(200));
    }

    // =========================================================================
    // filter_by_method
    // =========================================================================

    #[test]
    fn filter_by_method_case_insensitive() {
        let requests = vec![
            make_request(0, "GET", "https://a.com", Some(200), "document"),
            make_request(1, "POST", "https://b.com", Some(200), "xhr"),
            make_request(2, "GET", "https://c.com", Some(200), "document"),
        ];
        let filtered = filter_by_method(requests, "post");
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].method, "POST");
    }

    // =========================================================================
    // paginate
    // =========================================================================

    fn make_requests(count: usize) -> Vec<NetworkRequestSummary> {
        (0..count)
            .map(|i| {
                make_request(
                    i,
                    "GET",
                    &format!("https://example.com/{i}"),
                    Some(200),
                    "document",
                )
            })
            .collect()
    }

    #[test]
    fn paginate_page_0() {
        let requests = make_requests(30);
        let result = paginate(requests, 10, 0);
        assert_eq!(result.len(), 10);
        assert_eq!(result[0].id, 0);
        assert_eq!(result[9].id, 9);
    }

    #[test]
    fn paginate_page_1() {
        let requests = make_requests(30);
        let result = paginate(requests, 10, 1);
        assert_eq!(result.len(), 10);
        assert_eq!(result[0].id, 10);
        assert_eq!(result[9].id, 19);
    }

    #[test]
    fn paginate_beyond_available() {
        let requests = make_requests(5);
        let result = paginate(requests, 10, 1);
        assert!(result.is_empty());
    }

    #[test]
    fn paginate_partial_last_page() {
        let requests = make_requests(15);
        let result = paginate(requests, 10, 1);
        assert_eq!(result.len(), 5);
        assert_eq!(result[0].id, 10);
    }

    // =========================================================================
    // parse_status_filter
    // =========================================================================

    #[test]
    fn parse_status_filter_exact_value() {
        let filter = parse_status_filter("404");
        assert!(filter.matches(404));
        assert!(!filter.matches(200));
    }

    #[test]
    fn parse_status_filter_wildcard_4xx() {
        let filter = parse_status_filter("4xx");
        assert!(filter.matches(400));
        assert!(filter.matches(404));
        assert!(filter.matches(499));
        assert!(!filter.matches(500));
        assert!(!filter.matches(200));
    }

    #[test]
    fn parse_status_filter_wildcard_5xx() {
        let filter = parse_status_filter("5xx");
        assert!(filter.matches(500));
        assert!(filter.matches(503));
        assert!(!filter.matches(400));
    }

    #[test]
    fn parse_status_filter_wildcard_2xx() {
        let filter = parse_status_filter("2xx");
        assert!(filter.matches(200));
        assert!(filter.matches(201));
        assert!(filter.matches(299));
        assert!(!filter.matches(300));
    }

    // =========================================================================
    // timestamp_to_iso
    // =========================================================================

    #[test]
    fn timestamp_to_iso_epoch_zero() {
        assert_eq!(timestamp_to_iso(0.0), "1970-01-01T00:00:00.000Z");
    }

    #[test]
    fn timestamp_to_iso_known_value() {
        // 2024-02-14T12:00:00.000Z = 1707912000 seconds since epoch
        assert_eq!(
            timestamp_to_iso(1_707_912_000.0),
            "2024-02-14T12:00:00.000Z"
        );
    }

    #[test]
    fn timestamp_to_iso_with_milliseconds() {
        // 2024-02-14T12:00:00.123Z = 1707912000.123 seconds since epoch
        assert_eq!(
            timestamp_to_iso(1_707_912_000.123),
            "2024-02-14T12:00:00.123Z"
        );
    }

    #[test]
    fn builder_to_summary_uses_wall_time_not_monotonic() {
        // Monotonic timestamp ~62090s maps to 1970-01-01 if treated as epoch (the old bug).
        // wallTime provides the real epoch seconds. Verify the summary uses wallTime.
        let builder = NetworkRequestBuilder {
            cdp_request_id: "1".to_string(),
            assigned_id: 0,
            method: "GET".to_string(),
            url: "https://example.com".to_string(),
            resource_type: "document".to_string(),
            timestamp: 62090.044, // monotonic (seconds since browser start)
            wall_time: 1_707_912_000.123, // epoch seconds (2024-02-14T12:00:00.123Z)
            request_headers: serde_json::Value::Null,
            status: Some(200),
            status_text: "OK".to_string(),
            response_headers: serde_json::Value::Null,
            mime_type: None,
            encoded_data_length: None,
            timing: None,
            redirect_chain: Vec::new(),
            completed: true,
            failed: false,
            error_text: None,
            navigation_id: 0,
            loading_finished_timestamp: Some(62090.544),
        };
        let summary = builder_to_summary(&builder);
        // Must show 2024, NOT 1970
        assert!(
            summary.timestamp.starts_with("2024-"),
            "Expected wall-clock year 2024, got: {}",
            summary.timestamp
        );
        assert_eq!(summary.timestamp, "2024-02-14T12:00:00.123Z");
        // Duration should still be computed from monotonic timestamps
        assert!(
            (summary.duration_ms.unwrap() - 500.0).abs() < 1.0,
            "Duration should be ~500ms from monotonic diff"
        );
    }

    // =========================================================================
    // is_binary_mime
    // =========================================================================

    #[test]
    fn binary_mime_detection() {
        assert!(is_binary_mime("image/png"));
        assert!(is_binary_mime("image/jpeg"));
        assert!(is_binary_mime("audio/mpeg"));
        assert!(is_binary_mime("video/mp4"));
        assert!(is_binary_mime("application/octet-stream"));
        assert!(is_binary_mime("application/pdf"));
        assert!(is_binary_mime("font/woff2"));
        assert!(is_binary_mime("application/wasm"));
        assert!(!is_binary_mime("text/html"));
        assert!(!is_binary_mime("application/json"));
        assert!(!is_binary_mime("text/css"));
    }

    // =========================================================================
    // extract_timing
    // =========================================================================

    #[test]
    fn extract_timing_full() {
        let timing = serde_json::json!({
            "dnsStart": 0.0,
            "dnsEnd": 5.0,
            "connectStart": 5.0,
            "connectEnd": 15.0,
            "sslStart": 10.0,
            "sslEnd": 15.0,
            "sendEnd": 16.0,
            "receiveHeadersEnd": 66.0
        });
        let ti = extract_timing(&timing);
        assert!((ti.dns_ms - 5.0).abs() < f64::EPSILON);
        assert!((ti.connect_ms - 10.0).abs() < f64::EPSILON);
        assert!((ti.tls_ms - 5.0).abs() < f64::EPSILON);
        assert!((ti.ttfb_ms - 50.0).abs() < f64::EPSILON);
    }

    #[test]
    fn extract_timing_missing_fields() {
        let timing = serde_json::json!({});
        let ti = extract_timing(&timing);
        assert!((ti.dns_ms).abs() < f64::EPSILON);
        assert!((ti.connect_ms).abs() < f64::EPSILON);
        assert!((ti.tls_ms).abs() < f64::EPSILON);
        assert!((ti.ttfb_ms).abs() < f64::EPSILON);
    }

    // =========================================================================
    // body truncation logic
    // =========================================================================

    #[test]
    fn body_under_limit_not_truncated() {
        let body = "a".repeat(100);
        assert!(body.len() <= MAX_INLINE_BODY_SIZE);
    }

    #[test]
    fn body_over_limit_truncated() {
        let body = "a".repeat(MAX_INLINE_BODY_SIZE + 1000);
        let truncated = &body[..MAX_INLINE_BODY_SIZE];
        assert_eq!(truncated.len(), MAX_INLINE_BODY_SIZE);
    }

    // =========================================================================
    // resolve_type_filter
    // =========================================================================

    #[test]
    fn resolve_type_filter_none() {
        assert!(resolve_type_filter(None).is_none());
    }

    #[test]
    fn resolve_type_filter_single() {
        let result = resolve_type_filter(Some("xhr"));
        let types = result.unwrap();
        assert_eq!(types, vec!["xhr"]);
    }

    #[test]
    fn resolve_type_filter_multiple() {
        let result = resolve_type_filter(Some("xhr,fetch,document"));
        let types = result.unwrap();
        assert_eq!(types.len(), 3);
        assert!(types.contains(&"xhr".to_string()));
        assert!(types.contains(&"fetch".to_string()));
        assert!(types.contains(&"document".to_string()));
    }

    // =========================================================================
    // Plain text output (no panics)
    // =========================================================================

    #[test]
    fn plain_text_list_empty() {
        print_list_plain(&[]);
    }

    #[test]
    fn plain_text_list_requests() {
        let requests = vec![
            make_request(0, "GET", "https://example.com", Some(200), "document"),
            make_request(1, "POST", "https://api.example.com", Some(404), "xhr"),
        ];
        print_list_plain(&requests);
    }

    #[test]
    fn plain_text_detail() {
        let detail = NetworkRequestDetail {
            id: 0,
            request: RequestInfo {
                method: "GET".to_string(),
                url: "https://example.com".to_string(),
                headers: serde_json::json!({}),
                body: None,
            },
            response: ResponseInfo {
                status: Some(200),
                status_text: "OK".to_string(),
                headers: serde_json::json!({}),
                body: Some("hello".to_string()),
                binary: false,
                truncated: false,
                mime_type: Some("text/html".to_string()),
            },
            timing: TimingInfo {
                dns_ms: 1.0,
                connect_ms: 2.0,
                tls_ms: 3.0,
                ttfb_ms: 4.0,
                download_ms: 5.0,
            },
            redirect_chain: vec![],
            resource_type: "document".to_string(),
            size: Some(5),
            duration_ms: Some(15.0),
            timestamp: "2026-02-14T12:00:00.000Z".to_string(),
        };
        print_detail_plain(&detail);
    }

    // =========================================================================
    // RedirectEntry serialization
    // =========================================================================

    // =========================================================================
    // resolve_size
    // =========================================================================

    #[test]
    fn resolve_size_uses_encoded_data_length_when_nonzero() {
        let headers = serde_json::json!({"content-length": "5000"});
        assert_eq!(resolve_size(Some(1234), &headers), Some(1234));
    }

    #[test]
    fn resolve_size_falls_back_to_content_length_when_zero() {
        let headers = serde_json::json!({"content-length": "5000"});
        assert_eq!(resolve_size(Some(0), &headers), Some(5000));
    }

    #[test]
    fn resolve_size_falls_back_to_content_length_when_none() {
        let headers = serde_json::json!({"content-length": "3000"});
        assert_eq!(resolve_size(None, &headers), Some(3000));
    }

    #[test]
    fn resolve_size_case_insensitive_header() {
        let headers = serde_json::json!({"Content-Length": "7777"});
        assert_eq!(resolve_size(Some(0), &headers), Some(7777));
    }

    #[test]
    fn resolve_size_returns_none_when_both_absent() {
        let headers = serde_json::json!({});
        assert_eq!(resolve_size(None, &headers), None);
    }

    #[test]
    fn resolve_size_returns_none_for_malformed_content_length() {
        let headers = serde_json::json!({"content-length": "not-a-number"});
        assert_eq!(resolve_size(Some(0), &headers), None);
    }

    #[test]
    fn resolve_size_returns_none_when_headers_null() {
        assert_eq!(resolve_size(Some(0), &serde_json::Value::Null), None);
    }

    #[test]
    fn resolve_size_skips_zero_content_length() {
        let headers = serde_json::json!({"content-length": "0"});
        assert_eq!(resolve_size(Some(0), &headers), None);
    }

    #[test]
    fn resolve_size_builder_to_summary_integration() {
        // Simulates the original bug: encodedDataLength is 0, but content-length is present
        let builder = NetworkRequestBuilder {
            cdp_request_id: "1".to_string(),
            assigned_id: 0,
            method: "GET".to_string(),
            url: "https://example.com".to_string(),
            resource_type: "document".to_string(),
            timestamp: 62090.044,
            wall_time: 1_707_912_000.123,
            request_headers: serde_json::Value::Null,
            status: Some(200),
            status_text: "OK".to_string(),
            response_headers: serde_json::json!({"content-length": "377301"}),
            mime_type: None,
            encoded_data_length: Some(0),
            timing: None,
            redirect_chain: Vec::new(),
            completed: true,
            failed: false,
            error_text: None,
            navigation_id: 0,
            loading_finished_timestamp: Some(62090.544),
        };
        let summary = builder_to_summary(&builder);
        assert_eq!(
            summary.size,
            Some(377_301),
            "Size should fall back to content-length when encodedDataLength is 0"
        );
    }

    // =========================================================================
    // RedirectEntry serialization
    // =========================================================================

    #[test]
    fn redirect_entry_serialization() {
        let entry = RedirectEntry {
            url: "http://example.com".to_string(),
            status: 301,
        };
        let json: serde_json::Value = serde_json::to_value(&entry).unwrap();
        assert_eq!(json["url"], "http://example.com");
        assert_eq!(json["status"], 301);
    }
}