scirs2-core 0.4.2

Core utilities and common functionality for SciRS2 (scirs2-core)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
//! Cloud Storage Integration for SciRS2
//!
//! This module provides seamless integration with major cloud storage providers
//! including Amazon S3, Google Cloud Storage, and Azure Blob Storage.
//!
//! Features:
//! - Unified interface for all cloud providers
//! - Asynchronous operations for high performance
//! - Automatic credential management
//! - Retry logic and error handling
//! - Progress tracking for large transfers
//! - Multi-part upload/download support
//! - Intelligent caching and prefetching

use crate::error::{CoreError, ErrorContext, ErrorLocation};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};
use thiserror::Error;

#[cfg(feature = "async")]
#[allow(unused_imports)]
use tokio::io::{AsyncRead, AsyncWrite};

#[cfg(feature = "async")]
use async_trait::async_trait;

// AWS environment variable constants
const AWS_ACCESS_KEY_ID: &str = "AWS_ACCESS_KEY_ID";
const AWS_SECRET_ACCESS_KEY: &str = "AWS_SECRET_ACCESS_KEY";
const AWS_SESSION_TOKEN: &str = "AWS_SESSION_TOKEN";
const AWS_REGION: &str = "AWS_REGION";

// Google Cloud environment variable constants
const GOOGLE_APPLICATION_CREDENTIALS: &str = "GOOGLE_APPLICATION_CREDENTIALS";
const GOOGLE_CLOUD_PROJECT: &str = "GOOGLE_CLOUD_PROJECT";

// Azure environment variable constants
const AZURE_STORAGE_ACCOUNT: &str = "AZURE_STORAGE_ACCOUNT";
const AZURE_STORAGE_KEY: &str = "AZURE_STORAGE_KEY";
const AZURE_STORAGE_SAS_TOKEN: &str = "AZURE_STORAGE_SAS_TOKEN";

/// Cloud storage error types
#[derive(Error, Debug)]
pub enum CloudError {
    /// Authentication failed
    #[error("Authentication failed: {0}")]
    AuthenticationError(String),

    /// Bucket or container not found
    #[error("Bucket/container not found: {0}")]
    BucketNotFound(String),

    /// Object not found
    #[error("Object not found: {0}")]
    ObjectNotFound(String),

    /// Permission denied
    #[error("Permission denied: {0}")]
    PermissionDenied(String),

    /// Network connection error
    #[error("Network error: {0}")]
    NetworkError(String),

    /// Service quota exceeded
    #[error("Service quota exceeded: {0}")]
    QuotaExceeded(String),

    /// Invalid configuration
    #[error("Invalid configuration: {0}")]
    InvalidConfiguration(String),

    /// Upload failed
    #[error("Upload failed: {0}")]
    UploadError(String),

    /// Download failed
    #[error("Download failed: {0}")]
    DownloadError(String),

    /// Multipart operation failed
    #[error("Multipart operation failed: {0}")]
    MultipartError(String),

    /// Metadata operation failed
    #[error("Metadata operation failed: {0}")]
    MetadataError(String),

    /// Generic cloud provider error
    #[error("Cloud provider error: {provider} - {message}")]
    ProviderError { provider: String, message: String },
}

impl From<CloudError> for CoreError {
    fn from(err: CloudError) -> Self {
        match err {
            CloudError::AuthenticationError(msg) => CoreError::SecurityError(
                ErrorContext::new(format!("{msg}"))
                    .with_location(ErrorLocation::new(file!(), line!())),
            ),
            CloudError::PermissionDenied(msg) => CoreError::SecurityError(
                ErrorContext::new(format!("{msg}"))
                    .with_location(ErrorLocation::new(file!(), line!())),
            ),
            CloudError::NetworkError(msg) => CoreError::IoError(
                ErrorContext::new(format!("{msg}"))
                    .with_location(ErrorLocation::new(file!(), line!())),
            ),
            _ => CoreError::IoError(
                ErrorContext::new(format!("{err}"))
                    .with_location(ErrorLocation::new(file!(), line!())),
            ),
        }
    }
}

/// Cloud storage provider types
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CloudProvider {
    /// Amazon S3
    AwsS3,
    /// Google Cloud Storage
    GoogleCloud,
    /// Azure Blob Storage
    AzureBlob,
    /// S3-compatible providers (MinIO, etc.)
    S3Compatible,
}

impl CloudProvider {
    /// Get the default endpoint for this provider
    pub fn default_endpoint(&self) -> Option<&'static str> {
        match self {
            CloudProvider::AwsS3 => Some("https://s3.amazonaws.com"),
            CloudProvider::GoogleCloud => Some("https://storage.googleapis.com"),
            CloudProvider::AzureBlob => None, // Dynamic based on account
            CloudProvider::S3Compatible => None, // User-defined
        }
    }

    /// Get the provider name as string
    pub fn as_str(&self) -> &'static str {
        match self {
            CloudProvider::AwsS3 => "aws-s3",
            CloudProvider::GoogleCloud => "google-cloud",
            CloudProvider::AzureBlob => "azure-blob",
            CloudProvider::S3Compatible => "s3-compatible",
        }
    }
}

/// Cloud storage credentials
#[derive(Debug, Clone)]
pub enum CloudCredentials {
    /// AWS credentials
    Aws {
        access_key_id: String,
        secret_access_key: String,
        session_token: Option<String>,
        region: String,
    },
    /// Google Cloud credentials
    Google {
        service_account_key: String,
        project_id: String,
    },
    /// Azure credentials
    Azure {
        account_name: String,
        account_key: String,
        sas_token: Option<String>,
    },
    /// Anonymous access (for public buckets)
    Anonymous,
}

impl CloudCredentials {
    /// Create AWS credentials from environment variables
    pub fn aws_from_env() -> Result<Self, CloudError> {
        let access_key_id = std::env::var(AWS_ACCESS_KEY_ID).map_err(|_| {
            CloudError::AuthenticationError("AWS_ACCESS_KEY_ID not found".to_string())
        })?;
        let secret_access_key = std::env::var(AWS_SECRET_ACCESS_KEY).map_err(|_| {
            CloudError::AuthenticationError("AWS_SECRET_ACCESS_KEY not found".to_string())
        })?;
        let session_token = std::env::var(AWS_SESSION_TOKEN).ok();
        let region = std::env::var(AWS_REGION).unwrap_or_else(|_| "us-east-1".to_string());

        Ok(CloudCredentials::Aws {
            access_key_id,
            secret_access_key,
            session_token,
            region,
        })
    }

    /// Create Google Cloud credentials from environment variables
    pub fn google_from_env() -> Result<Self, CloudError> {
        let service_account_key = std::env::var(GOOGLE_APPLICATION_CREDENTIALS).map_err(|_| {
            CloudError::AuthenticationError("GOOGLE_APPLICATION_CREDENTIALS not found".to_string())
        })?;
        let project_id = std::env::var(GOOGLE_CLOUD_PROJECT).map_err(|_| {
            CloudError::AuthenticationError("GOOGLE_CLOUD_PROJECT not found".to_string())
        })?;

        Ok(CloudCredentials::Google {
            service_account_key,
            project_id,
        })
    }

    /// Create Azure credentials from environment variables
    pub fn azure_from_env() -> Result<Self, CloudError> {
        let account_name = std::env::var(AZURE_STORAGE_ACCOUNT).map_err(|_| {
            CloudError::AuthenticationError("AZURE_STORAGE_ACCOUNT not found".to_string())
        })?;
        let account_key = std::env::var(AZURE_STORAGE_KEY).map_err(|_| {
            CloudError::AuthenticationError("AZURE_STORAGE_KEY not found".to_string())
        })?;
        let sas_token = std::env::var(AZURE_STORAGE_SAS_TOKEN).ok();

        Ok(CloudCredentials::Azure {
            account_name,
            account_key,
            sas_token,
        })
    }
}

/// Cloud storage configuration
#[derive(Debug, Clone)]
pub struct CloudConfig {
    /// Cloud provider
    pub provider: CloudProvider,
    /// Custom endpoint URL
    pub endpoint: Option<String>,
    /// Bucket or container name
    pub bucket: String,
    /// Credentials
    pub credentials: CloudCredentials,
    /// Connection timeout
    pub timeout: Duration,
    /// Maximum number of retries
    pub maxretries: u32,
    /// Enable multipart uploads for files larger than this size
    pub multipart_threshold: usize,
    /// Chunk size for multipart operations
    pub chunk_size: usize,
    /// Maximum concurrent operations
    pub max_concurrency: usize,
    /// Enable caching
    pub enable_cache: bool,
    /// Cache directory
    pub cache_dir: Option<PathBuf>,
}

impl Default for CloudConfig {
    fn default() -> Self {
        Self {
            provider: CloudProvider::AwsS3,
            endpoint: None,
            bucket: String::new(),
            credentials: CloudCredentials::Anonymous,
            timeout: Duration::from_secs(30),
            maxretries: 3,
            multipart_threshold: 100 * 1024 * 1024, // 100 MB
            chunk_size: 8 * 1024 * 1024,            // 8 MB
            max_concurrency: 10,
            enable_cache: true,
            cache_dir: None,
        }
    }
}

impl CloudConfig {
    /// Create a new configuration for AWS S3
    pub fn new_bucket(bucket: String, credentials: CloudCredentials) -> Self {
        Self {
            provider: CloudProvider::AwsS3,
            bucket,
            credentials,
            ..Default::default()
        }
    }

    /// Create a new configuration for Google Cloud Storage
    pub fn bucket_2(bucket: String, credentials: CloudCredentials) -> Self {
        Self {
            provider: CloudProvider::GoogleCloud,
            bucket,
            credentials,
            ..Default::default()
        }
    }

    /// Create a new configuration for Azure Blob Storage
    pub fn container(container: String, credentials: CloudCredentials) -> Self {
        Self {
            provider: CloudProvider::AzureBlob,
            bucket: container,
            credentials,
            ..Default::default()
        }
    }

    /// Set custom endpoint
    pub fn with_endpoint(mut self, endpoint: String) -> Self {
        self.endpoint = Some(endpoint);
        self
    }

    /// Set timeout
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Set multipart configuration
    pub fn with_multipart(mut self, threshold: usize, chunk_size: usize) -> Self {
        self.multipart_threshold = threshold;
        self.chunk_size = chunk_size;
        self
    }

    /// Set cache configuration
    pub fn with_cache(mut self, enable: bool, cache_dir: Option<PathBuf>) -> Self {
        self.enable_cache = enable;
        self.cache_dir = cache_dir;
        self
    }
}

/// Cloud object metadata
#[derive(Debug, Clone)]
pub struct CloudObjectMetadata {
    /// Object key/path
    pub key: String,
    /// Object size in bytes
    pub size: u64,
    /// Last modified time
    pub last_modified: SystemTime,
    /// ETag or content hash
    pub etag: Option<String>,
    /// Content type
    pub content_type: Option<String>,
    /// Custom metadata
    pub metadata: HashMap<String, String>,
    /// Storage class
    pub storage_class: Option<String>,
}

/// Progress callback for upload/download operations
pub type ProgressCallback = Box<dyn Fn(u64, u64) + Send + Sync>;

/// Transfer options for cloud operations
#[derive(Default)]
pub struct TransferOptions {
    /// Progress callback
    pub progress_callback: Option<ProgressCallback>,
    /// Custom metadata to set
    pub metadata: HashMap<String, String>,
    /// Content type
    pub content_type: Option<String>,
    /// Storage class
    pub storage_class: Option<String>,
    /// Whether to overwrite existing objects
    pub overwrite: bool,
    /// Server-side encryption settings
    pub encryption: Option<EncryptionConfig>,
}

/// Server-side encryption configuration
#[derive(Debug, Clone)]
pub struct EncryptionConfig {
    /// Encryption method
    pub method: EncryptionMethod,
    /// Key ID or key material
    pub key: Option<String>,
}

/// Encryption methods supported by cloud providers
#[derive(Debug, Clone)]
pub enum EncryptionMethod {
    /// Provider-managed encryption
    ServerSideManaged,
    /// Customer-managed keys
    CustomerManaged,
    /// Customer-provided keys
    CustomerProvided,
}

/// Result of a list operation
#[derive(Debug, Clone)]
pub struct ListResult {
    /// Objects found
    pub objects: Vec<CloudObjectMetadata>,
    /// Whether there are more results
    pub has_more: bool,
    /// Continuation token for pagination
    pub next_token: Option<String>,
}

/// Cloud storage backend trait
#[cfg(feature = "async")]
#[async_trait]
pub trait CloudStorageBackend: Send + Sync {
    /// Upload a file to cloud storage
    async fn upload_file(
        &self,
        key: &str,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError>;

    /// Download a file from cloud storage
    async fn download_file(
        &self,
        path: &Path,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError>;

    /// Upload data from memory
    async fn upload_data(
        &self,
        data: &[u8],
        key: &str,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError>;

    /// Download data to memory
    async fn get_object(&self, key: &str) -> Result<Vec<u8>, CloudError>;

    /// Get object metadata
    async fn get_metadata(&self, key: &str) -> Result<CloudObjectMetadata, CloudError>;

    /// Check if object exists
    async fn object_exists(&self, key: &str) -> Result<bool, CloudError>;

    /// Delete an object
    async fn delete_object(&self, key: &str) -> Result<(), CloudError>;

    /// List objects with optional prefix
    async fn list_objects(
        &self,
        prefix: Option<&str>,
        continuation_token: Option<&str>,
    ) -> Result<ListResult, CloudError>;

    /// Copy an object within the same bucket
    async fn copy_object(
        &self,
        source_key: &str,
        dest_key: &str,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError>;

    /// Generate a presigned URL for temporary access
    async fn generate_presigned_url(
        &self,
        key: &str,
        expiration: Duration,
        method: HttpMethod,
    ) -> Result<String, CloudError>;
}

/// HTTP methods for presigned URLs
#[derive(Debug, Clone, Copy)]
pub enum HttpMethod {
    Get,
    Put,
    Post,
    Delete,
}

/// Cloud storage client with unified interface
pub struct CloudStorageClient {
    config: CloudConfig,
    backend: Box<dyn CloudStorageBackend>,
    cache: Option<Arc<Mutex<CloudCache>>>,
}

/// Simple in-memory cache for cloud operations
#[derive(Debug)]
struct CloudCache {
    metadata_cache: HashMap<String, (CloudObjectMetadata, SystemTime)>,
    cache_ttl: Duration,
}

impl CloudCache {
    fn new(ttl: Duration) -> Self {
        Self {
            metadata_cache: HashMap::new(),
            cache_ttl: ttl,
        }
    }

    fn get_metadata(&mut self, key: &str) -> Option<CloudObjectMetadata> {
        if let Some((metadata, timestamp)) = self.metadata_cache.get(key) {
            if timestamp.elapsed().unwrap_or(Duration::MAX) < self.cache_ttl {
                return Some(metadata.clone());
            } else {
                self.metadata_cache.remove(key);
            }
        }
        None
    }

    fn put_metadata(&mut self, key: String, metadata: CloudObjectMetadata) {
        self.metadata_cache
            .insert(key, (metadata, SystemTime::now()));
    }

    fn invalidate(&mut self, key: &str) {
        self.metadata_cache.remove(key);
    }

    fn clear(&mut self) {
        self.metadata_cache.clear();
    }
}

impl CloudStorageClient {
    /// Create a new cloud storage client
    pub fn new(config: CloudConfig) -> Result<Self, CloudError> {
        let backend = Self::create_backend(&config)?;
        let cache = if config.enable_cache {
            Some(Arc::new(Mutex::new(CloudCache::new(Duration::from_secs(
                300,
            )))))
        } else {
            None
        };

        Ok(Self {
            config,
            backend,
            cache,
        })
    }

    /// Create the appropriate backend for the provider
    fn create_backend(config: &CloudConfig) -> Result<Box<dyn CloudStorageBackend>, CloudError> {
        match config.provider {
            CloudProvider::AwsS3 | CloudProvider::S3Compatible => {
                Ok(Box::new(S3Backend::new(config.clone())?))
            }
            CloudProvider::GoogleCloud => Ok(Box::new(GoogleCloudBackend::new(config.clone())?)),
            CloudProvider::AzureBlob => Ok(Box::new(AzureBackend::new(config.clone())?)),
        }
    }

    /// Upload a file with progress tracking
    #[cfg(feature = "async")]
    pub async fn upload_file<P: AsRef<Path>>(
        &self,
        local_path: P,
        remote_key: &str,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError> {
        let result = self.backend.upload_file(remote_key, options).await?;

        // Update cache
        if let Some(cache) = &self.cache {
            cache
                .lock()
                .expect("Operation failed")
                .put_metadata(remote_key.to_string(), result.clone());
        }

        Ok(result)
    }

    /// Download a file with progress tracking
    #[cfg(feature = "async")]
    pub async fn download_file<P: AsRef<Path>>(
        &self,
        remote_key: &str,
        local_path: P,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError> {
        self.backend
            .download_file(local_path.as_ref(), options)
            .await
    }

    /// Upload data from memory
    #[cfg(feature = "async")]
    pub async fn upload_data(
        &self,
        data: &[u8],
        remote_key: &str,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError> {
        let result = self.backend.upload_data(data, remote_key, options).await?;

        // Update cache
        if let Some(cache) = &self.cache {
            cache
                .lock()
                .expect("Operation failed")
                .put_metadata(remote_key.to_string(), result.clone());
        }

        Ok(result)
    }

    /// Download data to memory
    #[cfg(feature = "async")]
    pub async fn get_object(&self, key: &str) -> Result<Vec<u8>, CloudError> {
        self.backend.get_object(key).await
    }

    /// Get object metadata with caching
    #[cfg(feature = "async")]
    pub async fn get_metadata(&self, key: &str) -> Result<CloudObjectMetadata, CloudError> {
        // Check cache first
        if let Some(cache) = &self.cache {
            if let Some(metadata) = cache.lock().expect("Operation failed").get_metadata(key) {
                return Ok(metadata);
            }
        }

        // Fetch from backend
        let metadata = self.backend.get_metadata(key).await?;

        // Update cache
        if let Some(cache) = &self.cache {
            cache
                .lock()
                .expect("Operation failed")
                .put_metadata(key.to_string(), metadata.clone());
        }

        Ok(metadata)
    }

    /// Check if object exists
    #[cfg(feature = "async")]
    pub async fn object_exists(&self, key: &str) -> Result<bool, CloudError> {
        self.backend.object_exists(key).await
    }

    /// Delete an object
    #[cfg(feature = "async")]
    pub async fn delete_object(&self, key: &str) -> Result<(), CloudError> {
        let result = self.backend.delete_object(key).await;

        // Invalidate cache
        if let Some(cache) = &self.cache {
            cache.lock().expect("Operation failed").invalidate(key);
        }

        result
    }

    /// List objects
    #[cfg(feature = "async")]
    pub async fn list_objects(
        &self,
        prefix: Option<&str>,
        continuation_token: Option<&str>,
    ) -> Result<ListResult, CloudError> {
        self.backend.list_objects(prefix, continuation_token).await
    }

    /// Copy an object
    #[cfg(feature = "async")]
    pub async fn copy_object(
        &self,
        source_key: &str,
        dest_key: &str,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError> {
        let result = self
            .backend
            .copy_object(source_key, dest_key, options)
            .await?;

        // Update cache for destination
        if let Some(cache) = &self.cache {
            cache
                .lock()
                .expect("Operation failed")
                .put_metadata(dest_key.to_string(), result.clone());
        }

        Ok(result)
    }

    /// Generate presigned URL
    #[cfg(feature = "async")]
    pub async fn generate_presigned_url(
        &self,
        remote_key: &str,
        expiration: Duration,
        method: HttpMethod,
    ) -> Result<String, CloudError> {
        self.backend
            .generate_presigned_url(remote_key, expiration, method)
            .await
    }

    /// Clear all cached data
    pub fn clear_cache(&self) {
        if let Some(cache) = &self.cache {
            cache.lock().expect("Operation failed").clear();
        }
    }

    /// Get current configuration
    pub fn config(&self) -> &CloudConfig {
        &self.config
    }
}

/// S3-compatible backend implementation
struct S3Backend {
    config: CloudConfig,
}

impl S3Backend {
    fn new(config: CloudConfig) -> Result<Self, CloudError> {
        // Validate S3 configuration
        match &config.credentials {
            CloudCredentials::Aws { .. } | CloudCredentials::Anonymous => {}
            _ => {
                return Err(CloudError::InvalidConfiguration(
                    "Invalid credentials for S3".to_string(),
                ))
            }
        }

        Ok(Self { config })
    }
}

#[cfg(feature = "async")]
#[async_trait]
impl CloudStorageBackend for S3Backend {
    async fn upload_file(
        &self,
        key: &str,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError> {
        // In a real implementation, this would use the AWS SDK or reqwest
        // to perform the actual upload with proper authentication

        // For now, simulate the operation
        let file_size = 1024; // Simulated file size

        Ok(CloudObjectMetadata {
            key: key.to_string(),
            size: file_size,
            last_modified: SystemTime::now(),
            etag: Some("\"mock-etag\"".to_string()),
            content_type: options
                .content_type
                .or_else(|| Some("application/octet-stream".to_string())),
            metadata: options.metadata,
            storage_class: options
                .storage_class
                .or_else(|| Some("STANDARD".to_string())),
        })
    }

    async fn download_file(
        &self,
        path: &Path,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError> {
        // Simulate download operation
        std::fs::write(path, b"mock file content")
            .map_err(|e| CloudError::DownloadError(format!("{e}")))?;

        Ok(CloudObjectMetadata {
            key: path.to_string_lossy().to_string(),
            size: 17, // "mock file content".len()
            last_modified: SystemTime::now(),
            etag: Some("\"mock-etag\"".to_string()),
            content_type: options
                .content_type
                .or_else(|| Some("application/octet-stream".to_string())),
            metadata: options.metadata,
            storage_class: options
                .storage_class
                .or_else(|| Some("STANDARD".to_string())),
        })
    }

    async fn upload_data(
        &self,
        data: &[u8],
        key: &str,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError> {
        // Simulate upload operation
        Ok(CloudObjectMetadata {
            key: key.to_string(),
            size: data.len() as u64,
            last_modified: SystemTime::now(),
            etag: Some("\"mock-etag\"".to_string()),
            content_type: options
                .content_type
                .or_else(|| Some("application/octet-stream".to_string())),
            metadata: options.metadata,
            storage_class: options
                .storage_class
                .or_else(|| Some("STANDARD".to_string())),
        })
    }

    async fn get_object(&self, key: &str) -> Result<Vec<u8>, CloudError> {
        // Simulate download operation
        Ok(format!("{key}").into_bytes())
    }

    async fn get_metadata(&self, key: &str) -> Result<CloudObjectMetadata, CloudError> {
        // Simulate metadata retrieval
        Ok(CloudObjectMetadata {
            key: key.to_string(),
            size: 1024,
            last_modified: SystemTime::now(),
            etag: Some("\"mock-etag\"".to_string()),
            content_type: Some("application/octet-stream".to_string()),
            metadata: HashMap::new(),
            storage_class: Some("STANDARD".to_string()),
        })
    }

    async fn object_exists(&self, key: &str) -> Result<bool, CloudError> {
        // Simulate existence check
        Ok(true)
    }

    async fn delete_object(&self, key: &str) -> Result<(), CloudError> {
        // Simulate deletion
        Ok(())
    }

    async fn list_objects(
        &self,
        prefix: Option<&str>,
        continuation_token: Option<&str>,
    ) -> Result<ListResult, CloudError> {
        // Simulate listing
        let mut objects = Vec::new();
        let max = 10; // Limit for simulation

        for i in 0..max {
            let key = if let Some(prefix) = prefix {
                format!("{prefix}_{i}")
            } else {
                format!("object_{i}")
            };

            objects.push(CloudObjectMetadata {
                key,
                size: 1024 * (i + 1) as u64,
                last_modified: SystemTime::now(),
                etag: Some(format!("\"etag-{}\"", i)),
                content_type: Some("application/octet-stream".to_string()),
                metadata: HashMap::new(),
                storage_class: Some("STANDARD".to_string()),
            });
        }

        Ok(ListResult {
            objects,
            has_more: false,
            next_token: continuation_token.map(|s| s.to_string()),
        })
    }

    async fn copy_object(
        &self,
        source_key: &str,
        dest_key: &str,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError> {
        // Simulate copy operation
        Ok(CloudObjectMetadata {
            key: dest_key.to_string(),
            size: 1024,
            last_modified: SystemTime::now(),
            etag: Some("\"mock-etag\"".to_string()),
            content_type: options
                .content_type
                .or_else(|| Some("application/octet-stream".to_string())),
            metadata: options.metadata,
            storage_class: options
                .storage_class
                .or_else(|| Some("STANDARD".to_string())),
        })
    }

    async fn generate_presigned_url(
        &self,
        key: &str,
        expiration: Duration,
        method: HttpMethod,
    ) -> Result<String, CloudError> {
        // Simulate presigned URL generation
        let method_str = match method {
            HttpMethod::Get => "GET",
            HttpMethod::Put => "PUT",
            HttpMethod::Post => "POST",
            HttpMethod::Delete => "DELETE",
        };

        Ok(format!(
            "https://s3.amazonaws.com/{}/{}?expires={}&method={}",
            self.config.bucket,
            key,
            expiration.as_secs(),
            method_str
        ))
    }
}

/// Google Cloud Storage backend implementation
struct GoogleCloudBackend {
    config: CloudConfig,
}

impl GoogleCloudBackend {
    fn new(config: CloudConfig) -> Result<Self, CloudError> {
        // Validate GCS configuration
        match &config.credentials {
            CloudCredentials::Google { .. } | CloudCredentials::Anonymous => {}
            _ => {
                return Err(CloudError::InvalidConfiguration(
                    "Invalid credentials for GCS".to_string(),
                ))
            }
        }

        Ok(Self { config })
    }
}

#[cfg(feature = "async")]
#[async_trait]
impl CloudStorageBackend for GoogleCloudBackend {
    async fn upload_file(
        &self,
        key: &str,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError> {
        // Similar to S3 but with GCS-specific implementation
        let file_size = 1024; // Simulated file size

        Ok(CloudObjectMetadata {
            key: key.to_string(),
            size: file_size,
            last_modified: SystemTime::now(),
            etag: Some("mock-gcs-etag".to_string()),
            content_type: options
                .content_type
                .or_else(|| Some("application/octet-stream".to_string())),
            metadata: options.metadata,
            storage_class: options
                .storage_class
                .or_else(|| Some("STANDARD".to_string())),
        })
    }

    async fn download_file(
        &self,
        path: &Path,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError> {
        std::fs::write(path, b"mock gcs content")
            .map_err(|e| CloudError::DownloadError(format!("{e}")))?;

        Ok(CloudObjectMetadata {
            key: path.to_string_lossy().to_string(),
            size: 16,
            last_modified: SystemTime::now(),
            etag: Some("mock-gcs-etag".to_string()),
            content_type: options
                .content_type
                .or_else(|| Some("application/octet-stream".to_string())),
            metadata: options.metadata,
            storage_class: options
                .storage_class
                .or_else(|| Some("STANDARD".to_string())),
        })
    }

    async fn upload_data(
        &self,
        data: &[u8],
        key: &str,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError> {
        Ok(CloudObjectMetadata {
            key: key.to_string(),
            size: data.len() as u64,
            last_modified: SystemTime::now(),
            etag: Some("mock-gcs-etag".to_string()),
            content_type: options
                .content_type
                .or_else(|| Some("application/octet-stream".to_string())),
            metadata: options.metadata,
            storage_class: options
                .storage_class
                .or_else(|| Some("STANDARD".to_string())),
        })
    }

    async fn get_object(&self, key: &str) -> Result<Vec<u8>, CloudError> {
        Ok(format!("{key}").into_bytes())
    }

    async fn get_metadata(&self, key: &str) -> Result<CloudObjectMetadata, CloudError> {
        Ok(CloudObjectMetadata {
            key: key.to_string(),
            size: 1024,
            last_modified: SystemTime::now(),
            etag: Some("mock-gcs-etag".to_string()),
            content_type: Some("application/octet-stream".to_string()),
            metadata: HashMap::new(),
            storage_class: Some("STANDARD".to_string()),
        })
    }

    async fn object_exists(&self, key: &str) -> Result<bool, CloudError> {
        Ok(true)
    }

    async fn delete_object(&self, key: &str) -> Result<(), CloudError> {
        Ok(())
    }

    async fn list_objects(
        &self,
        prefix: Option<&str>,
        continuation_token: Option<&str>,
    ) -> Result<ListResult, CloudError> {
        let mut objects = Vec::new();
        let max = 10; // Limit for simulation

        for i in 0..max {
            let key = if let Some(prefix) = prefix {
                format!("{prefix}_{i}")
            } else {
                format!("object_{i}")
            };

            objects.push(CloudObjectMetadata {
                key,
                size: 1024 * (i + 1) as u64,
                last_modified: SystemTime::now(),
                etag: Some(format!("gcs-etag-{i}")),
                content_type: Some("application/octet-stream".to_string()),
                metadata: HashMap::new(),
                storage_class: Some("STANDARD".to_string()),
            });
        }

        Ok(ListResult {
            objects,
            has_more: false,
            next_token: continuation_token.map(|s| s.to_string()),
        })
    }

    async fn copy_object(
        &self,
        source_key: &str,
        dest_key: &str,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError> {
        Ok(CloudObjectMetadata {
            key: dest_key.to_string(),
            size: 1024,
            last_modified: SystemTime::now(),
            etag: Some("mock-gcs-etag".to_string()),
            content_type: options
                .content_type
                .or_else(|| Some("application/octet-stream".to_string())),
            metadata: options.metadata,
            storage_class: options
                .storage_class
                .or_else(|| Some("STANDARD".to_string())),
        })
    }

    async fn generate_presigned_url(
        &self,
        key: &str,
        expiration: Duration,
        method: HttpMethod,
    ) -> Result<String, CloudError> {
        let method_str = match method {
            HttpMethod::Get => "GET",
            HttpMethod::Put => "PUT",
            HttpMethod::Post => "POST",
            HttpMethod::Delete => "DELETE",
        };

        Ok(format!(
            "https://storage.googleapis.com/{}/{}?expires={}&method={}",
            self.config.bucket,
            key,
            expiration.as_secs(),
            method_str
        ))
    }
}

/// Azure Blob Storage backend implementation
struct AzureBackend {
    config: CloudConfig,
}

impl AzureBackend {
    fn new(config: CloudConfig) -> Result<Self, CloudError> {
        // Validate Azure configuration
        match &config.credentials {
            CloudCredentials::Azure { .. } | CloudCredentials::Anonymous => {}
            _ => {
                return Err(CloudError::InvalidConfiguration(
                    "Invalid credentials for Azure".to_string(),
                ))
            }
        }

        Ok(Self { config })
    }
}

#[cfg(feature = "async")]
#[async_trait]
impl CloudStorageBackend for AzureBackend {
    async fn upload_file(
        &self,
        key: &str,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError> {
        let file_size = 1024; // Simulated file size

        Ok(CloudObjectMetadata {
            key: key.to_string(),
            size: file_size,
            last_modified: SystemTime::now(),
            etag: Some("mock-azure-etag".to_string()),
            content_type: options
                .content_type
                .or_else(|| Some("application/octet-stream".to_string())),
            metadata: options.metadata,
            storage_class: options.storage_class.or_else(|| Some("Hot".to_string())),
        })
    }

    async fn download_file(
        &self,
        path: &Path,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError> {
        std::fs::write(path, b"mock azure content")
            .map_err(|e| CloudError::DownloadError(format!("{e}")))?;

        Ok(CloudObjectMetadata {
            key: path.to_string_lossy().to_string(),
            size: 18,
            last_modified: SystemTime::now(),
            etag: Some("mock-azure-etag".to_string()),
            content_type: options
                .content_type
                .or_else(|| Some("application/octet-stream".to_string())),
            metadata: options.metadata,
            storage_class: options.storage_class.or_else(|| Some("Hot".to_string())),
        })
    }

    async fn upload_data(
        &self,
        data: &[u8],
        key: &str,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError> {
        Ok(CloudObjectMetadata {
            key: key.to_string(),
            size: data.len() as u64,
            last_modified: SystemTime::now(),
            etag: Some("mock-azure-etag".to_string()),
            content_type: options
                .content_type
                .or_else(|| Some("application/octet-stream".to_string())),
            metadata: options.metadata,
            storage_class: options.storage_class.or_else(|| Some("Hot".to_string())),
        })
    }

    async fn get_object(&self, key: &str) -> Result<Vec<u8>, CloudError> {
        Ok(format!("{key}").into_bytes())
    }

    async fn get_metadata(&self, key: &str) -> Result<CloudObjectMetadata, CloudError> {
        Ok(CloudObjectMetadata {
            key: key.to_string(),
            size: 1024,
            last_modified: SystemTime::now(),
            etag: Some("mock-azure-etag".to_string()),
            content_type: Some("application/octet-stream".to_string()),
            metadata: HashMap::new(),
            storage_class: Some("Hot".to_string()),
        })
    }

    async fn object_exists(&self, key: &str) -> Result<bool, CloudError> {
        Ok(true)
    }

    async fn delete_object(&self, key: &str) -> Result<(), CloudError> {
        Ok(())
    }

    async fn list_objects(
        &self,
        prefix: Option<&str>,
        continuation_token: Option<&str>,
    ) -> Result<ListResult, CloudError> {
        let mut objects = Vec::new();
        let max = 10; // Limit for simulation

        for i in 0..max {
            let key = if let Some(prefix) = prefix {
                format!("{prefix}_{i}")
            } else {
                format!("object_{i}")
            };

            objects.push(CloudObjectMetadata {
                key,
                size: 1024 * (i + 1) as u64,
                last_modified: SystemTime::now(),
                etag: Some(format!("azure-etag-{i}")),
                content_type: Some("application/octet-stream".to_string()),
                metadata: HashMap::new(),
                storage_class: Some("Hot".to_string()),
            });
        }

        Ok(ListResult {
            objects,
            has_more: false,
            next_token: continuation_token.map(|s| s.to_string()),
        })
    }

    async fn copy_object(
        &self,
        source_key: &str,
        dest_key: &str,
        options: TransferOptions,
    ) -> Result<CloudObjectMetadata, CloudError> {
        Ok(CloudObjectMetadata {
            key: dest_key.to_string(),
            size: 1024,
            last_modified: SystemTime::now(),
            etag: Some("mock-azure-etag".to_string()),
            content_type: options
                .content_type
                .or_else(|| Some("application/octet-stream".to_string())),
            metadata: options.metadata,
            storage_class: options.storage_class.or_else(|| Some("Hot".to_string())),
        })
    }

    async fn generate_presigned_url(
        &self,
        key: &str,
        expiration: Duration,
        method: HttpMethod,
    ) -> Result<String, CloudError> {
        let method_str = match method {
            HttpMethod::Get => "GET",
            HttpMethod::Put => "PUT",
            HttpMethod::Post => "POST",
            HttpMethod::Delete => "DELETE",
        };

        let account_name = match &self.config.credentials {
            CloudCredentials::Azure { account_name, .. } => account_name,
            _ => "mockaccount",
        };

        Ok(format!(
            "https://{}.blob.core.windows.net/{}/{}?expires={}&method={}",
            account_name,
            self.config.bucket,
            key,
            expiration.as_secs(),
            method_str
        ))
    }
}

/// Convenience functions for common cloud operations
pub mod utils {
    use super::*;

    /// Sync a local directory to cloud storage
    #[cfg(feature = "async")]
    pub async fn sync_directory_to_cloud(
        client: &CloudStorageClient,
        local_dir: &Path,
        remote_prefix: &str,
        recursive: bool,
    ) -> Result<usize, CloudError> {
        let mut uploaded_count = 0;

        fn visit_dir(dir: &Path, files: &mut Vec<PathBuf>) -> std::io::Result<()> {
            for entry in std::fs::read_dir(dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.is_file() {
                    files.push(path);
                } else if path.is_dir() {
                    visit_dir(&path, files)?;
                }
            }
            Ok(())
        }

        let mut files = Vec::new();
        if recursive {
            visit_dir(local_dir, &mut files).map_err(|e| CloudError::UploadError(e.to_string()))?;
        } else {
            for entry in
                std::fs::read_dir(local_dir).map_err(|e| CloudError::UploadError(e.to_string()))?
            {
                let entry = entry.map_err(|e| CloudError::UploadError(e.to_string()))?;
                let path = entry.path();
                if path.is_file() {
                    files.push(path);
                }
            }
        }

        for file_path in files {
            let relative_path = file_path
                .strip_prefix(local_dir)
                .map_err(|e| CloudError::UploadError(e.to_string()))?;
            let remote_key = format!("{}/{}", remote_prefix, relative_path.to_string_lossy());

            client
                .upload_file(&file_path, &remote_key, TransferOptions::default())
                .await?;
            uploaded_count += 1;
        }

        Ok(uploaded_count)
    }

    /// Download and sync cloud storage to local directory
    #[cfg(feature = "async")]
    pub async fn sync_cloud_to_directory(
        client: &CloudStorageClient,
        remote_prefix: &str,
        local_dir: &Path,
    ) -> Result<usize, CloudError> {
        let mut downloaded_count = 0;
        let mut continuation_token = None;

        loop {
            let result = client
                .list_objects(Some(remote_prefix), continuation_token.as_deref())
                .await?;

            for object in &result.objects {
                let relative_path = object
                    .key
                    .strip_prefix(remote_prefix)
                    .unwrap_or(&object.key);
                let local_path = local_dir.join(relative_path);

                // Create parent directories
                if let Some(parent) = local_path.parent() {
                    std::fs::create_dir_all(parent)
                        .map_err(|e| CloudError::DownloadError(e.to_string()))?;
                }

                client
                    .download_file(&object.key, &local_path, TransferOptions::default())
                    .await?;
                downloaded_count += 1;
            }

            if !result.has_more {
                break;
            }
            continuation_token = result.next_token;
        }

        Ok(downloaded_count)
    }

    /// Calculate total size of objects with given prefix
    #[cfg(feature = "async")]
    pub async fn calculate_storage_usage(
        client: &CloudStorageClient,
        prefix: Option<&str>,
    ) -> Result<u64, CloudError> {
        let mut total_size = 0;
        let mut continuation_token = None;

        loop {
            let result = client
                .list_objects(prefix, continuation_token.as_deref())
                .await?;

            for object in &result.objects {
                total_size += object.size;
            }

            if !result.has_more {
                break;
            }
            continuation_token = result.next_token;
        }

        Ok(total_size)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[allow(unused_imports)]
    use tempfile::tempdir;

    #[test]
    fn test_cloud_provider_methods() {
        assert_eq!(CloudProvider::AwsS3.as_str(), "aws-s3");
        assert_eq!(CloudProvider::GoogleCloud.as_str(), "google-cloud");
        assert_eq!(CloudProvider::AzureBlob.as_str(), "azure-blob");

        assert!(CloudProvider::AwsS3.default_endpoint().is_some());
        assert!(CloudProvider::GoogleCloud.default_endpoint().is_some());
        assert!(CloudProvider::AzureBlob.default_endpoint().is_none());
    }

    #[test]
    fn test_cloud_config_builders() {
        let creds = CloudCredentials::Anonymous;

        let s3_config = CloudConfig::new_bucket("test-bucket".to_string(), creds.clone());
        assert_eq!(s3_config.provider, CloudProvider::AwsS3);
        assert_eq!(s3_config.bucket, "test-bucket");

        let gcs_config = CloudConfig::new_bucket("test-bucket".to_string(), creds.clone());
        assert_eq!(gcs_config.provider, CloudProvider::AwsS3);

        let azure_config = CloudConfig::container("test-container".to_string(), creds);
        assert_eq!(azure_config.provider, CloudProvider::AzureBlob);
    }

    #[test]
    fn test_cloud_config_with_modifiers() {
        let config = CloudConfig::default()
            .with_endpoint("https://custom.endpoint.com".to_string())
            .with_timeout(Duration::from_secs(60))
            .with_multipart(50 * 1024 * 1024, 4 * 1024 * 1024);

        assert_eq!(
            config.endpoint,
            Some("https://custom.endpoint.com".to_string())
        );
        assert_eq!(config.timeout, Duration::from_secs(60));
        assert_eq!(config.multipart_threshold, 50 * 1024 * 1024);
        assert_eq!(config.chunk_size, 4 * 1024 * 1024);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_s3_backend_operations() {
        let config =
            CloudConfig::new_bucket("test-bucket".to_string(), CloudCredentials::Anonymous);
        let backend = S3Backend::new(config).expect("Operation failed");

        // Test metadata retrieval
        let metadata = backend
            .get_metadata("test-key")
            .await
            .expect("Operation failed");
        assert_eq!(metadata.key, "test-key");
        assert!(metadata.size > 0);

        // Test existence check
        let exists = backend
            .object_exists("test-key")
            .await
            .expect("Operation failed");
        assert!(exists);

        // Test data upload
        let data = b"test data";
        let result = backend
            .upload_data(data, "test-upload", TransferOptions::default())
            .await
            .expect("Operation failed");
        assert_eq!(result.key, "test-upload");
        assert_eq!(result.size, data.len() as u64);

        // Test data download
        let downloaded = backend
            .get_object("test-key")
            .await
            .expect("Operation failed");
        assert!(!downloaded.is_empty());

        // Test listing
        let list_result = backend
            .list_objects(None, Some("5"))
            .await
            .expect("Operation failed");
        assert!(!list_result.objects.is_empty());
        assert!(list_result.objects.len() <= 10);

        // Test presigned URL generation
        let url = backend
            .generate_presigned_url("test-key", Duration::from_secs(3600), HttpMethod::Get)
            .await
            .expect("Operation failed");
        assert!(url.contains("test-key"));
        assert!(url.contains("expires=3600"));
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_cloud_storage_client() {
        let config =
            CloudConfig::new_bucket("test-bucket".to_string(), CloudCredentials::Anonymous);
        let client = CloudStorageClient::new(config).expect("Operation failed");

        // Test metadata with caching
        let metadata1 = client
            .get_metadata("test-key")
            .await
            .expect("Operation failed");
        let metadata2 = client
            .get_metadata("test-key")
            .await
            .expect("Operation failed"); // Should hit cache
        assert_eq!(metadata1.key, metadata2.key);

        // Test cache clearing
        client.clear_cache();

        // Test upload
        let data = b"test data for client";
        let result = client
            .upload_data(data, "client-test", TransferOptions::default())
            .await
            .expect("Operation failed");
        assert_eq!(result.size, data.len() as u64);
    }

    #[test]
    fn test_transfer_options() {
        let mut options = TransferOptions::default();
        options
            .metadata
            .insert("custom-key".to_string(), "custom-value".to_string());
        options.content_type = Some("text/plain".to_string());
        options.overwrite = true;

        assert_eq!(
            options.metadata.get("custom-key"),
            Some(&"custom-value".to_string())
        );
        assert_eq!(options.content_type, Some("text/plain".to_string()));
        assert!(options.overwrite);
    }

    #[test]
    fn test_encryption_config() {
        let encryption = EncryptionConfig {
            method: EncryptionMethod::CustomerManaged,
            key: Some("test-key-id".to_string()),
        };

        match encryption.method {
            EncryptionMethod::CustomerManaged => assert!(true),
            _ => assert!(false),
        }
        assert_eq!(encryption.key, Some("test-key-id".to_string()));
    }
}