netspeed-cli 0.10.2

Command-line interface for testing internet bandwidth using speedtest.net
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
//! Phase definitions for the speed test lifecycle.
//!
//! ## Design
//!
//! - [`PhaseContext`] — shared state with private fields (ISP: clients use accessors)
//! - [`PhaseOutcome`] — result of phase execution  
//! - Each phase is an async function that takes (orch, ctx)
//! - [`PhaseExecutor`] — runs phases in sequence

use crate::error::Error;
use crate::services::Services;
use crate::theme::Colors;
use futures::future::BoxFuture;
use std::sync::Arc;

use crate::orchestrator::Orchestrator;
use crate::task_runner::TestRunResult;
use crate::types::Server;

/// Named result from a ping/latency test — replaces the positional tuple.
#[derive(Debug, Clone)]
pub struct PingResult {
    pub latency_ms: f64,
    pub jitter_ms: f64,
    pub packet_loss_pct: f64,
    pub samples: Vec<f64>,
}

/// Context passed between phases — holds all data accumulated during execution.
pub struct PhaseContext {
    client_location: Option<crate::types::ClientLocation>,
    client_ip: Option<String>,
    server: Option<Server>,
    ping_result: Option<PingResult>,
    download_result: Option<TestRunResult>,
    upload_result: Option<TestRunResult>,
    list_printed: bool,
    elapsed: Option<std::time::Duration>,
    services: std::sync::Arc<dyn Services>,
}

impl PhaseContext {
    /// Create a new context with the given services.
    pub fn new(services: std::sync::Arc<dyn Services>) -> Self {
        Self {
            client_location: None,
            client_ip: None,
            server: None,
            ping_result: None,
            download_result: None,
            upload_result: None,
            list_printed: false,
            elapsed: None,
            services,
        }
    }

    // === New setter/taker methods for encapsulation ===

    /// Take the server (removes from context).
    pub fn take_server(&mut self) -> Option<Server> {
        self.server.take()
    }

    /// Set the server.
    pub fn set_server(&mut self, server: Server) {
        self.server = Some(server);
    }

    /// Set client IP.
    pub fn set_client_ip(&mut self, ip: String) {
        self.client_ip = Some(ip);
    }

    /// Set client location.
    pub fn set_client_location(&mut self, location: Option<crate::types::ClientLocation>) {
        self.client_location = location;
    }

    /// Set ping result.
    pub fn set_ping_result(&mut self, result: PingResult) {
        self.ping_result = Some(result);
    }

    /// Take ping result.
    pub fn take_ping_result(&mut self) -> Option<PingResult> {
        self.ping_result.take()
    }

    /// Set download result.
    pub fn set_download_result(&mut self, result: TestRunResult) {
        self.download_result = Some(result);
    }

    /// Take download result.
    pub fn take_download_result(&mut self) -> Option<TestRunResult> {
        self.download_result.take()
    }

    /// Set upload result.
    pub fn set_upload_result(&mut self, result: TestRunResult) {
        self.upload_result = Some(result);
    }

    /// Take upload result.
    pub fn take_upload_result(&mut self) -> Option<TestRunResult> {
        self.upload_result.take()
    }

    /// Mark list as printed.
    pub fn set_list_printed(&mut self) {
        self.list_printed = true;
    }
}

impl std::fmt::Debug for PhaseContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PhaseContext")
            .field("client_location", &self.client_location)
            .field("client_ip", &self.client_ip)
            .field("server", &self.server)
            .field("ping_result", &self.ping_result)
            .field("download_result", &self.download_result)
            .field("upload_result", &self.upload_result)
            .field("list_printed", &self.list_printed)
            .field("elapsed", &self.elapsed)
            .field("services", &"dyn Services")
            .finish()
    }
}

/// Phase outcome.
#[derive(Debug)]
pub enum PhaseOutcome {
    PhaseCompleted,
    PhaseEarlyExit,
    PhaseError(Error),
}

/// Async phase function signature.
pub type PhaseFn =
    for<'a> fn(&'a Orchestrator, &'a mut PhaseContext) -> BoxFuture<'a, PhaseOutcome>;

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

pub struct PhaseExecutor {
    phases: Vec<PhaseFn>,
}

impl PhaseExecutor {
    pub fn new() -> Self {
        Self { phases: Vec::new() }
    }

    pub fn register(mut self, phase: PhaseFn) -> Self {
        self.phases.push(phase);
        self
    }

    pub async fn execute_all(&self, orch: &Orchestrator) -> Result<(), Error> {
        let mut ctx = PhaseContext::new(orch.services_arc());
        for phase in &self.phases {
            let outcome = phase(orch, &mut ctx).await;
            match outcome {
                PhaseOutcome::PhaseCompleted => {}
                PhaseOutcome::PhaseEarlyExit => return Ok(()),
                PhaseOutcome::PhaseError(e) => return Err(e),
            }
        }
        Ok(())
    }
}

pub type PhaseResults = (
    Option<PingResult>,
    Option<TestRunResult>,
    Option<TestRunResult>,
);

/// PhaseContext accessor methods.
impl PhaseContext {
    pub fn client_location(&self) -> Option<&crate::types::ClientLocation> {
        self.client_location.as_ref()
    }

    pub fn client_ip(&self) -> Option<&str> {
        self.client_ip.as_deref()
    }

    pub fn server(&self) -> Option<&Server> {
        self.server.as_ref()
    }

    pub fn ping_result(&self) -> Option<&PingResult> {
        self.ping_result.as_ref()
    }

    pub fn download_result(&self) -> Option<&TestRunResult> {
        self.download_result.as_ref()
    }

    pub fn upload_result(&self) -> Option<&TestRunResult> {
        self.upload_result.as_ref()
    }

    pub fn is_list_printed(&self) -> bool {
        self.list_printed
    }

    pub fn elapsed(&self) -> Option<std::time::Duration> {
        self.elapsed
    }

    pub fn services(&self) -> &dyn Services {
        self.services.as_ref()
    }

    pub fn services_arc(&self) -> std::sync::Arc<dyn Services> {
        self.services.clone()
    }

    pub fn with_client_ip(mut self, ip: impl Into<String>) -> Self {
        self.client_ip = Some(ip.into());
        self
    }

    pub fn with_client_location(mut self, location: crate::types::ClientLocation) -> Self {
        self.client_location = Some(location);
        self
    }

    pub fn with_server(mut self, server: Server) -> Self {
        self.server = Some(server);
        self
    }

    pub fn with_ping_result(mut self, ping: PingResult) -> Self {
        self.ping_result = Some(ping);
        self
    }

    pub fn with_download_result(mut self, result: TestRunResult) -> Self {
        self.download_result = Some(result);
        self
    }

    pub fn with_upload_result(mut self, result: TestRunResult) -> Self {
        self.upload_result = Some(result);
        self
    }

    pub fn mark_list_printed(&mut self) {
        self.list_printed = true;
    }

    pub fn set_elapsed(&mut self, elapsed: std::time::Duration) {
        self.elapsed = Some(elapsed);
    }

    pub fn take_results(&mut self) -> PhaseResults {
        let ping = self.ping_result.take();
        let download = self.download_result.take();
        let upload = self.upload_result.take();
        (ping, download, upload)
    }

    pub fn with_services(mut self, services: std::sync::Arc<dyn Services>) -> Self {
        self.services = services;
        self
    }
}

// ============================================================================
// Phase Implementations (use task_runner for async operations)
// ============================================================================

pub(crate) fn run_early_exit<'a>(
    orch: &'a Orchestrator,
    _ctx: &'a mut PhaseContext,
) -> BoxFuture<'a, PhaseOutcome> {
    let early_exit = orch.early_exit().clone();
    Box::pin(async move {
        // early_exit already cloned above

        if early_exit.show_config_path {
            match crate::config::get_config_path_internal() {
                Some(path) => eprintln!("Configuration file: {}", path.display()),
                None => eprintln!("No configuration path available."),
            }
            return PhaseOutcome::PhaseEarlyExit;
        }

        if let Some(shell) = early_exit.generate_completion {
            let shell_name = match shell {
                crate::cli::ShellType::Bash => "netspeed-cli.bash",
                crate::cli::ShellType::Zsh => "_netspeed-cli",
                crate::cli::ShellType::Fish => "netspeed-cli.fish",
                crate::cli::ShellType::PowerShell => "_netspeed-cli.ps1",
                crate::cli::ShellType::Elvish => "netspeed-cli.elv",
            };
            eprintln!("Shell completions for {shell:?}: {shell_name}");
            return PhaseOutcome::PhaseEarlyExit;
        }

        if early_exit.history {
            match crate::history::show(orch.config().theme()) {
                Ok(()) => PhaseOutcome::PhaseEarlyExit,
                Err(e) => PhaseOutcome::PhaseError(e),
            }
        } else if early_exit.dry_run {
            orch.run_dry_run();
            PhaseOutcome::PhaseEarlyExit
        } else {
            PhaseOutcome::PhaseCompleted
        }
    })
}

pub(crate) fn run_header<'a>(
    orch: &'a Orchestrator,
    _ctx: &'a mut PhaseContext,
) -> BoxFuture<'a, PhaseOutcome> {
    Box::pin(async move {
        if orch.is_verbose() {
            let version = env!("CARGO_PKG_VERSION");
            let nc = crate::terminal::no_color();
            let theme = orch.config().theme();
            eprintln!();
            if nc {
                eprintln!("  netspeed-cli v{version}  ·  speedtest.net");
                eprintln!();
            } else {
                eprintln!(
                    "  {} v{}  {}  {}",
                    Colors::header("NetSpeed CLI", theme),
                    version,
                    Colors::dimmed("·", theme),
                    Colors::muted("speedtest.net", theme)
                );
                eprintln!();
            }
        }
        PhaseOutcome::PhaseCompleted
    })
}

pub(crate) fn run_server_discovery<'a>(
    orch: &'a Orchestrator,
    ctx: &'a mut PhaseContext,
) -> BoxFuture<'a, PhaseOutcome> {
    let is_verbose = orch.is_verbose();
    let spinner = if is_verbose {
        Some(crate::progress::create_spinner("Finding servers..."))
    } else {
        None
    };

    Box::pin(async move {
        // Discover servers asynchronously using injected service
        let result = ctx.services().server_service().fetch_servers().await;
        let (mut servers, client_location) = match result {
            Ok((servers, location)) => (servers, location),
            Err(e) => return PhaseOutcome::PhaseError(e),
        };
        ctx.set_client_location(client_location);

        if let Some(ref pb) = spinner {
            let theme = orch.config().theme();
            crate::progress::finish_ok(pb, &format!("Found {} servers", servers.len()), theme);
            eprintln!();
        }

        if orch.config().list() {
            if let Err(e) = crate::formatter::format_list(&servers, orch.config().theme()) {
                return PhaseOutcome::PhaseError(e.into());
            }
            ctx.set_list_printed();
            return PhaseOutcome::PhaseEarlyExit;
        }

        if !orch.config().server_ids().is_empty() {
            servers.retain(|s| orch.config().server_ids().contains(&s.id));
        }
        if !orch.config().exclude_ids().is_empty() {
            servers.retain(|s| !orch.config().exclude_ids().contains(&s.id));
        }

        if servers.is_empty() {
            return PhaseOutcome::PhaseError(crate::error::Error::ServerNotFound(
                "No servers match your criteria.".to_string(),
            ));
        }

        let server = match ctx.services().server_service().select_best(&servers) {
            Ok(s) => s,
            Err(e) => return PhaseOutcome::PhaseError(e),
        };

        if is_verbose {
            let dist = crate::common::format_distance(server.distance);
            eprintln!();
            let theme = orch.config().theme();
            if crate::terminal::no_color() {
                eprintln!("  Server:   {} ({})", server.sponsor, server.name);
                eprintln!("  Location: {} ({dist})", server.country);
            } else {
                eprintln!(
                    "  {}   {} ({})",
                    Colors::dimmed("Server:", theme),
                    Colors::bold(&server.sponsor, theme),
                    server.name
                );
                eprintln!(
                    "  {} {} ({dist})",
                    Colors::dimmed("Location:", theme),
                    server.country
                );
            }
            eprintln!();
        }

        ctx.set_server(server);
        PhaseOutcome::PhaseCompleted
    })
}

pub(crate) fn run_ip_discovery<'a>(
    orch: &'a Orchestrator,
    ctx: &'a mut PhaseContext,
) -> BoxFuture<'a, PhaseOutcome> {
    Box::pin(async move {
        let is_verbose = orch.is_verbose();
        let result = ctx.services().ip_service().discover_ip().await;
        match result {
            Ok(ip) => ctx.set_client_ip(ip),
            Err(e) => {
                if is_verbose {
                    eprintln!("Warning: Could not discover client IP: {e}");
                }
            }
        }
        PhaseOutcome::PhaseCompleted
    })
}

pub(crate) fn run_ping<'a>(
    orch: &'a Orchestrator,
    ctx: &'a mut PhaseContext,
) -> BoxFuture<'a, PhaseOutcome> {
    let no_download = orch.config().no_download();
    let no_upload = orch.config().no_upload();
    if no_download && no_upload {
        return Box::pin(async { PhaseOutcome::PhaseCompleted });
    }

    let server = match ctx.take_server() {
        Some(s) => s,
        None => {
            return Box::pin(async {
                PhaseOutcome::PhaseError(crate::error::Error::context("No server selected"))
            });
        }
    };

    let is_verbose = orch.is_verbose();
    let spinner = if is_verbose {
        Some(crate::progress::create_spinner("Testing latency..."))
    } else {
        None
    };

    let services = ctx.services_arc();

    Box::pin(async move {
        let result = services.server_service().ping_server(&server).await;
        let ping_result = match result {
            Ok(r) => r,
            Err(e) => return PhaseOutcome::PhaseError(e),
        };

        if let Some(ref pb) = spinner {
            let theme = orch.config().theme();
            let msg = if crate::terminal::no_color() {
                format!("Latency: {:.2} ms", ping_result.0)
            } else {
                format!(
                    "Latency: {}",
                    Colors::info(&format!("{:.2} ms", ping_result.0), theme)
                )
            };
            crate::progress::finish_ok(pb, &msg, theme);
        }

        ctx.set_ping_result(PingResult {
            latency_ms: ping_result.0,
            jitter_ms: ping_result.1,
            packet_loss_pct: ping_result.2,
            samples: ping_result.3,
        });
        // Put server back for download/upload phases
        ctx.set_server(server);
        PhaseOutcome::PhaseCompleted
    })
}

pub(crate) fn run_download<'a>(
    orch: &'a Orchestrator,
    ctx: &'a mut PhaseContext,
) -> BoxFuture<'a, PhaseOutcome> {
    let single = orch.config().single();
    let is_verbose = orch.is_verbose();
    // Only show spinner in non-verbose mode (verbose mode has progress bar which is better)
    let spinner = if !is_verbose {
        Some(crate::progress::create_spinner("Testing download..."))
    } else {
        None
    };

    Box::pin(async move {
        if orch.config().no_download() {
            return PhaseOutcome::PhaseCompleted;
        }

        let server = match ctx.take_server() {
            Some(s) => s,
            None => {
                return PhaseOutcome::PhaseError(crate::error::Error::context(
                    "No server selected",
                ));
            }
        };

        let client = orch.http_client();
        let progress = if is_verbose {
            Arc::new(crate::progress::Tracker::new_animated("Download"))
        } else {
            Arc::new(crate::progress::Tracker::with_target(
                "Download",
                indicatif::ProgressDrawTarget::hidden(),
            ))
        };

        match crate::download::run(client, &server, single, progress).await {
            Ok((avg, peak, total_bytes, samples)) => {
                if let Some(ref pb) = spinner {
                    let theme = orch.config().theme();
                    let msg = if crate::terminal::no_color() {
                        format!("Download: {:.2} Mbps", avg / 1_000_000.0)
                    } else {
                        format!(
                            "Download: {}",
                            Colors::good(&format!("{:.2} Mbps", avg / 1_000_000.0), theme)
                        )
                    };
                    crate::progress::finish_ok(pb, &msg, theme);
                }
                ctx.set_download_result(crate::task_runner::TestRunResult {
                    avg_bps: avg,
                    peak_bps: peak,
                    total_bytes,
                    duration_secs: 0.0,
                    speed_samples: samples,
                    latency_under_load: None,
                });
                // Put server back for upload phase
                ctx.set_server(server);
                PhaseOutcome::PhaseCompleted
            }
            Err(e) => PhaseOutcome::PhaseError(e),
        }
    })
}

pub(crate) fn run_upload<'a>(
    orch: &'a Orchestrator,
    ctx: &'a mut PhaseContext,
) -> BoxFuture<'a, PhaseOutcome> {
    let single = orch.config().single();
    let is_verbose = orch.is_verbose();
    // Only show spinner in non-verbose mode (verbose mode has progress bar which is better)
    let spinner = if !is_verbose {
        Some(crate::progress::create_spinner("Testing upload..."))
    } else {
        None
    };

    Box::pin(async move {
        if orch.config().no_upload() {
            return PhaseOutcome::PhaseCompleted;
        }

        let server = match ctx.take_server() {
            Some(s) => s,
            None => {
                return PhaseOutcome::PhaseError(crate::error::Error::context(
                    "No server selected",
                ));
            }
        };

        let client = orch.http_client();
        let progress = if is_verbose {
            Arc::new(crate::progress::Tracker::new_animated("Upload"))
        } else {
            Arc::new(crate::progress::Tracker::with_target(
                "Upload",
                indicatif::ProgressDrawTarget::hidden(),
            ))
        };

        match crate::upload::run(client, &server, single, progress).await {
            Ok((avg, peak, total_bytes, samples)) => {
                if let Some(ref pb) = spinner {
                    let theme = orch.config().theme();
                    let msg = if crate::terminal::no_color() {
                        format!("Upload: {:.2} Mbps", avg / 1_000_000.0)
                    } else {
                        format!(
                            "Upload: {}",
                            Colors::good(&format!("{:.2} Mbps", avg / 1_000_000.0), theme)
                        )
                    };
                    crate::progress::finish_ok(pb, &msg, theme);
                }
                ctx.set_upload_result(crate::task_runner::TestRunResult {
                    avg_bps: avg,
                    peak_bps: peak,
                    total_bytes,
                    duration_secs: 0.0,
                    speed_samples: samples,
                    latency_under_load: None,
                });
                // Put server back for result phase
                ctx.set_server(server);
                PhaseOutcome::PhaseCompleted
            }
            Err(e) => PhaseOutcome::PhaseError(e),
        }
    })
}

// Bandwidth and result phases use async task_runner - handled in legacy for now

pub(crate) fn run_result<'a>(
    orch: &'a Orchestrator,
    ctx: &'a mut PhaseContext,
) -> BoxFuture<'a, PhaseOutcome> {
    Box::pin(async move {
        // Take server info before taking results
        let server_info = match ctx.take_server() {
            Some(s) => crate::types::ServerInfo {
                id: s.id.clone(),
                name: s.name.clone(),
                sponsor: s.sponsor.clone(),
                country: s.country.clone(),
                distance: s.distance,
            },
            None => return PhaseOutcome::PhaseCompleted,
        };

        let (ping_result, download_result, upload_result) = ctx.take_results();

        let (ping, jitter, packet_loss, ping_samples) = match ping_result {
            Some(r) => (
                Some(r.latency_ms),
                Some(r.jitter_ms),
                Some(r.packet_loss_pct),
                r.samples,
            ),
            None => (None, None, None, Vec::new()),
        };

        let dl_result = download_result.unwrap_or_default();
        let ul_result = upload_result.unwrap_or_default();

        let mut result = crate::types::TestResult::from_test_runs(
            server_info,
            ping,
            jitter,
            packet_loss,
            &ping_samples,
            &dl_result,
            &ul_result,
            ctx.client_ip().map(|s| s.to_string()),
            ctx.client_location().cloned(),
        );

        let config = orch.config();
        result.phases = crate::types::TestPhases {
            ping: if config.no_download() && config.no_upload() {
                crate::types::PhaseResult::skipped("both bandwidth phases disabled")
            } else {
                crate::types::PhaseResult::completed()
            },
            download: if config.no_download() {
                crate::types::PhaseResult::skipped("disabled by user")
            } else {
                crate::types::PhaseResult::completed()
            },
            upload: if config.no_upload() {
                crate::types::PhaseResult::skipped("disabled by user")
            } else {
                crate::types::PhaseResult::completed()
            },
        };

        if config.should_save_history() {
            if let Err(e) = orch.saver().save(&result) {
                eprintln!("Warning: Failed to save test result: {e}");
            }
        }

        // Delegate to orchestrator for output
        match orch.output_results(
            &mut result,
            &dl_result,
            &ul_result,
            std::time::Duration::from_secs(0),
        ) {
            Ok(()) => PhaseOutcome::PhaseCompleted,
            Err(e) => PhaseOutcome::PhaseError(e),
        }
    })
}

// ============================================================================
// Default Phase Registry
// ============================================================================

pub fn create_default_executor() -> PhaseExecutor {
    PhaseExecutor::new()
        .register(run_early_exit)
        .register(run_header)
        .register(run_server_discovery)
        .register(run_ip_discovery)
        .register(run_ping)
        .register(run_download)
        .register(run_upload)
        .register(run_result)
}

/// Run all phases in order.
pub async fn run_all_phases(orch: &Orchestrator) -> Result<(), Error> {
    let executor = create_default_executor();
    executor.execute_all(orch).await
}

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

    fn make_test_services() -> std::sync::Arc<dyn Services> {
        let client = reqwest::Client::new();
        std::sync::Arc::new(crate::services::ServiceContainer::new(client))
    }

    #[test]
    fn test_phase_context_default() {
        let ctx = PhaseContext::new(make_test_services());
        assert!(ctx.client_ip().is_none());
        assert!(ctx.server().is_none());
    }

    #[test]
    fn test_phase_context_builder() {
        let ctx = PhaseContext::new(make_test_services()).with_client_ip("192.168.1.1");

        assert_eq!(ctx.client_ip(), Some("192.168.1.1"));
    }

    #[test]
    fn test_phase_executor_register() {
        let _executor = PhaseExecutor::new()
            .register(run_early_exit)
            .register(run_header);
    }

    fn make_ping_result() -> PingResult {
        PingResult {
            latency_ms: 12.5,
            jitter_ms: 1.3,
            packet_loss_pct: 0.0,
            samples: vec![11.0, 12.0, 14.0],
        }
    }

    #[test]
    fn test_ping_result_fields() {
        let r = make_ping_result();
        assert!((r.latency_ms - 12.5).abs() < f64::EPSILON);
        assert!((r.jitter_ms - 1.3).abs() < f64::EPSILON);
        assert!((r.packet_loss_pct - 0.0).abs() < f64::EPSILON);
        assert_eq!(r.samples, vec![11.0, 12.0, 14.0]);
    }

    #[test]
    fn test_phase_context_set_take_ping_result() {
        let mut ctx = PhaseContext::new(make_test_services());
        assert!(ctx.ping_result().is_none());

        ctx.set_ping_result(make_ping_result());
        assert!(ctx.ping_result().is_some());
        assert!((ctx.ping_result().unwrap().latency_ms - 12.5).abs() < f64::EPSILON);

        let taken = ctx.take_ping_result().unwrap();
        assert!((taken.latency_ms - 12.5).abs() < f64::EPSILON);
        assert!(ctx.ping_result().is_none());
    }

    #[test]
    fn test_phase_context_with_ping_result_builder() {
        let ctx = PhaseContext::new(make_test_services()).with_ping_result(make_ping_result());
        assert!((ctx.ping_result().unwrap().jitter_ms - 1.3).abs() < f64::EPSILON);
    }

    #[test]
    fn test_take_results_returns_ping() {
        let mut ctx = PhaseContext::new(make_test_services());
        ctx.set_ping_result(make_ping_result());

        let (ping, dl, ul) = ctx.take_results();
        assert!(ping.is_some());
        assert!((ping.unwrap().packet_loss_pct).abs() < f64::EPSILON);
        assert!(dl.is_none());
        assert!(ul.is_none());
        // Fields consumed — context is empty after take
        assert!(ctx.ping_result().is_none());
    }
}