shaul-core 1.0.3

Core domain, engine, task store, resume and finalizers for shaul
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
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::Duration;

use directories::{BaseDirs, ProjectDirs};
use serde::{Deserialize, Serialize};

use crate::error::{Error, Result};
use crate::header::{Header, RequestOptions};
use crate::task::{TaskOptions, VerifyMode};

/// Effective configuration. Precedence is CLI flags > config file >
/// environment variables > built-in defaults; see `Config::load`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
#[derive(Default)]
#[non_exhaustive]
pub struct Config {
    /// Download behavior and defaults.
    pub download: DownloadConfig,
    /// HTTP timeout, retry and user-agent settings.
    pub network: NetworkConfig,
    /// Hub provider cache and endpoint settings.
    pub hub: HubConfig,
    /// BitTorrent backend settings.
    pub bt: BtConfig,
    /// Directory for task sidecars; defaults to the platform data directory.
    pub state_dir: Option<PathBuf>,
    /// Default headers applied to every request; values may use `${env:NAME}`
    /// placeholders.
    pub headers: BTreeMap<String, String>,
}

/// Defaults for how files are downloaded, resumed, verified and extracted.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct DownloadConfig {
    /// Default destination directory.
    pub dir: PathBuf,
    /// Default number of parallel connections per task.
    pub connections: usize,
    /// Maximum number of idle connections kept per host in the HTTP pool.
    pub per_host: usize,
    /// Global connection budget. The HTTP backend currently enforces per-task
    /// `connections`; this value is reserved for a scheduler-wide limit.
    pub global: usize,
    /// Size in bytes of each ranged HTTP segment.
    pub segment_size: u64,
    /// Resume interrupted downloads from checkpoints by default.
    pub resume: bool,
    /// Default checksum verification policy.
    pub verify: VerifyMode,
    /// Extract archives after download by default.
    pub extract: bool,
    /// Default extraction directory; `None` extracts under the destination.
    pub extract_dir: Option<PathBuf>,
    /// Delete archives after successful extraction by default.
    pub delete_archive: bool,
}

/// HTTP networking defaults: timeouts, retries, user agent and auth policy.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct NetworkConfig {
    /// Total request timeout in seconds.
    pub timeout_secs: u64,
    /// Connection timeout in seconds.
    pub connect_timeout_secs: u64,
    /// Number of retry attempts for failed transfers.
    pub retries: u32,
    /// `User-Agent` header sent with every request.
    pub user_agent: String,
    /// Allow authentication headers to follow cross-origin redirects.
    pub allow_cross_origin_auth: bool,
}

/// Hugging Face and ModelScope cache and endpoint settings.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
#[derive(Default)]
#[non_exhaustive]
pub struct HubConfig {
    /// Populate a provider cache while downloading. HF uses the Python
    /// compatible `models--org--repo` layout.
    pub use_cache: bool,
    /// Override for the Hugging Face cache root.
    pub hf_cache: Option<PathBuf>,
    /// Override for the ModelScope cache root.
    pub modelscope_cache: Option<PathBuf>,
    /// Override for the Hugging Face endpoint; defaults to the public site.
    pub hf_endpoint: Option<String>,
    /// Override for the ModelScope endpoint; defaults to the public site.
    pub modelscope_endpoint: Option<String>,
}

/// BitTorrent backend settings.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct BtConfig {
    /// Enable DHT peer discovery.
    pub dht: bool,
    /// Use the trackers announced by the torrent.
    pub trackers: bool,
    /// Listen for incoming peer connections.
    pub listen: bool,
    /// Persist session state and fastresume data under the state directory.
    pub persistence: bool,
    /// Optional limit on connected peers.
    pub peer_limit: Option<usize>,
    /// `ip:port` endpoints used directly as initial peers.
    pub initial_peers: Vec<String>,
}

impl Default for BtConfig {
    fn default() -> Self {
        Self {
            dht: true,
            trackers: true,
            listen: true,
            persistence: true,
            peer_limit: None,
            initial_peers: Vec::new(),
        }
    }
}

impl Default for DownloadConfig {
    fn default() -> Self {
        Self {
            dir: PathBuf::from("."),
            connections: 8,
            per_host: 16,
            global: 64,
            segment_size: 8 * 1024 * 1024,
            resume: true,
            verify: VerifyMode::Auto,
            extract: false,
            extract_dir: None,
            delete_archive: false,
        }
    }
}

impl Default for NetworkConfig {
    fn default() -> Self {
        Self {
            timeout_secs: 60,
            connect_timeout_secs: 15,
            retries: 5,
            user_agent: format!("shaul/{}", env!("CARGO_PKG_VERSION")),
            allow_cross_origin_auth: false,
        }
    }
}

/// Options after task overrides and config defaults have been resolved.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct ResolvedOptions {
    /// Root directory for the task's output files.
    pub destination: PathBuf,
    /// Explicit output path, if one was requested.
    pub output: Option<PathBuf>,
    /// Effective connection count for this task.
    pub connections: usize,
    /// Effective HTTP idle-connection limit per host.
    pub per_host: usize,
    /// Global connection budget carried from configuration; currently reserved
    /// for a scheduler-wide limit.
    pub global: usize,
    /// Byte size of each ranged HTTP segment.
    pub segment_size: u64,
    /// Whether resume is enabled for this task.
    pub resume: bool,
    /// Effective checksum verification policy.
    pub verify: VerifyMode,
    /// Expected checksum supplied by the task, if any.
    pub checksum: Option<crate::checksum::Checksum>,
    /// Whether archives should be extracted after download.
    pub extract: bool,
    /// Directory to extract archives into; `None` means the destination.
    pub extract_dir: Option<PathBuf>,
    /// Whether to delete the archive after extraction.
    pub delete_archive: bool,
    /// Whether to populate the provider cache for Hub tasks.
    pub cache: bool,
    /// Include glob filters passed from the task.
    pub include: Vec<String>,
    /// Exclude glob filters passed from the task.
    pub exclude: Vec<String>,
    /// Merged request options: config headers plus task overrides.
    pub request: RequestOptions,
    /// Whether existing destination files are replaced.
    pub overwrite: bool,
    /// Whether conflicting destinations are renamed.
    pub rename_on_conflict: bool,
    /// Effective retry count for failed transfers.
    pub retries: u32,
    /// Effective total request timeout.
    pub timeout: Duration,
    /// Effective connection timeout.
    pub connect_timeout: Duration,
    /// Effective `User-Agent` header.
    pub user_agent: String,
}

impl Config {
    /// Platform default config file path (`config.toml` in the user config
    /// directory).
    pub fn default_config_path() -> Result<PathBuf> {
        let dirs = project_dirs()?;
        Ok(dirs.config_dir().join("config.toml"))
    }

    /// Platform default directory for task sidecars.
    pub fn default_state_dir() -> Result<PathBuf> {
        let dirs = project_dirs()?;
        Ok(dirs.data_dir().join("tasks"))
    }

    /// Configured state directory, or the platform default.
    pub fn state_dir(&self) -> Result<PathBuf> {
        match &self.state_dir {
            Some(dir) => Ok(dir.clone()),
            None => Self::default_state_dir(),
        }
    }

    /// Resolved Hugging Face cache root: configured override or
    /// `~/.cache/huggingface/hub`.
    pub fn hf_cache_dir(&self) -> Result<PathBuf> {
        if let Some(dir) = &self.hub.hf_cache {
            return Ok(dir.clone());
        }
        let base = BaseDirs::new()
            .ok_or_else(|| Error::Config("cannot determine home directory".to_string()))?;
        Ok(base
            .home_dir()
            .join(".cache")
            .join("huggingface")
            .join("hub"))
    }

    /// Resolved ModelScope cache root: configured override or the platform
    /// cache directory.
    pub fn modelscope_cache_dir(&self) -> Result<PathBuf> {
        if let Some(dir) = &self.hub.modelscope_cache {
            return Ok(dir.clone());
        }
        Ok(project_dirs()?.cache_dir().join("modelscope"))
    }

    /// Configured Hugging Face endpoint or the public default.
    pub fn hf_endpoint(&self) -> String {
        self.hub
            .hf_endpoint
            .clone()
            .unwrap_or_else(|| "https://huggingface.co".to_string())
    }

    /// Configured ModelScope endpoint or the public default.
    pub fn modelscope_endpoint(&self) -> String {
        self.hub
            .modelscope_endpoint
            .clone()
            .unwrap_or_else(|| "https://modelscope.cn".to_string())
    }

    /// Resolve the config path from an explicit argument, `SHAUL_CONFIG`, or
    /// the platform default.
    pub fn resolve_path(explicit: Option<&Path>) -> Result<PathBuf> {
        if let Some(path) = explicit {
            return Ok(path.to_path_buf());
        }
        if let Ok(path) = std::env::var("SHAUL_CONFIG")
            && !path.trim().is_empty()
        {
            return Ok(PathBuf::from(path));
        }
        Self::default_config_path()
    }

    /// Load defaults, then environment variables, then the config file. CLI
    /// flags are applied by the caller afterwards.
    pub fn load(explicit: Option<&Path>) -> Result<(Self, PathBuf)> {
        let path = Self::resolve_path(explicit)?;
        let mut config = Self::default();
        config.apply_env()?;
        if path.exists() {
            let text = std::fs::read_to_string(&path)?;
            let partial: PartialConfig = toml::from_str(&text)?;
            partial.apply(&mut config)?;
        }
        Ok((config, path))
    }

    /// Load only defaults + file. Used by `config set` so environment values
    /// are not baked into the file.
    pub fn load_file_only(path: &Path) -> Result<Self> {
        let mut config = Self::default();
        if path.exists() {
            let text = std::fs::read_to_string(path)?;
            let partial: PartialConfig = toml::from_str(&text)?;
            partial.apply(&mut config)?;
        }
        Ok(config)
    }

    /// Serialize the config as TOML, creating parent directories as needed.
    pub fn save(&self, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent()
            && !parent.as_os_str().is_empty()
        {
            std::fs::create_dir_all(parent)?;
        }
        let text = toml::to_string_pretty(self)?;
        std::fs::write(path, text)?;
        Ok(())
    }

    /// Apply `SHAUL_*` and provider environment variables on top of the
    /// current values.
    pub fn apply_env(&mut self) -> Result<()> {
        if let Some(value) = env("SHAUL_DIR") {
            self.download.dir = PathBuf::from(value);
        }
        if let Some(value) = env_parse::<usize>("SHAUL_CONNECTIONS")? {
            self.download.connections = value;
        }
        if let Some(value) = env_parse::<usize>("SHAUL_PER_HOST")? {
            self.download.per_host = value;
        }
        if let Some(value) = env_parse::<usize>("SHAUL_GLOBAL")? {
            self.download.global = value;
        }
        if let Some(value) = env("SHAUL_SEGMENT_SIZE") {
            self.download.segment_size = parse_bytes(&value)?;
        }
        if let Some(value) = env_parse::<bool>("SHAUL_RESUME")? {
            self.download.resume = value;
        }
        if let Some(value) = env("SHAUL_VERIFY") {
            self.download.verify = parse_verify_mode(&value)?;
        }
        if let Some(value) = env_parse::<bool>("SHAUL_EXTRACT")? {
            self.download.extract = value;
        }
        if let Some(value) = env("SHAUL_EXTRACT_DIR") {
            self.download.extract_dir = Some(PathBuf::from(value));
        }
        if let Some(value) = env_parse::<bool>("SHAUL_DELETE_ARCHIVE")? {
            self.download.delete_archive = value;
        }
        if let Some(value) = env("SHAUL_STATE_DIR") {
            self.state_dir = Some(PathBuf::from(value));
        }
        if let Some(value) = env_parse::<u64>("SHAUL_TIMEOUT_SECS")? {
            self.network.timeout_secs = value;
        }
        if let Some(value) = env_parse::<u64>("SHAUL_CONNECT_TIMEOUT_SECS")? {
            self.network.connect_timeout_secs = value;
        }
        if let Some(value) = env_parse::<u32>("SHAUL_RETRIES")? {
            self.network.retries = value;
        }
        if let Some(value) = env("SHAUL_USER_AGENT") {
            self.network.user_agent = value;
        }
        if let Some(value) = env_parse::<bool>("SHAUL_ALLOW_CROSS_ORIGIN_AUTH")? {
            self.network.allow_cross_origin_auth = value;
        }

        if let Some(value) = env("HF_HOME") {
            self.hub.hf_cache = Some(PathBuf::from(value).join("hub"));
        }
        if let Some(value) = env("HF_HUB_CACHE") {
            self.hub.hf_cache = Some(PathBuf::from(value));
        }
        if let Some(value) = env("SHAUL_HF_CACHE") {
            self.hub.hf_cache = Some(PathBuf::from(value));
        }
        if let Some(value) = env("HF_ENDPOINT") {
            self.hub.hf_endpoint = Some(value);
        }
        if let Some(value) = env("SHAUL_HF_ENDPOINT") {
            self.hub.hf_endpoint = Some(value);
        }
        if let Some(value) = env("MODELSCOPE_CACHE") {
            self.hub.modelscope_cache = Some(PathBuf::from(value));
        }
        if let Some(value) = env("SHAUL_MODELSCOPE_CACHE") {
            self.hub.modelscope_cache = Some(PathBuf::from(value));
        }
        if let Some(value) = env("MODELSCOPE_ENDPOINT").or_else(|| env("MODELSCOPE_DOMAIN")) {
            self.hub.modelscope_endpoint = Some(value);
        }
        if let Some(value) = env("SHAUL_MODELSCOPE_ENDPOINT") {
            self.hub.modelscope_endpoint = Some(value);
        }
        if let Some(value) = env_parse::<bool>("SHAUL_HUB_USE_CACHE")? {
            self.hub.use_cache = value;
        }

        if let Some(value) = env_parse::<bool>("SHAUL_BT_DHT")? {
            self.bt.dht = value;
        }
        if let Some(value) = env_parse::<bool>("SHAUL_BT_TRACKERS")? {
            self.bt.trackers = value;
        }
        if let Some(value) = env_parse::<bool>("SHAUL_BT_LISTEN")? {
            self.bt.listen = value;
        }
        if let Some(value) = env_parse::<bool>("SHAUL_BT_PERSISTENCE")? {
            self.bt.persistence = value;
        }
        if let Some(value) = env_parse::<usize>("SHAUL_BT_PEER_LIMIT")? {
            self.bt.peer_limit = Some(value);
        }
        if let Some(value) = env("SHAUL_BT_INITIAL_PEERS") {
            self.bt.initial_peers = value
                .split(',')
                .map(str::trim)
                .filter(|value| !value.is_empty())
                .map(str::to_string)
                .collect();
        }
        Ok(())
    }

    /// Parse the configured default headers into validated [`Header`] values.
    pub fn header_defaults(&self) -> Result<Vec<Header>> {
        self.headers
            .iter()
            .map(|(name, value)| Header::new(name, value))
            .collect()
    }

    /// Combine config defaults with per-task options into fully resolved
    /// settings.
    pub fn resolve(&self, destination: &Path, options: &TaskOptions) -> Result<ResolvedOptions> {
        let mut request = options.request.merged(&self.header_defaults()?);
        request.allow_cross_origin_auth |= self.network.allow_cross_origin_auth;
        Ok(ResolvedOptions {
            destination: destination.to_path_buf(),
            output: options.output.clone(),
            connections: options
                .connections
                .unwrap_or(self.download.connections)
                .max(1),
            per_host: self.download.per_host.max(1),
            global: self.download.global.max(1),
            segment_size: self.download.segment_size.max(64 * 1024),
            resume: options.resume.unwrap_or(self.download.resume),
            verify: options.verify.unwrap_or(self.download.verify),
            checksum: options.checksum.clone(),
            extract: options.extract.unwrap_or(self.download.extract),
            extract_dir: options
                .extract_dir
                .clone()
                .or_else(|| self.download.extract_dir.clone()),
            delete_archive: options
                .delete_archive
                .unwrap_or(self.download.delete_archive),
            cache: options.cache.unwrap_or(self.hub.use_cache),
            include: options.include.clone(),
            exclude: options.exclude.clone(),
            request,
            overwrite: options.overwrite,
            rename_on_conflict: options.rename_on_conflict,
            retries: self.network.retries,
            timeout: Duration::from_secs(self.network.timeout_secs.max(1)),
            connect_timeout: Duration::from_secs(self.network.connect_timeout_secs.max(1)),
            user_agent: self.network.user_agent.clone(),
        })
    }

    /// Read a config value by its dotted key, as used by `config get`.
    pub fn get_value(&self, key: &str) -> Result<String> {
        let value = match key {
            "download.dir" => self.download.dir.display().to_string(),
            "download.connections" => self.download.connections.to_string(),
            "download.per_host" => self.download.per_host.to_string(),
            "download.global" => self.download.global.to_string(),
            "download.segment_size" => self.download.segment_size.to_string(),
            "download.resume" => self.download.resume.to_string(),
            "download.verify" => verify_mode_str(self.download.verify).to_string(),
            "download.extract" => self.download.extract.to_string(),
            "download.extract_dir" => self
                .download
                .extract_dir
                .as_ref()
                .map(|path| path.display().to_string())
                .unwrap_or_default(),
            "download.delete_archive" => self.download.delete_archive.to_string(),
            "network.timeout_secs" => self.network.timeout_secs.to_string(),
            "network.connect_timeout_secs" => self.network.connect_timeout_secs.to_string(),
            "network.retries" => self.network.retries.to_string(),
            "network.user_agent" => self.network.user_agent.clone(),
            "network.allow_cross_origin_auth" => self.network.allow_cross_origin_auth.to_string(),
            "hub.use_cache" => self.hub.use_cache.to_string(),
            "hub.hf_cache" => self.hf_cache_dir()?.display().to_string(),
            "hub.modelscope_cache" => self.modelscope_cache_dir()?.display().to_string(),
            "hub.hf_endpoint" => self.hf_endpoint(),
            "hub.modelscope_endpoint" => self.modelscope_endpoint(),
            "bt.dht" => self.bt.dht.to_string(),
            "bt.trackers" => self.bt.trackers.to_string(),
            "bt.listen" => self.bt.listen.to_string(),
            "bt.persistence" => self.bt.persistence.to_string(),
            "bt.peer_limit" => self
                .bt
                .peer_limit
                .map(|value| value.to_string())
                .unwrap_or_default(),
            "bt.initial_peers" => self.bt.initial_peers.join(","),
            "state_dir" => self
                .state_dir
                .as_ref()
                .map(|path| path.display().to_string())
                .unwrap_or_default(),
            _ if key.starts_with("headers.") => {
                let name = &key["headers.".len()..];
                self.headers.get(name).cloned().unwrap_or_default()
            }
            _ => return Err(Error::Config(format!("unknown config key: {key}"))),
        };
        Ok(value)
    }

    /// Set a config value by its dotted key, as used by `config set`.
    pub fn set_value(&mut self, key: &str, value: &str) -> Result<()> {
        match key {
            "download.dir" => self.download.dir = PathBuf::from(value),
            "download.connections" => self.download.connections = parse_value(value)?,
            "download.per_host" => self.download.per_host = parse_value(value)?,
            "download.global" => self.download.global = parse_value(value)?,
            "download.segment_size" => self.download.segment_size = parse_bytes(value)?,
            "download.resume" => self.download.resume = parse_value(value)?,
            "download.verify" => self.download.verify = parse_verify_mode(value)?,
            "download.extract" => self.download.extract = parse_value(value)?,
            "download.extract_dir" => {
                self.download.extract_dir = if value.trim().is_empty() {
                    None
                } else {
                    Some(PathBuf::from(value))
                }
            }
            "download.delete_archive" => self.download.delete_archive = parse_value(value)?,
            "network.timeout_secs" => self.network.timeout_secs = parse_value(value)?,
            "network.connect_timeout_secs" => {
                self.network.connect_timeout_secs = parse_value(value)?
            }
            "network.retries" => self.network.retries = parse_value(value)?,
            "network.user_agent" => self.network.user_agent = value.to_string(),
            "network.allow_cross_origin_auth" => {
                self.network.allow_cross_origin_auth = parse_value(value)?
            }
            "hub.use_cache" => self.hub.use_cache = parse_value(value)?,
            "hub.hf_cache" => {
                self.hub.hf_cache = if value.trim().is_empty() {
                    None
                } else {
                    Some(PathBuf::from(value))
                }
            }
            "hub.modelscope_cache" => {
                self.hub.modelscope_cache = if value.trim().is_empty() {
                    None
                } else {
                    Some(PathBuf::from(value))
                }
            }
            "hub.hf_endpoint" => {
                self.hub.hf_endpoint = if value.trim().is_empty() {
                    None
                } else {
                    Some(value.to_string())
                }
            }
            "hub.modelscope_endpoint" => {
                self.hub.modelscope_endpoint = if value.trim().is_empty() {
                    None
                } else {
                    Some(value.to_string())
                }
            }
            "bt.dht" => self.bt.dht = parse_value(value)?,
            "bt.trackers" => self.bt.trackers = parse_value(value)?,
            "bt.listen" => self.bt.listen = parse_value(value)?,
            "bt.persistence" => self.bt.persistence = parse_value(value)?,
            "bt.peer_limit" => {
                self.bt.peer_limit = if value.trim().is_empty() {
                    None
                } else {
                    Some(parse_value(value)?)
                }
            }
            "bt.initial_peers" => {
                self.bt.initial_peers = value
                    .split(',')
                    .map(str::trim)
                    .filter(|value| !value.is_empty())
                    .map(str::to_string)
                    .collect();
            }
            "state_dir" => {
                self.state_dir = if value.trim().is_empty() {
                    None
                } else {
                    Some(PathBuf::from(value))
                }
            }
            _ if key.starts_with("headers.") => {
                let name = key["headers.".len()..].to_string();
                Header::new(&name, value)?;
                if value.trim().is_empty() {
                    self.headers.remove(&name);
                } else {
                    self.headers.insert(name, value.to_string());
                }
            }
            _ => return Err(Error::Config(format!("unknown config key: {key}"))),
        }
        Ok(())
    }
}

fn project_dirs() -> Result<ProjectDirs> {
    ProjectDirs::from("", "", "shaul")
        .ok_or_else(|| Error::Config("cannot determine platform config directory".to_string()))
}

fn env(name: &str) -> Option<String> {
    std::env::var(name)
        .ok()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
}

fn env_parse<T: FromStr>(name: &str) -> Result<Option<T>> {
    match env(name) {
        Some(value) => value
            .parse::<T>()
            .map(Some)
            .map_err(|_| Error::Config(format!("invalid value for {name}: {value}"))),
        None => Ok(None),
    }
}

fn parse_value<T: FromStr>(value: &str) -> Result<T> {
    value
        .parse::<T>()
        .map_err(|_| Error::Config(format!("invalid value: {value}")))
}

/// Parse a verify mode name or one of its boolean-like aliases.
pub fn parse_verify_mode(value: &str) -> Result<VerifyMode> {
    match value.trim().to_ascii_lowercase().as_str() {
        "auto" => Ok(VerifyMode::Auto),
        "require" | "on" | "true" | "yes" | "1" => Ok(VerifyMode::Require),
        "disabled" | "off" | "false" | "no" | "0" | "none" => Ok(VerifyMode::Disabled),
        _ => Err(Error::Config(format!("invalid verify mode: {value}"))),
    }
}

/// Canonical string form of a verify mode.
pub fn verify_mode_str(mode: VerifyMode) -> &'static str {
    match mode {
        VerifyMode::Auto => "auto",
        VerifyMode::Require => "require",
        VerifyMode::Disabled => "disabled",
    }
}

/// Parse byte sizes such as `8MiB`, `256K`, `1G` or a plain byte count.
pub fn parse_bytes(value: &str) -> Result<u64> {
    let value = value.trim();
    let lower = value.to_ascii_lowercase();
    let (number, multiplier) = if let Some(number) = lower.strip_suffix("kib") {
        (number, 1024)
    } else if let Some(number) = lower.strip_suffix("mib") {
        (number, 1024 * 1024)
    } else if let Some(number) = lower.strip_suffix("gib") {
        (number, 1024 * 1024 * 1024)
    } else if let Some(number) = lower.strip_suffix("kb") {
        (number, 1000)
    } else if let Some(number) = lower.strip_suffix("mb") {
        (number, 1000 * 1000)
    } else if let Some(number) = lower.strip_suffix("gb") {
        (number, 1000 * 1000 * 1000)
    } else if let Some(number) = lower.strip_suffix('k') {
        (number, 1024)
    } else if let Some(number) = lower.strip_suffix('m') {
        (number, 1024 * 1024)
    } else if let Some(number) = lower.strip_suffix('g') {
        (number, 1024 * 1024 * 1024)
    } else {
        (lower.as_str(), 1)
    };
    let number = number.trim();
    let parsed = number
        .parse::<f64>()
        .map_err(|_| Error::Config(format!("invalid byte size: {value}")))?;
    if !parsed.is_finite() || parsed < 0.0 {
        return Err(Error::Config(format!("invalid byte size: {value}")));
    }
    Ok((parsed * multiplier as f64) as u64)
}

#[derive(Debug, Default, Deserialize)]
struct PartialConfig {
    #[serde(default)]
    download: Option<PartialDownload>,
    #[serde(default)]
    network: Option<PartialNetwork>,
    #[serde(default)]
    hub: Option<PartialHub>,
    #[serde(default)]
    bt: Option<PartialBt>,
    #[serde(default)]
    state_dir: Option<PathBuf>,
    #[serde(default)]
    headers: Option<BTreeMap<String, String>>,
}

#[derive(Debug, Default, Deserialize)]
struct PartialDownload {
    #[serde(default)]
    dir: Option<PathBuf>,
    #[serde(default)]
    connections: Option<usize>,
    #[serde(default)]
    per_host: Option<usize>,
    #[serde(default)]
    global: Option<usize>,
    #[serde(default)]
    segment_size: Option<u64>,
    #[serde(default)]
    resume: Option<bool>,
    #[serde(default)]
    verify: Option<VerifyMode>,
    #[serde(default)]
    extract: Option<bool>,
    #[serde(default)]
    extract_dir: Option<PathBuf>,
    #[serde(default)]
    delete_archive: Option<bool>,
}

#[derive(Debug, Default, Deserialize)]
struct PartialNetwork {
    #[serde(default)]
    timeout_secs: Option<u64>,
    #[serde(default)]
    connect_timeout_secs: Option<u64>,
    #[serde(default)]
    retries: Option<u32>,
    #[serde(default)]
    user_agent: Option<String>,
    #[serde(default)]
    allow_cross_origin_auth: Option<bool>,
}

#[derive(Debug, Default, Deserialize)]
struct PartialHub {
    #[serde(default)]
    use_cache: Option<bool>,
    #[serde(default)]
    hf_cache: Option<PathBuf>,
    #[serde(default)]
    modelscope_cache: Option<PathBuf>,
    #[serde(default)]
    hf_endpoint: Option<String>,
    #[serde(default)]
    modelscope_endpoint: Option<String>,
}

#[derive(Debug, Default, Deserialize)]
struct PartialBt {
    #[serde(default)]
    dht: Option<bool>,
    #[serde(default)]
    trackers: Option<bool>,
    #[serde(default)]
    listen: Option<bool>,
    #[serde(default)]
    persistence: Option<bool>,
    #[serde(default)]
    peer_limit: Option<usize>,
    #[serde(default)]
    initial_peers: Option<Vec<String>>,
}

impl PartialConfig {
    fn apply(self, config: &mut Config) -> Result<()> {
        if let Some(download) = self.download {
            if let Some(value) = download.dir {
                config.download.dir = value;
            }
            if let Some(value) = download.connections {
                config.download.connections = value;
            }
            if let Some(value) = download.per_host {
                config.download.per_host = value;
            }
            if let Some(value) = download.global {
                config.download.global = value;
            }
            if let Some(value) = download.segment_size {
                config.download.segment_size = value;
            }
            if let Some(value) = download.resume {
                config.download.resume = value;
            }
            if let Some(value) = download.verify {
                config.download.verify = value;
            }
            if let Some(value) = download.extract {
                config.download.extract = value;
            }
            if let Some(value) = download.extract_dir {
                config.download.extract_dir = Some(value);
            }
            if let Some(value) = download.delete_archive {
                config.download.delete_archive = value;
            }
        }
        if let Some(network) = self.network {
            if let Some(value) = network.timeout_secs {
                config.network.timeout_secs = value;
            }
            if let Some(value) = network.connect_timeout_secs {
                config.network.connect_timeout_secs = value;
            }
            if let Some(value) = network.retries {
                config.network.retries = value;
            }
            if let Some(value) = network.user_agent {
                config.network.user_agent = value;
            }
            if let Some(value) = network.allow_cross_origin_auth {
                config.network.allow_cross_origin_auth = value;
            }
        }
        if let Some(hub) = self.hub {
            if let Some(value) = hub.use_cache {
                config.hub.use_cache = value;
            }
            if let Some(value) = hub.hf_cache {
                config.hub.hf_cache = Some(value);
            }
            if let Some(value) = hub.modelscope_cache {
                config.hub.modelscope_cache = Some(value);
            }
            if let Some(value) = hub.hf_endpoint {
                config.hub.hf_endpoint = Some(value);
            }
            if let Some(value) = hub.modelscope_endpoint {
                config.hub.modelscope_endpoint = Some(value);
            }
        }
        if let Some(bt) = self.bt {
            if let Some(value) = bt.dht {
                config.bt.dht = value;
            }
            if let Some(value) = bt.trackers {
                config.bt.trackers = value;
            }
            if let Some(value) = bt.listen {
                config.bt.listen = value;
            }
            if let Some(value) = bt.persistence {
                config.bt.persistence = value;
            }
            if let Some(value) = bt.peer_limit {
                config.bt.peer_limit = Some(value);
            }
            if let Some(value) = bt.initial_peers {
                config.bt.initial_peers = value;
            }
        }
        if let Some(value) = self.state_dir {
            config.state_dir = Some(value);
        }
        if let Some(headers) = self.headers {
            for (name, value) in headers {
                Header::new(&name, &value)?;
                config.headers.insert(name, value);
            }
        }
        Ok(())
    }
}

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

    #[test]
    fn file_overrides_environment_layer() {
        let mut config = Config::default();
        config.download.connections = 3; // pretend env set this
        let partial: PartialConfig = toml::from_str("[download]\nconnections = 11\n").unwrap();
        partial.apply(&mut config).unwrap();
        assert_eq!(config.download.connections, 11);
    }

    #[test]
    fn parses_byte_sizes() {
        assert_eq!(parse_bytes("8MiB").unwrap(), 8 * 1024 * 1024);
        assert_eq!(parse_bytes("1.5G").unwrap(), 1_610_612_736);
    }

    #[test]
    fn gets_and_sets_values() {
        let mut config = Config::default();
        config.set_value("download.connections", "12").unwrap();
        assert_eq!(config.get_value("download.connections").unwrap(), "12");
        config.set_value("headers.X-Test", "yes").unwrap();
        assert_eq!(config.get_value("headers.X-Test").unwrap(), "yes");
    }
}