rust-mc-status 2.0.0

High-performance asynchronous Rust library for querying Minecraft server status (Java & Bedrock)
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
//! Client for querying Minecraft server status.
//!
//! This module provides the [`McClient`] struct for performing server status queries.
//! It supports both Java Edition and Bedrock Edition servers with automatic SRV record
//! lookup, DNS caching, and batch queries.
//!
//! # Examples
//!
//! ## Basic Usage
//!
//! ```no_run
//! use rust_mc_status::{McClient, ServerEdition};
//! use std::time::Duration;
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let client = McClient::new()
//!     .with_timeout(Duration::from_secs(5))
//!     .with_max_parallel(10);
//!
//! // Ping a Java server (automatically uses SRV lookup if port not specified)
//! let status = client.ping("mc.hypixel.net", ServerEdition::Java).await?;
//! println!("Server is online: {}", status.online);
//! # Ok(())
//! # }
//! ```
//!
//! ## Batch Queries
//!
//! ```no_run
//! use rust_mc_status::{McClient, ServerEdition, ServerInfo};
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let client = McClient::new();
//! let servers = vec![
//!     ServerInfo {
//!         address: "mc.hypixel.net".to_string(),
//!         edition: ServerEdition::Java,
//!     },
//!     ServerInfo {
//!         address: "geo.hivebedrock.network:19132".to_string(),
//!         edition: ServerEdition::Bedrock,
//!     },
//! ];
//!
//! let results = client.ping_many(&servers).await;
//! for (server, result) in results {
//!     match result {
//!         Ok(status) => println!("{}: Online ({}ms)", server.address, status.latency),
//!         Err(e) => println!("{}: Error - {}", server.address, e),
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## SRV Record Lookup
//!
//! When pinging Java servers without an explicit port, the library automatically
//! performs an SRV DNS lookup for `_minecraft._tcp.{hostname}`. This mimics the
//! behavior of the official Minecraft client.
//!
//! ```no_run
//! use rust_mc_status::{McClient, ServerEdition};
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let client = McClient::new();
//!
//! // This will perform SRV lookup for _minecraft._tcp.example.com
//! let status = client.ping("example.com", ServerEdition::Java).await?;
//!
//! // This will skip SRV lookup and use port 25565 directly
//! let status = client.ping("example.com:25565", ServerEdition::Java).await?;
//! # Ok(())
//! # }
//! ```

use std::io::Cursor;
use std::net::{SocketAddr, ToSocketAddrs};
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use dashmap::DashMap;
use once_cell::sync::Lazy;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpStream, UdpSocket};
use tokio::sync::OnceCell;
use tokio::time::timeout;
use trust_dns_resolver::{
    config::{ResolverConfig, ResolverOpts},
    TokioAsyncResolver,
};

use crate::error::McError;
use crate::models::*;

/// Default timeout for server queries (10 seconds).
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);

/// Default maximum number of parallel queries (10).
const DEFAULT_MAX_PARALLEL: usize = 10;

/// DNS cache TTL in seconds (5 minutes).
const DNS_CACHE_TTL: u64 = 300;

/// Default Java Edition port.
const JAVA_DEFAULT_PORT: u16 = 25565;

/// Default Bedrock Edition port.
const BEDROCK_DEFAULT_PORT: u16 = 19132;

/// Protocol version for status requests (legacy protocol).
const PROTOCOL_VERSION: i32 = 47;

/// Handshake packet ID.
const HANDSHAKE_PACKET_ID: i32 = 0x00;

/// Status request packet ID.
const STATUS_REQUEST_PACKET_ID: i32 = 0x00;

/// Status response packet ID.
const STATUS_RESPONSE_PACKET_ID: i32 = 0x00;

/// Maximum VarInt size (35 bits).
const MAX_VARINT_SHIFT: u32 = 35;

/// Initial buffer capacity for packets.
const INITIAL_PACKET_CAPACITY: usize = 64;

/// Initial response buffer capacity.
const INITIAL_RESPONSE_CAPACITY: usize = 1024;

/// Read buffer size.
const READ_BUFFER_SIZE: usize = 4096;

/// Bedrock ping packet size.
const BEDROCK_PING_PACKET_SIZE: usize = 35;

/// Minimum Bedrock response size.
const BEDROCK_MIN_RESPONSE_SIZE: usize = 35;

/// DNS resolution cache.
///
/// Maps `"{host}:{port}"` to `(SocketAddr, timestamp)`.
static DNS_CACHE: Lazy<DashMap<String, (SocketAddr, SystemTime)>> = Lazy::new(DashMap::new);

/// SRV record cache.
///
/// Maps `"srv:{host}"` to `((target_host, port), timestamp)`.
static SRV_CACHE: Lazy<DashMap<String, ((String, u16), SystemTime)>> = Lazy::new(DashMap::new);

/// Global DNS resolver for SRV lookups.
///
/// Initialized lazily on first use and reused for all subsequent lookups.
/// This improves performance by avoiding resolver creation overhead.
static RESOLVER: OnceCell<Arc<TokioAsyncResolver>> = OnceCell::const_new();

/// Initialize the global DNS resolver.
///
/// Creates a resolver with default configuration optimized for performance.
async fn get_resolver() -> Arc<TokioAsyncResolver> {
    RESOLVER
        .get_or_init(|| async {
            let config = ResolverConfig::default();
            let mut opts = ResolverOpts::default();
            // Optimize for performance
            opts.cache_size = 1000;
            opts.positive_min_ttl = Some(Duration::from_secs(60));
            opts.negative_min_ttl = Some(Duration::from_secs(10));
            
            Arc::new(TokioAsyncResolver::tokio(config, opts))
        })
        .await
        .clone()
}

/// Minecraft server status client.
///
/// This client provides methods for querying Minecraft server status with
/// support for both Java Edition and Bedrock Edition servers.
///
/// # Features
///
/// - Automatic SRV record lookup for Java servers
/// - DNS caching for improved performance
/// - Configurable timeouts and concurrency limits
/// - Batch queries for multiple servers
///
/// # Example
///
/// ```no_run
/// use rust_mc_status::{McClient, ServerEdition};
/// use std::time::Duration;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = McClient::new()
///     .with_timeout(Duration::from_secs(5))
///     .with_max_parallel(10);
///
/// let status = client.ping("mc.hypixel.net", ServerEdition::Java).await?;
/// println!("Server is online: {}", status.online);
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct McClient {
    /// Request timeout.
    timeout: Duration,
    /// Maximum number of parallel queries.
    max_parallel: usize,
}

impl Default for McClient {
    fn default() -> Self {
        Self {
            timeout: DEFAULT_TIMEOUT,
            max_parallel: DEFAULT_MAX_PARALLEL,
        }
    }
}

impl McClient {
    /// Create a new client with default settings.
    ///
    /// Default settings:
    /// - Timeout: 10 seconds
    /// - Max parallel: 10 queries
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_mc_status::McClient;
    ///
    /// let client = McClient::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the request timeout.
    ///
    /// This timeout applies to all network operations including DNS resolution,
    /// connection establishment, and response reading.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Maximum time to wait for a server response
    ///   - Default: 10 seconds
    ///   - Recommended: 5-10 seconds for most use cases
    ///   - Use shorter timeouts (1-3 seconds) for quick checks
    ///
    /// # Returns
    ///
    /// Returns `Self` for method chaining.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_mc_status::McClient;
    /// use std::time::Duration;
    ///
    /// // Quick timeout for fast checks
    /// let fast_client = McClient::new()
    ///     .with_timeout(Duration::from_secs(2));
    ///
    /// // Longer timeout for reliable queries
    /// let reliable_client = McClient::new()
    ///     .with_timeout(Duration::from_secs(10));
    /// ```
    #[must_use]
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Set the maximum number of parallel queries.
    ///
    /// This limit controls how many servers can be queried simultaneously
    /// when using [`ping_many`](Self::ping_many). Higher values increase
    /// throughput but consume more resources.
    ///
    /// # Arguments
    ///
    /// * `max_parallel` - Maximum number of concurrent server queries
    ///   - Default: 10
    ///   - Recommended: 5-20 for most use cases
    ///   - Higher values (50-100) for batch processing
    ///   - Lower values (1-5) for resource-constrained environments
    ///
    /// # Returns
    ///
    /// Returns `Self` for method chaining.
    ///
    /// # Performance
    ///
    /// - Higher values = faster batch processing but more memory/CPU usage
    /// - Lower values = slower but more resource-friendly
    /// - DNS and SRV caches are shared across all parallel queries
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_mc_status::{McClient, ServerEdition, ServerInfo};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// // High concurrency for batch processing
    /// let batch_client = McClient::new()
    ///     .with_max_parallel(50);
    ///
    /// // Low concurrency for resource-constrained environments
    /// let limited_client = McClient::new()
    ///     .with_max_parallel(3);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn with_max_parallel(mut self, max_parallel: usize) -> Self {
        self.max_parallel = max_parallel;
        self
    }

    /// Get the maximum number of parallel queries.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_mc_status::McClient;
    ///
    /// let client = McClient::new().with_max_parallel(20);
    /// assert_eq!(client.max_parallel(), 20);
    /// ```
    #[must_use]
    pub fn max_parallel(&self) -> usize {
        self.max_parallel
    }

    /// Get the request timeout.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_mc_status::McClient;
    /// use std::time::Duration;
    ///
    /// let client = McClient::new().with_timeout(Duration::from_secs(5));
    /// assert_eq!(client.timeout(), Duration::from_secs(5));
    /// ```
    #[must_use]
    pub fn timeout(&self) -> Duration {
        self.timeout
    }

    /// Clear DNS cache.
    ///
    /// This method clears all cached DNS resolutions. Useful when you need to
    /// force fresh DNS lookups or free memory.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_mc_status::McClient;
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let client = McClient::new();
    /// client.clear_dns_cache();
    /// # }
    /// ```
    pub fn clear_dns_cache(&self) {
        DNS_CACHE.clear();
    }

    /// Clear SRV record cache.
    ///
    /// This method clears all cached SRV record lookups. Useful when you need to
    /// force fresh SRV lookups or free memory.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_mc_status::McClient;
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let client = McClient::new();
    /// client.clear_srv_cache();
    /// # }
    /// ```
    pub fn clear_srv_cache(&self) {
        SRV_CACHE.clear();
    }

    /// Clear all caches (DNS and SRV).
    ///
    /// This method clears both DNS and SRV caches. Useful when you need to
    /// force fresh lookups or free memory.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_mc_status::McClient;
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let client = McClient::new();
    /// client.clear_all_caches();
    /// # }
    /// ```
    pub fn clear_all_caches(&self) {
        self.clear_dns_cache();
        self.clear_srv_cache();
    }

    /// Get cache statistics.
    ///
    /// Returns the number of entries in DNS and SRV caches.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_mc_status::McClient;
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let client = McClient::new();
    /// let stats = client.cache_stats();
    /// println!("DNS cache entries: {}", stats.dns_entries);
    /// println!("SRV cache entries: {}", stats.srv_entries);
    /// # }
    /// ```
    #[must_use]
    pub fn cache_stats(&self) -> CacheStats {
        CacheStats {
            dns_entries: DNS_CACHE.len(),
            srv_entries: SRV_CACHE.len(),
        }
    }

    /// Resolve DNS and measure resolution time.
    ///
    /// This method resolves a hostname to an IP address and returns both
    /// the resolved address and the time taken for resolution. Useful for
    /// measuring cache effectiveness and DNS performance.
    ///
    /// # Arguments
    ///
    /// * `host` - Hostname to resolve (e.g., `"mc.hypixel.net"` or `"192.168.1.1"`)
    /// * `port` - Port number (e.g., `25565` for Java, `19132` for Bedrock)
    ///
    /// # Returns
    ///
    /// Returns `Ok((SocketAddr, f64))` where:
    /// - `SocketAddr`: Resolved IP address and port
    /// - `f64`: Resolution time in milliseconds
    ///
    /// # Errors
    ///
    /// Returns [`McError::DnsError`] if DNS resolution fails.
    ///
    /// # Performance Notes
    ///
    /// - First resolution (cold cache): Typically 10-100ms
    /// - Subsequent resolutions (warm cache): Typically <1ms
    /// - Cache TTL: 5 minutes
    /// - Use [`clear_dns_cache`](Self::clear_dns_cache) to force fresh lookups
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_mc_status::McClient;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = McClient::new();
    ///
    /// // First resolution (cold cache - actual DNS lookup)
    /// let (addr1, time1) = client.resolve_dns_timed("mc.hypixel.net", 25565).await?;
    /// println!("First resolution: {:.2} ms", time1);
    /// println!("Resolved to: {}", addr1);
    ///
    /// // Second resolution (warm cache - from cache)
    /// let (addr2, time2) = client.resolve_dns_timed("mc.hypixel.net", 25565).await?;
    /// println!("Cached resolution: {:.2} ms", time2);
    /// println!("Cache speedup: {:.1}x faster", time1 / time2);
    /// println!("Time saved: {:.2} ms", time1 - time2);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn resolve_dns_timed(&self, host: &str, port: u16) -> Result<(SocketAddr, f64), McError> {
        let start = std::time::Instant::now();
        let addr = self.resolve_dns(host, port).await?;
        let elapsed = start.elapsed().as_secs_f64() * 1000.0;
        Ok((addr, elapsed))
    }

    /// Ping a server and get its status.
    ///
    /// This is a convenience method that dispatches to either [`ping_java`](Self::ping_java)
    /// or [`ping_bedrock`](Self::ping_bedrock) based on the server edition.
    ///
    /// # Arguments
    ///
    /// * `address` - Server address in one of the following formats:
    ///   - `"hostname"` - Hostname without port (uses default port for edition)
    ///   - `"hostname:port"` - Hostname with explicit port
    ///   - `"192.168.1.1"` - IP address without port (uses default port)
    ///   - `"192.168.1.1:25565"` - IP address with explicit port
    /// * `edition` - Server edition: `ServerEdition::Java` or `ServerEdition::Bedrock`
    ///
    /// # Returns
    ///
    /// Returns a [`ServerStatus`] struct containing:
    /// - `online`: Whether the server is online
    /// - `ip`: Resolved IP address
    /// - `port`: Server port number
    /// - `hostname`: Original hostname used for query
    /// - `latency`: Response time in milliseconds
    /// - `dns`: Optional DNS information (A records, CNAME, TTL)
    /// - `data`: Edition-specific server data (version, players, plugins, etc.)
    ///
    /// # Errors
    ///
    /// Returns [`McError`] if:
    /// - DNS resolution fails ([`McError::DnsError`])
    /// - Connection cannot be established ([`McError::ConnectionError`])
    /// - Request times out ([`McError::Timeout`])
    /// - Server returns invalid response ([`McError::InvalidResponse`])
    /// - Invalid port number in address ([`McError::InvalidPort`])
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_mc_status::{McClient, ServerEdition};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = McClient::new();
    ///
    /// // Ping Java server (automatic SRV lookup)
    /// let status = client.ping("mc.hypixel.net", ServerEdition::Java).await?;
    /// println!("Server is online: {}", status.online);
    /// println!("Latency: {:.2}ms", status.latency);
    ///
    /// // Ping Bedrock server
    /// let status = client.ping("geo.hivebedrock.network:19132", ServerEdition::Bedrock).await?;
    /// println!("Players: {}/{}", status.players().unwrap_or((0, 0)).0, status.players().unwrap_or((0, 0)).1);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn ping(&self, address: &str, edition: ServerEdition) -> Result<ServerStatus, McError> {
        match edition {
            ServerEdition::Java => self.ping_java(address).await,
            ServerEdition::Bedrock => self.ping_bedrock(address).await,
        }
    }

    /// Ping a Java Edition server and get its status.
    ///
    /// This method automatically performs an SRV DNS lookup if no port is specified
    /// in the address. The lookup follows the Minecraft client behavior:
    /// - Queries `_minecraft._tcp.{hostname}` for SRV records
    /// - Uses the target host and port from the SRV record if found
    /// - Falls back to the default port (25565) if no SRV record exists
    /// - Skips SRV lookup if port is explicitly specified
    ///
    /// # Arguments
    ///
    /// * `address` - Server address in one of the following formats:
    ///   - `"hostname"` - Hostname without port (performs SRV lookup, defaults to 25565)
    ///   - `"hostname:25565"` - Hostname with explicit port (skips SRV lookup)
    ///   - `"192.168.1.1"` - IP address without port (uses port 25565)
    ///   - `"192.168.1.1:25565"` - IP address with explicit port
    ///
    /// # Returns
    ///
    /// Returns a [`ServerStatus`] with `ServerData::Java` containing:
    /// - Version information (name, protocol version)
    /// - Player information (online count, max players, sample list)
    /// - Server description (MOTD)
    /// - Optional favicon (base64-encoded PNG)
    /// - Optional plugins list
    /// - Optional mods list
    /// - Additional metadata (map, gamemode, software)
    ///
    /// # Errors
    ///
    /// Returns [`McError`] if:
    /// - DNS resolution fails ([`McError::DnsError`])
    /// - SRV lookup fails (non-critical, falls back to default port)
    /// - Connection cannot be established ([`McError::ConnectionError`])
    /// - Request times out ([`McError::Timeout`])
    /// - Server returns invalid response ([`McError::InvalidResponse`])
    /// - JSON parsing fails ([`McError::JsonError`])
    /// - Invalid port number ([`McError::InvalidPort`])
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_mc_status::McClient;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = McClient::new();
    ///
    /// // Automatic SRV lookup (queries _minecraft._tcp.mc.hypixel.net)
    /// let status = client.ping_java("mc.hypixel.net").await?;
    /// if let rust_mc_status::ServerData::Java(java) = &status.data {
    ///     println!("Version: {}", java.version.name);
    ///     println!("Players: {}/{}", java.players.online, java.players.max);
    ///     println!("Description: {}", java.description);
    /// }
    ///
    /// // Skip SRV lookup (uses port 25565 directly)
    /// let status = client.ping_java("mc.hypixel.net:25565").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn ping_java(&self, address: &str) -> Result<ServerStatus, McError> {
        let start = SystemTime::now();
        let (host, port) = Self::parse_address(address, JAVA_DEFAULT_PORT)?;

        // Check for SRV record first (mimics Minecraft's server address field behavior)
        // Only perform SRV lookup if port was not explicitly specified in address
        let port_explicit = address.contains(':');
        let (actual_host, actual_port) = if port_explicit {
            // Port was explicitly specified, skip SRV lookup
            (host.to_string(), port)
        } else {
            // No port specified, check for SRV record
            self.lookup_srv_record(host, port).await?
        };

        let resolved = self.resolve_dns(&actual_host, actual_port).await?;
        let dns_info = self.get_dns_info(host).await.ok(); // DNS info is optional

        let mut stream = timeout(self.timeout, TcpStream::connect(resolved))
            .await
            .map_err(|_| McError::Timeout)?
            .map_err(|e| McError::ConnectionError(e.to_string()))?;

        stream.set_nodelay(true).map_err(McError::IoError)?;

        // Send handshake - use original host and actual port in handshake packet
        // (Minecraft protocol expects original hostname in handshake, but actual port)
        self.send_handshake(&mut stream, host, actual_port).await?;

        // Send status request
        self.send_status_request(&mut stream).await?;

        // Read and parse response
        let response = self.read_response(&mut stream).await?;
        let (json, latency) = self.parse_java_response(response, start)?;

        // Build result
        Ok(ServerStatus {
            online: true,
            ip: resolved.ip().to_string(),
            port: resolved.port(),
            hostname: host.to_string(),
            latency,
            dns: dns_info,
            data: ServerData::Java(self.parse_java_json(&json)?),
        })
    }

    /// Ping a Bedrock Edition server and get its status.
    ///
    /// Bedrock Edition servers use UDP protocol and typically run on port 19132.
    /// This method sends a UDP ping packet and parses the response.
    ///
    /// # Arguments
    ///
    /// * `address` - Server address in one of the following formats:
    ///   - `"hostname"` - Hostname without port (uses default port 19132)
    ///   - `"hostname:19132"` - Hostname with explicit port
    ///   - `"192.168.1.1"` - IP address without port (uses port 19132)
    ///   - `"192.168.1.1:19132"` - IP address with explicit port
    ///
    /// # Returns
    ///
    /// Returns a [`ServerStatus`] with `ServerData::Bedrock` containing:
    /// - Edition information (e.g., "MCPE")
    /// - Version information
    /// - Player counts (online and max)
    /// - Message of the day (MOTD)
    /// - Protocol version
    /// - Server UID
    /// - Game mode information
    /// - Port information (IPv4 and IPv6)
    /// - Optional map name and software
    ///
    /// # Errors
    ///
    /// Returns [`McError`] if:
    /// - DNS resolution fails ([`McError::DnsError`])
    /// - Connection cannot be established ([`McError::ConnectionError`])
    /// - Request times out ([`McError::Timeout`])
    /// - Server returns invalid response ([`McError::InvalidResponse`])
    /// - Invalid port number ([`McError::InvalidPort`])
    /// - UTF-8 conversion fails ([`McError::Utf8Error`])
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_mc_status::McClient;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = McClient::new();
    /// let status = client.ping_bedrock("geo.hivebedrock.network:19132").await?;
    ///
    /// if let rust_mc_status::ServerData::Bedrock(bedrock) = &status.data {
    ///     println!("Edition: {}", bedrock.edition);
    ///     println!("Version: {}", bedrock.version);
    ///     println!("Players: {}/{}", bedrock.online_players, bedrock.max_players);
    ///     println!("MOTD: {}", bedrock.motd);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn ping_bedrock(&self, address: &str) -> Result<ServerStatus, McError> {
        let start = SystemTime::now();
        let (host, port) = Self::parse_address(address, BEDROCK_DEFAULT_PORT)?;
        let resolved = self.resolve_dns(host, port).await?;
        let dns_info = self.get_dns_info(host).await.ok(); // DNS info is optional

        let socket = UdpSocket::bind("0.0.0.0:0").await.map_err(McError::IoError)?;

        // Send ping packet
        let ping_packet = self.create_bedrock_ping_packet();
        timeout(self.timeout, socket.send_to(&ping_packet, resolved))
            .await
            .map_err(|_| McError::Timeout)?
            .map_err(McError::IoError)?;

        // Receive response
        let mut buf = [0u8; READ_BUFFER_SIZE];
        let (len, _) = timeout(self.timeout, socket.recv_from(&mut buf))
            .await
            .map_err(|_| McError::Timeout)?
            .map_err(McError::IoError)?;

        if len < BEDROCK_MIN_RESPONSE_SIZE {
            return Err(McError::InvalidResponse("Response too short".to_string()));
        }

        let latency = start
            .elapsed()
            .map_err(|_| McError::InvalidResponse("Time error".to_string()))?
            .as_secs_f64()
            * 1000.0;

        let pong_data = String::from_utf8_lossy(&buf[BEDROCK_PING_PACKET_SIZE..len]).to_string();

        Ok(ServerStatus {
            online: true,
            ip: resolved.ip().to_string(),
            port: resolved.port(),
            hostname: host.to_string(),
            latency,
            dns: dns_info,
            data: ServerData::Bedrock(self.parse_bedrock_response(&pong_data)?),
        })
    }

    /// Quick check if a server is online.
    ///
    /// This method performs a minimal connection check without retrieving
    /// full server status. It's faster than `ping()` but provides less information.
    /// Use this method when you only need to know if a server is reachable.
    ///
    /// # Arguments
    ///
    /// * `address` - Server address in one of the following formats:
    ///   - `"hostname"` - Hostname without port (uses default port for edition)
    ///   - `"hostname:port"` - Hostname with explicit port
    ///   - `"192.168.1.1"` - IP address without port (uses default port)
    ///   - `"192.168.1.1:25565"` - IP address with explicit port
    /// * `edition` - Server edition: `ServerEdition::Java` or `ServerEdition::Bedrock`
    ///
    /// # Returns
    ///
    /// Returns `true` if the server is reachable and responds to ping requests,
    /// `false` if the server is offline, unreachable, or times out.
    ///
    /// # Performance
    ///
    /// This method is faster than `ping()` because it:
    /// - Doesn't parse full server status
    /// - Doesn't retrieve player information
    /// - Doesn't parse JSON responses (for Java servers)
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_mc_status::{McClient, ServerEdition};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = McClient::new();
    ///
    /// // Quick check without full status
    /// if client.is_online("mc.hypixel.net", ServerEdition::Java).await {
    ///     println!("Server is online!");
    ///     // Now get full status if needed
    ///     let status = client.ping("mc.hypixel.net", ServerEdition::Java).await?;
    ///     println!("Players: {}/{}", status.players().unwrap_or((0, 0)).0, status.players().unwrap_or((0, 0)).1);
    /// } else {
    ///     println!("Server is offline or unreachable");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn is_online(&self, address: &str, edition: ServerEdition) -> bool {
        self.ping(address, edition).await.is_ok()
    }

    /// Ping multiple servers in parallel.
    ///
    /// This method queries multiple servers concurrently with a configurable
    /// concurrency limit. Results are returned in the same order as input.
    /// The concurrency limit is controlled by [`with_max_parallel`](Self::with_max_parallel).
    ///
    /// # Arguments
    ///
    /// * `servers` - Slice of [`ServerInfo`] structures containing:
    ///   - `address`: Server address (hostname or IP, optionally with port)
    ///   - `edition`: Server edition (`ServerEdition::Java` or `ServerEdition::Bedrock`)
    ///
    /// # Returns
    ///
    /// Returns a `Vec<(ServerInfo, Result<ServerStatus, McError>)>` where:
    /// - Each tuple contains the original `ServerInfo` and the query result
    /// - Results are in the same order as the input slice
    /// - `Ok(ServerStatus)` contains full server status information
    /// - `Err(McError)` contains error information (timeout, DNS error, etc.)
    ///
    /// # Performance
    ///
    /// - Queries are executed in parallel up to the configured limit
    /// - DNS and SRV caches are shared across all queries
    /// - Failed queries don't block other queries
    /// - Use `with_max_parallel()` to control resource usage
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_mc_status::{McClient, ServerEdition, ServerInfo};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = McClient::new()
    ///     .with_max_parallel(5)  // Process up to 5 servers concurrently
    ///     .with_timeout(std::time::Duration::from_secs(5));
    ///
    /// let servers = vec![
    ///     ServerInfo {
    ///         address: "mc.hypixel.net".to_string(),
    ///         edition: ServerEdition::Java,
    ///     },
    ///     ServerInfo {
    ///         address: "geo.hivebedrock.network:19132".to_string(),
    ///         edition: ServerEdition::Bedrock,
    ///     },
    /// ];
    ///
    /// let results = client.ping_many(&servers).await;
    /// for (server, result) in results {
    ///     match result {
    ///         Ok(status) => {
    ///             println!("{}: ✅ Online ({}ms)", server.address, status.latency);
    ///             if let Some((online, max)) = status.players() {
    ///                 println!("  Players: {}/{}", online, max);
    ///             }
    ///         }
    ///         Err(e) => println!("{}: ❌ Error - {}", server.address, e),
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn ping_many(&self, servers: &[ServerInfo]) -> Vec<(ServerInfo, Result<ServerStatus, McError>)> {
        use futures::stream::StreamExt;
        use tokio::sync::Semaphore;

        let semaphore = Arc::new(Semaphore::new(self.max_parallel));
        let client = self.clone();

        let futures = servers.iter().map(|server| {
            let server = server.clone();
            let semaphore = semaphore.clone();
            let client = client.clone();

            async move {
                let _permit = semaphore.acquire().await;
                let result = client.ping(&server.address, server.edition).await;
                (server, result)
            }
        });

        futures::stream::iter(futures)
            .buffer_unordered(self.max_parallel)
            .collect()
            .await
    }

    // === Private Helper Methods ===

    /// Parse server address into host and port.
    ///
    /// # Arguments
    ///
    /// * `address` - Server address string
    /// * `default_port` - Default port to use if not specified
    ///
    /// # Returns
    ///
    /// Tuple of `(host, port)`.
    ///
    /// # Errors
    ///
    /// Returns an error if the port cannot be parsed as a `u16`.
    fn parse_address(address: &str, default_port: u16) -> Result<(&str, u16), McError> {
        if let Some((host, port_str)) = address.split_once(':') {
            let port = port_str
                .parse::<u16>()
                .map_err(|e| McError::InvalidPort(e.to_string()))?;
            Ok((host, port))
        } else {
            Ok((address, default_port))
        }
    }

    /// Lookup SRV record for Minecraft Java server.
    ///
    /// This method mimics Minecraft's server address field behavior by querying
    /// `_minecraft._tcp.{host}` for SRV records. Results are cached for 5 minutes.
    ///
    /// # Arguments
    ///
    /// * `host` - Hostname to lookup
    /// * `port` - Default port to use if no SRV record is found
    ///
    /// # Returns
    ///
    /// Tuple of `(target_host, port)` from SRV record or original values.
    ///
    /// # Errors
    ///
    /// Returns an error if DNS resolution fails critically (timeouts are handled gracefully).
    async fn lookup_srv_record(&self, host: &str, port: u16) -> Result<(String, u16), McError> {
        let cache_key = format!("srv:{}", host);

        // Check cache with TTL validation
        if let Some(entry) = SRV_CACHE.get(&cache_key) {
            let ((cached_host, cached_port), timestamp) = entry.value();
            if timestamp
                .elapsed()
                .map(|d| d.as_secs() < DNS_CACHE_TTL)
                .unwrap_or(false)
            {
                return Ok((cached_host.clone(), *cached_port));
            }
        }

        // Build SRV record name: _minecraft._tcp.{host}
        let srv_name = format!("_minecraft._tcp.{}", host);

        // Try to resolve SRV record using cached resolver
        let resolver = get_resolver().await;

        match timeout(self.timeout, resolver.srv_lookup(&srv_name)).await {
            Ok(Ok(srv_lookup)) => {
                // Get the first SRV record (sorted by priority and weight)
                if let Some(srv) = srv_lookup.iter().next() {
                    let target = srv.target().to_string().trim_end_matches('.').to_string();
                    let srv_port = srv.port();

                    // Cache and return SRV result
                    let result = (target, srv_port);
                    SRV_CACHE.insert(cache_key, (result.clone(), SystemTime::now()));
                    return Ok(result);
                }
            }
            Ok(Err(_)) => {
                // SRV record not found - this is normal, use original values
            }
            Err(_) => {
                // Timeout - use original values
            }
        }

        // No SRV record found or error occurred, use original host and port
        let result = (host.to_string(), port);
        SRV_CACHE.insert(cache_key, (result.clone(), SystemTime::now()));
        Ok(result)
    }

    /// Resolve hostname to IP address with caching.
    ///
    /// DNS resolutions are cached for 5 minutes to improve performance.
    ///
    /// # Arguments
    ///
    /// * `host` - Hostname to resolve
    /// * `port` - Port number
    ///
    /// # Returns
    ///
    /// Resolved `SocketAddr`.
    ///
    /// # Errors
    ///
    /// Returns an error if DNS resolution fails.
    async fn resolve_dns(&self, host: &str, port: u16) -> Result<SocketAddr, McError> {
        let cache_key = format!("{}:{}", host, port);

        // Check cache with TTL validation
        if let Some(entry) = DNS_CACHE.get(&cache_key) {
            let (addr, timestamp) = *entry.value();
            if timestamp
                .elapsed()
                .map(|d| d.as_secs() < DNS_CACHE_TTL)
                .unwrap_or(false)
            {
                return Ok(addr);
            }
        }

        // Resolve and cache
        let addrs: Vec<SocketAddr> = format!("{}:{}", host, port)
            .to_socket_addrs()
            .map_err(|e| McError::DnsError(e.to_string()))?
            .collect();

        let addr = addrs
            .iter()
            .find(|a| a.is_ipv4())
            .or_else(|| addrs.first())
            .copied()
            .ok_or_else(|| McError::DnsError("No addresses resolved".to_string()))?;

        DNS_CACHE.insert(cache_key, (addr, SystemTime::now()));
        Ok(addr)
    }

    /// Get DNS information for a hostname.
    ///
    /// This is a simplified implementation that retrieves A records.
    /// More advanced DNS queries (e.g., CNAME) would require additional DNS library features.
    ///
    /// # Arguments
    ///
    /// * `host` - Hostname to query
    ///
    /// # Returns
    ///
    /// DNS information or an error if resolution fails.
    async fn get_dns_info(&self, host: &str) -> Result<DnsInfo, McError> {
        let addrs: Vec<SocketAddr> = format!("{}:0", host)
            .to_socket_addrs()
            .map_err(|e| McError::DnsError(e.to_string()))?
            .collect();

        Ok(DnsInfo {
            a_records: addrs.iter().map(|a| a.ip().to_string()).collect(),
            cname: None, // This would require proper DNS queries
            ttl: DNS_CACHE_TTL as u32,
        })
    }

    /// Send handshake packet to Java server.
    ///
    /// # Arguments
    ///
    /// * `stream` - TCP stream to write to
    /// * `host` - Hostname (used in handshake packet)
    /// * `port` - Port number (used in handshake packet)
    ///
    /// # Errors
    ///
    /// Returns an error if writing to the stream fails or times out.
    async fn send_handshake(&self, stream: &mut TcpStream, host: &str, port: u16) -> Result<(), McError> {
        let mut handshake = Vec::with_capacity(INITIAL_PACKET_CAPACITY);
        write_var_int(&mut handshake, HANDSHAKE_PACKET_ID);
        write_var_int(&mut handshake, PROTOCOL_VERSION);
        write_string(&mut handshake, host);
        handshake.extend_from_slice(&port.to_be_bytes());
        write_var_int(&mut handshake, 1); // Next state: status

        let mut packet = Vec::with_capacity(handshake.len() + 5);
        write_var_int(&mut packet, handshake.len() as i32);
        packet.extend_from_slice(&handshake);

        timeout(self.timeout, stream.write_all(&packet))
            .await
            .map_err(|_| McError::Timeout)?
            .map_err(McError::IoError)
    }

    /// Send status request packet to Java server.
    ///
    /// # Arguments
    ///
    /// * `stream` - TCP stream to write to
    ///
    /// # Errors
    ///
    /// Returns an error if writing to the stream fails or times out.
    async fn send_status_request(&self, stream: &mut TcpStream) -> Result<(), McError> {
        let mut status_request = Vec::with_capacity(5);
        write_var_int(&mut status_request, STATUS_REQUEST_PACKET_ID);

        let mut status_packet = Vec::with_capacity(status_request.len() + 5);
        write_var_int(&mut status_packet, status_request.len() as i32);
        status_packet.extend_from_slice(&status_request);

        timeout(self.timeout, stream.write_all(&status_packet))
            .await
            .map_err(|_| McError::Timeout)?
            .map_err(McError::IoError)
    }

    /// Read response from Java server.
    ///
    /// This method reads the complete response packet, handling variable-length
    /// packets correctly.
    ///
    /// # Arguments
    ///
    /// * `stream` - TCP stream to read from
    ///
    /// # Returns
    ///
    /// Complete response packet as bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if reading fails, times out, or no data is received.
    async fn read_response(&self, stream: &mut TcpStream) -> Result<Vec<u8>, McError> {
        let mut response = Vec::with_capacity(INITIAL_RESPONSE_CAPACITY);
        let mut buf = [0u8; READ_BUFFER_SIZE];
        let mut expected_length = None;

        loop {
            let n = timeout(self.timeout, stream.read(&mut buf))
                .await
                .map_err(|_| McError::Timeout)?
                .map_err(McError::IoError)?;

            if n == 0 {
                break;
            }

            response.extend_from_slice(&buf[..n]);

            // Check if we have enough data to determine packet length
            if expected_length.is_none() && response.len() >= 5 {
                let mut cursor = Cursor::new(&response);
                if let Ok(packet_length) = read_var_int(&mut cursor) {
                    expected_length = Some(cursor.position() as usize + packet_length as usize);
                }
            }

            if let Some(expected) = expected_length {
                if response.len() >= expected {
                    break;
                }
            }
        }

        if response.is_empty() {
            return Err(McError::InvalidResponse("No response from server".to_string()));
        }

        Ok(response)
    }

    /// Parse Java server response.
    ///
    /// Extracts JSON data and calculates latency from the response packet.
    ///
    /// # Arguments
    ///
    /// * `response` - Complete response packet
    /// * `start` - Start time for latency calculation
    ///
    /// # Returns
    ///
    /// Tuple of `(JSON value, latency in milliseconds)`.
    ///
    /// # Errors
    ///
    /// Returns an error if the packet is malformed or contains invalid data.
    fn parse_java_response(&self, response: Vec<u8>, start: SystemTime) -> Result<(serde_json::Value, f64), McError> {
        let mut cursor = Cursor::new(&response);
        let packet_length = read_var_int(&mut cursor)
            .map_err(|e| McError::InvalidResponse(format!("Failed to read packet length: {}", e)))?;

        let total_expected = cursor.position() as usize + packet_length as usize;
        if response.len() < total_expected {
            return Err(McError::InvalidResponse(format!(
                "Incomplete packet: expected {}, got {}",
                total_expected, response.len()
            )));
        }

        let packet_id = read_var_int(&mut cursor)
            .map_err(|e| McError::InvalidResponse(format!("Failed to read packet ID: {}", e)))?;

        if packet_id != STATUS_RESPONSE_PACKET_ID {
            return Err(McError::InvalidResponse(format!("Unexpected packet ID: {}", packet_id)));
        }

        let json_length = read_var_int(&mut cursor)
            .map_err(|e| McError::InvalidResponse(format!("Failed to read JSON length: {}", e)))?;

        if cursor.position() as usize + json_length as usize > response.len() {
            return Err(McError::InvalidResponse("JSON data truncated".to_string()));
        }

        let json_buf = &response[cursor.position() as usize..cursor.position() as usize + json_length as usize];
        let json_str = String::from_utf8(json_buf.to_vec()).map_err(McError::Utf8Error)?;

        let json: serde_json::Value = serde_json::from_str(&json_str).map_err(McError::JsonError)?;

        let latency = start
            .elapsed()
            .map_err(|_| McError::InvalidResponse("Time error".to_string()))?
            .as_secs_f64()
            * 1000.0;

        Ok((json, latency))
    }

    /// Parse Java server JSON response.
    ///
    /// Extracts structured data from the JSON response, including version info,
    /// players, plugins, mods, and more.
    ///
    /// # Arguments
    ///
    /// * `json` - JSON value from server response
    ///
    /// # Returns
    ///
    /// Parsed `JavaStatus` structure.
    ///
    /// # Errors
    ///
    /// Returns an error if required fields are missing or malformed.
    fn parse_java_json(&self, json: &serde_json::Value) -> Result<JavaStatus, McError> {
        let version = JavaVersion {
            name: json["version"]["name"]
                .as_str()
                .unwrap_or("Unknown")
                .to_string(),
            protocol: json["version"]["protocol"].as_i64().unwrap_or(0),
        };

        let players = JavaPlayers {
            online: json["players"]["online"].as_i64().unwrap_or(0),
            max: json["players"]["max"].as_i64().unwrap_or(0),
            sample: if let Some(sample) = json["players"]["sample"].as_array() {
                Some(
                    sample
                        .iter()
                        .filter_map(|p| {
                    Some(JavaPlayer {
                        name: p["name"].as_str()?.to_string(),
                        id: p["id"].as_str()?.to_string(),
                    })
                        })
                        .collect(),
                )
            } else {
                None
            },
        };

        let description = if let Some(desc) = json["description"].as_str() {
            desc.to_string()
        } else if let Some(text) = json["description"]["text"].as_str() {
            text.to_string()
        } else {
            "No description".to_string()
        };

        let favicon = json["favicon"].as_str().map(|s| s.to_string());
        let map = json["map"].as_str().map(|s| s.to_string());
        let gamemode = json["gamemode"].as_str().map(|s| s.to_string());
        let software = json["software"].as_str().map(|s| s.to_string());

        let plugins = if let Some(plugins_array) = json["plugins"].as_array() {
            Some(
                plugins_array
                    .iter()
                    .filter_map(|p| {
                Some(JavaPlugin {
                    name: p["name"].as_str()?.to_string(),
                    version: p["version"].as_str().map(|s| s.to_string()),
                })
                    })
                    .collect(),
            )
        } else {
            None
        };

        let mods = if let Some(mods_array) = json["mods"].as_array() {
            Some(
                mods_array
                    .iter()
                    .filter_map(|m| {
                Some(JavaMod {
                    modid: m["modid"].as_str()?.to_string(),
                    version: m["version"].as_str().map(|s| s.to_string()),
                })
                    })
                    .collect(),
            )
        } else {
            None
        };

        Ok(JavaStatus {
            version,
            players,
            description,
            favicon,
            map,
            gamemode,
            software,
            plugins,
            mods,
            raw_data: json.clone(),
        })
    }

    /// Create Bedrock ping packet.
    ///
    /// Returns a properly formatted UDP packet for querying Bedrock servers.
    fn create_bedrock_ping_packet(&self) -> Vec<u8> {
        let mut ping_packet = Vec::with_capacity(BEDROCK_PING_PACKET_SIZE);
        ping_packet.push(0x01);
        ping_packet.extend_from_slice(
            &(SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64)
                .to_be_bytes(),
        );
        ping_packet.extend_from_slice(&[
            0x00, 0xFF, 0xFF, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0xFD, 0xFD, 0xFD, 0xFD, 0x12, 0x34, 0x56, 0x78,
        ]);
        ping_packet.extend_from_slice(&[0x00; 8]);
        ping_packet
    }

    /// Parse Bedrock server response.
    ///
    /// Extracts structured data from the Bedrock server's UDP response.
    ///
    /// # Arguments
    ///
    /// * `pong_data` - Response data string from server
    ///
    /// # Returns
    ///
    /// Parsed `BedrockStatus` structure.
    ///
    /// # Errors
    ///
    /// Returns an error if the response is malformed or missing required fields.
    fn parse_bedrock_response(&self, pong_data: &str) -> Result<BedrockStatus, McError> {
        let parts: Vec<&str> = pong_data.split(';').collect();

        if parts.len() < 6 {
            return Err(McError::InvalidResponse("Invalid Bedrock response".to_string()));
        }

        Ok(BedrockStatus {
            edition: parts[0].to_string(),
            motd: parts[1].to_string(),
            protocol_version: parts[2].to_string(),
            version: parts[3].to_string(),
            online_players: parts[4].to_string(),
            max_players: parts[5].to_string(),
            server_uid: parts.get(6).map_or("", |s| *s).to_string(),
            motd2: parts.get(7).map_or("", |s| *s).to_string(),
            game_mode: parts.get(8).map_or("", |s| *s).to_string(),
            game_mode_numeric: parts.get(9).map_or("", |s| *s).to_string(),
            port_ipv4: parts.get(10).map_or("", |s| *s).to_string(),
            port_ipv6: parts.get(11).map_or("", |s| *s).to_string(),
            map: parts.get(12).map(|s| s.to_string()),
            software: parts.get(13).map(|s| s.to_string()),
            raw_data: pong_data.to_string(),
        })
    }
}

// === Protocol Helper Functions ===

/// Write a VarInt to a buffer.
///
/// VarInt is a variable-length integer encoding used in Minecraft protocol.
/// It uses 7 bits per byte, with the most significant bit indicating continuation.
///
/// # Arguments
///
/// * `buffer` - Buffer to write to
/// * `value` - Integer value to encode
fn write_var_int(buffer: &mut Vec<u8>, value: i32) {
    let mut value = value as u32;
    loop {
        let mut temp = (value & 0x7F) as u8;
        value >>= 7;
        if value != 0 {
            temp |= 0x80;
        }
        buffer.push(temp);
        if value == 0 {
            break;
        }
    }
}

/// Write a string to a buffer (VarInt length + UTF-8 bytes).
///
/// # Arguments
///
/// * `buffer` - Buffer to write to
/// * `s` - String to write
fn write_string(buffer: &mut Vec<u8>, s: &str) {
    write_var_int(buffer, s.len() as i32);
    buffer.extend_from_slice(s.as_bytes());
}

/// Read a VarInt from a reader.
///
/// # Arguments
///
/// * `reader` - Reader to read from
///
/// # Returns
///
/// Decoded integer value.
///
/// # Errors
///
/// Returns an error if:
/// - Reading fails
/// - VarInt is too large (exceeds 35 bits)
fn read_var_int(reader: &mut impl std::io::Read) -> Result<i32, String> {
    let mut result = 0i32;
    let mut shift = 0;
    loop {
        let mut byte = [0u8];
        reader.read_exact(&mut byte).map_err(|e| e.to_string())?;
        let value = byte[0] as i32;
        result |= (value & 0x7F) << shift;
        shift += 7;
        if shift > MAX_VARINT_SHIFT {
            return Err("VarInt too big".to_string());
        }
        if (value & 0x80) == 0 {
            break;
        }
    }
    Ok(result)
}