devpulse 1.0.0

Developer diagnostics: HTTP timing, build artifact cleanup, environment health checks, port scanning, PATH analysis, and config format conversion
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
//! HTTP request timing visualizer with per-phase breakdown.
//!
//! Uses manual socket-level connections to measure DNS, TCP, TLS,
//! server processing, and content transfer times independently.
//! reqwest cannot expose per-phase timing — manual sockets are required.
//!
//! Extended features:
//! - Security header audit (HSTS, CSP, X-Frame-Options, etc.)
//! - TLS certificate inspection via x509-parser
//! - HTTP redirect following with per-hop timing

use std::collections::BTreeMap;
use std::io::{self, BufRead, BufReader, Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::{Duration, Instant};

use colored::Colorize;
use serde::Serialize;
use thiserror::Error;

use crate::utils::format_size;

/// Errors specific to the HTTP timing module.
#[derive(Error, Debug)]
pub enum HttpError {
    /// The provided URL could not be parsed
    #[error("Invalid URL: {0}")]
    InvalidUrl(String),

    /// DNS lookup failed for the given host
    #[error("DNS lookup failed for '{host}': {source}")]
    DnsError { host: String, source: io::Error },

    /// TCP connection failed
    #[error("TCP connection failed: {0}")]
    TcpError(io::Error),

    /// TLS handshake failed
    #[error("TLS handshake failed: {0}")]
    TlsError(#[from] native_tls::Error),

    /// Server returned an invalid or unparseable response
    #[error("Invalid response from server")]
    InvalidResponse,

    /// Response body exceeds size limit
    #[error("Response body exceeds {0} byte limit")]
    #[allow(dead_code)]
    BodyTooLarge(usize),

    /// Header contains invalid characters (CRLF injection attempt)
    #[error("Invalid header: contains CR/LF characters — possible injection attempt")]
    InvalidHeader,

    /// IO error during request/response
    #[error("IO error: {0}")]
    Io(io::Error),
}

/// Per-phase timing measurements for an HTTP request.
#[derive(Debug, Serialize)]
pub struct TimingResult {
    pub dns_ms: u64,
    pub tcp_ms: u64,
    pub tls_ms: Option<u64>,
    pub server_ms: u64,
    pub transfer_ms: u64,
    pub total_ms: u64,
}

/// HTTP response metadata.
#[derive(Debug, Serialize)]
pub struct ResponseInfo {
    pub status_line: String,
    pub status_code: u16,
    pub headers: BTreeMap<String, String>,
    pub body_size: usize,
}

/// JSON-serializable output combining timing and response info.
#[derive(Debug, Serialize)]
struct JsonOutput {
    url: String,
    status_code: u16,
    status_line: String,
    timing: TimingResult,
    headers: BTreeMap<String, String>,
    body_size: usize,
    remote_addr: String,
}

/// Parsed URL components.
#[derive(Debug)]
struct ParsedUrl {
    scheme: String,
    host: String,
    port: u16,
    path: String,
}

/// Parse a URL string into scheme, host, port, and path components.
fn parse_url(url: &str) -> Result<ParsedUrl, HttpError> {
    let (scheme, rest) = if let Some(stripped) = url.strip_prefix("https://") {
        ("https".to_string(), stripped)
    } else if let Some(stripped) = url.strip_prefix("http://") {
        ("http".to_string(), stripped)
    } else {
        return Err(HttpError::InvalidUrl(format!(
            "{url} — must start with http:// or https://"
        )));
    };

    let default_port: u16 = if scheme == "https" { 443 } else { 80 };

    // Split host from path
    let (host_port, path) = match rest.find('/') {
        Some(i) => (&rest[..i], &rest[i..]),
        None => (rest, "/"),
    };

    // Split host from port
    let (host, port) = if let Some(colon_idx) = host_port.rfind(':') {
        // Check if this is an IPv6 address (contains [ )
        if host_port.contains('[') {
            (host_port.to_string(), default_port)
        } else {
            let port_str = &host_port[colon_idx + 1..];
            let port = port_str
                .parse::<u16>()
                .map_err(|_| HttpError::InvalidUrl(format!("invalid port: {port_str}")))?;
            (host_port[..colon_idx].to_string(), port)
        }
    } else {
        (host_port.to_string(), default_port)
    };

    if host.is_empty() {
        return Err(HttpError::InvalidUrl("empty host".to_string()));
    }

    Ok(ParsedUrl {
        scheme,
        host,
        port,
        path: path.to_string(),
    })
}

/// Maximum allowed HTTP response body size (10 MB).
const MAX_BODY_SIZE: usize = 10 * 1024 * 1024;

/// Build the raw HTTP/1.1 request string.
///
/// Validates all user-supplied headers for CRLF injection before inclusion.
fn build_request(
    method: &str,
    parsed: &ParsedUrl,
    headers: &[String],
    data: &Option<String>,
) -> Result<String, HttpError> {
    let mut req = format!("{method} {} HTTP/1.1\r\n", parsed.path);
    req.push_str(&format!("Host: {}\r\n", parsed.host));
    req.push_str(&format!("User-Agent: devpulse/{}\r\n", env!("CARGO_PKG_VERSION")));
    req.push_str("Accept: */*\r\n");
    req.push_str("Connection: close\r\n");

    // Add user-supplied headers — reject any containing CR or LF to prevent HTTP request smuggling
    for h in headers {
        if h.contains('\r') || h.contains('\n') {
            return Err(HttpError::InvalidHeader);
        }
        req.push_str(h);
        req.push_str("\r\n");
    }

    // Add body with Content-Length if present
    if let Some(body) = data {
        req.push_str(&format!("Content-Length: {}\r\n", body.len()));
        req.push_str("\r\n");
        req.push_str(body);
    } else {
        req.push_str("\r\n");
    }

    Ok(req)
}

/// Parse the HTTP status line (e.g., "HTTP/1.1 200 OK") into the full line and numeric code.
fn parse_status_line(line: &str) -> Result<(String, u16), HttpError> {
    let parts: Vec<&str> = line.splitn(3, ' ').collect();
    if parts.len() < 2 {
        return Err(HttpError::InvalidResponse);
    }
    let code = parts[1]
        .parse::<u16>()
        .map_err(|_| HttpError::InvalidResponse)?;
    Ok((line.to_string(), code))
}

/// Read headers from a buffered reader until the blank line separator.
fn read_headers(
    reader: &mut BufReader<&mut dyn ReadWrite>,
) -> Result<BTreeMap<String, String>, HttpError> {
    let mut headers = BTreeMap::new();
    loop {
        let mut line = String::new();
        reader.read_line(&mut line).map_err(HttpError::Io)?;
        let trimmed = line.trim_end_matches(['\r', '\n']);
        if trimmed.is_empty() {
            break;
        }
        if let Some((key, val)) = trimmed.split_once(':') {
            headers.insert(key.trim().to_lowercase(), val.trim().to_string());
        }
    }
    Ok(headers)
}

/// Trait to unify TcpStream and TlsStream behind a single Read+Write interface.
trait ReadWrite: Read + Write {}
impl ReadWrite for TcpStream {}
impl<S: Read + Write> ReadWrite for native_tls::TlsStream<S> {}

// ─── Security Header Audit ──────────────────────────────────────────────────

/// Security header audit result.
#[derive(Debug, Serialize, Clone)]
pub struct SecurityAudit {
    /// Overall grade: A, B, C, D, or F
    pub grade: char,
    /// Individual header check results
    pub checks: Vec<SecurityCheck>,
    /// Count of headers present
    pub present: usize,
    /// Count of headers missing
    pub missing: usize,
}

/// A single security header check.
#[derive(Debug, Serialize, Clone)]
pub struct SecurityCheck {
    /// Header name
    pub header: String,
    /// Whether the header is present
    pub present: bool,
    /// Current value (if present)
    pub value: Option<String>,
    /// Severity: "critical", "important", or "nice-to-have"
    pub severity: String,
}

/// Headers we audit and their severity classification.
const SECURITY_HEADERS: &[(&str, &str)] = &[
    ("strict-transport-security", "critical"),
    ("content-security-policy", "critical"),
    ("x-frame-options", "important"),
    ("x-content-type-options", "important"),
    ("referrer-policy", "important"),
    ("permissions-policy", "nice-to-have"),
    ("x-xss-protection", "nice-to-have"),
    ("cross-origin-opener-policy", "nice-to-have"),
];

/// Audit response headers for security best practices.
pub fn audit_headers(headers: &BTreeMap<String, String>) -> SecurityAudit {
    let mut checks = Vec::new();
    let mut present = 0usize;
    let mut missing = 0usize;
    let mut score = 0i32;
    let total_weight: i32 = SECURITY_HEADERS
        .iter()
        .map(|(_, sev)| match *sev {
            "critical" => 30,
            "important" => 20,
            _ => 10,
        })
        .sum();

    for &(header, severity) in SECURITY_HEADERS {
        let value = headers.get(header).cloned();
        let is_present = value.is_some();

        if is_present {
            present += 1;
            let weight = match severity {
                "critical" => 30,
                "important" => 20,
                _ => 10,
            };
            score += weight;
        } else {
            missing += 1;
        }

        checks.push(SecurityCheck {
            header: header.to_string(),
            present: is_present,
            value,
            severity: severity.to_string(),
        });
    }

    let pct = if total_weight > 0 {
        (score * 100) / total_weight
    } else {
        0
    };

    let grade = match pct {
        90..=100 => 'A',
        70..=89 => 'B',
        50..=69 => 'C',
        30..=49 => 'D',
        _ => 'F',
    };

    SecurityAudit {
        grade,
        checks,
        present,
        missing,
    }
}

// ─── TLS Certificate Inspection ─────────────────────────────────────────────

/// TLS certificate information extracted via x509-parser.
#[derive(Debug, Serialize, Clone)]
pub struct CertInfo {
    /// Certificate subject (CN or full subject)
    pub subject: String,
    /// Issuer organization or CN
    pub issuer: String,
    /// Not valid before (ISO 8601)
    pub not_before: String,
    /// Not valid after (ISO 8601)
    pub not_after: String,
    /// Days until expiry (negative = expired)
    pub days_until_expiry: i64,
    /// Public key algorithm (RSA, ECDSA, Ed25519, etc.)
    pub key_algorithm: String,
    /// Key size in bits (if applicable)
    pub key_bits: Option<u32>,
    /// Subject Alternative Names
    pub san: Vec<String>,
}

/// Inspect a TLS certificate for a given host.
///
/// Connects to the host, completes a TLS handshake, and extracts
/// certificate metadata using native-tls + x509-parser.
pub fn inspect_cert(host: &str, port: u16) -> Result<CertInfo, HttpError> {
    let addr_str = format!("{host}:{port}");
    let socket_addr = addr_str
        .to_socket_addrs()
        .map_err(|e| HttpError::DnsError {
            host: host.to_string(),
            source: e,
        })?
        .next()
        .ok_or_else(|| HttpError::DnsError {
            host: host.to_string(),
            source: io::Error::new(io::ErrorKind::NotFound, "no addresses found"),
        })?;

    let tcp = TcpStream::connect_timeout(&socket_addr, Duration::from_secs(5))
        .map_err(HttpError::TcpError)?;

    let connector = native_tls::TlsConnector::new()?;
    let tls_stream = connector
        .connect(host, tcp)
        .map_err(|e| match e {
            native_tls::HandshakeError::Failure(err) => HttpError::TlsError(err),
            native_tls::HandshakeError::WouldBlock(_) => HttpError::Io(io::Error::new(
                io::ErrorKind::TimedOut,
                "TLS handshake would block",
            )),
        })?;

    let peer_cert = tls_stream
        .peer_certificate()
        .map_err(HttpError::TlsError)?
        .ok_or(HttpError::InvalidResponse)?;

    let der = peer_cert.to_der().map_err(HttpError::TlsError)?;

    parse_certificate_der(&der)
}

/// Parse a DER-encoded X.509 certificate into our CertInfo struct.
fn parse_certificate_der(der: &[u8]) -> Result<CertInfo, HttpError> {
    use x509_parser::prelude::*;

    let (_, cert) = X509Certificate::from_der(der)
        .map_err(|_| HttpError::InvalidResponse)?;

    // Subject: prefer CN, fall back to full subject string
    let subject = cert
        .subject()
        .iter_common_name()
        .next()
        .and_then(|cn| cn.as_str().ok())
        .map(|s| s.to_string())
        .unwrap_or_else(|| cert.subject().to_string());

    // Issuer: prefer O (organization), fall back to CN, then full string
    let issuer = cert
        .issuer()
        .iter_organization()
        .next()
        .and_then(|o| o.as_str().ok())
        .map(|s| s.to_string())
        .or_else(|| {
            cert.issuer()
                .iter_common_name()
                .next()
                .and_then(|cn| cn.as_str().ok())
                .map(|s| s.to_string())
        })
        .unwrap_or_else(|| cert.issuer().to_string());

    // Validity dates
    let not_before = cert.validity().not_before.to_rfc2822()
        .unwrap_or_else(|_| "unknown".to_string());
    let not_after = cert.validity().not_after.to_rfc2822()
        .unwrap_or_else(|_| "unknown".to_string());

    // Days until expiry
    let now_secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or(Duration::from_secs(0))
        .as_secs() as i64;
    let expiry_secs = cert.validity().not_after.timestamp();
    let days_until_expiry = (expiry_secs - now_secs) / 86400;

    // Key algorithm and size
    let spki = cert.public_key();
    let key_algorithm = match spki.algorithm.algorithm.to_string().as_str() {
        "1.2.840.113549.1.1.1" => "RSA".to_string(),
        "1.2.840.10045.2.1" => "ECDSA".to_string(),
        "1.3.101.112" => "Ed25519".to_string(),
        "1.3.101.113" => "Ed448".to_string(),
        other => other.to_string(),
    };

    let key_bits = match key_algorithm.as_str() {
        "RSA" => Some((spki.raw.len() as u32).saturating_mul(8).saturating_sub(160)),
        "ECDSA" => {
            let raw_len = spki.subject_public_key.data.len();
            if raw_len >= 64 { Some(256) }
            else if raw_len >= 96 { Some(384) }
            else { Some(raw_len as u32 * 4) }
        }
        _ => None,
    };

    // SAN (Subject Alternative Names)
    let san = cert
        .extensions()
        .iter()
        .filter_map(|ext| {
            if let ParsedExtension::SubjectAlternativeName(san) = ext.parsed_extension() {
                Some(san.general_names.iter().filter_map(|name| {
                    match name {
                        GeneralName::DNSName(dns) => Some(dns.to_string()),
                        GeneralName::IPAddress(ip) => Some(format!("{ip:?}")),
                        _ => None,
                    }
                }).collect::<Vec<_>>())
            } else {
                None
            }
        })
        .flatten()
        .collect();

    Ok(CertInfo {
        subject,
        issuer,
        not_before,
        not_after,
        days_until_expiry,
        key_algorithm,
        key_bits,
        san,
    })
}

// ─── Redirect Following ─────────────────────────────────────────────────────

/// A single hop in a redirect chain.
#[derive(Debug, Serialize, Clone)]
pub struct RedirectHop {
    /// URL of this hop
    pub url: String,
    /// HTTP status code
    pub status_code: u16,
    /// Location header (where it redirects to)
    pub location: Option<String>,
    /// Total time for this hop in milliseconds
    pub time_ms: u64,
}

/// Follow HTTP redirects up to `max_hops` times, collecting each hop.
///
/// Returns the list of hops (empty if request was not a redirect),
/// plus the final TimingResult, ResponseInfo, and remote address.
pub fn collect_timing_follow_redirects(
    url: &str,
    method: &str,
    headers: &[String],
    data: &Option<String>,
    max_hops: usize,
) -> Result<(Vec<RedirectHop>, TimingResult, ResponseInfo, String), HttpError> {
    let mut hops = Vec::new();
    let mut current_url = url.to_string();

    for _ in 0..max_hops {
        let hop_start = Instant::now();
        let (timing, response, remote_addr) =
            collect_timing(&current_url, method, headers, data)?;
        let hop_time = hop_start.elapsed().as_millis() as u64;

        // Check if this is a redirect
        if matches!(response.status_code, 301 | 302 | 303 | 307 | 308) {
            let location = response.headers.get("location").cloned();
            hops.push(RedirectHop {
                url: current_url.clone(),
                status_code: response.status_code,
                location: location.clone(),
                time_ms: hop_time,
            });

            if let Some(loc) = location {
                // Handle relative redirects
                if loc.starts_with("http://") || loc.starts_with("https://") {
                    current_url = loc;
                } else if loc.starts_with('/') {
                    // Absolute path: reuse scheme + host
                    let parsed = parse_url(&current_url)?;
                    let port_str = if (parsed.scheme == "https" && parsed.port == 443)
                        || (parsed.scheme == "http" && parsed.port == 80)
                    {
                        String::new()
                    } else {
                        format!(":{}", parsed.port)
                    };
                    current_url = format!("{}://{}{}{}", parsed.scheme, parsed.host, port_str, loc);
                } else {
                    // Relative path
                    let parsed = parse_url(&current_url)?;
                    current_url = format!("{}://{}/{}", parsed.scheme, parsed.host, loc);
                }
            } else {
                // Redirect without Location header — stop
                return Ok((hops, timing, response, remote_addr));
            }
        } else {
            // Not a redirect — return final result
            return Ok((hops, timing, response, remote_addr));
        }
    }

    // Max redirects reached — make one final request
    let (timing, response, remote_addr) = collect_timing(&current_url, method, headers, data)?;
    Ok((hops, timing, response, remote_addr))
}

/// Collect HTTP timing data without printing.
/// Returns (TimingResult, ResponseInfo, remote_addr) for TUI rendering.
pub fn collect_timing(
    url: &str,
    method: &str,
    headers: &[String],
    data: &Option<String>,
) -> Result<(TimingResult, ResponseInfo, String), HttpError> {
    let parsed = parse_url(url)?;
    let is_tls = parsed.scheme == "https";
    let addr_str = format!("{}:{}", parsed.host, parsed.port);
    let total_start = Instant::now();

    let dns_start = Instant::now();
    let socket_addr = addr_str
        .to_socket_addrs()
        .map_err(|e| HttpError::DnsError {
            host: parsed.host.clone(),
            source: e,
        })?
        .next()
        .ok_or_else(|| HttpError::DnsError {
            host: parsed.host.clone(),
            source: io::Error::new(io::ErrorKind::NotFound, "no addresses found"),
        })?;
    let dns_dur = dns_start.elapsed();

    let tcp_start = Instant::now();
    let tcp_stream = TcpStream::connect_timeout(&socket_addr, Duration::from_secs(10))
        .map_err(HttpError::TcpError)?;
    // Set read/write timeouts to prevent hanging on unresponsive servers
    tcp_stream
        .set_read_timeout(Some(Duration::from_secs(30)))
        .map_err(HttpError::Io)?;
    tcp_stream
        .set_write_timeout(Some(Duration::from_secs(10)))
        .map_err(HttpError::Io)?;
    let tcp_dur = tcp_start.elapsed();

    let remote_addr = format!("{socket_addr}");

    let (mut stream, tls_dur): (Box<dyn ReadWrite>, Option<Duration>) = if is_tls {
        let tls_start = Instant::now();
        let connector = native_tls::TlsConnector::new()?;
        let tls_stream = connector
            .connect(&parsed.host, tcp_stream)
            .map_err(|e| match e {
                native_tls::HandshakeError::Failure(err) => HttpError::TlsError(err),
                native_tls::HandshakeError::WouldBlock(_) => HttpError::Io(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "TLS handshake would block",
                )),
            })?;
        let dur = tls_start.elapsed();
        (Box::new(tls_stream), Some(dur))
    } else {
        (Box::new(tcp_stream), None)
    };

    let request = build_request(method, &parsed, headers, data)?;
    stream
        .write_all(request.as_bytes())
        .map_err(HttpError::Io)?;
    stream.flush().map_err(HttpError::Io)?;

    let server_start = Instant::now();
    let mut reader = BufReader::new(&mut *stream as &mut dyn ReadWrite);

    let mut status_line_raw = String::new();
    reader
        .read_line(&mut status_line_raw)
        .map_err(HttpError::Io)?;
    let server_dur = server_start.elapsed();

    let (status_line, status_code) =
        parse_status_line(status_line_raw.trim_end_matches(['\r', '\n']))?;

    let resp_headers = read_headers(&mut reader)?;

    let transfer_start = Instant::now();
    // Cap body read at MAX_BODY_SIZE to prevent OOM from malicious servers
    let mut body = Vec::new();
    reader
        .take(MAX_BODY_SIZE as u64)
        .read_to_end(&mut body)
        .map_err(HttpError::Io)?;
    let transfer_dur = transfer_start.elapsed();

    let total_dur = total_start.elapsed();

    let timing = TimingResult {
        dns_ms: dns_dur.as_millis() as u64,
        tcp_ms: tcp_dur.as_millis() as u64,
        tls_ms: tls_dur.map(|d| d.as_millis() as u64),
        server_ms: server_dur.as_millis() as u64,
        transfer_ms: transfer_dur.as_millis() as u64,
        total_ms: total_dur.as_millis() as u64,
    };

    let response = ResponseInfo {
        status_line,
        status_code,
        headers: resp_headers,
        body_size: body.len(),
    };

    Ok((timing, response, remote_addr))
}

/// Execute the HTTP request with per-phase timing, print colored output or JSON.
pub fn run(
    url: &str,
    method: &str,
    headers: &[String],
    data: &Option<String>,
    json: bool,
) -> Result<(), HttpError> {
    let parsed = parse_url(url)?;
    let is_tls = parsed.scheme == "https";
    let addr_str = format!("{}:{}", parsed.host, parsed.port);
    let total_start = Instant::now();

    // Phase 1: DNS Lookup
    let dns_start = Instant::now();
    let socket_addr = addr_str
        .to_socket_addrs()
        .map_err(|e| HttpError::DnsError {
            host: parsed.host.clone(),
            source: e,
        })?
        .next()
        .ok_or_else(|| HttpError::DnsError {
            host: parsed.host.clone(),
            source: io::Error::new(io::ErrorKind::NotFound, "no addresses found"),
        })?;
    let dns_dur = dns_start.elapsed();

    // Phase 2: TCP Connection
    let tcp_start = Instant::now();
    let tcp_stream = TcpStream::connect_timeout(&socket_addr, Duration::from_secs(10))
        .map_err(HttpError::TcpError)?;
    // Set read/write timeouts to prevent hanging on unresponsive servers
    tcp_stream
        .set_read_timeout(Some(Duration::from_secs(30)))
        .map_err(HttpError::Io)?;
    tcp_stream
        .set_write_timeout(Some(Duration::from_secs(10)))
        .map_err(HttpError::Io)?;
    let tcp_dur = tcp_start.elapsed();

    let remote_addr = format!("{socket_addr}");

    // Phase 3: TLS Handshake (if HTTPS)
    let (mut stream, tls_dur): (Box<dyn ReadWrite>, Option<Duration>) = if is_tls {
        let tls_start = Instant::now();
        let connector = native_tls::TlsConnector::new()?;
        let tls_stream = connector
            .connect(&parsed.host, tcp_stream)
            .map_err(|e| match e {
                native_tls::HandshakeError::Failure(err) => HttpError::TlsError(err),
                native_tls::HandshakeError::WouldBlock(_) => HttpError::Io(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "TLS handshake would block",
                )),
            })?;
        let dur = tls_start.elapsed();
        (Box::new(tls_stream), Some(dur))
    } else {
        (Box::new(tcp_stream), None)
    };

    // Phase 4: Send request + Server processing (TTFB)
    let request = build_request(method, &parsed, headers, data)?;
    stream
        .write_all(request.as_bytes())
        .map_err(HttpError::Io)?;
    stream.flush().map_err(HttpError::Io)?;

    let server_start = Instant::now();
    let mut reader = BufReader::new(&mut *stream as &mut dyn ReadWrite);

    // Read status line
    let mut status_line_raw = String::new();
    reader
        .read_line(&mut status_line_raw)
        .map_err(HttpError::Io)?;
    let server_dur = server_start.elapsed();

    let (status_line, status_code) =
        parse_status_line(status_line_raw.trim_end_matches(['\r', '\n']))?;

    // Read headers
    let resp_headers = read_headers(&mut reader)?;

    // Phase 5: Content Transfer
    let transfer_start = Instant::now();
    // Cap body read at MAX_BODY_SIZE to prevent OOM from malicious servers
    let mut body = Vec::new();
    reader
        .take(MAX_BODY_SIZE as u64)
        .read_to_end(&mut body)
        .map_err(HttpError::Io)?;
    let transfer_dur = transfer_start.elapsed();

    let total_dur = total_start.elapsed();

    let timing = TimingResult {
        dns_ms: dns_dur.as_millis() as u64,
        tcp_ms: tcp_dur.as_millis() as u64,
        tls_ms: tls_dur.map(|d| d.as_millis() as u64),
        server_ms: server_dur.as_millis() as u64,
        transfer_ms: transfer_dur.as_millis() as u64,
        total_ms: total_dur.as_millis() as u64,
    };

    let response = ResponseInfo {
        status_line,
        status_code,
        headers: resp_headers,
        body_size: body.len(),
    };

    // Output
    if json {
        print_json(url, &timing, &response, &remote_addr)?;
    } else {
        print_colored(url, &timing, &response, &remote_addr);
    }

    Ok(())
}

/// Print JSON output for scripting/CI usage.
fn print_json(
    url: &str,
    timing: &TimingResult,
    response: &ResponseInfo,
    remote_addr: &str,
) -> Result<(), HttpError> {
    let output = JsonOutput {
        url: url.to_string(),
        status_code: response.status_code,
        status_line: response.status_line.clone(),
        timing: TimingResult {
            dns_ms: timing.dns_ms,
            tcp_ms: timing.tcp_ms,
            tls_ms: timing.tls_ms,
            server_ms: timing.server_ms,
            transfer_ms: timing.transfer_ms,
            total_ms: timing.total_ms,
        },
        headers: response.headers.clone(),
        body_size: response.body_size,
        remote_addr: remote_addr.to_string(),
    };
    let json_str =
        serde_json::to_string_pretty(&output).map_err(|e| HttpError::Io(io::Error::other(e)))?;
    println!("{json_str}");
    Ok(())
}

/// Print colored terminal output with timing bars and cumulative labels.
fn print_colored(url: &str, timing: &TimingResult, response: &ResponseInfo, remote_addr: &str) {
    println!();
    println!(
        "  {} {} {} {} {}",
        "devpulse".bold(),
        "──".dimmed(),
        "HTTP Timing".bold(),
        "──".dimmed(),
        url.dimmed()
    );
    println!();

    // Status line with color based on status code
    let status_colored = match response.status_code {
        200..=299 => response.status_line.green().bold().to_string(),
        300..=399 => response.status_line.yellow().bold().to_string(),
        _ => response.status_line.red().bold().to_string(),
    };
    println!("  {status_colored}");
    println!();

    // Phase timing bar
    let dns_str = format!("  {}ms  ", timing.dns_ms);
    let tcp_str = format!("  {}ms  ", timing.tcp_ms);
    let tls_str = timing
        .tls_ms
        .map(|ms| format!("  {}ms  ", ms))
        .unwrap_or_default();
    let server_str = format!("  {}ms  ", timing.server_ms);
    let transfer_str = format!("  {}ms  ", timing.transfer_ms);

    // Labels row
    print!("  {}", "DNS Lookup".cyan());
    print!("   {}", "TCP Connect".green());
    if timing.tls_ms.is_some() {
        print!("   {}", "TLS Handshake".yellow());
    }
    print!("   {}", "Server Wait".magenta());
    println!("   {}", "Transfer".blue());

    // Timing values row
    print!("  {}{}", "|".dimmed(), dns_str.cyan());
    print!("{}{}", "|".dimmed(), tcp_str.green());
    if !tls_str.is_empty() {
        print!("{}{}", "|".dimmed(), tls_str.yellow());
    }
    print!("{}{}", "|".dimmed(), server_str.magenta());
    println!("{}{}{}", "|".dimmed(), transfer_str.blue(), "|".dimmed());
    println!();

    // Cumulative timing labels
    let connect = timing.dns_ms + timing.tcp_ms;
    let pretransfer = connect + timing.tls_ms.unwrap_or(0);
    let ttfb = pretransfer + timing.server_ms;

    println!("  {:>14} {:>5}ms", "namelookup:".dimmed(), timing.dns_ms);
    println!("  {:>14} {:>5}ms", "connect:".dimmed(), connect);
    if timing.tls_ms.is_some() {
        println!("  {:>14} {:>5}ms", "pretransfer:".dimmed(), pretransfer);
    }
    println!("  {:>14} {:>5}ms", "TTFB:".dimmed(), ttfb);
    println!(
        "  {:>14} {:>5}ms",
        "total:".white().bold(),
        timing.total_ms.to_string().white().bold()
    );
    println!();

    // Headers
    println!("  {}:", "Headers".bold());
    for (key, val) in &response.headers {
        println!("    {}: {}", key.dimmed(), val);
    }
    println!();

    // Body size
    println!(
        "  {}: {}",
        "Body".bold(),
        format_size(response.body_size as u64)
    );

    // Remote address
    println!("  {}: {}", "Connected to".dimmed(), remote_addr);
    println!();
}

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

    #[test]
    fn test_parse_url_https() {
        let url = parse_url("https://example.com/path").unwrap();
        assert_eq!(url.scheme, "https");
        assert_eq!(url.host, "example.com");
        assert_eq!(url.port, 443);
        assert_eq!(url.path, "/path");
    }

    #[test]
    fn test_parse_url_http_with_port() {
        let url = parse_url("http://localhost:8080/api/test").unwrap();
        assert_eq!(url.scheme, "http");
        assert_eq!(url.host, "localhost");
        assert_eq!(url.port, 8080);
        assert_eq!(url.path, "/api/test");
    }

    #[test]
    fn test_parse_url_no_path() {
        let url = parse_url("https://example.com").unwrap();
        assert_eq!(url.path, "/");
    }

    #[test]
    fn test_parse_url_invalid_no_scheme() {
        assert!(parse_url("example.com").is_err());
    }

    #[test]
    fn test_parse_url_empty_host() {
        assert!(parse_url("http:///path").is_err());
    }

    #[test]
    fn test_parse_status_line_200() {
        let (line, code) = parse_status_line("HTTP/1.1 200 OK").unwrap();
        assert_eq!(code, 200);
        assert_eq!(line, "HTTP/1.1 200 OK");
    }

    #[test]
    fn test_parse_status_line_404() {
        let (_, code) = parse_status_line("HTTP/1.1 404 Not Found").unwrap();
        assert_eq!(code, 404);
    }

    #[test]
    fn test_parse_status_line_invalid() {
        assert!(parse_status_line("INVALID").is_err());
    }

    #[test]
    fn test_build_request_basic() {
        let parsed = ParsedUrl {
            scheme: "https".to_string(),
            host: "example.com".to_string(),
            port: 443,
            path: "/test".to_string(),
        };
        let req = build_request("GET", &parsed, &[], &None).unwrap();
        assert!(req.starts_with("GET /test HTTP/1.1\r\n"));
        assert!(req.contains("Host: example.com\r\n"));
        assert!(req.contains(&format!("User-Agent: devpulse/{}\r\n", env!("CARGO_PKG_VERSION"))));
    }

    #[test]
    fn test_build_request_with_body() {
        let parsed = ParsedUrl {
            scheme: "https".to_string(),
            host: "api.example.com".to_string(),
            port: 443,
            path: "/data".to_string(),
        };
        let body = Some("{\"key\":\"value\"}".to_string());
        let req = build_request("POST", &parsed, &[], &body).unwrap();
        assert!(req.contains("Content-Length: 15\r\n"));
        assert!(req.ends_with("{\"key\":\"value\"}"));
    }

    #[test]
    fn test_build_request_rejects_crlf_header() {
        let parsed = ParsedUrl {
            scheme: "https".to_string(),
            host: "example.com".to_string(),
            port: 443,
            path: "/".to_string(),
        };
        let headers = vec!["X-Evil: injected\r\nX-Fake: yes".to_string()];
        assert!(build_request("GET", &parsed, &headers, &None).is_err());
    }
}