netrunner_cli 0.7.1

A feature-rich Rust-based CLI to test and analyze your internet connection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
//! Speed Test Module
//!
//! A robust, high-performance speed testing implementation optimized for gigabit+ connections:
//! - 50 parallel connections for maximum throughput
//! - Large 500MB chunk downloads to minimize overhead
//! - 2-second warmup period to establish connections
//! - Intelligent server selection based on geolocation
//! - Progressive speed sampling with averaging for accuracy
//! - Excludes warmup period from final calculations
//! - Support for speeds up to 10 Gbps
//! - Fault tolerance and automatic fallbacks

use chrono::Utc;
use colored::*;
use futures::stream::{FuturesUnordered, StreamExt};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::net::IpAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{Mutex, RwLock};

use crate::modules::types::{
    ConnectionQuality, ServerCapabilities, ServerProvider, SpeedTestResult, TestConfig, TestServer,
};
use crate::modules::ui::UI;

const PARALLEL_CONNECTIONS: usize = 50;
const SERVER_SELECTION_COUNT: usize = 3;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeoLocation {
    pub country: String,
    pub city: String,
    pub latitude: f64,
    pub longitude: f64,
    pub isp: Option<String>,
}

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct ServerPerformance {
    pub server: TestServer,
    pub latency_ms: f64,
    pub jitter_ms: f64,
    pub packet_loss: f64,
    pub download_score: f64,
    pub upload_score: f64,
    pub overall_score: f64,
}

pub struct SpeedTest {
    config: TestConfig,
    client: Client,
    ui: UI,
    geo_location: Arc<RwLock<Option<GeoLocation>>>,
    server_pool: Arc<RwLock<Vec<TestServer>>>,
}

impl SpeedTest {
    pub fn new(config: TestConfig) -> Result<Self, Box<dyn std::error::Error>> {
        let client = Client::builder()
            .timeout(Duration::from_secs(30))
            .pool_max_idle_per_host(100)
            .pool_idle_timeout(Duration::from_secs(120))
            .tcp_keepalive(Duration::from_secs(10))
            .http2_keep_alive_interval(Duration::from_secs(10))
            .http2_adaptive_window(true)
            .http2_initial_stream_window_size(1024 * 1024) // 1MB
            .http2_initial_connection_window_size(2 * 1024 * 1024) // 2MB
            .danger_accept_invalid_certs(false)
            .build()?;

        let ui = UI::new(config.clone());

        Ok(Self {
            config,
            client,
            ui,
            geo_location: Arc::new(RwLock::new(None)),
            server_pool: Arc::new(RwLock::new(Vec::new())),
        })
    }

    /// Run the complete speed test with intelligent server selection
    pub async fn run_full_test(&self) -> Result<SpeedTestResult, Box<dyn std::error::Error>> {
        let start = Instant::now();

        // Phase 1: Detect location
        let geo = self.detect_location().await?;
        *self.geo_location.write().await = Some(geo.clone());

        // Phase 2: Build server pool
        self.build_server_pool(&geo).await?;

        // Phase 3: Select best servers
        let best_servers = self.select_best_servers().await?;

        if !self.config.json_output {
            println!(
                "{} {} ({}, {:.0} km)",
                "✓ Selected:".bright_green().bold(),
                best_servers[0].name,
                best_servers[0].location,
                best_servers[0].distance_km.unwrap_or(0.0)
            );
        }

        // Phase 4: Measure latency
        let ping_ms = self.measure_latency(&best_servers[0]).await?;

        // Phase 5: Download test (progressive)
        let download_mbps = self.progressive_download_test(&best_servers).await?;

        // Phase 6: Upload test (progressive)
        let upload_mbps = self.progressive_upload_test(&best_servers).await?;

        // Phase 7: Calculate statistics
        let (jitter_ms, packet_loss) = self.measure_jitter_and_loss(&best_servers[0]).await?;

        let quality = ConnectionQuality::from_speed_and_ping(download_mbps, upload_mbps, ping_ms);
        let test_duration = start.elapsed().as_secs_f64();

        let result = SpeedTestResult {
            timestamp: Utc::now(),
            download_mbps,
            upload_mbps,
            ping_ms,
            jitter_ms,
            packet_loss_percent: packet_loss,
            server_location: best_servers[0].location.clone(),
            server_ip: self.resolve_server_ip(&best_servers[0].url).await,
            client_ip: self.get_client_ip().await,
            quality,
            test_duration_seconds: test_duration,
            isp: geo.isp.clone(),
        };

        if !self.config.json_output {
            self.display_results(&result)?;
        }

        Ok(result)
    }

    /// Detect user's geolocation using multiple services
    async fn detect_location(&self) -> Result<GeoLocation, Box<dyn std::error::Error>> {
        if !self.config.json_output {
            println!("{}", "🌍 Detecting your location...".bright_cyan());
        }

        // Try multiple geolocation services sequentially (first success wins)
        // Try ipapi.co
        match self.try_ipapi_co().await {
            Ok(geo) => {
                if !self.config.json_output {
                    println!(
                        "{} {}, {} (via ipapi.co)",
                        "📍 Location:".bright_green(),
                        geo.city,
                        geo.country
                    );
                    if let Some(isp) = &geo.isp {
                        println!("{} {}", "🔌 ISP:".bright_blue(), isp);
                    }
                }
                return Ok(geo);
            }
            Err(e) => {
                // Log error at trace level for debugging
                if std::env::var("NETRUNNER_DEBUG").is_ok() {
                    eprintln!("[TRACE] ipapi.co geolocation failed: {}", e);
                }
            }
        }

        // Try ip-api.com
        match self.try_ip_api_com().await {
            Ok(geo) => {
                if !self.config.json_output {
                    println!(
                        "{} {}, {} (via ip-api.com)",
                        "📍 Location:".bright_green(),
                        geo.city,
                        geo.country
                    );
                    if let Some(isp) = &geo.isp {
                        println!("{} {}", "🔌 ISP:".bright_blue(), isp);
                    }
                }
                return Ok(geo);
            }
            Err(e) => {
                // Log error at trace level for debugging
                if std::env::var("NETRUNNER_DEBUG").is_ok() {
                    eprintln!("[TRACE] ip-api.com geolocation failed: {}", e);
                }
            }
        }

        // Try ipinfo.io
        match self.try_ipinfo_io().await {
            Ok(geo) => {
                if !self.config.json_output {
                    println!(
                        "{} {}, {} (via ipinfo.io)",
                        "📍 Location:".bright_green(),
                        geo.city,
                        geo.country
                    );
                    if let Some(isp) = &geo.isp {
                        println!("{} {}", "🔌 ISP:".bright_blue(), isp);
                    }
                }
                return Ok(geo);
            }
            Err(e) => {
                // Log error at trace level for debugging
                if std::env::var("NETRUNNER_DEBUG").is_ok() {
                    eprintln!("[TRACE] ipinfo.io geolocation failed: {}", e);
                }
            }
        }

        // Try freegeoip.app
        match self.try_freegeoip_app().await {
            Ok(geo) => {
                if !self.config.json_output {
                    println!(
                        "{} {}, {} (via freegeoip.app)",
                        "📍 Location:".bright_green(),
                        geo.city,
                        geo.country
                    );
                    if let Some(isp) = &geo.isp {
                        println!("{} {}", "🔌 ISP:".bright_blue(), isp);
                    }
                }
                return Ok(geo);
            }
            Err(e) => {
                // Log error at trace level for debugging
                if std::env::var("NETRUNNER_DEBUG").is_ok() {
                    eprintln!("[TRACE] freegeoip.app geolocation failed: {}", e);
                }
            }
        }

        // Try ipwhois.app
        match self.try_ipwhois_app().await {
            Ok(geo) => {
                if !self.config.json_output {
                    println!(
                        "{} {}, {} (via ipwhois.app)",
                        "📍 Location:".bright_green(),
                        geo.city,
                        geo.country
                    );
                    if let Some(isp) = &geo.isp {
                        println!("{} {}", "🔌 ISP:".bright_blue(), isp);
                    }
                }
                return Ok(geo);
            }
            Err(e) => {
                // Log error at trace level for debugging
                if std::env::var("NETRUNNER_DEBUG").is_ok() {
                    eprintln!("[TRACE] ipwhois.app geolocation failed: {}", e);
                }
            }
        }

        // Fallback: Use a default location (USA central) if all services fail
        if !self.config.json_output {
            println!(
                "{} Using default location (USA Central) - all geolocation services failed",
                "".bright_yellow()
            );
        }

        Ok(GeoLocation {
            country: "United States".to_string(),
            city: "Kansas City".to_string(),
            latitude: 39.0997,
            longitude: -94.5786,
            isp: None,
        })
    }

    async fn try_ipapi_co(&self) -> Result<GeoLocation, Box<dyn std::error::Error>> {
        let response = self
            .client
            .get("https://ipapi.co/json/")
            .timeout(Duration::from_secs(5))
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(format!("HTTP error: {}", response.status()).into());
        }

        let json: serde_json::Value = response.json().await?;

        // Check for API error
        if json.get("error").is_some() {
            return Err(format!(
                "API error: {}",
                json["reason"].as_str().unwrap_or("Unknown")
            )
            .into());
        }

        let country = json["country_name"]
            .as_str()
            .filter(|s| !s.is_empty() && *s != "Unknown")
            .ok_or("Invalid country")?
            .to_string();

        let city = json["city"]
            .as_str()
            .filter(|s| !s.is_empty() && *s != "Unknown")
            .ok_or("Invalid city")?
            .to_string();

        let latitude = json["latitude"].as_f64().ok_or("Invalid latitude")?;
        let longitude = json["longitude"].as_f64().ok_or("Invalid longitude")?;

        if latitude == 0.0 && longitude == 0.0 {
            return Err("Invalid coordinates".into());
        }

        Ok(GeoLocation {
            country,
            city,
            latitude,
            longitude,
            isp: json["org"].as_str().map(String::from),
        })
    }

    async fn try_ip_api_com(&self) -> Result<GeoLocation, Box<dyn std::error::Error>> {
        let response = self
            .client
            .get("http://ip-api.com/json/?fields=status,message,country,city,lat,lon,isp")
            .timeout(Duration::from_secs(5))
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(format!("HTTP error: {}", response.status()).into());
        }

        let json: serde_json::Value = response.json().await?;

        // Check for API error
        if json["status"].as_str() != Some("success") {
            return Err(format!(
                "API error: {}",
                json["message"].as_str().unwrap_or("Unknown")
            )
            .into());
        }

        let country = json["country"]
            .as_str()
            .filter(|s| !s.is_empty() && *s != "Unknown")
            .ok_or("Invalid country")?
            .to_string();

        let city = json["city"]
            .as_str()
            .filter(|s| !s.is_empty() && *s != "Unknown")
            .ok_or("Invalid city")?
            .to_string();

        let latitude = json["lat"].as_f64().ok_or("Invalid latitude")?;
        let longitude = json["lon"].as_f64().ok_or("Invalid longitude")?;

        if latitude == 0.0 && longitude == 0.0 {
            return Err("Invalid coordinates".into());
        }

        Ok(GeoLocation {
            country,
            city,
            latitude,
            longitude,
            isp: json["isp"].as_str().map(String::from),
        })
    }

    async fn try_ipinfo_io(&self) -> Result<GeoLocation, Box<dyn std::error::Error>> {
        let response = self
            .client
            .get("https://ipinfo.io/json")
            .timeout(Duration::from_secs(5))
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(format!("HTTP error: {}", response.status()).into());
        }

        let json: serde_json::Value = response.json().await?;

        let country = json["country"]
            .as_str()
            .filter(|s| !s.is_empty())
            .ok_or("Invalid country")?
            .to_string();

        let city = json["city"]
            .as_str()
            .filter(|s| !s.is_empty())
            .ok_or("Invalid city")?
            .to_string();

        // ipinfo.io returns "lat,lon" in the "loc" field
        let loc = json["loc"].as_str().ok_or("Invalid location")?;
        let coords: Vec<&str> = loc.split(',').collect();
        if coords.len() != 2 {
            return Err("Invalid coordinates format".into());
        }

        let latitude: f64 = coords[0].parse().map_err(|_| "Invalid latitude")?;
        let longitude: f64 = coords[1].parse().map_err(|_| "Invalid longitude")?;

        if latitude == 0.0 && longitude == 0.0 {
            return Err("Invalid coordinates".into());
        }

        Ok(GeoLocation {
            country,
            city,
            latitude,
            longitude,
            isp: json["org"].as_str().map(String::from),
        })
    }

    async fn try_freegeoip_app(&self) -> Result<GeoLocation, Box<dyn std::error::Error>> {
        let response = self
            .client
            .get("https://freegeoip.app/json/")
            .timeout(Duration::from_secs(5))
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(format!("HTTP error: {}", response.status()).into());
        }

        let json: serde_json::Value = response.json().await?;

        let country = json["country_name"]
            .as_str()
            .filter(|s| !s.is_empty())
            .ok_or("Invalid country")?
            .to_string();

        let city = json["city"]
            .as_str()
            .filter(|s| !s.is_empty())
            .ok_or("Invalid city")?
            .to_string();

        let latitude = json["latitude"].as_f64().ok_or("Invalid latitude")?;
        let longitude = json["longitude"].as_f64().ok_or("Invalid longitude")?;

        if latitude == 0.0 && longitude == 0.0 {
            return Err("Invalid coordinates".into());
        }

        Ok(GeoLocation {
            country,
            city,
            latitude,
            longitude,
            isp: None,
        })
    }

    async fn try_ipwhois_app(&self) -> Result<GeoLocation, Box<dyn std::error::Error>> {
        let response = self
            .client
            .get("https://ipwho.is/")
            .timeout(Duration::from_secs(5))
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(format!("HTTP error: {}", response.status()).into());
        }

        let json: serde_json::Value = response.json().await?;

        if !json["success"].as_bool().unwrap_or(false) {
            return Err(format!(
                "API error: {}",
                json["message"].as_str().unwrap_or("Unknown")
            )
            .into());
        }

        let country = json["country"]
            .as_str()
            .filter(|s| !s.is_empty())
            .ok_or("Invalid country")?
            .to_string();

        let city = json["city"]
            .as_str()
            .filter(|s| !s.is_empty())
            .ok_or("Invalid city")?
            .to_string();

        let latitude = json["latitude"].as_f64().ok_or("Invalid latitude")?;
        let longitude = json["longitude"].as_f64().ok_or("Invalid longitude")?;

        if latitude == 0.0 && longitude == 0.0 {
            return Err("Invalid coordinates".into());
        }

        Ok(GeoLocation {
            country,
            city,
            latitude,
            longitude,
            isp: json["connection"]["isp"].as_str().map(String::from),
        })
    }

    /// Build a comprehensive server pool based on location
    async fn build_server_pool(&self, geo: &GeoLocation) -> Result<(), Box<dyn std::error::Error>> {
        if !self.config.json_output {
            println!("{}", "🔍 Building server pool...".bright_cyan());
        }

        let mut servers = Vec::new();

        // Try dynamic server discovery first
        servers.extend(self.discover_nearby_servers(geo).await);

        // Add global CDN endpoints as fallback
        servers.extend(self.get_global_cdn_servers());

        // Calculate distances for servers that don't have them
        for server in &mut servers {
            if server.distance_km.is_none() {
                server.distance_km = Some(self.estimate_distance(geo, server));
            }
        }

        // Sort by distance (nearest first)
        servers.sort_by(|a, b| {
            a.distance_km
                .unwrap_or(f64::MAX)
                .partial_cmp(&b.distance_km.unwrap_or(f64::MAX))
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        // Keep only the best servers
        servers.truncate(20);

        let server_count = servers.len();
        *self.server_pool.write().await = servers;

        if !self.config.json_output {
            println!("{} {} servers in pool", "".bright_green(), server_count);
        }

        Ok(())
    }

    fn get_global_cdn_servers(&self) -> Vec<TestServer> {
        // Global fallback servers - used with low priority
        vec![
            TestServer {
                name: "Cloudflare Global".to_string(),
                url: "https://speed.cloudflare.com".to_string(),
                location: "Global CDN".to_string(),
                distance_km: Some(5000.0), // Lower priority than regional servers
                latency_ms: None,
                provider: ServerProvider::Cloudflare,
                capabilities: ServerCapabilities {
                    supports_download: true,
                    supports_upload: true,
                    supports_latency: true,
                    max_test_size_mb: 2000,
                    geographic_weight: 0.5, // Medium weight for global anycast
                },
                quality_score: None,
                country_code: None,
                city: None,
                is_backup: true,
            },
            TestServer {
                name: "Google Global".to_string(),
                url: "https://www.google.com".to_string(),
                location: "Global CDN".to_string(),
                distance_km: Some(5000.0),
                latency_ms: None,
                provider: ServerProvider::Google,
                capabilities: ServerCapabilities {
                    supports_download: true,
                    supports_upload: false,
                    supports_latency: true,
                    max_test_size_mb: 100,
                    geographic_weight: 0.4,
                },
                quality_score: None,
                country_code: None,
                city: None,
                is_backup: true,
            },
        ]
    }

    /// Dynamically discover nearby speed test servers based on user location
    async fn discover_nearby_servers(&self, geo: &GeoLocation) -> Vec<TestServer> {
        let mut servers = Vec::new();

        if !self.config.json_output {
            println!(
                "{}",
                "🔍 Discovering nearby speed test servers...".bright_cyan()
            );
        }

        // Try to fetch speedtest.net server list
        if let Ok(speedtest_servers) = self.fetch_speedtest_net_servers(geo).await {
            servers.extend(speedtest_servers);
        }

        // Add continent-based CDN servers
        servers.extend(self.get_continent_servers(geo));

        // Add country-specific servers
        servers.extend(self.get_country_servers(geo));

        if !self.config.json_output {
            println!(
                "{} {} nearby servers",
                "✓ Found".bright_green(),
                servers.len()
            );
        }

        servers
    }

    /// Fetch real speedtest.net server list based on location
    async fn fetch_speedtest_net_servers(
        &self,
        geo: &GeoLocation,
    ) -> Result<Vec<TestServer>, Box<dyn std::error::Error>> {
        // Speedtest.net uses a JSON API to get nearby servers
        let url = "https://www.speedtest.net/api/js/servers?engine=js&limit=10";

        if let Ok(response) = self.client.get(url).send().await {
            if let Ok(text) = response.text().await {
                // Parse the response and create TestServer objects
                if let Ok(servers) = self.parse_speedtest_servers(&text, geo) {
                    return Ok(servers);
                }
            }
        }

        // Fallback: Use Open Speed Test servers
        self.get_open_speedtest_servers(geo).await
    }

    fn parse_speedtest_servers(
        &self,
        json: &str,
        geo: &GeoLocation,
    ) -> Result<Vec<TestServer>, Box<dyn std::error::Error>> {
        // Simple JSON parsing for speedtest.net format
        // Format: [{"id":123,"host":"server.host.com","lat":40.7,"lon":-74.0,"name":"New York","country":"US","sponsor":"ISP Name"}]

        let mut servers = Vec::new();

        // Use serde_json to parse
        if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(json) {
            if let Some(array) = parsed.as_array() {
                for server in array.iter().take(10) {
                    if let (Some(host), Some(name), Some(country), Some(lat), Some(lon)) = (
                        server.get("host").and_then(|v| v.as_str()),
                        server.get("name").and_then(|v| v.as_str()),
                        server.get("country").and_then(|v| v.as_str()),
                        server.get("lat").and_then(|v| v.as_f64()),
                        server.get("lon").and_then(|v| v.as_f64()),
                    ) {
                        let distance =
                            self.calculate_distance(geo.latitude, geo.longitude, lat, lon);

                        servers.push(TestServer {
                            name: format!("{}, {}", name, country),
                            url: format!("https://{}", host),
                            location: format!("{}, {}", name, country),
                            distance_km: Some(distance),
                            latency_ms: None,
                            provider: ServerProvider::Custom(
                                host.split('.').next().unwrap_or("speedtest").to_string(),
                            ),
                            capabilities: ServerCapabilities {
                                supports_download: true,
                                supports_upload: true,
                                supports_latency: true,
                                max_test_size_mb: 1000,
                                geographic_weight: 1.0,
                            },
                            quality_score: None,
                            country_code: Some(country.to_string()),
                            city: Some(name.to_string()),
                            is_backup: false,
                        });
                    }
                }
            }
        }

        if servers.is_empty() {
            Err("No servers parsed".into())
        } else {
            Ok(servers)
        }
    }

    async fn get_open_speedtest_servers(
        &self,
        geo: &GeoLocation,
    ) -> Result<Vec<TestServer>, Box<dyn std::error::Error>> {
        // Fallback to manually curated list of high-performance servers
        let mut servers = Vec::new();

        // Major internet exchanges and data centers
        let endpoints = vec![
            (
                "Cloudflare (Anycast)",
                "https://speed.cloudflare.com",
                0.0,
                0.0,
                "Global",
            ),
            (
                "LibreSpeed DE-IX",
                "https://frankfurt.speedtest.wtnet.de",
                50.1109,
                8.6821,
                "Frankfurt, Germany",
            ),
            (
                "LibreSpeed AMS-IX",
                "https://ams.speedtest.wtnet.de",
                52.3676,
                4.9041,
                "Amsterdam, Netherlands",
            ),
            (
                "LibreSpeed Singapore",
                "https://sg.speedtest.wtnet.de",
                1.3521,
                103.8198,
                "Singapore",
            ),
            (
                "LibreSpeed New York",
                "https://nyc.speedtest.wtnet.de",
                40.7128,
                -74.0060,
                "New York, USA",
            ),
            (
                "LibreSpeed Los Angeles",
                "https://la.speedtest.wtnet.de",
                34.0522,
                -118.2437,
                "Los Angeles, USA",
            ),
            (
                "LibreSpeed Tokyo",
                "https://tyo.speedtest.wtnet.de",
                35.6762,
                139.6503,
                "Tokyo, Japan",
            ),
            (
                "LibreSpeed London",
                "https://lon.speedtest.wtnet.de",
                51.5074,
                -0.1278,
                "London, UK",
            ),
            (
                "LibreSpeed Sydney",
                "https://syd.speedtest.wtnet.de",
                -33.8688,
                151.2093,
                "Sydney, Australia",
            ),
        ];

        for (name, url, lat, lon, location) in endpoints {
            let distance = if lat == 0.0 && lon == 0.0 {
                999999.0 // Global anycast
            } else {
                self.calculate_distance(geo.latitude, geo.longitude, lat, lon)
            };

            servers.push(TestServer {
                name: name.to_string(),
                url: url.to_string(),
                location: location.to_string(),
                distance_km: Some(distance),
                latency_ms: None,
                provider: ServerProvider::Custom("LibreSpeed".to_string()),
                capabilities: ServerCapabilities {
                    supports_download: true,
                    supports_upload: true,
                    supports_latency: true,
                    max_test_size_mb: 2000,
                    geographic_weight: 0.9,
                },
                quality_score: None,
                country_code: Some(location.split(", ").last().unwrap_or("").to_string()),
                city: Some(location.split(", ").next().unwrap_or(location).to_string()),
                is_backup: false,
            });
        }

        Ok(servers)
    }

    fn get_continent_servers(&self, geo: &GeoLocation) -> Vec<TestServer> {
        let mut servers = Vec::new();

        // Determine continent based on coordinates
        let continent = self.determine_continent(geo.latitude, geo.longitude);

        match continent.as_str() {
            "North America" => {
                servers.push(self.create_server_with_coords(
                    geo,
                    "US East Coast Hub",
                    "https://ash.speedtest.wtnet.de",
                    "Ashburn, USA",
                    Some("US".to_string()),
                    39.0438,
                    -77.4874,
                ));
                servers.push(self.create_server_with_coords(
                    geo,
                    "US West Coast Hub",
                    "https://lax.speedtest.wtnet.de",
                    "Los Angeles, USA",
                    Some("US".to_string()),
                    34.0522,
                    -118.2437,
                ));
            }
            "Europe" => {
                servers.push(self.create_server_with_coords(
                    geo,
                    "Europe Central Hub",
                    "https://frankfurt.speedtest.wtnet.de",
                    "Frankfurt, Germany",
                    Some("DE".to_string()),
                    50.1109,
                    8.6821,
                ));
                servers.push(self.create_server_with_coords(
                    geo,
                    "Europe West Hub",
                    "https://lon.speedtest.wtnet.de",
                    "London, UK",
                    Some("GB".to_string()),
                    51.5074,
                    -0.1278,
                ));
            }
            "Asia" => {
                servers.push(self.create_server_with_coords(
                    geo,
                    "Asia Pacific Hub",
                    "https://sg.speedtest.wtnet.de",
                    "Singapore",
                    Some("SG".to_string()),
                    1.3521,
                    103.8198,
                ));
                servers.push(self.create_server_with_coords(
                    geo,
                    "Asia East Hub",
                    "https://tokyo.speedtest.wtnet.de",
                    "Tokyo, Japan",
                    Some("JP".to_string()),
                    35.6762,
                    139.6503,
                ));
            }
            "South America" => {
                servers.push(self.create_server_with_coords(
                    geo,
                    "South America Hub",
                    "https://saopaulo.speedtest.wtnet.de",
                    "São Paulo, Brazil",
                    Some("BR".to_string()),
                    -23.5505,
                    -46.6333,
                ));
            }
            "Africa" => {
                servers.push(self.create_server_with_coords(
                    geo,
                    "Africa Hub",
                    "https://capetown.speedtest.wtnet.de",
                    "Cape Town, South Africa",
                    Some("ZA".to_string()),
                    -33.9249,
                    18.4241,
                ));
            }
            "Oceania" => {
                servers.push(self.create_server_with_coords(
                    geo,
                    "Oceania Hub",
                    "https://syd.speedtest.wtnet.de",
                    "Sydney, Australia",
                    Some("AU".to_string()),
                    -33.8688,
                    151.2093,
                ));
            }
            _ => {}
        }

        servers
    }

    fn determine_continent(&self, lat: f64, lon: f64) -> String {
        // Simple continent determination based on coordinates
        if lat > 15.0 && lon > -130.0 && lon < -50.0 {
            "North America".to_string()
        } else if lat < 15.0 && lat > -60.0 && lon > -85.0 && lon < -30.0 {
            "South America".to_string()
        } else if lat > 35.0 && lon > -15.0 && lon < 60.0 {
            "Europe".to_string()
        } else if lat > -40.0 && lat < 40.0 && lon > -20.0 && lon < 55.0 {
            "Africa".to_string()
        } else if lat > -15.0 && lon > 60.0 && lon < 180.0 {
            "Asia".to_string()
        } else if lat < -10.0 && lon > 110.0 && lon < 180.0 {
            "Oceania".to_string()
        } else {
            "Unknown".to_string()
        }
    }

    fn get_country_servers(&self, geo: &GeoLocation) -> Vec<TestServer> {
        let mut servers = Vec::new();

        // Add country-specific servers based on common countries
        match geo.country.as_str() {
            "United States" | "US" => {
                servers.push(self.create_server(
                    "US Central",
                    "https://dal.speedtest.wtnet.de",
                    "Dallas, USA",
                    Some("US".to_string()),
                ));
            }
            "United Kingdom" | "GB" | "UK" => {
                servers.push(self.create_server(
                    "UK Primary",
                    "https://lon.speedtest.wtnet.de",
                    "London, UK",
                    Some("GB".to_string()),
                ));
            }
            "Germany" | "DE" => {
                servers.push(self.create_server(
                    "DE Primary",
                    "https://frankfurt.speedtest.wtnet.de",
                    "Frankfurt, Germany",
                    Some("DE".to_string()),
                ));
            }
            "France" | "FR" => {
                servers.push(self.create_server(
                    "FR Primary",
                    "https://paris.speedtest.wtnet.de",
                    "Paris, France",
                    Some("FR".to_string()),
                ));
            }
            "Japan" | "JP" => {
                servers.push(self.create_server(
                    "JP Primary",
                    "https://tyo.speedtest.wtnet.de",
                    "Tokyo, Japan",
                    Some("JP".to_string()),
                ));
            }
            "Australia" | "AU" => {
                servers.push(self.create_server(
                    "AU Primary",
                    "https://syd.speedtest.wtnet.de",
                    "Sydney, Australia",
                    Some("AU".to_string()),
                ));
            }
            "Canada" | "CA" => {
                servers.push(self.create_server(
                    "CA Primary",
                    "https://tor.speedtest.wtnet.de",
                    "Toronto, Canada",
                    Some("CA".to_string()),
                ));
            }
            _ => {}
        }

        servers
    }

    fn calculate_distance(&self, lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
        // Haversine formula for distance calculation
        let r = 6371.0; // Earth's radius in km
        let d_lat = (lat2 - lat1).to_radians();
        let d_lon = (lon2 - lon1).to_radians();
        let lat1 = lat1.to_radians();
        let lat2 = lat2.to_radians();

        let a = (d_lat / 2.0).sin() * (d_lat / 2.0).sin()
            + lat1.cos() * lat2.cos() * (d_lon / 2.0).sin() * (d_lon / 2.0).sin();
        let c = 2.0 * a.sqrt().atan2((1.0 - a).sqrt());

        r * c
    }

    #[allow(clippy::too_many_arguments)]
    fn create_server_with_coords(
        &self,
        geo: &GeoLocation,
        name: &str,
        url: &str,
        location: &str,
        country_code: Option<String>,
        lat: f64,
        lon: f64,
    ) -> TestServer {
        let distance = self.calculate_distance(geo.latitude, geo.longitude, lat, lon);

        TestServer {
            name: name.to_string(),
            url: url.to_string(),
            location: location.to_string(),
            distance_km: Some(distance),
            latency_ms: None,
            provider: ServerProvider::Custom("LibreSpeed".to_string()),
            capabilities: ServerCapabilities {
                supports_download: true,
                supports_upload: true,
                supports_latency: true,
                max_test_size_mb: 2000,
                geographic_weight: 1.0,
            },
            quality_score: None,
            country_code,
            city: Some(location.split(", ").next().unwrap_or(location).to_string()),
            is_backup: false,
        }
    }

    fn create_server(
        &self,
        name: &str,
        url: &str,
        location: &str,
        country_code: Option<String>,
    ) -> TestServer {
        TestServer {
            name: name.to_string(),
            url: url.to_string(),
            location: location.to_string(),
            distance_km: None,
            latency_ms: None,
            provider: ServerProvider::Cloudflare,
            capabilities: ServerCapabilities {
                supports_download: true,
                supports_upload: true,
                supports_latency: true,
                max_test_size_mb: 1000,
                geographic_weight: 1.2,
            },
            quality_score: None,
            country_code,
            city: Some(location.split(',').next().unwrap_or("").trim().to_string()),
            is_backup: false,
        }
    }

    fn determine_region(&self, country: &str) -> String {
        match country {
            "United States" | "Canada" | "Mexico" => "North America".to_string(),
            "United Kingdom" | "Germany" | "France" | "Spain" | "Italy" | "Netherlands"
            | "Belgium" | "Switzerland" | "Austria" | "Poland" => "Europe".to_string(),
            "Japan" | "China" | "South Korea" | "Singapore" | "Australia" | "New Zealand"
            | "India" => "Asia Pacific".to_string(),
            "Brazil" | "Argentina" | "Chile" => "South America".to_string(),
            _ => "Other".to_string(),
        }
    }

    fn estimate_distance(&self, geo: &GeoLocation, server: &TestServer) -> f64 {
        // Simplified distance estimation based on region
        // In production, use actual server coordinates
        let region = self.determine_region(&geo.country);

        if let Some(city) = &server.city {
            if city.contains(&geo.city) {
                return 10.0; // Same city
            }
        }

        match (region.as_str(), server.location.as_str()) {
            ("North America", loc) if loc.contains("USA") || loc.contains("Canada") => 500.0,
            ("Europe", loc) if loc.contains("Europe") || loc.contains("UK") => 300.0,
            ("Asia Pacific", loc) if loc.contains("Asia") || loc.contains("Japan") => 400.0,
            _ => 5000.0, // Cross-region
        }
    }

    /// Select the best servers by testing them concurrently
    async fn select_best_servers(&self) -> Result<Vec<TestServer>, Box<dyn std::error::Error>> {
        if !self.config.json_output {
            println!("{}", "⚡ Testing server performance...".bright_cyan());
        }

        let servers = self.server_pool.read().await.clone();

        if servers.is_empty() {
            return Err("No servers in pool".into());
        }

        let mut test_results = Vec::new();

        // Test servers concurrently - test up to 15 servers
        let mut futures = FuturesUnordered::new();

        for server in servers.into_iter().take(15) {
            let client = self.client.clone();
            futures.push(async move { Self::quick_latency_test(&client, &server).await });
        }

        while let Some(result) = futures.next().await {
            if let Ok(mut server) = result {
                if let Some(latency) = server.latency_ms {
                    let distance = server.distance_km.unwrap_or(1000.0);
                    let geographic_weight = server.capabilities.geographic_weight;

                    // Calculate quality score considering latency, distance, and geographic weight
                    // Lower latency and distance = higher score
                    // Formula: base_score * geographic_weight / (latency_penalty + distance_penalty)
                    let latency_penalty = latency.max(1.0); // Avoid division by near-zero
                    let distance_penalty = (distance / 100.0).max(1.0);
                    server.quality_score =
                        Some((10000.0 * geographic_weight) / (latency_penalty + distance_penalty));

                    test_results.push(server);
                }
            }
        }

        if test_results.is_empty() {
            return Err("No servers responded to latency tests".into());
        }

        // Sort by quality score (highest first)
        test_results.sort_by(|a, b| {
            b.quality_score
                .unwrap_or(0.0)
                .partial_cmp(&a.quality_score.unwrap_or(0.0))
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        let selected = test_results
            .into_iter()
            .take(SERVER_SELECTION_COUNT)
            .collect::<Vec<_>>();

        if !self.config.json_output {
            println!(
                "{} {} servers selected for testing",
                "".bright_green(),
                selected.len()
            );
            for (i, server) in selected.iter().enumerate() {
                println!(
                    "  {}. {} - {:.1} ms ({:.0} km)",
                    i + 1,
                    server.name,
                    server.latency_ms.unwrap_or(0.0),
                    server.distance_km.unwrap_or(0.0)
                );
            }
        }

        Ok(selected)
    }

    async fn quick_latency_test(
        client: &Client,
        server: &TestServer,
    ) -> Result<TestServer, Box<dyn std::error::Error>> {
        let mut latencies = Vec::new();
        let mut server = server.clone();

        for _ in 0..3 {
            let start = Instant::now();
            match client
                .head(&server.url)
                .timeout(Duration::from_secs(2))
                .send()
                .await
            {
                Ok(resp) if resp.status().is_success() || resp.status().is_redirection() => {
                    latencies.push(start.elapsed().as_millis() as f64);
                }
                _ => {}
            }
        }

        if !latencies.is_empty() {
            server.latency_ms = Some(latencies.iter().sum::<f64>() / latencies.len() as f64);
        }

        Ok(server)
    }

    /// Progressive download test - starts with rough estimate, refines over time
    async fn progressive_download_test(
        &self,
        servers: &[TestServer],
    ) -> Result<f64, Box<dyn std::error::Error>> {
        if !self.config.json_output {
            self.ui.show_section_header("Testing Download Speed")?;
        }

        // Create bandwidth monitor (render at end)
        let bw_monitor = if !self.config.json_output && self.config.animation_enabled {
            let monitor = self
                .ui
                .create_bandwidth_monitor("DOWNLOAD SPEED BANDWIDTH MONITOR", "Download");
            Some(monitor)
        } else {
            None
        };

        let total_bytes = Arc::new(Mutex::new(0usize));
        let start = Instant::now();
        let test_duration = Duration::from_secs(15);

        let mut handles = Vec::new();

        // Start 50 parallel download connections
        for i in 0..PARALLEL_CONNECTIONS {
            let server = &servers[i % servers.len()];
            let url = format!("{}/__down?bytes=100000000", server.url); // 100MB chunks
            let client = self.client.clone();
            let total_bytes = Arc::clone(&total_bytes);
            let test_start = start;

            let handle = tokio::spawn(async move {
                let end_time = test_start + test_duration;

                while Instant::now() < end_time {
                    match client.get(&url).send().await {
                        Ok(response) => {
                            let mut stream = response.bytes_stream();

                            while let Some(chunk_result) = stream.next().await {
                                if Instant::now() >= end_time {
                                    break;
                                }
                                if let Ok(chunk) = chunk_result {
                                    let mut total = total_bytes.lock().await;
                                    *total += chunk.len();
                                }
                            }
                        }
                        Err(_) => {
                            tokio::time::sleep(Duration::from_millis(100)).await;
                        }
                    }

                    if Instant::now() >= end_time {
                        break;
                    }
                }
            });

            handles.push(handle);
        }

        // Monitor progress and collect speed samples with live rendering
        let total_bytes_monitor = Arc::clone(&total_bytes);
        let monitor_clone = bw_monitor.clone();

        let monitor_handle = tokio::spawn(async move {
            let mut last_bytes = 0;
            let mut last_time = Instant::now();
            let end_time = start + test_duration;
            let mut first_render = true;

            while Instant::now() < end_time {
                tokio::time::sleep(Duration::from_millis(200)).await;

                let bytes = *total_bytes_monitor.lock().await;
                let time_diff = last_time.elapsed().as_secs_f64();

                if time_diff >= 0.2 {
                    let bytes_diff = bytes.saturating_sub(last_bytes);
                    let speed = (bytes_diff as f64 * 8.0) / (time_diff * 1_000_000.0);

                    if let Some(ref monitor) = monitor_clone {
                        monitor.update(speed).await;

                        // Render live update
                        if first_render {
                            let _ = monitor.render_live().await;
                            first_render = false;
                        } else {
                            let _ = monitor.render_live_update().await;
                        }
                    }

                    last_bytes = bytes;
                    last_time = Instant::now();
                }
            }
        });

        // Wait for all tasks to complete
        for handle in handles {
            let _ = handle.await;
        }
        let _ = monitor_handle.await;

        // Calculate final speed
        let elapsed = start.elapsed().as_secs_f64();
        let total = *total_bytes.lock().await;

        let mbps = if total > 1_000_000 && elapsed > 1.0 {
            let bits = total as f64 * 8.0;
            bits / (elapsed * 1_000_000.0)
        } else {
            1.0 // Minimum 1 Mbps if test failed
        };

        // Mark as final and render one last time with checkmark
        if let Some(ref monitor) = bw_monitor {
            monitor.update(mbps).await;
            monitor.mark_final().await;
            let _ = monitor.render_live_update().await;
        }

        Ok(mbps.clamp(1.0, 10_000.0))
    }

    /// Progressive upload test
    async fn progressive_upload_test(
        &self,
        servers: &[TestServer],
    ) -> Result<f64, Box<dyn std::error::Error>> {
        if !self.config.json_output {
            self.ui.show_section_header("Testing Upload Speed")?;
        }

        // Create bandwidth monitor (render at end)
        let bw_monitor = if !self.config.json_output && self.config.animation_enabled {
            let monitor = self
                .ui
                .create_bandwidth_monitor("UPLOAD SPEED BANDWIDTH MONITOR", "Upload");
            Some(monitor)
        } else {
            None
        };

        let total_bytes = Arc::new(Mutex::new(0usize));
        let start = Instant::now();
        let test_duration = Duration::from_secs(15);

        // Use 5MB chunks for upload
        let chunk_size = 5 * 1024 * 1024;
        let test_data = vec![0u8; chunk_size];

        let mut handles = Vec::new();

        // Start 10 parallel upload connections
        for i in 0..10 {
            let server = &servers[i % servers.len()];
            let url = format!("{}/__up", server.url);
            let client = self.client.clone();
            let total_bytes = Arc::clone(&total_bytes);
            let data = test_data.clone();
            let test_start = start;

            let handle = tokio::spawn(async move {
                let end_time = test_start + test_duration;

                while Instant::now() < end_time {
                    match client
                        .post(&url)
                        .body(data.clone())
                        .timeout(Duration::from_secs(10))
                        .send()
                        .await
                    {
                        Ok(_) => {
                            let mut total = total_bytes.lock().await;
                            *total += data.len();
                        }
                        Err(_) => {
                            tokio::time::sleep(Duration::from_millis(100)).await;
                        }
                    }
                }
            });

            handles.push(handle);
        }

        // Monitor progress and collect speed samples with live rendering
        let total_bytes_monitor = Arc::clone(&total_bytes);
        let monitor_clone = bw_monitor.clone();

        let monitor_handle = tokio::spawn(async move {
            let mut last_bytes = 0;
            let mut last_time = Instant::now();
            let end_time = start + test_duration;
            let mut first_render = true;

            while Instant::now() < end_time {
                tokio::time::sleep(Duration::from_millis(200)).await;

                let bytes = *total_bytes_monitor.lock().await;
                let time_diff = last_time.elapsed().as_secs_f64();

                if time_diff >= 0.2 {
                    let bytes_diff = bytes.saturating_sub(last_bytes);
                    let speed = (bytes_diff as f64 * 8.0) / (time_diff * 1_000_000.0);

                    if let Some(ref monitor) = monitor_clone {
                        monitor.update(speed).await;

                        // Render live update
                        if first_render {
                            let _ = monitor.render_live().await;
                            first_render = false;
                        } else {
                            let _ = monitor.render_live_update().await;
                        }
                    }

                    last_bytes = bytes;
                    last_time = Instant::now();
                }
            }
        });

        // Wait for all tasks to complete
        for handle in handles {
            let _ = handle.await;
        }
        let _ = monitor_handle.await;

        // Calculate final speed
        let elapsed = start.elapsed().as_secs_f64();
        let total = *total_bytes.lock().await;

        let mbps = if total > 1_000_000 && elapsed > 1.0 {
            let bits = total as f64 * 8.0;
            bits / (elapsed * 1_000_000.0)
        } else {
            1.0 // Minimum 1 Mbps if test failed
        };

        // Mark as final and render one last time with checkmark
        if let Some(ref monitor) = bw_monitor {
            monitor.update(mbps).await;
            monitor.mark_final().await;
            let _ = monitor.render_live_update().await;
        }

        Ok(mbps.clamp(1.0, 10_000.0))
    }

    async fn measure_latency(
        &self,
        server: &TestServer,
    ) -> Result<f64, Box<dyn std::error::Error>> {
        if !self.config.json_output {
            self.ui.show_section_header("Testing Latency")?;
        }

        let pb = if !self.config.json_output && self.config.animation_enabled {
            Some(self.ui.create_ping_spinner("Latency: -- ms"))
        } else {
            None
        };

        let mut latencies = Vec::new();

        for _i in 0..10 {
            let start = Instant::now();
            match self
                .client
                .head(&server.url)
                .timeout(Duration::from_secs(2))
                .send()
                .await
            {
                Ok(resp) if resp.status().is_success() || resp.status().is_redirection() => {
                    let latency = start.elapsed().as_millis() as f64;
                    latencies.push(latency);

                    // Update spinner with current average
                    if let Some(pb) = &pb {
                        let current_avg = latencies.iter().sum::<f64>() / latencies.len() as f64;
                        pb.set_message(format!("Latency: {:.1} ms", current_avg));
                    }
                }
                _ => {}
            }

            tokio::time::sleep(Duration::from_millis(100)).await;
        }

        let avg_latency = if !latencies.is_empty() {
            latencies.iter().sum::<f64>() / latencies.len() as f64
        } else {
            50.0
        };

        if let Some(pb) = pb {
            pb.finish_and_clear();

            // Color code based on latency thresholds with explanations
            let (latency_colored, explanation) = if avg_latency <= 20.0 {
                (
                    format!("{:.1} ms", avg_latency).bright_green(),
                    "(Excellent - ideal for gaming)".bright_green().dimmed(),
                )
            } else if avg_latency <= 50.0 {
                (
                    format!("{:.1} ms", avg_latency).bright_cyan(),
                    "(Good - suitable for most activities)"
                        .bright_cyan()
                        .dimmed(),
                )
            } else if avg_latency <= 100.0 {
                (
                    format!("{:.1} ms", avg_latency).bright_yellow(),
                    "(Fair - noticeable lag)".bright_yellow().dimmed(),
                )
            } else {
                (
                    format!("{:.1} ms", avg_latency).bright_red(),
                    "(Poor - significant lag)".bright_red().dimmed(),
                )
            };

            println!("✓ Latency: {} {}", latency_colored, explanation);
        }

        Ok(avg_latency)
    }

    async fn measure_jitter_and_loss(
        &self,
        server: &TestServer,
    ) -> Result<(f64, f64), Box<dyn std::error::Error>> {
        let mut latencies = Vec::new();
        let mut lost = 0;
        let total = 20;

        for _ in 0..total {
            let start = Instant::now();
            match self
                .client
                .head(&server.url)
                .timeout(Duration::from_secs(1))
                .send()
                .await
            {
                Ok(resp) if resp.status().is_success() || resp.status().is_redirection() => {
                    latencies.push(start.elapsed().as_millis() as f64);
                }
                _ => {
                    lost += 1;
                }
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }

        let jitter = if latencies.len() > 1 {
            let mean = latencies.iter().sum::<f64>() / latencies.len() as f64;
            let variance =
                latencies.iter().map(|&x| (x - mean).powi(2)).sum::<f64>() / latencies.len() as f64;
            variance.sqrt()
        } else {
            0.0
        };

        let packet_loss = (lost as f64 / total as f64) * 100.0;

        Ok((jitter, packet_loss))
    }

    async fn get_client_ip(&self) -> Option<IpAddr> {
        if let Ok(response) = self
            .client
            .get("https://api.ipify.org?format=json")
            .timeout(Duration::from_secs(3))
            .send()
            .await
        {
            if let Ok(json) = response.json::<serde_json::Value>().await {
                return json["ip"].as_str().and_then(|s| s.parse::<IpAddr>().ok());
            }
        }
        None
    }

    async fn resolve_server_ip(&self, url: &str) -> Option<IpAddr> {
        if let Ok(parsed) = url.parse::<reqwest::Url>() {
            if let Some(host) = parsed.host_str() {
                if let Ok(addrs) = tokio::net::lookup_host(format!("{}:443", host)).await {
                    return addrs.into_iter().next().map(|addr| addr.ip());
                }
            }
        }
        None
    }

    fn display_results(&self, result: &SpeedTestResult) -> std::io::Result<()> {
        println!();
        println!("{}", "".repeat(60).bright_blue());
        println!(
            "{}",
            "           SPEED TEST RESULTS           "
                .bright_yellow()
                .bold()
        );
        println!("{}", "".repeat(60).bright_blue());
        println!();

        println!(
            "{:20} {}",
            "Download:".bright_blue().bold(),
            format!("{:.1} Mbps", result.download_mbps)
                .bright_green()
                .bold()
        );

        println!(
            "{:20} {}",
            "Upload:".bright_blue().bold(),
            format!("{:.1} Mbps", result.upload_mbps)
                .bright_green()
                .bold()
        );

        println!(
            "{:20} {}",
            "Ping:".bright_blue().bold(),
            format!("{:.1} ms", result.ping_ms).bright_cyan().bold()
        );

        println!(
            "{:20} {}",
            "Jitter:".bright_blue().bold(),
            format!("{:.1} ms", result.jitter_ms).bright_cyan()
        );

        if result.packet_loss_percent > 0.0 {
            println!(
                "{:20} {}",
                "Packet Loss:".bright_blue().bold(),
                format!("{:.1}%", result.packet_loss_percent).bright_red()
            );
        }

        println!(
            "{:20} {}",
            "Server:".bright_blue().bold(),
            result.server_location.bright_cyan()
        );

        if let Some(isp) = &result.isp {
            println!("{:20} {}", "ISP:".bright_blue().bold(), isp.bright_cyan());
        }

        println!(
            "{:20} {}",
            "Quality:".bright_blue().bold(),
            format!("{}", result.quality).bright_yellow().bold()
        );

        println!();
        println!("{}", "".repeat(60).bright_blue());

        Ok(())
    }
}

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

    #[test]
    fn test_region_determination() {
        // Install the ring crypto provider (reqwest needs a TLS backend even for unit tests)
        let _ = rustls::crypto::ring::default_provider().install_default();
        let config = TestConfig::default();
        let speed_test = SpeedTest::new(config).unwrap();

        assert_eq!(
            speed_test.determine_region("United States"),
            "North America"
        );
        assert_eq!(speed_test.determine_region("Germany"), "Europe");
        assert_eq!(speed_test.determine_region("Japan"), "Asia Pacific");
    }
}