Kget 1.7.0

A powerful and versatile download manager and library
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
//! Advanced parallel download functionality with resume support.
//!
//! The [`AdvancedDownloader`] provides high-performance downloads using:
//! - **Parallel connections**: Split files into chunks downloaded simultaneously
//! - **Resume support**: Continue interrupted downloads from where they left off
//! - **Progress callbacks**: Real-time progress and status updates
//! - **Cancellation**: Graceful download cancellation via atomic tokens
//!
//! # Example
//!
//! ```rust,no_run
//! use kget::{AdvancedDownloader, ProxyConfig, Optimizer};
//!
//! let mut downloader = AdvancedDownloader::new(
//!     "https://releases.ubuntu.com/22.04/ubuntu-22.04-desktop-amd64.iso".to_string(),
//!     "ubuntu.iso".to_string(),
//!     false,
//!     ProxyConfig::default(),
//!     Optimizer::new(),
//! );
//!
//! // Set progress callback (0.0 to 1.0)
//! downloader.set_progress_callback(|progress| {
//!     println!("Progress: {:.1}%", progress * 100.0);
//! });
//!
//! // Set status callback for messages
//! downloader.set_status_callback(|msg| {
//!     println!("Status: {}", msg);
//! });
//!
//! // Start download
//! downloader.download().unwrap();
//! ```
//!
//! # Parallel Downloads
//!
//! The downloader automatically determines the optimal number of connections
//! based on the [`Optimizer`] configuration. For large files,
//! this can provide significant speed improvements.

use crate::config::ProxyConfig;
use crate::optimization::Optimizer;
use hex;
use indicatif::{ProgressBar, ProgressStyle};
use rayon::prelude::*;
use reqwest::blocking::Client;
use sha2::{Digest, Sha256};
use std::error::Error;
use std::fs::File;
use std::io::{BufReader, Read, Seek, SeekFrom, Write};
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

#[cfg(target_family = "unix")]
use std::os::unix::fs::FileExt;
#[cfg(target_family = "windows")]
use std::os::windows::fs::FileExt;

/// Minimum chunk size for parallel downloads (4 MB)
const MIN_CHUNK_SIZE: u64 = 4 * 1024 * 1024;
/// Maximum retry attempts per chunk
const MAX_RETRIES: usize = 3;

/// Controls how [`AdvancedDownloader`] behaves when user interaction would otherwise be required.
///
/// Non-interactive callers (library, `--jsonl`, automation) must use
/// [`AlwaysResume`](ResumePolicy::AlwaysResume) or [`AlwaysRestart`](ResumePolicy::AlwaysRestart)
/// to avoid blocking on stdin.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ResumePolicy {
    /// Block on stdin for user confirmation (interactive CLI only).
    #[default]
    Ask,
    /// Proceed automatically without prompting; verifies integrity when a hash is set.
    AlwaysResume,
    /// Always restart from scratch, discarding any existing partial file.
    AlwaysRestart,
}

/// Token bucket for global download rate limiting across parallel threads.
///
/// Unlike per-thread throttling, this bounds aggregate throughput regardless of
/// how many threads are active.
struct TokenBucket {
    limit_bps: u64,
    tokens: f64,
    last_refill: Instant,
}

impl TokenBucket {
    fn new(limit_bps: u64) -> Self {
        Self {
            limit_bps,
            tokens: limit_bps as f64,
            last_refill: Instant::now(),
        }
    }

    /// Consume `n` bytes from the bucket and return how long to sleep before writing.
    ///
    /// The caller must release the lock before sleeping.
    fn consume(&mut self, n: u64) -> Option<Duration> {
        let elapsed = self.last_refill.elapsed();
        let refill = elapsed.as_secs_f64() * self.limit_bps as f64;
        self.tokens = (self.tokens + refill).min(self.limit_bps as f64);
        self.last_refill = Instant::now();

        if self.tokens >= n as f64 {
            self.tokens -= n as f64;
            None
        } else {
            let deficit = n as f64 - self.tokens;
            self.tokens = 0.0;
            Some(Duration::from_secs_f64(deficit / self.limit_bps as f64))
        }
    }
}

/// High-performance downloader with parallel connections and resume support.
///
/// `AdvancedDownloader` is the recommended way to download large files. It provides:
///
/// - **Parallel chunk downloads**: Splits files into segments downloaded simultaneously
/// - **Automatic resume**: Detects existing partial files and resumes from last position
/// - **Server compatibility**: Falls back to single-stream if server doesn't support ranges
/// - **ISO optimization**: Disables compression for binary files to prevent corruption
/// - **Progress tracking**: Real-time callbacks for UI integration
/// - **Cancellation support**: Stop downloads gracefully via atomic cancel token
///
/// # Example
///
/// ```rust,no_run
/// use kget::{AdvancedDownloader, ProxyConfig, Optimizer};
///
/// let downloader = AdvancedDownloader::new(
///     "https://example.com/large-file.zip".to_string(),
///     "large-file.zip".to_string(),
///     false,  // quiet_mode
///     ProxyConfig::default(),
///     Optimizer::new(),
/// );
///
/// downloader.download().expect("Download failed");
/// ```
///
/// # With Progress Tracking
///
/// ```rust,no_run
/// use kget::{AdvancedDownloader, ProxyConfig, Optimizer};
///
/// let mut dl = AdvancedDownloader::new(
///     "https://example.com/file.iso".to_string(),
///     "file.iso".to_string(),
///     true, // quiet mode (no stdout)
///     ProxyConfig::default(),
///     Optimizer::new(),
/// );
///
/// dl.set_progress_callback(|p| {
///     // p is 0.0 to 1.0
///     update_ui_progress(p);
/// });
///
/// dl.set_status_callback(|msg| println!("{}", msg));
///
/// dl.download().unwrap();
///
/// fn update_ui_progress(p: f32) {
///     // Update your UI here
/// }
/// ```
pub struct AdvancedDownloader {
    client: Client,
    url: String,
    output_path: String,
    quiet_mode: bool,
    #[allow(dead_code)]
    proxy: ProxyConfig,
    optimizer: Optimizer,
    progress_callback: Option<Arc<dyn Fn(f32) + Send + Sync>>,
    status_callback: Option<Arc<dyn Fn(String) + Send + Sync>>,
    cancel_token: Arc<AtomicBool>,
    expected_sha256: Option<String>,
    extra_headers: Vec<(String, String)>,
    resume_policy: ResumePolicy,
}

impl AdvancedDownloader {
    /// Create a new `AdvancedDownloader` instance.
    ///
    /// # Arguments
    ///
    /// * `url` - URL to download from
    /// * `output_path` - Local path for the downloaded file
    /// * `quiet_mode` - If true, suppress console output
    /// * `proxy_config` - Proxy settings (use `ProxyConfig::default()` for direct connection)
    /// * `optimizer` - Optimizer for connection settings
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use kget::{AdvancedDownloader, ProxyConfig, Optimizer};
    ///
    /// let dl = AdvancedDownloader::new(
    ///     "https://example.com/file.zip".to_string(),
    ///     "./downloads/file.zip".to_string(),
    ///     false,
    ///     ProxyConfig::default(),
    ///     Optimizer::new(),
    /// );
    /// ```
    pub fn new(
        url: String,
        output_path: String,
        quiet_mode: bool,
        proxy_config: ProxyConfig,
        optimizer: Optimizer,
    ) -> Result<Self, Box<dyn Error + Send + Sync>> {
        let _is_iso = url.to_lowercase().ends_with(".iso");

        let mut client_builder = Client::builder()
            .timeout(std::time::Duration::from_secs(300))
            .connect_timeout(std::time::Duration::from_secs(20))
            .user_agent(concat!("KGet/", env!("CARGO_PKG_VERSION")))
            .no_gzip()
            .no_deflate();

        if proxy_config.enabled {
            if let Some(proxy_url) = &proxy_config.url {
                let proxy = match proxy_config.proxy_type {
                    crate::config::ProxyType::Http => reqwest::Proxy::http(proxy_url),
                    crate::config::ProxyType::Https => reqwest::Proxy::https(proxy_url),
                    crate::config::ProxyType::Socks5 => reqwest::Proxy::all(proxy_url),
                };

                if let Ok(mut proxy) = proxy {
                    if let (Some(username), Some(password)) =
                        (&proxy_config.username, &proxy_config.password)
                    {
                        proxy = proxy.basic_auth(username, password);
                    }
                    client_builder = client_builder.proxy(proxy);
                }
            }
        }

        let client = client_builder
            .build()
            .map_err(|e| format!("Failed to create HTTP client: {}", e))?;

        Ok(Self {
            client,
            url,
            output_path,
            quiet_mode,
            proxy: proxy_config,
            optimizer,
            progress_callback: None,
            status_callback: None,
            cancel_token: Arc::new(AtomicBool::new(false)),
            expected_sha256: None,
            extra_headers: Vec::new(),
            resume_policy: ResumePolicy::default(),
        })
    }

    /// Set a custom cancellation token for graceful download interruption.
    ///
    /// When the token is set to `true`, the download will stop at the next
    /// checkpoint and return an error.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use kget::{AdvancedDownloader, ProxyConfig, Optimizer};
    /// use std::sync::Arc;
    /// use std::sync::atomic::AtomicBool;
    ///
    /// let cancel = Arc::new(AtomicBool::new(false));
    /// let mut dl = AdvancedDownloader::new(/* ... */
    /// #    "".to_string(), "".to_string(), false, ProxyConfig::default(), Optimizer::new()
    /// );
    /// dl.set_cancel_token(cancel.clone());
    ///
    /// // In another thread:
    /// // cancel.store(true, std::sync::atomic::Ordering::Relaxed);
    /// ```
    pub fn set_cancel_token(&mut self, token: Arc<AtomicBool>) {
        self.cancel_token = token;
    }

    /// Check if the download has been cancelled.
    pub fn is_cancelled(&self) -> bool {
        self.cancel_token.load(Ordering::Relaxed)
    }

    /// Set a callback for progress updates.
    ///
    /// The callback receives a value from 0.0 (start) to 1.0 (complete).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use kget::{AdvancedDownloader, ProxyConfig, Optimizer};
    /// # let mut dl = AdvancedDownloader::new("".to_string(), "".to_string(), false, ProxyConfig::default(), Optimizer::new());
    /// dl.set_progress_callback(|progress| {
    ///     println!("Downloaded: {:.1}%", progress * 100.0);
    /// });
    /// ```
    pub fn set_progress_callback(&mut self, callback: impl Fn(f32) + Send + Sync + 'static) {
        self.progress_callback = Some(Arc::new(callback));
    }

    /// Set a callback for status messages.
    ///
    /// Receives human-readable status updates during the download.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use kget::{AdvancedDownloader, ProxyConfig, Optimizer};
    /// # let mut dl = AdvancedDownloader::new("".to_string(), "".to_string(), false, ProxyConfig::default(), Optimizer::new());
    /// dl.set_status_callback(|msg| {
    ///     println!("Download status: {}", msg);
    /// });
    /// ```
    pub fn set_status_callback(&mut self, callback: impl Fn(String) + Send + Sync + 'static) {
        self.status_callback = Some(Arc::new(callback));
    }

    /// Set an expected SHA-256 hash for automatic verification after download.
    pub fn set_expected_sha256(&mut self, expected_sha256: impl Into<String>) {
        self.expected_sha256 = Some(expected_sha256.into());
    }

    /// Set extra HTTP headers sent with every request (e.g. `Referer` or `Cookie`).
    pub fn set_extra_headers(&mut self, headers: Vec<(String, String)>) {
        self.extra_headers = headers;
    }

    /// Set how the downloader handles interactive prompts.
    ///
    /// Library and automation callers must set [`ResumePolicy::AlwaysResume`] to
    /// avoid blocking on stdin.
    pub fn set_resume_policy(&mut self, policy: ResumePolicy) {
        self.resume_policy = policy;
    }

    /// Apply `self.extra_headers` to a request builder.
    fn apply_headers(&self, mut req: reqwest::blocking::RequestBuilder) -> reqwest::blocking::RequestBuilder {
        for (name, value) in &self.extra_headers {
            if let (Ok(n), Ok(v)) = (
                reqwest::header::HeaderName::from_bytes(name.as_bytes()),
                reqwest::header::HeaderValue::from_str(value),
            ) {
                req = req.header(n, v);
            }
        }
        req
    }

    fn send_status(&self, msg: &str) {
        if let Some(cb) = &self.status_callback {
            cb(msg.to_string());
        }
        if !self.quiet_mode {
            println!("{}", msg);
        }
    }

    /// Start the download.
    ///
    /// This method:
    /// 1. Checks for existing partial file (resume support)
    /// 2. Queries server for file size and range support
    /// 3. Downloads using parallel connections if supported
    /// 4. Falls back to single-stream if server doesn't support ranges
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on successful download, or an error if the download fails.
    ///
    /// # Errors
    ///
    /// - Network connection failures
    /// - Existing file larger than remote (corrupted state)
    /// - Cancellation via cancel token
    /// - Disk I/O errors
    pub fn download(&self) -> Result<(), Box<dyn Error + Send + Sync>> {
        let is_iso = self.url.to_lowercase().ends_with(".iso");
        if !self.quiet_mode {
            println!("Starting advanced download for: {}", self.url);
            if is_iso {
                println!(
                    "Warning: ISO mode active. Disabling optimizations that could corrupt binary data."
                );
            }
        }

        // Verify if the output path is valid
        let existing_size = if Path::new(&self.output_path).exists() {
            let size = std::fs::metadata(&self.output_path)?.len();
            if !self.quiet_mode {
                println!("Existing file found with size: {} bytes", size);
            }
            Some(size)
        } else {
            if !self.quiet_mode {
                println!("Output file does not exist, starting fresh download");
            }
            None
        };

        // Get the total file size and range support
        if !self.quiet_mode {
            println!("Querying server for file size and range support...");
        }
        let (total_size, supports_range) = self.get_file_size_and_range()?;
        if !self.quiet_mode {
            println!("Total file size: {} bytes", total_size);
            println!("Server supports range requests: {}", supports_range);
        }

        if let Some(size) = existing_size {
            if size > total_size {
                return Err("Existing file is larger than remote; aborting".into());
            }
            if !self.quiet_mode {
                println!("Resuming download from byte: {}", size);
            }
        }

        // AlwaysRestart: discard any existing partial file and start fresh.
        let existing_size = if self.resume_policy == ResumePolicy::AlwaysRestart {
            None
        } else {
            existing_size
        };

        // Create a progress bar if not quiet or if we have a callback
        let progress = if !self.quiet_mode || self.progress_callback.is_some() {
            let bar = ProgressBar::new(total_size);
            if let Some(size) = existing_size {
                bar.set_position(size);
            }
            if self.quiet_mode {
                bar.set_draw_target(indicatif::ProgressDrawTarget::hidden());
            } else {
                bar.set_style(ProgressStyle::with_template(
                    "{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec}, {eta})"
                ).unwrap().progress_chars("#>-"));
            }
            Some(Arc::new(Mutex::new(bar)))
        } else {
            None
        };

        // Create or open the output file and preallocate
        if !self.quiet_mode {
            println!("Preparing output file: {}", self.output_path);
        }
        let file = if existing_size.is_some() {
            File::options()
                .read(true)
                .write(true)
                .open(&self.output_path)?
        } else {
            File::create(&self.output_path)?
        };

        // If range not supported, do a single download (no preallocation required)
        if !supports_range {
            if !self.quiet_mode {
                println!("Range requests not supported, falling back to single-threaded download");
            }
            self.download_whole(&file, existing_size.unwrap_or(0), progress.clone())?;
            if let Some(ref bar) = progress {
                bar.lock()
                    .expect("Progress bar mutex was poisoned")
                    .finish_with_message("Download completed");
            }
            if !self.quiet_mode {
                println!("Single-threaded download completed");
            }
            return Ok(());
        }

        // Range supported: preallocate file so parallel chunk writes land at the right offsets.
        file.set_len(total_size)?;
        if !self.quiet_mode {
            println!("File preallocated to {} bytes", total_size);
        }

        // Calculate chunks for parallel download
        if !self.quiet_mode {
            println!("Calculating download chunks...");
        }
        let chunks = self.calculate_chunks(total_size, existing_size)?;
        if !self.quiet_mode {
            println!("Download will be split into {} chunks", chunks.len());
        }

        // Build a global token bucket so the aggregate rate across all threads stays at the limit.
        let throttle_bucket = self.optimizer.speed_limit.map(|limit| {
            Arc::new(Mutex::new(TokenBucket::new(limit)))
        });

        // Download parallel chunks
        if !self.quiet_mode {
            println!("Starting parallel chunk downloads...");
        }
        self.download_chunks_parallel(
            chunks,
            &file,
            progress.clone(),
            total_size,
            existing_size.unwrap_or(0),
            throttle_bucket,
        )?;

        if let Some(ref bar) = progress {
            bar.lock()
                .expect("Progress bar mutex was poisoned")
                .finish_with_message("Download completed");
        }

        // Verify download integrity
        if !self.quiet_mode || self.status_callback.is_some() {
            if is_iso || self.expected_sha256.is_some() {
                let should_verify = if self.status_callback.is_some()
                    || self.expected_sha256.is_some()
                {
                    true
                } else {
                    match self.resume_policy {
                        ResumePolicy::Ask => {
                            println!(
                                "\nThis is an ISO file. Would you like to verify its integrity? (y/N)"
                            );
                            let mut input = String::new();
                            std::io::stdin().read_line(&mut input).is_ok()
                                && input.trim().to_lowercase() == "y"
                        }
                        ResumePolicy::AlwaysResume => true,
                        ResumePolicy::AlwaysRestart => false,
                    }
                };

                if should_verify {
                    self.verify_integrity(total_size)?;
                }
            } else {
                let metadata = std::fs::metadata(&self.output_path)?;
                if metadata.len() != total_size {
                    return Err(format!(
                        "File size mismatch: expected {} bytes, got {} bytes",
                        total_size,
                        metadata.len()
                    )
                    .into());
                }
            }
            self.send_status("Advanced download completed successfully!");
        }

        Ok(())
    }

    fn get_file_size_and_range(&self) -> Result<(u64, bool), Box<dyn Error + Send + Sync>> {
        let head_response = self.apply_headers(self.client.head(&self.url)).send();
        let Ok(response) = head_response else {
            return self.get_file_size_with_range_probe();
        };

        if !response.status().is_success() {
            return self.get_file_size_with_range_probe();
        }

        let content_length = response
            .headers()
            .get(reqwest::header::CONTENT_LENGTH)
            .and_then(|v| v.to_str().ok())
            .and_then(|s| s.parse::<u64>().ok());

        let accepts_range = response
            .headers()
            .get(reqwest::header::ACCEPT_RANGES)
            .and_then(|v| v.to_str().ok())
            .map(|s| s.eq_ignore_ascii_case("bytes"))
            .unwrap_or(false);

        if let Some(content_length) = content_length {
            Ok((content_length, accepts_range))
        } else {
            self.get_file_size_with_range_probe()
        }
    }

    fn get_file_size_with_range_probe(&self) -> Result<(u64, bool), Box<dyn Error + Send + Sync>> {
        let response = self
            .apply_headers(self.client.get(&self.url))
            .header(reqwest::header::RANGE, "bytes=0-0")
            .send()?;

        if response.status() == reqwest::StatusCode::PARTIAL_CONTENT {
            if let Some(total) = response
                .headers()
                .get(reqwest::header::CONTENT_RANGE)
                .and_then(|v| v.to_str().ok())
                .and_then(parse_content_range_total)
            {
                return Ok((total, true));
            }
        }

        if response.status().is_success() {
            if let Some(total) = response
                .headers()
                .get(reqwest::header::CONTENT_LENGTH)
                .and_then(|v| v.to_str().ok())
                .and_then(|s| s.parse::<u64>().ok())
            {
                return Ok((total, false));
            }
        }

        Err("Could not determine file size".into())
    }

    fn calculate_chunks(
        &self,
        total_size: u64,
        existing_size: Option<u64>,
    ) -> Result<Vec<(u64, u64)>, Box<dyn Error + Send + Sync>> {
        let mut chunks = Vec::new();
        let start_from = existing_size.unwrap_or(0);

        let configured_parallelism = self.optimizer.max_connections() as u64;
        let runtime_parallelism = rayon::current_num_threads() as u64;
        let parallelism = configured_parallelism.min(runtime_parallelism).max(1);
        let target_chunks = parallelism.saturating_mul(2).max(2); // Keep workers fed without overwhelming servers.
        let chunk_size = ((total_size / target_chunks).max(MIN_CHUNK_SIZE)).min(64 * 1024 * 1024);

        let mut start = start_from;
        while start < total_size {
            let end = (start + chunk_size).min(total_size);
            chunks.push((start, end));
            start = end;
        }

        Ok(chunks)
    }

    fn download_whole(
        &self,
        file: &File,
        offset: u64,
        progress: Option<Arc<Mutex<ProgressBar>>>,
    ) -> Result<(), Box<dyn Error + Send + Sync>> {
        let response = self.apply_headers(self.client.get(&self.url)).send()?;
        if offset > 0 {
            // Resume not possible without range; warn
            return Err("Server does not support range; cannot resume partial file".into());
        }

        let mut reader = BufReader::new(response);
        let mut f = file.try_clone()?;
        f.seek(SeekFrom::Start(0))?;

        struct ProgressWriter<'a, W> {
            inner: W,
            progress: Option<Arc<Mutex<ProgressBar>>>,
            callback: Option<&'a Arc<dyn Fn(f32) + Send + Sync>>,
        }

        impl<'a, W: Write> Write for ProgressWriter<'a, W> {
            fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
                let n = self.inner.write(buf)?;
                if let Some(ref bar) = self.progress {
                    let guard = bar.lock().expect("Progress bar mutex was poisoned");
                    guard.inc(n as u64);
                    if let Some(cb) = self.callback {
                        let pos = guard.position();
                        let len = guard.length().unwrap_or(1);
                        drop(guard);
                        (cb)(pos as f32 / len as f32);
                    }
                }
                Ok(n)
            }

            fn flush(&mut self) -> std::io::Result<()> {
                self.inner.flush()
            }
        }

        let mut writer = ProgressWriter {
            inner: f,
            progress,
            callback: self.progress_callback.as_ref(),
        };
        std::io::copy(&mut reader, &mut writer)?;

        Ok(())
    }

    fn download_chunks_parallel(
        &self,
        chunks: Vec<(u64, u64)>,
        file: &File,
        progress: Option<Arc<Mutex<ProgressBar>>>,
        total_size: u64,
        initial_downloaded: u64,
        throttle_bucket: Option<Arc<Mutex<TokenBucket>>>,
    ) -> Result<(), Box<dyn Error + Send + Sync>> {
        let file = Arc::new(file);
        let client = Arc::new(self.client.clone());
        let url = Arc::new(self.url.clone());
        let progress_callback = self.progress_callback.clone();
        let cancel_token = self.cancel_token.clone();
        let extra_headers = Arc::new(self.extra_headers.clone());

        // Shared progress counter for pipe-friendly output
        let downloaded_bytes = Arc::new(AtomicU64::new(initial_downloaded));
        let last_print_time = Arc::new(Mutex::new(Instant::now()));
        let quiet_mode = self.quiet_mode;

        chunks.par_iter().try_for_each(|&(start, end)| {
            // Check for cancellation before starting chunk
            if cancel_token.load(Ordering::Relaxed) {
                return Err("Download cancelled".into());
            }

            let range = format!("bytes={}-{}", start, end - 1);
            let range_header = reqwest::header::HeaderValue::from_str(&range)
                .map_err(|e| format!("Invalid range header {}: {}", range, e))?;

            for retry in 0..=MAX_RETRIES {
                // Check for cancellation on each retry
                if cancel_token.load(Ordering::Relaxed) {
                    return Err("Download cancelled".into());
                }

                let mut request = client.get(url.as_str());
                for (name, value) in extra_headers.as_ref() {
                    if let (Ok(n), Ok(v)) = (
                        reqwest::header::HeaderName::from_bytes(name.as_bytes()),
                        reqwest::header::HeaderValue::from_str(value),
                    ) {
                        request = request.header(n, v);
                    }
                }
                let request = request.header(reqwest::header::RANGE, range_header.clone());

                match request.send() {
                    Ok(mut response) => {
                        let status = response.status();
                        if status == reqwest::StatusCode::PARTIAL_CONTENT {
                            // Use FileExt to write at specific offset without seeking shared cursor
                            // This prevents race conditions when multiple threads write to the same file

                            let mut current_pos = start;
                            let mut buffer = [0u8; 16384];

                            while current_pos < end {
                                // Check for cancellation periodically during download
                                if cancel_token.load(Ordering::Relaxed) {
                                    return Err("Download cancelled".into());
                                }

                                let limit = (end - current_pos).min(buffer.len() as u64);
                                let n = response.read(&mut buffer[..limit as usize])?;
                                if n == 0 {
                                    break;
                                }

                                #[cfg(target_family = "unix")]
                                file.write_at(&buffer[..n], current_pos)?;

                                #[cfg(target_family = "windows")]
                                file.seek_write(&buffer[..n], current_pos)?;

                                current_pos += n as u64;

                                // Update shared progress counter
                                let new_downloaded = downloaded_bytes
                                    .fetch_add(n as u64, Ordering::Relaxed)
                                    + n as u64;

                                // Print progress periodically (every 200ms) for pipe-friendly output
                                {
                                    let mut last_time = last_print_time.lock().expect("Timer mutex was poisoned");
                                    if !quiet_mode && last_time.elapsed() >= Duration::from_millis(200) {
                                let percent = (new_downloaded as f64 / total_size.max(1) as f64
                                            * 100.0)
                                            .min(100.0);
                                        // PROGRESS: format that Swift can parse
                                        println!(
                                            "PROGRESS: {:.1}% ({}/{})",
                                            percent, new_downloaded, total_size
                                        );
                                        *last_time = Instant::now();
                                    }
                                }

                                if let Some(ref bucket) = throttle_bucket {
                                    let sleep_dur = {
                                        let mut guard = bucket
                                            .lock()
                                            .expect("throttle bucket poisoned");
                                        guard.consume(n as u64)
                                    };
                                    if let Some(dur) = sleep_dur {
                                        std::thread::sleep(dur);
                                    }
                                }

                                if let Some(ref bar) = progress {
                                    let guard = bar.lock().expect("Progress bar mutex was poisoned");
                                    guard.inc(n as u64);
                                    if let Some(ref cb) = progress_callback {
                                        let pos = guard.position();
                                        let len = guard.length().unwrap_or(1);
                                        drop(guard);
                                        (cb)(pos as f32 / len as f32);
                                    }
                                }
                            }

                            return Ok::<(), Box<dyn Error + Send + Sync>>(());
                        } else if status == reqwest::StatusCode::OK {
                            return Err(format!(
                                "Server ignored range request for chunk {}-{}; refusing to write mismatched data",
                                start, end
                            )
                            .into());
                        } else if status.as_u16() == 416 {
                            if retry == MAX_RETRIES {
                                return Err(format!(
                                    "Failed to download chunk {}-{}: HTTP {}",
                                    start, end, status
                                )
                                .into());
                            }
                            std::thread::sleep(Duration::from_millis(250 * (retry as u64 + 1)));
                        }
                    }
                    Err(e) => {
                        if retry == MAX_RETRIES {
                            return Err(format!(
                                "Failed to download chunk {}-{}: {}",
                                start, end, e
                            )
                            .into());
                        }
                        std::thread::sleep(Duration::from_millis(250 * (retry as u64 + 1)));
                    }
                }
            }
            Err(format!("Failed to download chunk {}-{} after retries", start, end).into())
        })?;

        Ok(())
    }

    fn verify_integrity(&self, expected_size: u64) -> Result<(), Box<dyn Error + Send + Sync>> {
        let metadata = std::fs::metadata(&self.output_path)?;
        let actual_size = metadata.len();

        if actual_size != expected_size {
            return Err(format!(
                "File size mismatch: expected {} bytes, got {} bytes",
                expected_size, actual_size
            )
            .into());
        }

        self.send_status(&format!("File size verified: {} bytes", actual_size));

        // Calculate SHA256 hash for corruption check
        self.send_status("Calculating SHA256 hash...");

        let mut file = File::open(&self.output_path)?;
        let mut hasher = Sha256::new();
        let mut buffer = [0; 8192];
        loop {
            let n = file.read(&mut buffer)?;
            if n == 0 {
                break;
            }
            hasher.update(&buffer[..n]);
        }
        let hash = hasher.finalize();
        let hash_hex = hex::encode(hash);

        self.send_status(&format!("SHA256 hash: {}", hash_hex));
        if let Some(expected_sha256) = &self.expected_sha256 {
            let expected_sha256 = expected_sha256.trim().to_ascii_lowercase();
            if hash_hex != expected_sha256 {
                return Err(format!(
                    "SHA256 mismatch: expected {}, got {}",
                    expected_sha256, hash_hex
                )
                .into());
            }
            self.send_status("SHA256 matches expected hash.");
        }
        self.send_status("Integrity check passed - file is not corrupted");

        Ok(())
    }
}

fn parse_content_range_total(value: &str) -> Option<u64> {
    let (_, total) = value.rsplit_once('/')?;
    if total == "*" {
        return None;
    }
    total.parse::<u64>().ok()
}