mocopr-core 0.1.0

Core types and protocol implementation for MoCoPr (Model Context Protocol)
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
//! Utility functions and helpers

use crate::Result;
use serde::{Serialize, de::DeserializeOwned};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

/// Utility functions for MCP implementation
pub struct Utils;

impl Utils {
    /// Convert a serializable object to a JSON value.
    ///
    /// This utility method converts any Rust type that implements the `Serialize` trait
    /// into a `serde_json::Value` representation, which is useful for generic JSON handling.
    ///
    /// # Arguments
    ///
    /// * `value` - The value to convert to JSON
    ///
    /// # Returns
    ///
    /// A `Result` containing either the JSON value or an error if serialization fails
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    /// use serde::Serialize;
    ///
    /// #[derive(Serialize)]
    /// struct Person {
    ///     name: String,
    ///     age: u32,
    /// }
    ///
    /// let person = Person {
    ///     name: "Alice".to_string(),
    ///     age: 30,
    /// };
    ///
    /// let json_value = Utils::to_json_value(&person).unwrap();
    /// assert_eq!(json_value["name"], "Alice");
    /// assert_eq!(json_value["age"], 30);
    /// ```
    pub fn to_json_value<T: Serialize>(value: &T) -> Result<serde_json::Value> {
        serde_json::to_value(value).map_err(Into::into)
    }

    /// Convert a JSON value to a deserializable object.
    ///
    /// This utility method converts a `serde_json::Value` into any Rust type that
    /// implements the `DeserializeOwned` trait.
    ///
    /// # Arguments
    ///
    /// * `value` - The JSON value to convert
    ///
    /// # Returns
    ///
    /// A `Result` containing either the deserialized object or an error if deserialization fails
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    /// use serde::{Serialize, Deserialize};
    /// use serde_json::json;
    ///
    /// #[derive(Serialize, Deserialize, PartialEq, Debug)]
    /// struct Person {
    ///     name: String,
    ///     age: u32,
    /// }
    ///
    /// let json_value = json!({
    ///     "name": "Bob",
    ///     "age": 42
    /// });
    ///
    /// let person: Person = Utils::from_json_value(json_value).unwrap();
    /// assert_eq!(person.name, "Bob");
    /// assert_eq!(person.age, 42);
    /// ```
    pub fn from_json_value<T: DeserializeOwned>(value: serde_json::Value) -> Result<T> {
        serde_json::from_value(value).map_err(Into::into)
    }

    /// Get current timestamp as seconds since Unix epoch.
    ///
    /// This utility method provides a consistent way to get the current time
    /// as a Unix timestamp (seconds since January 1, 1970 UTC).
    ///
    /// # Returns
    ///
    /// The number of seconds since the Unix epoch
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    ///
    /// let timestamp = Utils::current_timestamp();
    /// println!("Current timestamp: {}", timestamp);
    /// ```
    pub fn current_timestamp() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs()
    }

    /// Get current timestamp as milliseconds since Unix epoch.
    ///
    /// This utility method provides a consistent way to get the current time
    /// as a Unix timestamp in milliseconds (thousandths of a second since
    /// January 1, 1970 UTC).
    ///
    /// # Returns
    ///
    /// The number of milliseconds since the Unix epoch
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    ///
    /// let timestamp_millis = Utils::current_timestamp_millis();
    /// println!("Current timestamp (millis): {}", timestamp_millis);
    /// ```
    pub fn current_timestamp_millis() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64
    }

    /// Validate URI format.
    ///
    /// This utility method checks if a given string is a well-formed URI.
    ///
    /// # Arguments
    ///
    /// * `uri` - The URI string to validate
    ///
    /// # Returns
    ///
    /// `true` if the URI is valid, `false` otherwise
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    ///
    /// assert!(Utils::validate_uri("https://www.example.com"));
    /// assert!(!Utils::validate_uri("invalid_uri"));
    /// ```
    pub fn validate_uri(uri: &str) -> bool {
        url::Url::parse(uri).is_ok()
    }

    /// Normalize URI by removing trailing slashes and fragments.
    ///
    /// This utility method converts a URI into a canonical form by removing
    /// unnecessary parts like trailing slashes and fragment identifiers.
    ///
    /// # Arguments
    ///
    /// * `uri` - The URI string to normalize
    ///
    /// # Returns
    ///
    /// A normalized URI string
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    ///
    /// let uri = "https://www.example.com/some/path/";
    /// let normalized = Utils::normalize_uri(uri).unwrap();
    /// assert_eq!(normalized, "https://www.example.com/some/path");
    ///
    /// let uri = "https://www.example.com/resource#section1";
    /// let normalized = Utils::normalize_uri(uri).unwrap();
    /// assert_eq!(normalized, "https://www.example.com/resource");
    /// ```
    pub fn normalize_uri(uri: &str) -> Result<String> {
        let mut url = url::Url::parse(uri)?;
        url.set_fragment(None);
        let mut normalized = url.to_string();
        if normalized.ends_with('/') && normalized.len() > 1 {
            normalized.pop();
        }
        Ok(normalized)
    }

    /// Check if a string is a valid JSON.
    ///
    /// This utility method attempts to parse a string as JSON and returns
    /// `true` if successful, `false` otherwise.
    ///
    /// # Arguments
    ///
    /// * `s` - The string to check
    ///
    /// # Returns
    ///
    /// `true` if the string is valid JSON, `false` otherwise
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    ///
    /// assert!(Utils::is_valid_json("{\"key\": \"value\"}"));
    /// assert!(!Utils::is_valid_json("invalid_json"));
    /// ```
    pub fn is_valid_json(s: &str) -> bool {
        serde_json::from_str::<serde_json::Value>(s).is_ok()
    }

    /// Pretty print JSON.
    ///
    /// This utility method converts a serializable object into a nicely formatted
    /// JSON string, with indentation and line breaks for readability.
    ///
    /// # Arguments
    ///
    /// * `value` - The value to convert to a pretty-printed JSON string
    ///
    /// # Returns
    ///
    /// A `Result` containing either the pretty-printed JSON string or an error if serialization fails
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    /// use serde::Serialize;
    ///
    /// #[derive(Serialize)]
    /// struct Person {
    ///     name: String,
    ///     age: u32,
    /// }
    ///
    /// let person = Person {
    ///     name: "Alice".to_string(),
    ///     age: 30,
    /// };
    ///
    /// let pretty_json = Utils::pretty_json(&person).unwrap();
    /// println!("{}", pretty_json);
    /// ```
    pub fn pretty_json<T: Serialize>(value: &T) -> Result<String> {
        serde_json::to_string_pretty(value).map_err(Into::into)
    }

    /// Compact JSON string.
    ///
    /// This utility method converts a serializable object into a compact JSON string,
    /// with all unnecessary whitespace removed.
    ///
    /// # Arguments
    ///
    /// * `value` - The value to convert to a compact JSON string
    ///
    /// # Returns
    ///
    /// A `Result` containing either the compact JSON string or an error if serialization fails
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    /// use serde::Serialize;
    ///
    /// #[derive(Serialize)]
    /// struct Person {
    ///     name: String,
    ///     age: u32,
    /// }
    ///
    /// let person = Person {
    ///     name: "Alice".to_string(),
    ///     age: 30,
    /// };
    ///
    /// let compact_json = Utils::compact_json(&person).unwrap();
    /// assert_eq!(compact_json, "{\"name\":\"Alice\",\"age\":30}");
    /// ```
    pub fn compact_json<T: Serialize>(value: &T) -> Result<String> {
        serde_json::to_string(value).map_err(Into::into)
    }

    /// Escape string for JSON.
    ///
    /// This utility method escapes special characters in a string to make it safe
    /// for inclusion in a JSON document.
    ///
    /// # Arguments
    ///
    /// * `s` - The string to escape
    ///
    /// # Returns
    ///
    /// An escaped string
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    ///
    /// let original = "This is a \"test\" string with a newline\n and a tab\t.";
    /// let escaped = Utils::escape_json_string(original);
    /// assert_eq!(escaped, "This is a \\\"test\\\" string with a newline\\n and a tab\\t.");
    /// ```
    pub fn escape_json_string(s: &str) -> String {
        s.chars()
            .map(|c| match c {
                '"' => "\\\"".to_string(),
                '\\' => "\\\\".to_string(),
                '\n' => "\\n".to_string(),
                '\r' => "\\r".to_string(),
                '\t' => "\\t".to_string(),
                c if c.is_control() => format!("\\u{:04x}", c as u32),
                c => c.to_string(),
            })
            .collect()
    }

    /// Generate a random string.
    ///
    /// This utility method creates a random string of the specified length using
    /// URL-safe base64 encoding.
    ///
    /// # Arguments
    ///
    /// * `length` - The length of the string to generate
    ///
    /// # Returns
    ///
    /// A random string
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    ///
    /// let random_str = Utils::random_string(10);
    /// println!("Random string: {}", random_str);
    /// ```
    pub fn random_string(length: usize) -> String {
        use uuid::Uuid;
        let uuid = Uuid::new_v4().to_string();
        let clean = uuid.replace('-', "");
        if length >= clean.len() {
            clean
        } else {
            clean[..length].to_string()
        }
    }

    /// Format bytes in a human-readable format.
    ///
    /// This utility method converts a byte count into a human-readable string
    /// representation, using appropriate units (B, KB, MB, GB, TB).
    ///
    /// # Arguments
    ///
    /// * `bytes` - The number of bytes to format
    ///
    /// # Returns
    ///
    /// A human-readable string representing the byte count
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    ///
    /// assert_eq!(Utils::format_bytes(1024), "1.00 KB");
    /// assert_eq!(Utils::format_bytes(1536), "1.50 KB");
    /// assert_eq!(Utils::format_bytes(1048576), "1.00 MB");
    /// ```
    pub fn format_bytes(bytes: u64) -> String {
        const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
        const THRESHOLD: f64 = 1024.0;

        if bytes == 0 {
            return "0 B".to_string();
        }

        let mut size = bytes as f64;
        let mut unit_index = 0;

        while size >= THRESHOLD && unit_index < UNITS.len() - 1 {
            size /= THRESHOLD;
            unit_index += 1;
        }

        if unit_index == 0 {
            format!("{} {}", bytes, UNITS[unit_index])
        } else {
            format!("{:.2} {}", size, UNITS[unit_index])
        }
    }

    /// Format duration in human readable format.
    ///
    /// This utility method converts a `Duration` value into a human-readable string,
    /// showing the elapsed time in hours, minutes, seconds, and milliseconds.
    ///
    /// # Arguments
    ///
    /// * `duration` - The duration to format
    ///
    /// # Returns
    ///
    /// A human-readable string representing the duration
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    ///
    /// let duration = std::time::Duration::new(3661, 500_000_000);
    /// let formatted = Utils::format_duration(duration);
    /// assert_eq!(formatted, "1h 1m 1s");
    /// ```
    pub fn format_duration(duration: std::time::Duration) -> String {
        let total_seconds = duration.as_secs();
        let hours = total_seconds / 3600;
        let minutes = (total_seconds % 3600) / 60;
        let seconds = total_seconds % 60;
        let millis = duration.subsec_millis();

        if hours > 0 {
            format!("{hours}h {minutes}m {seconds}s")
        } else if minutes > 0 {
            format!("{minutes}m {seconds}s")
        } else if seconds > 0 {
            format!("{seconds}.{millis:03}s")
        } else {
            format!("{millis}ms")
        }
    }

    /// Merge two JSON values recursively.
    ///
    /// This utility method merges the contents of one JSON value into another,
    /// recursively combining objects and replacing values as necessary.
    ///
    /// # Arguments
    ///
    /// * `a` - The target JSON value to merge into
    /// * `b` - The source JSON value to merge from
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    ///
    /// let mut a = serde_json::json!({"key1": "value1", "key2": "value2"});
    /// let b = serde_json::json!({"key2": "new_value2", "key3": "value3"});
    ///
    /// Utils::merge_json(&mut a, b);
    ///
    /// assert_eq!(a["key1"], "value1");
    /// assert_eq!(a["key2"], "new_value2");
    /// assert_eq!(a["key3"], "value3");
    /// ```
    pub fn merge_json(a: &mut serde_json::Value, b: serde_json::Value) {
        match (a, b) {
            (serde_json::Value::Object(a), serde_json::Value::Object(b)) => {
                for (k, v) in b {
                    Self::merge_json(a.entry(k).or_insert(serde_json::Value::Null), v);
                }
            }
            (a, b) => *a = b,
        }
    }

    /// Sanitize a file path to prevent directory traversal attacks.
    ///
    /// This function removes ".." components and ensures the path doesn't
    /// escape from a base directory when resolved.
    ///
    /// # Security
    ///
    /// This is a critical security function that should be used whenever
    /// accepting file paths from external sources.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    ///
    /// let safe_path = Utils::sanitize_path("../../../etc/passwd");
    /// assert!(!safe_path.to_string_lossy().contains(".."));
    /// ```
    pub fn sanitize_path<P: AsRef<Path>>(path: P) -> PathBuf {
        let path = path.as_ref();
        let mut components = Vec::new();

        for component in path.components() {
            match component {
                std::path::Component::Prefix(_) => {
                    // On Windows, preserve drive prefixes
                    components.push(component);
                }
                std::path::Component::RootDir => {
                    // Preserve root directory
                    components.push(component);
                }
                std::path::Component::CurDir => {
                    // Skip current directory references
                    continue;
                }
                std::path::Component::ParentDir => {
                    // Remove parent directory references to prevent traversal
                    if let Some(last) = components.last()
                        && !matches!(
                            last,
                            std::path::Component::RootDir | std::path::Component::Prefix(_)
                        )
                    {
                        components.pop();
                    }
                }
                std::path::Component::Normal(_name) => {
                    // Keep normal components
                    components.push(component);
                }
            }
        }

        components.iter().collect()
    }

    /// Validate that a URI scheme is allowed.
    ///
    /// Validates that a URI scheme is in the list of allowed schemes.
    ///
    /// This is an important security check to prevent URI-based attacks and
    /// ensure that resources only use approved protocols.
    ///
    /// # Arguments
    ///
    /// * `uri` - The URI to validate
    /// * `allowed_schemes` - List of schemes that are allowed (e.g., `["file", "http", "https"]`)
    ///
    /// # Returns
    ///
    /// `Ok(())` if the scheme is allowed, or an `Error` if not
    ///
    /// # Security
    ///
    /// This method helps prevent protocol-based injection attacks by restricting
    /// URIs to a known set of safe schemes. Always use this validation when
    /// accepting URIs from external sources.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    /// use url::Url;
    ///
    /// let url = Url::parse("https://example.com").unwrap();
    /// assert!(Utils::validate_uri_scheme(&url, &["http", "https"]).is_ok());
    ///
    /// let url = Url::parse("javascript:alert()").unwrap();
    /// assert!(Utils::validate_uri_scheme(&url, &["file", "http", "https"]).is_err());
    /// ```
    pub fn validate_uri_scheme(uri: &url::Url, allowed_schemes: &[&str]) -> Result<()> {
        if allowed_schemes.contains(&uri.scheme()) {
            Ok(())
        } else {
            Err(crate::Error::security(format!(
                "URI scheme '{}' is not allowed. Allowed schemes: {:?}",
                uri.scheme(),
                allowed_schemes
            )))
        }
    }

    /// Validate that a string doesn't contain dangerous characters.
    ///
    /// # Security
    ///
    /// This helps prevent injection attacks by validating input strings.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    ///
    /// assert!(Utils::validate_safe_string("normal_text-123").is_ok());
    /// assert!(Utils::validate_safe_string("text\x00with\x01control").is_err());
    /// ```
    pub fn validate_safe_string(input: &str) -> Result<()> {
        // Check for control characters (except whitespace)
        for ch in input.chars() {
            if ch.is_control() && !ch.is_whitespace() {
                return Err(crate::Error::validation(format!(
                    "String contains unsafe control character: {:?}",
                    ch
                )));
            }
        }

        // Check for null bytes
        if input.contains('\0') {
            return Err(crate::Error::validation(
                "String contains null byte".to_string(),
            ));
        }

        Ok(())
    }

    /// Validate that a file size is within reasonable limits.
    ///
    /// # Security
    ///
    /// This prevents denial of service attacks through extremely large files.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use mocopr_core::utils::Utils;
    ///
    /// assert!(Utils::validate_file_size(1024, 1024 * 1024).is_ok()); // 1KB file, 1MB limit
    /// assert!(Utils::validate_file_size(1024 * 1024 * 10, 1024 * 1024).is_err()); // 10MB file, 1MB limit
    /// ```
    pub fn validate_file_size(size: u64, max_size: u64) -> Result<()> {
        if size > max_size {
            Err(crate::Error::validation(format!(
                "File size {} exceeds maximum allowed size {}",
                Self::format_bytes(size),
                Self::format_bytes(max_size)
            )))
        } else {
            Ok(())
        }
    }

    /// Rate limiting check (simple token bucket implementation).
    ///
    /// # Security
    ///
    /// This helps prevent abuse by limiting the rate of operations.
    ///
    /// Note: This is a simple implementation. For production use,
    /// consider using a proper rate limiting library.
    pub fn check_rate_limit(
        last_request: &mut Option<SystemTime>,
        min_interval_ms: u64,
    ) -> Result<()> {
        let now = SystemTime::now();

        if let Some(last) = last_request {
            let elapsed = now
                .duration_since(*last)
                .unwrap_or(std::time::Duration::from_secs(0));

            let min_interval = std::time::Duration::from_millis(min_interval_ms);

            if elapsed < min_interval {
                return Err(crate::Error::validation(format!(
                    "Rate limit exceeded. Please wait {} before making another request.",
                    Self::format_duration(min_interval - elapsed)
                )));
            }
        }

        *last_request = Some(now);
        Ok(())
    }
}

/// Progress tracking utility
#[derive(Debug, Clone)]
pub struct ProgressTracker {
    /// Current progress value
    pub current: f64,
    /// Total progress value
    pub total: f64,
    /// Start time of the progress tracking
    pub start_time: std::time::Instant,
}

impl ProgressTracker {
    /// Creates a new progress tracker
    ///
    /// # Arguments
    /// * `total` - Total progress value
    pub fn new(total: f64) -> Self {
        Self {
            current: 0.0,
            total,
            start_time: std::time::Instant::now(),
        }
    }

    /// Updates the current progress
    ///
    /// # Arguments
    /// * `current` - New current progress value
    pub fn update(&mut self, current: f64) {
        self.current = current.min(self.total);
    }

    /// Increments the current progress
    ///
    /// # Arguments
    /// * `amount` - Amount to increment by
    pub fn increment(&mut self, amount: f64) {
        self.current = (self.current + amount).min(self.total);
    }

    /// Gets the progress percentage
    ///
    /// # Returns
    /// Progress percentage (0.0 to 100.0)
    pub fn percentage(&self) -> f64 {
        if self.total == 0.0 {
            0.0
        } else {
            (self.current / self.total * 100.0).min(100.0)
        }
    }

    /// Checks if progress is complete
    ///
    /// # Returns
    /// True if progress is complete
    pub fn is_complete(&self) -> bool {
        self.current >= self.total
    }

    /// Gets the elapsed time since start
    ///
    /// # Returns
    /// Elapsed duration
    pub fn elapsed(&self) -> std::time::Duration {
        self.start_time.elapsed()
    }

    /// Estimates remaining time
    ///
    /// # Returns
    /// Estimated remaining duration, or None if cannot estimate
    pub fn estimated_remaining(&self) -> Option<std::time::Duration> {
        if self.current == 0.0 || self.is_complete() {
            return None;
        }

        let elapsed = self.elapsed();
        let rate = self.current / elapsed.as_secs_f64();
        let remaining = (self.total - self.current) / rate;

        Some(std::time::Duration::from_secs_f64(remaining))
    }
}

/// Rate limiter utility
#[derive(Debug)]
pub struct RateLimiter {
    max_requests: u32,
    window_duration: std::time::Duration,
    requests: std::collections::VecDeque<std::time::Instant>,
}

impl RateLimiter {
    /// Creates a new rate limiter
    ///
    /// # Arguments
    /// * `max_requests` - Maximum number of requests allowed
    /// * `window_duration` - Time window for rate limiting
    pub fn new(max_requests: u32, window_duration: std::time::Duration) -> Self {
        Self {
            max_requests,
            window_duration,
            requests: std::collections::VecDeque::new(),
        }
    }

    /// Checks if a request can be made within rate limits
    ///
    /// # Returns
    /// True if request is allowed, false if rate limited
    pub fn check_rate_limit(&mut self) -> bool {
        let now = std::time::Instant::now();
        let cutoff = now - self.window_duration;

        // Remove old requests
        while let Some(&front) = self.requests.front() {
            if front < cutoff {
                self.requests.pop_front();
            } else {
                break;
            }
        }

        // Check if we can make another request
        if self.requests.len() < self.max_requests as usize {
            self.requests.push_back(now);
            true
        } else {
            false
        }
    }

    /// Gets the number of remaining requests
    ///
    /// # Returns
    /// Number of remaining requests within the current window
    pub fn remaining(&self) -> u32 {
        self.max_requests.saturating_sub(self.requests.len() as u32)
    }

    /// Gets the time when the rate limit will reset
    ///
    /// # Returns
    /// Instant when rate limit resets, or None if no requests made
    pub fn reset_time(&self) -> Option<std::time::Instant> {
        self.requests
            .front()
            .map(|&first| first + self.window_duration)
    }
}