aria2-core 0.2.3

High-performance download engine core: multi-protocol segmented downloads, rate limiting, config management, session persistence, and BitTorrent seeding
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
//! Session Entry module - Core data structure for session serialization
//!
//! This module provides the `SessionEntry` struct which represents a single download
//! task's state that can be serialized to and deserialized from session files.
//!
//! # Overview
//!
//! A `SessionEntry` captures all necessary information about an active or paused download:
//! - **URIs**: One or more source URLs (mirrors) for the download
//! - **GID**: Unique identifier for the download task
//! - **Options**: Download configuration options (split, dir, out, etc.)
//! - **Progress**: Current download/upload statistics
//! - **Status**: Active state of the download (active, waiting, paused, error)
//! - **BT-specific**: Bitfield and piece information for BitTorrent downloads
//!
//! # Architecture
//!
//! ```text
//! session_entry.rs (this file)
//!   ├── SessionEntry struct definition
//!   ├── Builder pattern methods (new, with_options, paused)
//!   └── Re-exports for convenience
//!
//! session_serialize_impl.rs
//!   └── impl SessionEntry { serialize(), deserialize_line() }
//!
//! session_uri_utils.rs
//!   └── escape_uri(), unescape_uri(), decode_hex()
//!
//! session_options.rs
//!   └── download_options_to_map()
//! ```
//!
//! # Examples
//!
//! ```rust
//! use aria2_core::session::session_entry::SessionEntry;
//! use std::collections::HashMap;
//!
//! // Create a basic entry
//! let entry = SessionEntry::new(1, vec!["http://example.com/file.zip".to_string()]);
//!
//! // Add options using builder pattern
//! let entry = SessionEntry::new(2, vec!["http://example.com/big.iso".to_string()])
//!     .with_options({
//!         let mut opts = HashMap::new();
//!         opts.insert("split".to_string(), "4".to_string());
//!         opts.insert("dir".to_string(), "/downloads".to_string());
//!         opts
//!     })
//!     .paused();
//! ```

use std::collections::HashMap;

use crate::error::{Aria2Error, Result};
use crate::request::request_group::DownloadOptions;

// =========================================================================
// URI Utility Functions (consolidated from session_uri_utils.rs)
// =========================================================================

/// Escapes special characters in URIs for safe serialization.
pub fn escape_uri(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('\t', "\\t")
        .replace('\n', "\\n")
}

/// Unescapes special characters previously escaped by [`escape_uri()`].
pub fn unescape_uri(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '\\' {
            if let Some(&next) = chars.peek() {
                match next {
                    't' => {
                        result.push('\t');
                        chars.next();
                    }
                    'n' => {
                        result.push('\n');
                        chars.next();
                    }
                    '\\' => {
                        result.push('\\');
                        chars.next();
                    }
                    _ => {
                        result.push(c);
                    }
                }
            } else {
                result.push(c);
            }
        } else {
            result.push(c);
        }
    }

    result
}

/// Decodes a hexadecimal string to a byte vector.
pub fn decode_hex(hex: &str) -> Result<Vec<u8>> {
    if !hex.len().is_multiple_of(2) {
        return Err(Aria2Error::Io(format!(
            "Hex string has odd length: {}",
            hex.len()
        )));
    }

    let mut bytes = Vec::with_capacity(hex.len() / 2);

    for i in (0..hex.len()).step_by(2) {
        let byte_str = &hex[i..i + 2];
        let byte = u8::from_str_radix(byte_str, 16).map_err(|e| {
            Aria2Error::Io(format!("Invalid hex character at position {}: {}", i, e))
        })?;
        bytes.push(byte);
    }

    Ok(bytes)
}

// =========================================================================
// Options Conversion (consolidated from session_options.rs)
// =========================================================================

/// Converts DownloadOptions struct to a HashMap for serialization.
///
/// Only non-default / non-empty values are included to keep the session file
/// compact. The load path (`map_entry_to_download_options`) uses
/// `unwrap_or(default)` for every field, so absent keys are safe.
pub fn download_options_to_map(opts: &DownloadOptions) -> HashMap<String, String> {
    let mut map = HashMap::new();

    // --- Basic download options ---
    if let Some(v) = opts.split {
        map.insert("split".to_string(), v.to_string());
    }
    if let Some(v) = opts.max_connection_per_server {
        map.insert("max-connection-per-server".to_string(), v.to_string());
    }
    if let Some(v) = opts.max_download_limit {
        map.insert("max-download-limit".to_string(), v.to_string());
    }
    if let Some(v) = opts.max_upload_limit {
        map.insert("max-upload-limit".to_string(), v.to_string());
    }
    if let Some(ref v) = opts.dir {
        map.insert("dir".to_string(), v.clone());
    }
    if let Some(ref v) = opts.out {
        map.insert("out".to_string(), v.clone());
    }
    if let Some(v) = opts.seed_time {
        map.insert("seed-time".to_string(), v.to_string());
    }
    if let Some(v) = opts.seed_ratio {
        map.insert("seed-ratio".to_string(), v.to_string());
    }

    // --- File allocation ---
    if let Some(ref v) = opts.file_allocation {
        map.insert("file-allocation".to_string(), v.clone());
    }
    if let Some(v) = opts.mmap_threshold {
        map.insert("mmap-threshold".to_string(), v.to_string());
    }
    if opts.secure_falloc {
        map.insert("secure-falloc".to_string(), "true".to_string());
    }

    // --- Checksum ---
    if let Some((ref algo, ref val)) = opts.checksum {
        map.insert("checksum".to_string(), format!("{}={}", algo, val));
    }

    // --- Cookies ---
    if let Some(ref v) = opts.cookie_file {
        map.insert("cookie-file".to_string(), v.clone());
    }
    if let Some(ref v) = opts.cookies {
        map.insert("cookies".to_string(), v.clone());
    }

    // --- BitTorrent options ---
    if opts.bt_force_encrypt {
        map.insert("bt-force-encrypt".to_string(), "true".to_string());
    }
    if opts.bt_require_crypto {
        map.insert("bt-require-crypto".to_string(), "true".to_string());
    }
    // enable_dht defaults to true; only save if disabled
    if !opts.enable_dht {
        map.insert("enable-dht".to_string(), "false".to_string());
    }
    if let Some(v) = opts.dht_listen_port {
        map.insert("dht-listen-port".to_string(), v.to_string());
    }
    if let Some(ref v) = opts.dht_entry_point {
        map.insert("dht-entry-point".to_string(), v.join(","));
    }
    // enable_public_trackers defaults to true; only save if disabled
    if !opts.enable_public_trackers {
        map.insert("enable-public-trackers".to_string(), "false".to_string());
    }
    if !opts.bt_piece_selection_strategy.is_empty() {
        map.insert(
            "bt-piece-selection-strategy".to_string(),
            opts.bt_piece_selection_strategy.clone(),
        );
    }
    if opts.bt_endgame_threshold > 0 {
        map.insert(
            "bt-endgame-threshold".to_string(),
            opts.bt_endgame_threshold.to_string(),
        );
    }
    if let Some(v) = opts.bt_max_upload_slots {
        map.insert("bt-max-upload-slots".to_string(), v.to_string());
    }
    if let Some(v) = opts.bt_optimistic_unchoke_interval {
        map.insert("bt-optimistic-unchoke-interval".to_string(), v.to_string());
    }
    if let Some(v) = opts.bt_snubbed_timeout {
        map.insert("bt-snubbed-timeout".to_string(), v.to_string());
    }
    if !opts.bt_prioritize_piece.is_empty() {
        map.insert(
            "bt-prioritize-piece".to_string(),
            opts.bt_prioritize_piece.clone(),
        );
    }
    if opts.enable_utp {
        map.insert("enable-utp".to_string(), "true".to_string());
    }
    if let Some(v) = opts.utp_listen_port {
        map.insert("utp-listen-port".to_string(), v.to_string());
    }

    // --- Retry options ---
    if opts.max_retries > 0 {
        map.insert("max-retries".to_string(), opts.max_retries.to_string());
    }
    if opts.retry_wait > 0 {
        map.insert("retry-wait".to_string(), opts.retry_wait.to_string());
    }

    // --- DHT file path ---
    if let Some(ref v) = opts.dht_file_path {
        map.insert("dht-file-path".to_string(), v.clone());
    }

    // --- Proxy options ---
    if let Some(ref v) = opts.http_proxy {
        map.insert("http-proxy".to_string(), v.clone());
    }
    if let Some(ref v) = opts.all_proxy {
        map.insert("all-proxy".to_string(), v.clone());
    }
    if let Some(ref v) = opts.https_proxy {
        map.insert("https-proxy".to_string(), v.clone());
    }
    if let Some(ref v) = opts.ftp_proxy {
        map.insert("ftp-proxy".to_string(), v.clone());
    }
    if let Some(ref v) = opts.no_proxy {
        map.insert("no-proxy".to_string(), v.clone());
    }

    // --- HTTP headers ---
    if !opts.header.is_empty() {
        map.insert("header".to_string(), opts.header.join(","));
    }
    if let Some(ref v) = opts.user_agent {
        map.insert("user-agent".to_string(), v.clone());
    }
    if let Some(ref v) = opts.referer {
        map.insert("referer".to_string(), v.clone());
    }

    map
}

/// Represents a single download task in a session file
///
/// This struct contains all information needed to resume a download task,
/// including URIs, options, current progress, and status.
///
/// # Fields
///
/// * `gid` - Unique global identifier for this download task
/// * `uris` - List of source URLs (primary URL + mirrors)
/// * `options` - Download configuration options as key-value pairs
/// * `paused` - Whether this download is currently paused
/// * `total_length` - Total size of the download in bytes
/// * `completed_length` - Number of bytes already downloaded
/// * `upload_length` - Number of bytes uploaded (for seeding)
/// * `download_speed` - Current download speed in bytes/sec
/// * `status` - Current status: "active", "waiting", "paused", or "error"
/// * `error_code` - Error code if status is "error"
/// * `bitfield` - BitTorrent piece completion bitmap (BT only)
/// * `num_pieces` - Number of pieces in torrent (BT only)
/// * `piece_length` - Size of each piece in bytes (BT only)
/// * `info_hash_hex` - Torrent info hash hex string (BT only)
/// * `resume_offset` - File offset for HTTP/FTP resume support
#[derive(Debug, Clone)]
pub struct SessionEntry {
    /// Unique global identifier for this download task
    pub gid: u64,

    /// List of source URIs (primary URL + mirrors), tab-separated in serialized form
    pub uris: Vec<String>,

    /// Download configuration options as key-value pairs
    pub options: HashMap<String, String>,

    /// Whether this download is currently paused
    pub paused: bool,

    // ==================== Progress & Status Fields ====================
    /// Total size of the download in bytes (0 if unknown)
    pub total_length: u64,

    /// Number of bytes already downloaded and verified
    pub completed_length: u64,

    /// Number of bytes uploaded (relevant for BitTorrent seeding)
    pub upload_length: u64,

    /// Current download speed in bytes/second
    pub download_speed: u64,

    /// Current status of the download: "active", "waiting", "paused", "error"
    pub status: String,

    /// Error code if the download is in error state
    pub error_code: Option<i32>,

    // ==================== BitTorrent-Specific Fields ====================
    // These fields are only populated for BitTorrent downloads
    /// Completed piece bitmap encoded as hex string in file format
    /// None for non-BT downloads
    pub bitfield: Option<Vec<u8>>,

    /// Total number of pieces in the torrent
    /// None for non-BT downloads
    pub num_pieces: Option<u32>,

    /// Size of each piece in bytes
    /// None for non-BT downloads
    pub piece_length: Option<u32>,

    /// Info hash of the torrent (hex string) for matching torrent files
    /// None for non-BT downloads
    pub info_hash_hex: Option<String>,

    // ==================== HTTP/FTP Resume Support ====================
    /// File offset where download should resume (for HTTP/FTP range requests)
    /// None if resumption is not applicable
    pub resume_offset: Option<u64>,
}

impl SessionEntry {
    /// Creates a new SessionEntry with default values
    ///
    /// # Arguments
    ///
    /// * `gid` - Unique identifier for this download task
    /// * `uris` - List of source URLs (at least one required)
    ///
    /// # Returns
    ///
    /// A new `SessionEntry` instance with sensible defaults:
    /// - `paused`: false
    /// - All progress fields: 0
    /// - `status`: "active"
    /// - All optional fields: None
    ///
    /// # Example
    ///
    /// ```rust
    /// use aria2_core::session::session_entry::SessionEntry;
    ///
    /// let entry = SessionEntry::new(1, vec!["http://example.com/file.zip".to_string()]);
    /// assert_eq!(entry.gid, 1);
    /// assert_eq!(entry.uris.len(), 1);
    /// assert!(!entry.paused);
    /// assert_eq!(entry.status, "active");
    /// ```
    pub fn new(gid: u64, uris: Vec<String>) -> Self {
        SessionEntry {
            gid,
            uris,
            options: HashMap::new(),
            paused: false,

            // Default values for progress fields
            total_length: 0,
            completed_length: 0,
            upload_length: 0,
            download_speed: 0,
            status: "active".to_string(),
            error_code: None,

            // BT-specific fields (None for non-BT downloads by default)
            bitfield: None,
            num_pieces: None,
            piece_length: None,
            info_hash_hex: None,

            // HTTP/FTP resume info (None by default)
            resume_offset: None,
        }
    }

    /// Sets download options using builder pattern
    ///
    /// # Arguments
    ///
    /// * `options` - HashMap of option key-value pairs
    ///
    /// # Returns
    ///
    /// Self for method chaining
    ///
    /// # Example
    ///
    /// ```rust
    /// use aria2_core::session::session_entry::SessionEntry;
    /// use std::collections::HashMap;
    ///
    /// let mut opts = HashMap::new();
    /// opts.insert("split".to_string(), "4".to_string());
    /// opts.insert("dir".to_string(), "/downloads".to_string());
    ///
    /// let entry = SessionEntry::new(1, vec!["http://example.com/f".to_string()])
    ///     .with_options(opts);
    /// assert_eq!(entry.options.get("split").unwrap(), "4");
    /// ```
    pub fn with_options(mut self, options: HashMap<String, String>) -> Self {
        self.options = options;
        self
    }

    /// Marks this entry as paused using builder pattern
    ///
    /// # Returns
    ///
    /// Self for method chaining
    ///
    /// # Example
    ///
    /// ```no_run
    /// use aria2_core::session::session_entry::SessionEntry;
    ///
    /// let entry = SessionEntry::new(1, vec!["http://example.com/f".to_string()])
    ///     .paused();
    /// assert!(entry.paused);
    /// ```
    pub fn paused(mut self) -> Self {
        self.paused = true;
        self
    }

    /// Gets an option value by key
    ///
    /// # Arguments
    ///
    /// * `key` - Option key to look up
    ///
    /// # Returns
    ///
    /// Some(&str) if the key exists, None otherwise
    #[allow(dead_code)] // Utility method for option retrieval, available for future use
    fn get_option(&self, key: &str) -> Option<&str> {
        self.options.get(key).map(|s| s.as_str())
    }

    // Note: serialize() and deserialize_line() are now implemented in
    // session_serialize_impl.rs as part of impl SessionEntry
    // They are available via the impl block there and accessible normally
}

// ==================== Unit Tests ====================

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

    #[test]
    fn test_serialize_single_entry() {
        let entry = SessionEntry::new(0xd270c8a2, vec!["http://example.com/file.zip".to_string()]);
        let text = entry.serialize();
        assert!(
            text.contains("http://example.com/file.zip"),
            "Should contain URI"
        );
        assert!(text.contains("GID=d270c8a2"), "Should contain GID");
    }

    #[test]
    fn test_serialize_multiple_entries_roundtrip() {
        let entries = vec![
            SessionEntry::new(1, vec!["http://a.com/1.bin".to_string()]).with_options({
                let mut m = HashMap::new();
                m.insert("split".to_string(), "4".to_string());
                m.insert("dir".to_string(), "/tmp".to_string());
                m
            }),
            SessionEntry::new(
                2,
                vec![
                    "ftp://b.com/2.iso".to_string(),
                    "http://mirror.b.com/2.iso".to_string(),
                ],
            )
            .paused(),
        ];

        let mut serialized = String::new();
        for e in &entries {
            serialized.push_str(&e.serialize());
            serialized.push('\n');
        }

        // Parse individually using deserialize_line
        let parts: Vec<&str> = serialized.split("\n\n").collect();
        assert!(parts.len() >= 2, "Should have at least 2 entries");

        let entry1 = SessionEntry::deserialize_line(parts[0]).unwrap();
        assert_eq!(entry1.uris.len(), 1);
        assert_eq!(entry1.uris[0], "http://a.com/1.bin");
        assert_eq!(entry1.options.get("split").unwrap(), "4");

        let entry2 = SessionEntry::deserialize_line(parts[1]).unwrap();
        assert_eq!(entry2.uris.len(), 2);
        assert!(entry2.paused);
    }

    #[test]
    fn test_deserialize_empty_file() {
        let entry = SessionEntry::deserialize_line("").unwrap();
        assert!(entry.uris.is_empty());

        let entry = SessionEntry::deserialize_line("\n\n\n").unwrap();
        assert!(entry.uris.is_empty());
    }

    #[test]
    fn test_deserialize_skip_comments_and_blanks() {
        let input = r#"# This is a comment
# Another comment

http://example.com/file
 GID=abc123
 dir=/downloads
"#;
        let entry = SessionEntry::deserialize_line(input).unwrap();
        // Should parse first entry and ignore comments
        assert_eq!(entry.uris.len(), 1);
        assert_eq!(entry.uris[0], "http://example.com/file");
    }

    #[test]
    fn test_deserialize_options_parsing() {
        let input = r#"http://example.com/file.zip
 GID=1
 split=4
 max-connection-per-server=2
 dir=C:\Users\test\Downloads
 out=file.zip
"#;
        let entry = SessionEntry::deserialize_line(input).unwrap();
        assert_eq!(entry.options.get("split").unwrap(), "4");
        assert_eq!(entry.options.get("max-connection-per-server").unwrap(), "2");
        assert_eq!(
            entry.options.get("dir").unwrap(),
            "C:\\Users\\test\\Downloads"
        );
        assert_eq!(entry.options.get("out").unwrap(), "file.zip");
    }

    #[test]
    fn test_pause_flag_serialization() {
        let input = r#"http://example.com/pause.me
 GID=42
 PAUSE=true
"#;
        let entry = SessionEntry::deserialize_line(input).unwrap();
        assert!(entry.paused);

        let text = entry.serialize();
        assert!(text.contains("PAUSE=true"));
    }

    #[test]
    fn test_serialize_tab_separated_uris() {
        let entry = SessionEntry::new(
            99,
            vec![
                "http://mirror1.com/f".to_string(),
                "http://mirror2.com/f".to_string(),
                "http://mirror3.com/f".to_string(),
            ],
        );
        let text = entry.serialize();
        let uri_line = text.lines().next().unwrap();
        assert_eq!(
            uri_line.matches('\t').count(),
            2,
            "3 URIs should have 2 tab separators"
        );
    }

    // ==================== New Field Tests (Session Persistence Enhancement) ====================

    #[test]
    fn test_serialize_new_fields() {
        let mut entry = SessionEntry::new(1, vec!["http://example.com/file.bin".to_string()]);
        entry.total_length = 1024 * 1024; // 1MB
        entry.completed_length = 512 * 1024; // 512KB
        entry.upload_length = 1024;
        entry.download_speed = 2048;
        entry.status = "active".to_string();
        entry.error_code = None;

        let text = entry.serialize();

        // Verify new fields appear in output
        assert!(
            text.contains("TOTAL_LENGTH=1048576"),
            "Should contain TOTAL_LENGTH"
        );
        assert!(
            text.contains("COMPLETED_LENGTH=524288"),
            "Should contain COMPLETED_LENGTH"
        );
        assert!(
            text.contains("UPLOAD_LENGTH=1024"),
            "Should contain UPLOAD_LENGTH"
        );
        assert!(
            text.contains("DOWNLOAD_SPEED=2048"),
            "Should contain DOWNLOAD_SPEED"
        );
        assert!(text.contains("STATUS=active"), "Should contain STATUS");
    }

    #[test]
    fn test_deserialize_with_all_fields() {
        let input = r#"http://example.com/bigfile.zip
 GID=1
 TOTAL_LENGTH=10485760
 COMPLETED_LENGTH=5242880
 UPLOAD_LENGTH=2048
 DOWNLOAD_SPEED=4096
 STATUS=active
 ERROR_CODE=
 BITFIELD=
 NUM_PIECES=0
 PIECE_LENGTH=0
 INFO_HASH=
 RESUME_OFFSET=5242880
"#;

        let entry = SessionEntry::deserialize_line(input).unwrap();

        assert_eq!(entry.total_length, 10485760);
        assert_eq!(entry.completed_length, 5242880);
        assert_eq!(entry.upload_length, 2048);
        assert_eq!(entry.download_speed, 4096);
        assert_eq!(entry.status, "active");
        assert_eq!(entry.error_code, None);
        assert_eq!(entry.resume_offset, Some(5242880));
    }

    #[test]
    fn test_deserialize_user_options() {
        // User-defined options should be stored in options map
        let input = r#"http://example.com/file.zip
 GID=1
 split=4
 dir=/downloads
 TOTAL_LENGTH=1000
"#;

        let entry = SessionEntry::deserialize_line(input).unwrap();

        // Known fields parsed normally
        assert_eq!(entry.total_length, 1000);

        // User options stored in options
        assert_eq!(entry.options.get("split").unwrap(), "4");
        assert_eq!(entry.options.get("dir").unwrap(), "/downloads");
    }

    #[test]
    fn test_bitfield_roundtrip() {
        let mut entry =
            SessionEntry::new(1, vec!["http://example.com/torrent.torrent".to_string()]);

        // Set bitfield: [0xFF, 0xF0, 0x0F] - indicates some pieces completed
        entry.bitfield = Some(vec![0xFF, 0xF0, 0x0F]);
        entry.num_pieces = Some(24); // 3 bytes * 8 bits = 24 pieces
        entry.piece_length = Some(262144); // 256KB

        let text = entry.serialize();

        // Verify hex encoding
        assert!(
            text.contains("BITFIELD=fff00f"),
            "bitfield should be encoded as hex string"
        );

        // Deserialize verification
        let restored = SessionEntry::deserialize_line(&text).unwrap();
        assert_eq!(
            restored.bitfield,
            Some(vec![0xFF, 0xF0, 0x0F]),
            "bitfield should be restored correctly"
        );
        assert_eq!(restored.num_pieces, Some(24));
        assert_eq!(restored.piece_length, Some(262144));
    }

    #[test]
    fn test_empty_bitfield_serialized_as_empty() {
        let entry = SessionEntry::new(1, vec!["http://example.com/file.zip".to_string()]);
        // bitfield defaults to None

        let text = entry.serialize();

        // None bitfield should produce empty value
        assert!(
            text.contains("BITFIELD=\n"),
            "None bitfield should be serialized as empty value"
        );

        // Deserialize verification
        let restored = SessionEntry::deserialize_line(&text).unwrap();
        assert_eq!(
            restored.bitfield, None,
            "Empty bitfield should restore to None"
        );
    }

    #[test]
    fn test_default_session_entry_has_zero_progress() {
        let entry = SessionEntry::new(99, vec!["http://test.com/f".to_string()]);

        // Verify all new fields have correct defaults
        assert_eq!(entry.total_length, 0);
        assert_eq!(entry.completed_length, 0);
        assert_eq!(entry.upload_length, 0);
        assert_eq!(entry.download_speed, 0);
        assert_eq!(entry.status, "active", "Default status should be 'active'");
        assert_eq!(entry.error_code, None);
        assert_eq!(entry.bitfield, None);
        assert_eq!(entry.num_pieces, None);
        assert_eq!(entry.piece_length, None);
        assert_eq!(entry.info_hash_hex, None);
        assert_eq!(entry.resume_offset, None);
    }

    #[test]
    fn test_status_field_values() {
        let statuses = ["active", "waiting", "paused", "error"];

        for status in statuses {
            let mut entry = SessionEntry::new(1, vec!["http://example.com/f".to_string()]);
            entry.status = status.to_string();

            let text = entry.serialize();
            assert!(
                text.contains(&format!("STATUS={}", status)),
                "Status '{}' should be serialized correctly",
                status
            );

            // Deserialize verification
            let restored = SessionEntry::deserialize_line(&text).unwrap();
            assert_eq!(
                restored.status, status,
                "Status '{}' should be deserialized correctly",
                status
            );
        }
    }

    #[test]
    fn test_resume_offset_for_http_ftp() {
        let mut entry = SessionEntry::new(1, vec!["http://example.com/large-file.iso".to_string()]);

        // Simulate HTTP download with partial data written
        entry.total_length = 1073741824; // 1GB
        entry.completed_length = 536870912; // 512MB completed
        entry.resume_offset = Some(536870912); // Resume from 512MB
        entry.status = "paused".to_string();

        let text = entry.serialize();

        // Verify resume offset is serialized correctly
        assert!(
            text.contains("RESUME_OFFSET=536870912"),
            "resume offset should be serialized correctly"
        );

        // Deserialize and verify
        let restored = SessionEntry::deserialize_line(&text).unwrap();
        assert_eq!(
            restored.resume_offset,
            Some(536870912),
            "resume offset should be restored correctly"
        );
        assert_eq!(restored.status, "paused");
    }

    #[test]
    fn test_bt_specific_fields_only_when_present() {
        // Test that BT-specific fields are truly optional
        let mut entry = SessionEntry::new(1, vec!["magnet:?xt=urn:btih:abc123".to_string()]);

        // Don't set any BT fields (keep them as None)
        let text_without_bt = entry.serialize();
        let restored_without_bt = SessionEntry::deserialize_line(&text_without_bt).unwrap();

        assert_eq!(restored_without_bt.bitfield, None);
        assert_eq!(restored_without_bt.num_pieces, None);
        assert_eq!(restored_without_bt.piece_length, None);
        assert_eq!(restored_without_bt.info_hash_hex, None);

        // Now set BT fields
        entry.bitfield = Some(vec![0xAA, 0xBB]);
        entry.num_pieces = Some(16);
        entry.piece_length = Some(524288);
        entry.info_hash_hex = Some("abc123def456".to_string());

        let text_with_bt = entry.serialize();
        let restored_with_bt = SessionEntry::deserialize_line(&text_with_bt).unwrap();

        assert_eq!(restored_with_bt.bitfield, Some(vec![0xAA, 0xBB]));
        assert_eq!(restored_with_bt.num_pieces, Some(16));
        assert_eq!(restored_with_bt.piece_length, Some(524288));
        assert_eq!(
            restored_with_bt.info_hash_hex,
            Some("abc123def456".to_string())
        );
    }

    #[test]
    fn test_download_options_to_map_all_fields() {
        // Verify that all non-default fields are serialized to the map
        let opts = DownloadOptions {
            split: Some(8),
            max_connection_per_server: Some(4),
            max_download_limit: Some(102400),
            max_upload_limit: Some(51200),
            dir: Some("/downloads".to_string()),
            out: Some("file.bin".to_string()),
            seed_time: Some(3600),
            seed_ratio: Some(2.0),
            // File allocation
            file_allocation: Some("trunc".to_string()),
            mmap_threshold: Some(128 * 1024 * 1024),
            secure_falloc: true,
            // Checksum
            checksum: Some(("sha256".to_string(), "abc123".to_string())),
            // Cookies
            cookie_file: Some("/tmp/cookies.txt".to_string()),
            cookies: Some("key=value".to_string()),
            // BT
            bt_force_encrypt: true,
            bt_require_crypto: true,
            enable_dht: false,
            dht_listen_port: Some(6881),
            dht_entry_point: Some(vec!["router.bittorrent.com:6881".to_string()]),
            enable_public_trackers: false,
            bt_piece_selection_strategy: "sequential".to_string(),
            bt_endgame_threshold: 10,
            bt_max_upload_slots: Some(4),
            bt_optimistic_unchoke_interval: Some(30),
            bt_snubbed_timeout: Some(60),
            bt_prioritize_piece: "head".to_string(),
            enable_utp: true,
            utp_listen_port: Some(6882),
            // Retry
            max_retries: 5,
            retry_wait: 3,
            // DHT file
            dht_file_path: Some("/tmp/dht.dat".to_string()),
            // Proxy
            http_proxy: Some("http://proxy:8080".to_string()),
            all_proxy: Some("socks5://proxy:1080".to_string()),
            https_proxy: Some("http://proxy:8443".to_string()),
            ftp_proxy: Some("http://proxy:8021".to_string()),
            no_proxy: Some("localhost,127.0.0.1".to_string()),
            // HTTP headers
            header: vec!["X-Custom: foo".to_string(), "X-Other: bar".to_string()],
            user_agent: Some("aria2-rust/1.0".to_string()),
            referer: Some("http://example.com".to_string()),
        };

        let map = download_options_to_map(&opts);

        // File allocation
        assert_eq!(map.get("file-allocation").unwrap(), "trunc");
        assert_eq!(map.get("mmap-threshold").unwrap(), "134217728");
        assert_eq!(map.get("secure-falloc").unwrap(), "true");

        // Checksum
        assert_eq!(map.get("checksum").unwrap(), "sha256=abc123");

        // Cookies
        assert_eq!(map.get("cookie-file").unwrap(), "/tmp/cookies.txt");
        assert_eq!(map.get("cookies").unwrap(), "key=value");

        // BT
        assert_eq!(map.get("bt-force-encrypt").unwrap(), "true");
        assert_eq!(map.get("bt-require-crypto").unwrap(), "true");
        assert_eq!(map.get("enable-dht").unwrap(), "false");
        assert_eq!(map.get("dht-listen-port").unwrap(), "6881");
        assert_eq!(
            map.get("dht-entry-point").unwrap(),
            "router.bittorrent.com:6881"
        );
        assert_eq!(map.get("enable-public-trackers").unwrap(), "false");
        assert_eq!(
            map.get("bt-piece-selection-strategy").unwrap(),
            "sequential"
        );
        assert_eq!(map.get("bt-endgame-threshold").unwrap(), "10");
        assert_eq!(map.get("bt-max-upload-slots").unwrap(), "4");
        assert_eq!(map.get("bt-optimistic-unchoke-interval").unwrap(), "30");
        assert_eq!(map.get("bt-snubbed-timeout").unwrap(), "60");
        assert_eq!(map.get("bt-prioritize-piece").unwrap(), "head");
        assert_eq!(map.get("enable-utp").unwrap(), "true");
        assert_eq!(map.get("utp-listen-port").unwrap(), "6882");

        // Retry
        assert_eq!(map.get("max-retries").unwrap(), "5");
        assert_eq!(map.get("retry-wait").unwrap(), "3");

        // DHT file
        assert_eq!(map.get("dht-file-path").unwrap(), "/tmp/dht.dat");

        // Proxy
        assert_eq!(map.get("http-proxy").unwrap(), "http://proxy:8080");
        assert_eq!(map.get("all-proxy").unwrap(), "socks5://proxy:1080");
        assert_eq!(map.get("https-proxy").unwrap(), "http://proxy:8443");
        assert_eq!(map.get("ftp-proxy").unwrap(), "http://proxy:8021");
        assert_eq!(map.get("no-proxy").unwrap(), "localhost,127.0.0.1");

        // HTTP headers
        assert_eq!(map.get("header").unwrap(), "X-Custom: foo,X-Other: bar");
        assert_eq!(map.get("user-agent").unwrap(), "aria2-rust/1.0");
        assert_eq!(map.get("referer").unwrap(), "http://example.com");
    }

    #[test]
    fn test_download_options_to_map_defaults_excluded() {
        // Default DownloadOptions should produce a minimal map.
        // enable_dht and enable_public_trackers default to true (matching the
        // load path's `unwrap_or(true)`), so they are NOT saved when at the
        // default value — the save logic only serializes them when disabled.
        let opts = DownloadOptions::default();
        let map = download_options_to_map(&opts);

        // secure_falloc defaults to false -> should NOT be in map
        assert!(!map.contains_key("secure-falloc"));
        // file_allocation defaults to None -> should NOT be in map
        assert!(!map.contains_key("file-allocation"));
        // enable_dht and enable_public_trackers default to true -> NOT saved
        assert!(!map.contains_key("enable-dht"));
        assert!(!map.contains_key("enable-public-trackers"));
    }
}