http-stat 0.6.2

httpstat visualizes curl(1) statistics in a way of beauty and clarity.
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
// See the License for the specific language governing permissions and
// limitations under the License.

// Copyright 2025 Tree xie.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::i18n::Lang;
use crate::tcp_info::{TcpInfo, TcpInfoDelta};
use bytes::Bytes;
use bytesize::ByteSize;
use chrono::{Local, TimeZone};
use heck::ToTrainCase;
use http::HeaderMap;
use http::HeaderValue;
use http::StatusCode;
use nu_ansi_term::Color::{LightCyan, LightGreen, LightRed, LightYellow};
use serde_json::{json, Map, Value};
use std::fmt;
use std::io::Write;
use std::time::Duration;
use tempfile::NamedTempFile;
use unicode_truncate::Alignment;
use unicode_truncate::UnicodeTruncateStr;

pub static ALPN_HTTP2: &str = "h2";
pub static ALPN_HTTP1: &str = "http/1.1";
pub static ALPN_HTTP3: &str = "h3";

// Format timestamp to human-readable string
pub(crate) fn format_time(timestamp_seconds: i64) -> String {
    Local
        .timestamp_nanos(timestamp_seconds * 1_000_000_000)
        .to_string()
}

pub fn format_duration(duration: Duration) -> String {
    if duration > Duration::from_secs(1) {
        return format!("{:.2}s", duration.as_secs_f64());
    }
    if duration > Duration::from_millis(1) {
        return format!("{}ms", duration.as_millis());
    }
    format!("{}µs", duration.as_micros())
}

/// Format a throughput value (bytes/s) into a human-readable string using
/// decimal units (MB/s = 10^6 B/s, the network-convention) — bandwidth is
/// almost universally reported in decimal, even when storage uses binary.
pub fn format_throughput(bytes_per_sec: f64) -> String {
    if !bytes_per_sec.is_finite() || bytes_per_sec <= 0.0 {
        return "-".to_string();
    }
    if bytes_per_sec >= 1_000_000.0 {
        format!("{:.1} MB/s", bytes_per_sec / 1_000_000.0)
    } else if bytes_per_sec >= 1_000.0 {
        format!("{:.1} KB/s", bytes_per_sec / 1_000.0)
    } else {
        format!("{bytes_per_sec:.0} B/s")
    }
}

/// Size of the "first chunk" window used for throughput splitting.
pub const FIRST_CHUNK_BYTES: usize = 100 * 1024;
/// Threshold above which we render the overall Throughput line.
pub const THROUGHPUT_DISPLAY_THRESHOLD: usize = 1024 * 1024;

struct Timeline {
    name: String,
    duration: Duration,
}

/// Statistics and information collected during an HTTP request.
///
/// This struct contains timing information for each phase of the request,
/// connection details, TLS information, and response data.
///
/// # Fields
///
/// * `dns_lookup` - Time taken for DNS resolution
/// * `quic_connect` - Time taken to establish QUIC connection (for HTTP/3)
/// * `tcp_connect` - Time taken to establish TCP connection
/// * `tls_handshake` - Time taken for TLS handshake (for HTTPS)
/// * `request_send` - Time to send the request headers and body
/// * `server_processing` - Time from request fully sent to first response byte
/// * `content_transfer` - Time taken to transfer the response body
/// * `total` - Total time taken for the entire request
/// * `addr` - Resolved IP address and port
/// * `status` - HTTP response status code
/// * `tls` - TLS protocol version used
/// * `alpn` - Application-Layer Protocol Negotiation (ALPN) protocol selected
/// * `cert_not_before` - Certificate validity start time
/// * `cert_not_after` - Certificate validity end time
/// * `cert_cipher` - TLS cipher suite used
/// * `cert_domains` - List of domains in the certificate's Subject Alternative Names
/// * `body` - Response body content
/// * `headers` - Response headers
/// * `error` - Any error that occurred during the request
#[derive(Default, Debug, Clone)]
pub struct HttpStat {
    pub is_grpc: bool,
    pub request_headers: HeaderMap<HeaderValue>,
    pub dns_lookup: Option<Duration>,
    /// Cold connect cost (TCP + TLS) to the DNS server. Only populated when
    /// using DoH or DoT — for plain UDP DNS this stays None. When present,
    /// the `dns_lookup` total can be split into `dns_connect` and a derived
    /// `dns_query = dns_lookup - dns_connect`, making it possible to tell
    /// whether DoH/DoT latency comes from TLS handshake or query processing.
    pub dns_connect: Option<Duration>,
    pub quic_connect: Option<Duration>,
    pub tcp_connect: Option<Duration>,
    /// Kernel TCP statistics sampled right after `connect(2)`. Provides the
    /// baseline RTT, MSS and initial cwnd before any application data flows.
    /// Linux + macOS only — None on other platforms.
    pub tcp_info_post_connect: Option<TcpInfo>,
    /// Kernel TCP statistics sampled after the response body has been fully
    /// received. The diff against `tcp_info_post_connect` reveals retransmits
    /// during the request — the diagnostic answer to "was Content Transfer
    /// slow because of packet loss or just slow start?".
    pub tcp_info_final: Option<TcpInfo>,
    pub tls_handshake: Option<Duration>,
    pub request_send: Option<Duration>,
    pub server_processing: Option<Duration>,
    pub content_transfer: Option<Duration>,
    /// Bytes actually received over the wire (pre-decompression). For an
    /// uncompressed response this matches `body_size`; for `gzip`/`br`/`zstd`
    /// it's smaller and is the right denominator for *network* throughput.
    pub wire_body_size: Option<usize>,
    /// Time from the start of `content_transfer` until the first 100 KiB of
    /// body bytes had arrived. Combined with the overall content_transfer
    /// duration, it splits download throughput into "first 100 KB" vs
    /// "tail" — the former is TCP slow-start dominated, the latter is the
    /// steady-state rate the server can sustain.
    pub time_to_first_100k: Option<Duration>,
    pub server_timing: Option<Vec<ServerTiming>>,
    pub total: Option<Duration>,
    pub addr: Option<String>,
    pub grpc_status: Option<String>,
    pub status: Option<StatusCode>,
    pub tls: Option<String>,
    pub tls_resumed: Option<bool>,
    pub tls_early_data_accepted: Option<bool>,
    pub tls_ocsp_stapled: Option<bool>,
    pub alpn: Option<String>,
    pub subject: Option<String>,
    pub issuer: Option<String>,
    pub cert_not_before: Option<String>,
    pub cert_not_after: Option<String>,
    pub cert_cipher: Option<String>,
    pub cert_domains: Option<Vec<String>>,
    pub certificates: Option<Vec<Certificate>>,
    pub body: Option<Bytes>,
    pub body_size: Option<usize>,
    pub headers: Option<HeaderMap<HeaderValue>>,
    pub error: Option<String>,
    pub silent: bool,
    pub verbose: bool,
    pub pretty: bool,
    pub include_headers: Option<Vec<String>>,
    pub exclude_headers: Option<Vec<String>>,
    pub waterfall: bool,
    pub jq_filter: Option<String>,
    /// When true, render the Kernel TCP block even without `--verbose`.
    /// Driven by the CLI `--tcp-info` flag.
    pub show_tcp_info: bool,
    /// Display language for the terminal renderer. JSON output is always
    /// in English (machine contract). Driven by `--lang` or auto-detected
    /// from LC_ALL/LC_MESSAGES/LANG.
    pub lang: Lang,
}

#[derive(Debug, Clone)]
pub struct Certificate {
    pub subject: String,
    pub issuer: String,
    pub not_before: String,
    pub not_after: String,
}

/// A single entry parsed from the `Server-Timing` response header (RFC 8673 / W3C).
///
/// Format: `name[;dur=<ms>][;desc="<text>"]`, possibly multiple comma-separated entries
/// per header, possibly multiple `Server-Timing` headers.
#[derive(Debug, Clone)]
pub struct ServerTiming {
    pub name: String,
    pub duration: Option<Duration>,
    pub description: Option<String>,
}

/// Parse all `Server-Timing` header values into a flat list of entries.
/// Returns `None` if the input iterator yields no entries.
pub fn parse_server_timing<'a, I>(values: I) -> Option<Vec<ServerTiming>>
where
    I: IntoIterator<Item = &'a str>,
{
    let mut out = Vec::new();
    for raw in values {
        for part in split_top_level_commas(raw) {
            let mut subparts = part.split(';').map(str::trim);
            let name = match subparts.next() {
                Some(n) if !n.is_empty() => n.to_string(),
                _ => continue,
            };
            let mut entry = ServerTiming {
                name,
                duration: None,
                description: None,
            };
            for kv in subparts {
                let Some(eq) = kv.find('=') else { continue };
                let key = kv[..eq].trim().to_ascii_lowercase();
                let mut val = kv[eq + 1..].trim();
                if val.starts_with('"') && val.ends_with('"') && val.len() >= 2 {
                    val = &val[1..val.len() - 1];
                }
                match key.as_str() {
                    "dur" => {
                        if let Ok(ms) = val.parse::<f64>() {
                            if ms.is_finite() && ms >= 0.0 {
                                entry.duration = Some(Duration::from_secs_f64(ms / 1000.0));
                            }
                        }
                    }
                    "desc" => entry.description = Some(val.to_string()),
                    _ => {}
                }
            }
            out.push(entry);
        }
    }
    if out.is_empty() {
        None
    } else {
        Some(out)
    }
}

/// Split on top-level commas, ignoring commas inside double-quoted strings.
fn split_top_level_commas(s: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut start = 0usize;
    let mut in_quotes = false;
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'"' => in_quotes = !in_quotes,
            b',' if !in_quotes => {
                parts.push(s[start..i].trim());
                start = i + 1;
            }
            _ => {}
        }
        i += 1;
    }
    parts.push(s[start..].trim());
    parts
}

/// Apply a simple jq-style field selector to a JSON string.
/// Supported syntax:
///   .                    identity (pretty-print)
///   .field               object key access
///   .field.sub           nested key access
///   .[0]                 array index
///   .[]                  iterate all array/object values
///   combinations: .items[].name, .a.b[2].c, etc.
fn apply_jq_filter(body: &str, filter: &str) -> Option<String> {
    let root: serde_json::Value = serde_json::from_str(body).ok()?;
    let filter = filter.trim();
    // Allow omitting the leading '.' for convenience (e.g. "os" → ".os")
    let owned;
    let filter = if !filter.starts_with('.') {
        owned = format!(".{filter}");
        owned.as_str()
    } else {
        filter
    };

    // Tokenise the filter string into a list of access steps.
    #[derive(Debug)]
    enum Step {
        Key(String),
        Index(usize),
        Iter,
    }

    fn tokenize(s: &str) -> Option<Vec<Step>> {
        let s = s.strip_prefix('.')?;
        if s.is_empty() {
            return Some(vec![]);
        }
        let mut steps = Vec::new();
        // Split on '.' but keep bracket expressions attached to the preceding key.
        // We walk char-by-char to handle `key[0].next` etc.
        let mut remaining = s;
        while !remaining.is_empty() {
            if remaining.starts_with('[') {
                // bracket at the start: .[0] or .[]
                let end = remaining.find(']')?;
                let inner = &remaining[1..end];
                if inner.is_empty() {
                    steps.push(Step::Iter);
                } else {
                    let idx: usize = inner.parse().ok()?;
                    steps.push(Step::Index(idx));
                }
                remaining = &remaining[end + 1..];
                if remaining.starts_with('.') {
                    remaining = &remaining[1..];
                }
            } else {
                // read up to next '.' or '['
                let end = remaining.find(['.', '[']).unwrap_or(remaining.len());
                let key = &remaining[..end];
                if !key.is_empty() {
                    steps.push(Step::Key(key.to_string()));
                }
                remaining = &remaining[end..];
                if remaining.starts_with('.') {
                    remaining = &remaining[1..];
                }
            }
        }
        Some(steps)
    }

    fn apply_steps(values: Vec<serde_json::Value>, steps: &[Step]) -> Vec<serde_json::Value> {
        if steps.is_empty() {
            return values;
        }
        let mut current = values;
        for step in steps {
            current = match step {
                Step::Key(k) => current
                    .into_iter()
                    .filter_map(|v| v.get(k).cloned())
                    .collect(),
                Step::Index(i) => current
                    .into_iter()
                    .filter_map(|v| v.get(i).cloned())
                    .collect(),
                Step::Iter => current
                    .into_iter()
                    .flat_map(|v| match v {
                        serde_json::Value::Array(arr) => arr,
                        serde_json::Value::Object(map) => map.into_values().collect(),
                        other => vec![other],
                    })
                    .collect(),
            };
        }
        current
    }

    let steps = tokenize(filter)?;
    let results = apply_steps(vec![root], &steps);

    if results.len() == 1 {
        serde_json::to_string_pretty(&results[0]).ok()
    } else {
        Some(
            results
                .iter()
                .filter_map(|v| serde_json::to_string_pretty(v).ok())
                .collect::<Vec<_>>()
                .join("\n"),
        )
    }
}

impl HttpStat {
    /// Returns a semantic exit code based on the error type:
    /// - 0: Success
    /// - 1: General/unknown error
    /// - 2: DNS resolution failure
    /// - 3: TCP connection failure
    /// - 4: TLS/SSL error
    /// - 5: Timeout
    /// - 6: HTTP 4xx client error
    /// - 7: HTTP 5xx server error
    pub fn exit_code(&self) -> i32 {
        if self.is_success() {
            return 0;
        }
        // HTTP status errors (no connection error, but bad status)
        if self.error.is_none() {
            if let Some(status) = &self.status {
                let code = status.as_u16();
                if code >= 500 {
                    return 7;
                }
                if code >= 400 {
                    return 6;
                }
            }
            return 1;
        }
        let err = self.error.as_deref().unwrap_or_default().to_lowercase();
        // Timeout (check before phase-based detection since timeout can happen in any phase)
        if err.contains("timeout") || err.contains("elapsed") {
            return 5;
        }
        // DNS failure: dns_lookup phase never completed
        if self.dns_lookup.is_none() {
            return 2;
        }
        // TCP failure: tcp/quic connection phase never completed
        if self.tcp_connect.is_none() && self.quic_connect.is_none() {
            return 3;
        }
        // TLS failure
        if err.contains("rustls")
            || err.contains("tls")
            || err.contains("certificate")
            || err.contains("invalid dns name")
        {
            return 4;
        }
        1
    }

    /// Derived "DNS Query" phase: the portion of `dns_lookup` not spent on
    /// `dns_connect`. Returns `None` when no DoH/DoT probe was performed.
    /// Clamped to ≥ 0 because the parallel probe can race slightly ahead of
    /// the real resolver in rare cases.
    pub fn dns_query(&self) -> Option<Duration> {
        match (self.dns_lookup, self.dns_connect) {
            (Some(total), Some(connect)) => Some(total.saturating_sub(connect)),
            _ => None,
        }
    }

    /// Overall download throughput in bytes/sec, based on wire bytes received
    /// over the content_transfer window. Returns `None` when either input is
    /// unavailable or content_transfer is zero (instant local response).
    pub fn throughput_bps(&self) -> Option<f64> {
        let bytes = self.wire_body_size? as f64;
        let secs = self.content_transfer?.as_secs_f64();
        if secs <= 0.0 {
            return None;
        }
        Some(bytes / secs)
    }

    /// Throughput across the first 100 KiB of body bytes — dominated by TCP
    /// slow-start on a cold connection. Compare with [`tail_throughput_bps`]
    /// to tell "slow start" from "server streams slowly".
    pub fn first_chunk_throughput_bps(&self) -> Option<f64> {
        let dur = self.time_to_first_100k?.as_secs_f64();
        if dur <= 0.0 {
            return None;
        }
        Some(FIRST_CHUNK_BYTES as f64 / dur)
    }

    /// Throughput of the remaining body after the first 100 KiB — the
    /// steady-state rate the server actually sustains.
    pub fn tail_throughput_bps(&self) -> Option<f64> {
        let total = self.content_transfer?;
        let head = self.time_to_first_100k?;
        let bytes = self.wire_body_size?;
        if bytes <= FIRST_CHUNK_BYTES || total <= head {
            return None;
        }
        let tail_bytes = (bytes - FIRST_CHUNK_BYTES) as f64;
        let tail_secs = (total - head).as_secs_f64();
        if tail_secs <= 0.0 {
            return None;
        }
        Some(tail_bytes / tail_secs)
    }

    pub fn is_success(&self) -> bool {
        if self.error.is_some() {
            return false;
        }
        if self.is_grpc {
            if let Some(grpc_status) = &self.grpc_status {
                return grpc_status == "0";
            }
            return false;
        }
        let Some(status) = &self.status else {
            return false;
        };
        if status.as_u16() >= 400 {
            return false;
        }
        true
    }

    /// Render a waterfall bar chart to `f`.
    /// Each phase is one row; bars are horizontally positioned by cumulative offset.
    fn fmt_waterfall(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let total = match self.total {
            Some(t) if t.as_nanos() > 0 => t,
            _ => return Ok(()),
        };

        const BAR_WIDTH: usize = 50;
        const LABEL_W: usize = 15;

        let s = self.lang.strings();
        // When a DoH/DoT probe ran, split the DNS column into Connect + Query.
        let (dns_a, dns_b) = if self.dns_connect.is_some() {
            (
                (s.dns_connect, self.dns_connect),
                (s.dns_query, self.dns_query()),
            )
        } else {
            ((s.dns_lookup, self.dns_lookup), ("", None))
        };
        let phases_vec: Vec<(&str, Option<Duration>)> = vec![
            dns_a,
            dns_b,
            (s.tcp_connect, self.tcp_connect),
            (s.tls_handshake, self.tls_handshake),
            (s.quic_connect, self.quic_connect),
            (s.request_send, self.request_send),
            (s.server_processing_short, self.server_processing),
            (s.content_transfer_short, self.content_transfer),
        ];
        let phases: &[(&str, Option<Duration>)] = &phases_vec;

        let total_ns = total.as_nanos() as f64;
        let mut elapsed = Duration::ZERO;
        let mut col_cursor: usize = 0;

        for (name, dur_opt) in phases {
            let Some(dur) = dur_opt else { continue };

            let start_col = col_cursor;
            elapsed += *dur;
            let ideal_end = ((elapsed.as_nanos() as f64 / total_ns * BAR_WIDTH as f64).round()
                as usize)
                .min(BAR_WIDTH);
            let end_col = ideal_end.min(BAR_WIDTH);
            if end_col > start_col {
                col_cursor = end_col;
            }

            let bar: String = (0..BAR_WIDTH)
                .map(|i| {
                    if i >= start_col && i < end_col {
                        ''
                    } else {
                        ''
                    }
                })
                .collect();

            writeln!(
                f,
                " {:<LABEL_W$} [{}]  {}",
                name,
                LightCyan.paint(bar),
                LightCyan.paint(format_duration(*dur))
            )?;
        }

        writeln!(f)?;
        writeln!(
            f,
            " {:LABEL_W$}  {:BAR_WIDTH$}  {}: {}",
            "",
            "",
            s.total,
            LightCyan.paint(format_duration(total))
        )?;
        writeln!(f)
    }

    pub fn to_json(&self) -> Value {
        let dur_us = |d: Option<Duration>| -> Value {
            d.map_or(Value::Null, |d| json!(d.as_micros() as u64))
        };

        let mut obj = Map::new();

        // Timing (microseconds)
        let mut timing = Map::new();
        timing.insert("dns_lookup_us".into(), dur_us(self.dns_lookup));
        timing.insert("dns_connect_us".into(), dur_us(self.dns_connect));
        timing.insert("dns_query_us".into(), dur_us(self.dns_query()));
        timing.insert("tcp_connect_us".into(), dur_us(self.tcp_connect));
        timing.insert("tls_handshake_us".into(), dur_us(self.tls_handshake));
        timing.insert("quic_connect_us".into(), dur_us(self.quic_connect));
        timing.insert("request_send_us".into(), dur_us(self.request_send));
        timing.insert(
            "server_processing_us".into(),
            dur_us(self.server_processing),
        );
        timing.insert("content_transfer_us".into(), dur_us(self.content_transfer));
        timing.insert(
            "time_to_first_100k_us".into(),
            dur_us(self.time_to_first_100k),
        );
        timing.insert("total_us".into(), dur_us(self.total));
        obj.insert("timing".into(), Value::Object(timing));

        // Throughput block — populated whenever a body was received with a
        // measurable content_transfer. Numerator is wire bytes (pre-decompress).
        if self.wire_body_size.is_some() && self.content_transfer.is_some() {
            let mut t = Map::new();
            t.insert(
                "wire_body_size".into(),
                self.wire_body_size.map_or(Value::Null, |v| json!(v)),
            );
            let opt_f = |v: Option<f64>| -> Value { v.map_or(Value::Null, |x| json!(x)) };
            t.insert("bps_total".into(), opt_f(self.throughput_bps()));
            t.insert(
                "bps_first_100k".into(),
                opt_f(self.first_chunk_throughput_bps()),
            );
            t.insert("bps_tail".into(), opt_f(self.tail_throughput_bps()));
            obj.insert("throughput".into(), Value::Object(t));
        }

        // Kernel TCP statistics (Linux + macOS): both samples plus a derived
        // delta highlighting what changed during the request.
        let tcp_info_json = |info: Option<&TcpInfo>| -> Value {
            let Some(info) = info else { return Value::Null };
            let mut m = Map::new();
            m.insert("rtt_us".into(), dur_us(info.rtt));
            m.insert("rttvar_us".into(), dur_us(info.rttvar));
            m.insert(
                "retransmits".into(),
                info.retransmits.map_or(Value::Null, |v| json!(v)),
            );
            m.insert("cwnd".into(), info.cwnd.map_or(Value::Null, |v| json!(v)));
            m.insert(
                "snd_mss".into(),
                info.snd_mss.map_or(Value::Null, |v| json!(v)),
            );
            Value::Object(m)
        };
        if self.tcp_info_post_connect.is_some() || self.tcp_info_final.is_some() {
            let mut block = Map::new();
            block.insert(
                "post_connect".into(),
                tcp_info_json(self.tcp_info_post_connect.as_ref()),
            );
            block.insert("final".into(), tcp_info_json(self.tcp_info_final.as_ref()));
            if let Some(delta) = TcpInfoDelta::compute(
                self.tcp_info_post_connect.as_ref(),
                self.tcp_info_final.as_ref(),
            ) {
                let mut d = Map::new();
                d.insert(
                    "retransmits_during".into(),
                    delta.retransmits_during.map_or(Value::Null, |v| json!(v)),
                );
                d.insert("rtt_final_us".into(), dur_us(delta.rtt_final));
                d.insert(
                    "cwnd_final".into(),
                    delta.cwnd_final.map_or(Value::Null, |v| json!(v)),
                );
                block.insert("delta".into(), Value::Object(d));
            }
            obj.insert("tcp_info".into(), Value::Object(block));
        }

        // Server-Timing entries (RFC 8673)
        if let Some(entries) = &self.server_timing {
            let arr: Vec<Value> = entries
                .iter()
                .map(|e| {
                    let mut m = Map::new();
                    m.insert("name".into(), json!(e.name));
                    m.insert(
                        "duration_us".into(),
                        e.duration
                            .map_or(Value::Null, |d| json!(d.as_micros() as u64)),
                    );
                    m.insert(
                        "description".into(),
                        e.description.as_deref().map_or(Value::Null, |s| json!(s)),
                    );
                    Value::Object(m)
                })
                .collect();
            obj.insert("server_timing".into(), Value::Array(arr));
        }

        // Connection
        obj.insert(
            "addr".into(),
            self.addr.as_deref().map_or(Value::Null, |s| json!(s)),
        );
        obj.insert(
            "status".into(),
            self.status.map_or(Value::Null, |s| json!(s.as_u16())),
        );
        obj.insert(
            "alpn".into(),
            self.alpn.as_deref().map_or(Value::Null, |s| json!(s)),
        );

        // TLS
        if self.tls.is_some() {
            let mut tls = Map::new();
            tls.insert(
                "version".into(),
                self.tls.as_deref().map_or(Value::Null, |s| json!(s)),
            );
            tls.insert(
                "cipher".into(),
                self.cert_cipher
                    .as_deref()
                    .map_or(Value::Null, |s| json!(s)),
            );
            tls.insert(
                "resumed".into(),
                self.tls_resumed.map_or(Value::Null, |b| json!(b)),
            );
            tls.insert(
                "early_data_accepted".into(),
                self.tls_early_data_accepted
                    .map_or(Value::Null, |b| json!(b)),
            );
            tls.insert(
                "ocsp_stapled".into(),
                self.tls_ocsp_stapled.map_or(Value::Null, |b| json!(b)),
            );
            tls.insert(
                "subject".into(),
                self.subject.as_deref().map_or(Value::Null, |s| json!(s)),
            );
            tls.insert(
                "issuer".into(),
                self.issuer.as_deref().map_or(Value::Null, |s| json!(s)),
            );
            tls.insert(
                "not_before".into(),
                self.cert_not_before
                    .as_deref()
                    .map_or(Value::Null, |s| json!(s)),
            );
            tls.insert(
                "not_after".into(),
                self.cert_not_after
                    .as_deref()
                    .map_or(Value::Null, |s| json!(s)),
            );
            tls.insert(
                "domains".into(),
                self.cert_domains.as_ref().map_or(Value::Null, |d| json!(d)),
            );
            obj.insert("tls".into(), Value::Object(tls));
        }

        // Headers
        if let Some(headers) = &self.headers {
            let mut hdr_map = Map::new();
            for (key, value) in headers.iter() {
                let v = value.to_str().unwrap_or_default().to_string();
                hdr_map.insert(key.to_string(), json!(v));
            }
            obj.insert("headers".into(), Value::Object(hdr_map));
        }

        // Body
        obj.insert(
            "body_size".into(),
            self.body_size.map_or(Value::Null, |s| json!(s)),
        );

        // Error
        obj.insert(
            "error".into(),
            self.error.as_deref().map_or(Value::Null, |e| json!(e)),
        );
        obj.insert("exit_code".into(), json!(self.exit_code()));

        Value::Object(obj)
    }
}

impl fmt::Display for HttpStat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = self.lang.strings();
        if let Some(addr) = &self.addr {
            let label = if self.tcp_connect.is_some() || self.quic_connect.is_some() {
                LightGreen.paint(s.connected_to)
            } else {
                LightYellow.paint(s.resolved_to)
            };
            let mut text = format!("{} {}", label, LightCyan.paint(addr));
            if self.silent {
                if let Some(status) = &self.status {
                    let alpn = self.alpn.as_deref().unwrap_or(ALPN_HTTP1);
                    let status_code = status.as_u16();
                    let status = if status_code < 400 {
                        LightGreen.paint(status.to_string())
                    } else {
                        LightRed.paint(status.to_string())
                    };
                    text = format!(
                        "{text} --> {} {}",
                        LightCyan.paint(alpn.to_uppercase()),
                        status
                    );
                } else {
                    text = format!("{text} --> {}", LightRed.paint(s.fail));
                }
                text = format!("{text} {}", format_duration(self.total.unwrap_or_default()));
                // Surface TLS resumption / 0-RTT inline — most useful in
                // benchmark (-n) output where iterations 2+ may resume.
                // "0-RTT" stays as a technical token across locales.
                if let Some(true) = self.tls_resumed {
                    let tag = if matches!(self.tls_early_data_accepted, Some(true)) {
                        "0-RTT"
                    } else {
                        s.handshake_resumed
                    };
                    text = format!("{text} [{}]", LightYellow.paint(tag));
                }
            }
            writeln!(f, "{text}")?;
        }
        if let Some(error) = &self.error {
            writeln!(f, "{}: {}", s.error_label, LightRed.paint(error))?;
        }
        if self.silent {
            return Ok(());
        }
        if self.verbose {
            for (key, value) in self.request_headers.iter() {
                writeln!(
                    f,
                    "{}: {}",
                    key.to_string().to_train_case(),
                    LightCyan.paint(value.to_str().unwrap_or_default())
                )?;
            }
            writeln!(f)?;
        }

        if let Some(status) = &self.status {
            let alpn = self.alpn.as_deref().unwrap_or(ALPN_HTTP1);
            let status_code = status.as_u16();
            let status = if status_code < 400 {
                LightGreen.paint(status.to_string())
            } else {
                LightRed.paint(status.to_string())
            };
            writeln!(f, "{} {}", LightCyan.paint(alpn.to_uppercase()), status)?;
        }
        if self.is_grpc {
            if self.is_success() {
                writeln!(f, "{}", LightGreen.paint(s.grpc_ok))?;
            }
            writeln!(f)?;
        }

        if let Some(tls) = &self.tls {
            writeln!(f)?;
            writeln!(f, "{}: {}", s.tls_label, LightCyan.paint(tls))?;
            writeln!(
                f,
                "{}: {}",
                s.cipher,
                LightCyan.paint(self.cert_cipher.as_deref().unwrap_or_default())
            )?;
            if let Some(resumed) = self.tls_resumed {
                let label = if resumed {
                    s.handshake_resumed
                } else {
                    s.handshake_full
                };
                writeln!(f, "{}: {}", s.handshake, LightCyan.paint(label))?;
            }
            if let Some(accepted) = self.tls_early_data_accepted {
                let label = if accepted {
                    s.early_data_accepted
                } else {
                    s.early_data_not_accepted
                };
                writeln!(f, "{}: {}", s.early_data, LightCyan.paint(label))?;
            }
            if let Some(stapled) = self.tls_ocsp_stapled {
                let label = if stapled {
                    s.ocsp_stapled
                } else {
                    s.ocsp_not_stapled
                };
                writeln!(f, "{}: {}", s.ocsp, LightCyan.paint(label))?;
            }
            writeln!(
                f,
                "{}: {}",
                s.not_before,
                LightCyan.paint(self.cert_not_before.as_deref().unwrap_or_default())
            )?;
            writeln!(
                f,
                "{}: {}",
                s.not_after,
                LightCyan.paint(self.cert_not_after.as_deref().unwrap_or_default())
            )?;
            if self.verbose {
                writeln!(
                    f,
                    "{}: {}",
                    s.subject,
                    LightCyan.paint(self.subject.as_deref().unwrap_or_default())
                )?;
                writeln!(
                    f,
                    "{}: {}",
                    s.issuer,
                    LightCyan.paint(self.issuer.as_deref().unwrap_or_default())
                )?;
                writeln!(
                    f,
                    "{}: {}",
                    s.cert_domains,
                    LightCyan.paint(self.cert_domains.as_deref().unwrap_or_default().join(", "))
                )?;
            }
            writeln!(f)?;

            if self.verbose {
                if let Some(certificates) = &self.certificates {
                    writeln!(f, "{}", s.cert_chain)?;
                    for (index, cert) in certificates.iter().enumerate() {
                        writeln!(
                            f,
                            " {index} {}: {}",
                            s.subject,
                            LightCyan.paint(cert.subject.as_str())
                        )?;
                        writeln!(
                            f,
                            "   {}: {}",
                            s.issuer,
                            LightCyan.paint(cert.issuer.as_str())
                        )?;
                        writeln!(
                            f,
                            "   {}: {}",
                            s.not_before,
                            LightCyan.paint(cert.not_before.as_str())
                        )?;
                        writeln!(
                            f,
                            "   {}: {}",
                            s.not_after,
                            LightCyan.paint(cert.not_after.as_str())
                        )?;
                        writeln!(f)?;
                    }
                }
            }
        }

        // Kernel TCP stats — shown under `-v` or whenever `--tcp-info` is set
        // via `self.show_tcp_info`. The "during" retransmit count is the
        // diagnostic gold: it isolates packet loss to *this* request's window
        // rather than the connection's lifetime.
        if (self.verbose || self.show_tcp_info)
            && (self.tcp_info_post_connect.is_some() || self.tcp_info_final.is_some())
        {
            writeln!(f, "{}", LightGreen.paint(s.kernel_tcp_heading))?;
            // Technical field names (rtt/retrans/cwnd/mss) stay English —
            // they're the standard `getsockopt(TCP_INFO)` field names.
            let render = |label: &str, info: &TcpInfo| -> String {
                let rtt = info.rtt.map(format_duration).unwrap_or_else(|| "-".into());
                let rttvar = info
                    .rttvar
                    .map(format_duration)
                    .unwrap_or_else(|| "-".into());
                let retrans = info
                    .retransmits
                    .map(|v| v.to_string())
                    .unwrap_or_else(|| "-".into());
                let cwnd = info
                    .cwnd
                    .map(|v| v.to_string())
                    .unwrap_or_else(|| "-".into());
                let mss = info
                    .snd_mss
                    .map(|v| v.to_string())
                    .unwrap_or_else(|| "-".into());
                format!(
                    "  {:<14} rtt {} \u{00B1} {}  retrans {}  cwnd {}  mss {}",
                    label, rtt, rttvar, retrans, cwnd, mss,
                )
            };
            if let Some(info) = &self.tcp_info_post_connect {
                writeln!(
                    f,
                    "{}",
                    LightCyan.paint(render(s.tcp_post_connect_row, info))
                )?;
            }
            if let Some(info) = &self.tcp_info_final {
                writeln!(f, "{}", LightCyan.paint(render(s.tcp_final_row, info)))?;
            }
            if let Some(delta) = TcpInfoDelta::compute(
                self.tcp_info_post_connect.as_ref(),
                self.tcp_info_final.as_ref(),
            ) {
                if let Some(n) = delta.retransmits_during {
                    let label = format!("  {} {n} {}", s.tcp_during, s.tcp_retransmit_word);
                    let painted = if n == 0 {
                        LightCyan.paint(label)
                    } else {
                        LightYellow.paint(label)
                    };
                    writeln!(f, "{painted}")?;
                }
            }
            writeln!(f)?;
        }

        let mut is_text = false;
        let mut is_json = false;
        if let Some(headers) = &self.headers {
            for (key, value) in headers.iter() {
                let value = value.to_str().unwrap_or_default();
                if key == http::header::CONTENT_TYPE {
                    if value.contains("text/") || value.contains("application/json") {
                        is_text = true;
                    }
                    if value.contains("application/json") {
                        is_json = true;
                    }
                }
                let key_lower = key.as_str();
                let show = if let Some(includes) = &self.include_headers {
                    includes.iter().any(|h| h == key_lower)
                } else if let Some(excludes) = &self.exclude_headers {
                    !excludes.iter().any(|h| h == key_lower)
                } else {
                    true
                };
                if show {
                    writeln!(
                        f,
                        "{}: {}",
                        key.to_string().to_train_case(),
                        LightCyan.paint(value)
                    )?;
                }
            }
            writeln!(f)?;
        }

        // Server-Timing breakdown (what the server says happened inside Server Processing).
        // Each row shows: name, a sparkline-style bar sized by share of the reported total,
        // duration, and percent. The header line reconciles the reported sum against the
        // measured Server Processing time so the unaccounted gap (network/queueing) is visible.
        if let Some(entries) = &self.server_timing {
            if !entries.is_empty() {
                const BAR_W: usize = 34;
                let name_w = entries
                    .iter()
                    .map(|e| e.name.chars().count())
                    .max()
                    .unwrap_or(0)
                    .max(4);

                let sum: Duration = entries.iter().filter_map(|e| e.duration).sum();
                let total_ns = (sum.as_nanos() as f64).max(1.0);
                let largest_idx: Option<usize> = entries
                    .iter()
                    .enumerate()
                    .filter_map(|(i, e)| e.duration.filter(|d| !d.is_zero()).map(|d| (i, d)))
                    .max_by_key(|(_, d)| *d)
                    .map(|(i, _)| i);

                let summary = match self.server_processing {
                    Some(sp) if sp > sum => format!(
                        "(\u{03A3} {} {} {} {} \u{00B7} {} {})",
                        format_duration(sum),
                        s.st_sum_of,
                        format_duration(sp),
                        s.server_processing,
                        format_duration(sp - sum),
                        s.st_unaccounted,
                    ),
                    Some(sp) => format!(
                        "(\u{03A3} {} {} {} {})",
                        format_duration(sum),
                        s.st_sum_of,
                        format_duration(sp),
                        s.server_processing,
                    ),
                    None => format!("(\u{03A3} {})", format_duration(sum)),
                };
                writeln!(
                    f,
                    "{} {}",
                    LightGreen.paint(s.server_timing_heading),
                    LightCyan.paint(&summary),
                )?;

                // Lay each bar out at its cumulative offset, so the sequence reads
                // left-to-right like a waterfall inside Server Processing.
                let sum_ns_u = sum.as_nanos();
                let mut cum_ns: u128 = 0;
                for (i, entry) in entries.iter().enumerate() {
                    let name_pad = " ".repeat(name_w.saturating_sub(entry.name.chars().count()));
                    let dur_ns = entry.duration.map(|d| d.as_nanos()).unwrap_or(0);

                    let start_col = ((cum_ns as f64 / total_ns) * BAR_W as f64).round() as usize;
                    let start_col = start_col.min(BAR_W);
                    let mut end_col =
                        (((cum_ns + dur_ns) as f64 / total_ns) * BAR_W as f64).round() as usize;
                    end_col = end_col.min(BAR_W);
                    // Non-zero entries should always paint at least one cell so they
                    // don't disappear into rounding.
                    if dur_ns > 0 && end_col <= start_col {
                        end_col = (start_col + 1).min(BAR_W);
                    }

                    let bar: String = (0..BAR_W)
                        .map(|col| {
                            if dur_ns == 0 {
                                let marker = start_col.min(BAR_W - 1);
                                if col == marker {
                                    '\u{00B7}'
                                } else {
                                    '\u{2591}'
                                }
                            } else if col >= start_col && col < end_col {
                                '\u{2588}'
                            } else {
                                '\u{2591}'
                            }
                        })
                        .collect();

                    let (dur_str, pct_str) = if dur_ns > 0 {
                        let pct = if sum_ns_u > 0 {
                            (dur_ns as f64 / sum_ns_u as f64) * 100.0
                        } else {
                            0.0
                        };
                        (
                            format_duration(entry.duration.unwrap_or_default()),
                            format!("{pct:>5.1}%"),
                        )
                    } else {
                        ("\u{2014}".to_string(), "\u{2013}".to_string())
                    };

                    let is_largest = Some(i) == largest_idx;
                    let bar_painted = if is_largest {
                        LightYellow.paint(&bar).to_string()
                    } else {
                        LightCyan.paint(&bar).to_string()
                    };
                    let dur_painted = if is_largest {
                        LightYellow.paint(format!("{dur_str:>8}")).to_string()
                    } else {
                        LightCyan.paint(format!("{dur_str:>8}")).to_string()
                    };
                    let pct_painted = LightCyan.paint(format!("{pct_str:>6}")).to_string();
                    let desc = entry
                        .description
                        .as_deref()
                        .map(|d| format!("  ({d})"))
                        .unwrap_or_default();

                    writeln!(
                        f,
                        "  {}{}  {}  {}  {}{}",
                        LightCyan.paint(&entry.name),
                        name_pad,
                        bar_painted,
                        dur_painted,
                        pct_painted,
                        desc,
                    )?;

                    cum_ns += dur_ns;
                }
                writeln!(f)?;
            }
        }

        if self.waterfall {
            self.fmt_waterfall(f)?;
        } else {
            let width = 20;

            let mut timelines = vec![];
            // When a DoH/DoT probe ran, render DNS as two columns so the user
            // can see whether the cost was the TLS handshake or the query.
            if let Some(connect) = self.dns_connect {
                timelines.push(Timeline {
                    name: s.dns_connect.to_string(),
                    duration: connect,
                });
                if let Some(query) = self.dns_query() {
                    timelines.push(Timeline {
                        name: s.dns_query.to_string(),
                        duration: query,
                    });
                }
            } else if let Some(value) = self.dns_lookup {
                timelines.push(Timeline {
                    name: s.dns_lookup.to_string(),
                    duration: value,
                });
            }
            if let Some(value) = self.tcp_connect {
                timelines.push(Timeline {
                    name: s.tcp_connect.to_string(),
                    duration: value,
                });
            }
            if let Some(value) = self.tls_handshake {
                timelines.push(Timeline {
                    name: s.tls_handshake.to_string(),
                    duration: value,
                });
            }
            if let Some(value) = self.quic_connect {
                timelines.push(Timeline {
                    name: s.quic_connect.to_string(),
                    duration: value,
                });
            }
            if let Some(value) = self.request_send {
                timelines.push(Timeline {
                    name: s.request_send.to_string(),
                    duration: value,
                });
            }
            if let Some(value) = self.server_processing {
                timelines.push(Timeline {
                    name: s.server_processing.to_string(),
                    duration: value,
                });
            }
            if let Some(value) = self.content_transfer {
                timelines.push(Timeline {
                    name: s.content_transfer.to_string(),
                    duration: value,
                });
            }

            if !timelines.is_empty() {
                write!(f, " ")?;
                for (i, timeline) in timelines.iter().enumerate() {
                    write!(
                        f,
                        "{}",
                        timeline.name.unicode_pad(width, Alignment::Center, true)
                    )?;
                    if i < timelines.len() - 1 {
                        write!(f, " ")?;
                    }
                }
                writeln!(f)?;

                write!(f, "[")?;
                for (i, timeline) in timelines.iter().enumerate() {
                    write!(
                        f,
                        "{}",
                        LightCyan.paint(
                            format_duration(timeline.duration)
                                .unicode_pad(width, Alignment::Center, true)
                                .to_string(),
                        )
                    )?;
                    if i < timelines.len() - 1 {
                        write!(f, "|")?;
                    }
                }
                writeln!(f, "]")?;
            }

            write!(f, " ")?;
            for _ in 0..timelines.len() {
                write!(f, "{}", " ".repeat(width))?;
                write!(f, "|")?;
            }
            writeln!(f)?;
            write!(f, "{}", " ".repeat(width * timelines.len()))?;
            write!(
                f,
                "{}:{}\n\n",
                s.total,
                LightCyan.paint(format_duration(self.total.unwrap_or_default()))
            )?;
        }

        if let Some(body) = &self.body {
            let status = self.status.unwrap_or(StatusCode::OK).as_u16();
            let mut body = std::str::from_utf8(body.as_ref())
                .unwrap_or_default()
                .to_string();
            if let Some(filter) = &self.jq_filter {
                if let Some(filtered) = apply_jq_filter(&body, filter) {
                    body = filtered;
                }
            } else if self.pretty && is_json {
                if let Ok(json_body) = serde_json::from_str::<serde_json::Value>(&body) {
                    if let Ok(value) = serde_json::to_string_pretty(&json_body) {
                        body = value;
                    }
                }
            }
            if self.verbose || self.jq_filter.is_some() || (is_text && body.len() < 4096) {
                let text = format!(
                    "{}: {}",
                    s.body_size,
                    ByteSize(self.body_size.unwrap_or(0) as u64)
                );
                writeln!(f, "{}", LightCyan.paint(text))?;
                self.fmt_throughput(f)?;
                writeln!(f)?;
                if status >= 400 {
                    writeln!(f, "{}", LightRed.paint(body))?;
                } else {
                    writeln!(f, "{body}")?;
                }
            } else {
                let mut save_tips = "".to_string();
                if let Ok(mut file) = NamedTempFile::new() {
                    if let Ok(()) = file.write_all(body.as_bytes()) {
                        save_tips = format!("{}: {}", s.saved_to, file.path().display());
                        let _ = file.keep();
                    }
                }
                let text = format!(
                    "{} {}",
                    s.body_discarded,
                    ByteSize(self.body_size.unwrap_or(0) as u64)
                );
                writeln!(f, "{} {}", LightCyan.paint(text), save_tips)?;
                self.fmt_throughput(f)?;
            }
        }

        Ok(())
    }
}

impl HttpStat {
    /// Render the throughput line(s) under the body summary. Always shown
    /// when the body exceeds `THROUGHPUT_DISPLAY_THRESHOLD` (1 MiB);
    /// verbose mode additionally splits "first 100 KB" vs "tail" so the
    /// user can tell TCP slow-start from steady-state server-side slowness.
    fn fmt_throughput(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Some(wire) = self.wire_body_size else {
            return Ok(());
        };
        if wire < THROUGHPUT_DISPLAY_THRESHOLD {
            return Ok(());
        }
        let Some(total) = self.throughput_bps() else {
            return Ok(());
        };
        let s = self.lang.strings();
        writeln!(
            f,
            "{} {}",
            LightCyan.paint(s.throughput),
            LightCyan.paint(format_throughput(total)),
        )?;
        if self.verbose {
            if let (Some(first), Some(tail)) = (
                self.first_chunk_throughput_bps(),
                self.tail_throughput_bps(),
            ) {
                writeln!(
                    f,
                    "  {} {}  {}  {} {}",
                    LightCyan.paint(s.throughput_first_100k),
                    LightCyan.paint(format_throughput(first)),
                    LightCyan.paint("·"),
                    LightCyan.paint(s.throughput_then),
                    LightCyan.paint(format_throughput(tail)),
                )?;
            }
        }
        Ok(())
    }
}

pub struct BenchmarkSummary {
    pub stats: Vec<HttpStat>,
    pub lang: Lang,
}

impl BenchmarkSummary {
    fn collect_sorted(&self, f: impl Fn(&HttpStat) -> Option<Duration>) -> Vec<Duration> {
        let mut v: Vec<Duration> = self.stats.iter().filter_map(f).collect();
        v.sort();
        v
    }

    fn percentile(sorted: &[Duration], p: f64) -> Option<Duration> {
        if sorted.is_empty() {
            return None;
        }
        let idx = ((p * sorted.len() as f64).ceil() as usize).saturating_sub(1);
        Some(sorted[idx.min(sorted.len() - 1)])
    }
}

impl fmt::Display for BenchmarkSummary {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let total = self.stats.len();
        if total == 0 {
            return Ok(());
        }

        let strs = self.lang.strings();
        // When any run used DoH/DoT, render DNS as two columns; otherwise keep
        // the single DNS Lookup column for the existing plain-UDP path.
        let has_dns_connect = self.stats.iter().any(|s| s.dns_connect.is_some());
        let dns_cols: Vec<(&str, Vec<Duration>)> = if has_dns_connect {
            vec![
                (strs.dns_connect, self.collect_sorted(|s| s.dns_connect)),
                (strs.dns_query, self.collect_sorted(|s| s.dns_query())),
            ]
        } else {
            vec![(strs.dns_lookup, self.collect_sorted(|s| s.dns_lookup))]
        };
        let phases: Vec<(&str, Vec<Duration>)> = dns_cols
            .into_iter()
            .chain([
                (strs.tcp_connect, self.collect_sorted(|s| s.tcp_connect)),
                (strs.tls_handshake, self.collect_sorted(|s| s.tls_handshake)),
                (strs.quic_connect, self.collect_sorted(|s| s.quic_connect)),
                (strs.request_send, self.collect_sorted(|s| s.request_send)),
                (
                    strs.server_processing_short,
                    self.collect_sorted(|s| s.server_processing),
                ),
                (
                    strs.content_transfer_short,
                    self.collect_sorted(|s| s.content_transfer),
                ),
                (strs.total, self.collect_sorted(|s| s.total)),
            ])
            .filter(|(_, v)| !v.is_empty())
            .collect();

        if phases.is_empty() {
            return Ok(());
        }

        writeln!(f)?;
        writeln!(
            f,
            "{}",
            LightGreen.paint(format!(
                "{} ({total} {}) ---",
                strs.benchmark_results_prefix, strs.benchmark_results_requests,
            ))
        )?;
        writeln!(f)?;

        let col_w = 18;
        let label_w = 6;

        // Header row
        write!(f, "{:>label_w$} ", "")?;
        for (name, _) in &phases {
            write!(f, "{}", name.unicode_pad(col_w, Alignment::Center, true))?;
        }
        writeln!(f)?;

        // Stats rows — p50/p95/p99 are standard percentile notation, kept
        // as-is across locales. Only min/max/avg get translated.
        let rows: [(&str, f64); 6] = [
            (strs.min, 0.0),
            (strs.max, f64::INFINITY),
            (strs.avg, f64::NAN),
            ("p50", 0.5),
            ("p95", 0.95),
            ("p99", 0.99),
        ];

        for (label, p) in &rows {
            write!(f, "{} ", LightGreen.paint(format!("{label:>label_w$}")))?;
            for (_, sorted) in &phases {
                let val = if p.is_nan() {
                    // avg
                    if sorted.is_empty() {
                        None
                    } else {
                        let sum: Duration = sorted.iter().sum();
                        Some(sum / sorted.len() as u32)
                    }
                } else if *p == 0.0 {
                    sorted.first().copied()
                } else if p.is_infinite() {
                    sorted.last().copied()
                } else {
                    Self::percentile(sorted, *p)
                };
                let text = match val {
                    Some(d) => format_duration(d),
                    None => "-".to_string(),
                };
                write!(
                    f,
                    "{}",
                    LightCyan.paint(text.unicode_pad(col_w, Alignment::Center, true).to_string())
                )?;
            }
            writeln!(f)?;
        }

        writeln!(f)?;
        let success = self.stats.iter().filter(|s| s.is_success()).count();
        let pct = (success as f64 / total as f64) * 100.0;
        let success_text = format!("{}: {success}/{total} ({pct:.1}%)", strs.success);
        if success == total {
            writeln!(f, "  {}", LightGreen.paint(success_text))?;
        } else {
            writeln!(f, "  {}", LightRed.paint(success_text))?;
        }

        Ok(())
    }
}