paladin-ai 0.5.1

Enterprise AI orchestration framework with multi-agent coordination patterns
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
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use s3::Bucket;
use s3::BucketConfiguration;
use s3::creds::Credentials;
use s3::error::S3Error;
use s3::region::Region;
use s3::serde_types::Object;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::time::timeout;
use uuid::Uuid;

use crate::core::base::entity::message::{Location, MessagePriority};
use crate::core::platform::container::log::{LogEntry, LogLevel, LogMessage};
use paladin_ports::output::file_storage_port::{
    AdvancedFileStoragePort, BatchFileStoragePort, DownloadOptions, FileItem, FileListResult,
    FileStorageError, FileStoragePort, FileStorageResult, FileStorageUtils, FileVersioningPort,
    FullFileStoragePort, ListOptions, StorageHealth, StorageStats, UploadOptions,
};
use paladin_ports::output::log_port::LogPort;

/// Configuration for MinIO connection using rust-s3
#[doc(hidden)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MinioConfig {
    pub endpoint: String,
    pub access_key: String,
    pub secret_key: String,
    pub bucket: String,
    pub region: Option<String>,
    pub secure: bool,
    pub path_style: bool,
    pub connection_timeout: Duration,
    pub request_timeout: Duration,
    pub max_retries: u32,
    pub max_idle_conns: u32,
}

impl Default for MinioConfig {
    fn default() -> Self {
        Self {
            endpoint: "localhost:9000".to_string(),
            access_key: "minioadmin".to_string(),
            secret_key: "minioadmin".to_string(),
            bucket: "paladin-files".to_string(),
            region: Some("us-east-1".to_string()),
            secure: false,
            path_style: true,
            connection_timeout: Duration::from_secs(30),
            request_timeout: Duration::from_secs(300),
            max_retries: 3,
            max_idle_conns: 10,
        }
    }
}

/// MinIO adapter using rust-s3 crate
#[doc(hidden)]
pub struct MinioAdapter {
    bucket: Box<Bucket>,
    config: MinioConfig,
    log_port: Option<Arc<dyn LogPort>>,
}

impl MinioAdapter {
    /// Create a new MinIO adapter using rust-s3
    pub async fn new(
        config: MinioConfig,
        log_port: Option<Arc<dyn LogPort>>,
    ) -> FileStorageResult<Self> {
        // Create credentials
        let credentials = Credentials::new(
            Some(&config.access_key),
            Some(&config.secret_key),
            None,
            None,
            None,
        )
        .map_err(|e| {
            FileStorageError::AuthenticationError(format!("Invalid credentials: {}", e))
        })?;

        // Create custom region for MinIO
        let region = if config.secure {
            Region::Custom {
                region: config
                    .region
                    .clone()
                    .unwrap_or_else(|| "us-east-1".to_string()),
                endpoint: format!("https://{}", config.endpoint),
            }
        } else {
            Region::Custom {
                region: config
                    .region
                    .clone()
                    .unwrap_or_else(|| "us-east-1".to_string()),
                endpoint: format!("http://{}", config.endpoint),
            }
        };

        // Create bucket instance
        let bucket = Bucket::new(&config.bucket, region, credentials)
            .map_err(|e| {
                FileStorageError::ConfigurationError(format!("Failed to create bucket: {}", e))
            })?
            .with_path_style();

        let adapter = Self {
            bucket,
            config,
            log_port,
        };

        // Ensure bucket exists
        adapter.ensure_bucket_exists().await?;

        adapter
            .log_operation(
                LogLevel::Info,
                "MinIO adapter initialized successfully".to_string(),
            )
            .await;

        Ok(adapter)
    }

    /// Ensure the bucket exists, create if it doesn't
    async fn ensure_bucket_exists(&self) -> FileStorageResult<()> {
        // Check if bucket exists by attempting to list objects
        match timeout(
            self.config.connection_timeout,
            self.bucket.list("".to_string(), Some("/".to_string())),
        )
        .await
        {
            Ok(Ok(_)) => {
                // Bucket exists and is accessible
                Ok(())
            }
            Ok(Err(S3Error::HttpFailWithBody(404, _))) | Ok(Err(S3Error::HttpFail)) => {
                // Bucket doesn't exist, try to create it
                self.create_bucket().await
            }
            Ok(Err(e)) => Err(FileStorageError::ConnectionError(format!(
                "Failed to check bucket: {}",
                e
            ))),
            Err(_) => Err(FileStorageError::Timeout),
        }
    }

    async fn create_bucket(&self) -> FileStorageResult<()> {
        let config = BucketConfiguration::default();

        // Fix: Use the static method Bucket::create instead of instance method
        match timeout(
            self.config.connection_timeout,
            Bucket::create(
                &self.config.bucket,
                self.bucket.region(),
                self.bucket.credentials().await.map_err(|e| {
                    FileStorageError::AuthenticationError(format!(
                        "Failed to get credentials: {}",
                        e
                    ))
                })?,
                config,
            ),
        )
        .await
        {
            Ok(Ok(_)) => {
                self.log_operation(
                    LogLevel::Info,
                    format!("Created bucket: {}", self.config.bucket),
                )
                .await;
                Ok(())
            }
            Ok(Err(e)) => {
                // Check if error is because bucket already exists
                if let S3Error::HttpFailWithBody(409, _) = e {
                    // Bucket already exists, which is fine
                    Ok(())
                } else {
                    Err(FileStorageError::ConnectionError(format!(
                        "Failed to create bucket: {}",
                        e
                    )))
                }
            }
            Err(_) => Err(FileStorageError::Timeout),
        }
    }

    /// Log operation to LogPort if available
    async fn log_operation(&self, level: LogLevel, message: String) {
        if let Some(log_port) = &self.log_port {
            let entry = LogEntry {
                id: Uuid::new_v4(),
                timestamp: Utc::now(),
                message: LogMessage::new(level, message.clone()),
                source: Location::service("minio-adapter"),
                destination: Location::system("minio-adapter"),
                correlation_id: None,
                priority: MessagePriority::Normal,
            };

            if let Err(e) = log_port.write_entry(entry).await {
                eprintln!("Failed to log operation: {} - Error: {}", message, e);
            }
        }
    }

    /// Convert PathBuf to string, ensuring proper format
    fn path_to_object_name(&self, path: &Path) -> FileStorageResult<String> {
        <() as FileStorageUtils>::validate_path(path)?;

        let path_str = path.to_string_lossy();
        // Remove leading slash if present
        let cleaned_path = path_str.strip_prefix('/').unwrap_or(&path_str);
        Ok(cleaned_path.to_string())
    }

    /// Convert S3 object info to FileItem
    fn s3_object_to_file_item(&self, object: &Object, path: PathBuf) -> FileItem {
        let mut metadata = HashMap::new();

        // Add S3-specific metadata
        if let Some(etag) = &object.e_tag {
            metadata.insert("etag".to_string(), etag.clone());
        }

        if let Some(storage_class) = &object.storage_class {
            metadata.insert("storage_class".to_string(), storage_class.clone());
        }

        let size = object.size;
        let mut file_item = FileItem::new(path, size);

        // Fix: Parse the last_modified string to DateTime<Utc>
        if let Ok(parsed_date) = DateTime::parse_from_rfc3339(&object.last_modified) {
            file_item.modified_at = parsed_date.with_timezone(&Utc);
        } else if let Ok(parsed_date) = DateTime::parse_from_rfc2822(&object.last_modified) {
            file_item.modified_at = parsed_date.with_timezone(&Utc);
        } else {
            // Fall back to current time if parsing fails
            file_item.modified_at = Utc::now();
        }

        file_item.metadata = metadata;

        if let Some(etag) = &object.e_tag {
            file_item.md5_hash = Some(etag.trim_matches('"').to_string());
        }

        // Detect content type
        if let Some(content_type) = <() as FileStorageUtils>::detect_content_type(&file_item.path) {
            file_item.content_type = Some(content_type);
        }

        file_item
    }

    /// Apply upload options by creating headers map
    fn create_upload_headers(&self, options: &UploadOptions) -> HashMap<String, String> {
        let mut headers = HashMap::new();

        if let Some(content_type) = &options.content_type {
            headers.insert("Content-Type".to_string(), content_type.clone());
        }

        if let Some(cache_control) = &options.cache_control {
            headers.insert("Cache-Control".to_string(), cache_control.clone());
        }

        if let Some(content_disposition) = &options.content_disposition {
            headers.insert(
                "Content-Disposition".to_string(),
                content_disposition.clone(),
            );
        }

        // Add user metadata with x-amz-meta- prefix
        for (key, value) in &options.metadata {
            headers.insert(format!("x-amz-meta-{}", key), value.clone());
        }

        // Add tags as metadata (S3 doesn't have separate tagging in basic operations)
        if !options.tags.is_empty() {
            let tags_value = options.tags.join(",");
            headers.insert("x-amz-meta-tags".to_string(), tags_value);
        }

        headers
    }

    /// Execute operation with timeout and retries
    async fn execute_with_retry<F, T, Fut>(&self, operation: F) -> FileStorageResult<T>
    where
        F: Fn() -> Fut,
        Fut: std::future::Future<Output = Result<T, S3Error>>,
    {
        let mut last_error = None;

        for attempt in 0..=self.config.max_retries {
            match timeout(self.config.request_timeout, operation()).await {
                Ok(Ok(result)) => return Ok(result),
                Ok(Err(e)) => {
                    last_error = Some(e);
                    if attempt < self.config.max_retries {
                        let delay = Duration::from_millis(100 * (attempt + 1) as u64);
                        tokio::time::sleep(delay).await;
                    }
                }
                Err(_) => {
                    return Err(FileStorageError::Timeout);
                }
            }
        }

        Err(FileStorageError::IoError(format!(
            "Operation failed after {} retries: {}",
            self.config.max_retries,
            last_error
                .map(|e| e.to_string())
                .unwrap_or_else(|| "Unknown error".to_string())
        )))
    }
}

#[async_trait]
impl FileStoragePort for MinioAdapter {
    async fn upload_file(
        &self,
        path: &Path,
        content: &[u8],
        options: Option<UploadOptions>,
    ) -> FileStorageResult<FileItem> {
        let object_name = self.path_to_object_name(path)?;
        let options = options.unwrap_or_default();

        // Check if file exists and overwrite is disabled
        if !options.overwrite && self.file_exists(path).await? {
            return Err(FileStorageError::InvalidPath(format!(
                "File already exists: {}",
                path.display()
            )));
        }

        // Create headers
        let headers = self.create_upload_headers(&options);

        // Auto-detect content type if not provided
        let content_type = headers
            .get("Content-Type")
            .cloned()
            .or_else(|| <() as FileStorageUtils>::detect_content_type(path))
            .unwrap_or_else(|| "application/octet-stream".to_string());

        // Upload the file
        self.execute_with_retry(|| {
            self.bucket
                .put_object_with_content_type(&object_name, content, &content_type)
        })
        .await
        .map_err(|e| FileStorageError::IoError(format!("Failed to upload file: {}", e)))?;

        // Get file info after upload
        let file_item = self.get_file_info(path).await?;

        self.log_operation(
            LogLevel::Info,
            format!(
                "Uploaded file: {} ({} bytes)",
                path.display(),
                content.len()
            ),
        )
        .await;

        Ok(file_item)
    }

    async fn download_file(
        &self,
        path: &Path,
        _options: Option<DownloadOptions>,
    ) -> FileStorageResult<Vec<u8>> {
        let object_name = self.path_to_object_name(path)?;

        let response = self
            .execute_with_retry(|| self.bucket.get_object(&object_name))
            .await
            .map_err(|e| {
                FileStorageError::FileNotFound(format!("Failed to download file: {}", e))
            })?;

        let content = response.bytes().to_vec();

        self.log_operation(
            LogLevel::Info,
            format!(
                "Downloaded file: {} ({} bytes)",
                path.display(),
                content.len()
            ),
        )
        .await;

        Ok(content)
    }

    async fn delete_file(&self, path: &Path) -> FileStorageResult<()> {
        let object_name = self.path_to_object_name(path)?;

        self.execute_with_retry(|| self.bucket.delete_object(&object_name))
            .await
            .map_err(|e| FileStorageError::IoError(format!("Failed to delete file: {}", e)))?;

        self.log_operation(LogLevel::Info, format!("Deleted file: {}", path.display()))
            .await;

        Ok(())
    }

    async fn file_exists(&self, path: &Path) -> FileStorageResult<bool> {
        let object_name = self.path_to_object_name(path)?;

        match timeout(
            self.config.connection_timeout,
            self.bucket.head_object(&object_name),
        )
        .await
        {
            Ok(Ok(_)) => Ok(true),
            Ok(Err(S3Error::HttpFail)) | Ok(Err(S3Error::HttpFailWithBody(404, _))) => Ok(false),
            Ok(Err(e)) => Err(FileStorageError::IoError(format!(
                "Failed to check file existence: {}",
                e
            ))),
            Err(_) => Err(FileStorageError::Timeout),
        }
    }

    async fn get_file_info(&self, path: &Path) -> FileStorageResult<FileItem> {
        let object_name = self.path_to_object_name(path)?;

        let (head_result, _) = self
            .execute_with_retry(|| self.bucket.head_object(&object_name))
            .await
            .map_err(|e| FileStorageError::FileNotFound(format!("File not found: {}", e)))?;

        // Parse the response to create FileItem
        let mut metadata = HashMap::new();

        // Extract user-defined metadata if available
        if let Some(user_metadata) = &head_result.metadata {
            for (key, value) in user_metadata {
                metadata.insert(key.clone(), value.clone());
            }
        }

        let size = head_result.content_length.unwrap_or(0) as u64;

        let mut file_item = FileItem::new(path.to_path_buf(), size);
        file_item.metadata = metadata;
        file_item.content_type = head_result.content_type.clone();

        if let Some(etag) = &head_result.e_tag {
            file_item.md5_hash = Some(etag.trim_matches('"').to_string());
        }

        if let Some(last_modified) = &head_result.last_modified
            && let Ok(dt) = DateTime::parse_from_rfc2822(last_modified)
        {
            file_item.modified_at = dt.with_timezone(&Utc);
        }

        Ok(file_item)
    }

    async fn list_files(&self, options: Option<ListOptions>) -> FileStorageResult<FileListResult> {
        let options = options.unwrap_or_default();

        let prefix = options.prefix.clone().unwrap_or_default();
        let max_keys = options.limit.map(|l| l.to_string());

        let results = self
            .execute_with_retry(|| self.bucket.list(prefix.clone(), max_keys.clone()))
            .await
            .map_err(|e| FileStorageError::IoError(format!("Failed to list files: {}", e)))?;

        let mut files = Vec::new();

        // Process all list results
        for list_result in results {
            for object in list_result.contents {
                let path = PathBuf::from(&object.key);

                // Apply filters
                if self.should_include_file(&object, &path, &options) {
                    let file_item = self.s3_object_to_file_item(&object, path);
                    files.push(file_item);
                }
            }
        }

        // Sort files by modification date (newest first)
        files.sort_by_key(|b| std::cmp::Reverse(b.modified_at));

        // For simplicity, we'll assume no more results for now
        let has_more = false;
        let continuation_token = None;

        Ok(FileListResult {
            files,
            continuation_token,
            has_more,
            total_count: None,
        })
    }

    async fn copy_file(
        &self,
        source_path: &Path,
        destination_path: &Path,
    ) -> FileStorageResult<FileItem> {
        let source_object = self.path_to_object_name(source_path)?;
        let dest_object = self.path_to_object_name(destination_path)?;

        // S3 copy operation
        let copy_source = format!("{}/{}", self.config.bucket, source_object);

        self.execute_with_retry(|| self.bucket.copy_object_internal(&copy_source, &dest_object))
            .await
            .map_err(|e| FileStorageError::IoError(format!("Failed to copy file: {}", e)))?;

        let file_item = self.get_file_info(destination_path).await?;

        self.log_operation(
            LogLevel::Info,
            format!(
                "Copied file: {} -> {}",
                source_path.display(),
                destination_path.display()
            ),
        )
        .await;

        Ok(file_item)
    }

    async fn move_file(
        &self,
        source_path: &Path,
        destination_path: &Path,
    ) -> FileStorageResult<FileItem> {
        // Copy file to new location
        let file_item = self.copy_file(source_path, destination_path).await?;

        // Delete original file
        self.delete_file(source_path).await?;

        self.log_operation(
            LogLevel::Info,
            format!(
                "Moved file: {} -> {}",
                source_path.display(),
                destination_path.display()
            ),
        )
        .await;

        Ok(file_item)
    }

    async fn get_storage_stats(&self) -> FileStorageResult<StorageStats> {
        let list_options = ListOptions::default();
        let file_list = self.list_files(Some(list_options)).await?;

        let mut total_files = 0u64;
        let mut total_size = 0u64;
        let mut files_by_type = HashMap::new();
        let mut size_by_type = HashMap::new();

        for file in file_list.files {
            total_files += 1;
            total_size += file.size;

            let file_type = file.extension().unwrap_or("unknown").to_lowercase();

            *files_by_type.entry(file_type.clone()).or_insert(0) += 1;
            *size_by_type.entry(file_type).or_insert(0) += file.size;
        }

        Ok(StorageStats {
            total_files,
            total_size,
            files_by_type,
            size_by_type,
            last_updated: Utc::now(),
        })
    }

    async fn health_check(&self) -> FileStorageResult<StorageHealth> {
        let start_time = std::time::Instant::now();

        // Try to list objects as a simple health check
        match timeout(
            self.config.connection_timeout,
            self.bucket.list("".to_string(), Some("1".to_string())),
        )
        .await
        {
            Ok(Ok(_)) => {
                let response_time = start_time.elapsed().as_millis() as u64;

                self.log_operation(LogLevel::Info, "MinIO health check passed".to_string())
                    .await;

                Ok(StorageHealth {
                    is_available: true,
                    response_time_ms: Some(response_time),
                    error: None,
                    checked_at: Utc::now(),
                })
            }
            Ok(Err(e)) => {
                let error_msg = format!("MinIO health check failed: {}", e);
                self.log_operation(LogLevel::Error, error_msg.clone()).await;

                Ok(StorageHealth {
                    is_available: false,
                    response_time_ms: None,
                    error: Some(error_msg),
                    checked_at: Utc::now(),
                })
            }
            Err(_) => {
                let error_msg = "MinIO health check timed out".to_string();
                self.log_operation(LogLevel::Error, error_msg.clone()).await;

                Ok(StorageHealth {
                    is_available: false,
                    response_time_ms: None,
                    error: Some(error_msg),
                    checked_at: Utc::now(),
                })
            }
        }
    }
}

impl MinioAdapter {
    fn should_include_file(&self, object: &Object, path: &Path, options: &ListOptions) -> bool {
        // Filter by extensions
        if !options.extensions.is_empty() {
            if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
                if !options.extensions.contains(&ext.to_lowercase()) {
                    return false;
                }
            } else {
                return false;
            }
        }

        // Filter by size
        let size = object.size; // Remove try_into() since object.size is already u64
        if let Some(min_size) = options.min_size
            && size < min_size
        {
            return false;
        }
        if let Some(max_size) = options.max_size
            && size > max_size
        {
            return false;
        }

        // Filter by modification date
        // Fix: object.last_modified is a String, not Option<String>
        if !object.last_modified.is_empty() {
            // Parse the last_modified string to DateTime<Utc>
            let parsed_date = if let Ok(dt) = DateTime::parse_from_rfc3339(&object.last_modified) {
                dt.with_timezone(&Utc)
            } else if let Ok(dt) = DateTime::parse_from_rfc2822(&object.last_modified) {
                dt.with_timezone(&Utc)
            } else {
                // If we can't parse the date, skip date filtering for this object
                return true;
            };

            if let Some(modified_after) = options.modified_after
                && parsed_date < modified_after
            {
                return false;
            }
            if let Some(modified_before) = options.modified_before
                && parsed_date > modified_before
            {
                return false;
            }
        }

        // Note: Tag filtering would require additional S3 API calls for each object
        // For performance, we skip tag filtering in the basic list operation
        if !options.tags.is_empty() {
            // This would require a separate API call to get object tags
            // For now, we'll return true and handle tag filtering in a more sophisticated way if needed
        }

        true
    }
}

// Implement the remaining traits with similar patterns
#[async_trait]
impl BatchFileStoragePort for MinioAdapter {
    async fn upload_files(
        &self,
        files: Vec<(PathBuf, Vec<u8>, Option<UploadOptions>)>,
    ) -> FileStorageResult<Vec<FileItem>> {
        let mut results = Vec::new();

        // Note: rust-s3 doesn't have native batch upload, so we do them concurrently
        let upload_tasks: Vec<_> = files
            .into_iter()
            .map(|(path, content, options)| async move {
                self.upload_file(&path, &content, options).await
            })
            .collect();

        // Execute uploads concurrently
        for task in upload_tasks {
            match task.await {
                Ok(file_item) => results.push(file_item),
                Err(e) => {
                    self.log_operation(
                        LogLevel::Error,
                        format!("Failed to upload file in batch: {}", e),
                    )
                    .await;
                    return Err(e);
                }
            }
        }

        self.log_operation(
            LogLevel::Info,
            format!("Batch uploaded {} files", results.len()),
        )
        .await;

        Ok(results)
    }

    async fn download_files(
        &self,
        paths: Vec<PathBuf>,
        options: Option<DownloadOptions>,
    ) -> FileStorageResult<Vec<(PathBuf, Vec<u8>)>> {
        let mut results = Vec::new();

        for path in paths {
            match self.download_file(&path, options.clone()).await {
                Ok(content) => results.push((path, content)),
                Err(e) => {
                    self.log_operation(
                        LogLevel::Error,
                        format!(
                            "Failed to download file in batch: {} - {}",
                            path.display(),
                            e
                        ),
                    )
                    .await;
                    return Err(e);
                }
            }
        }

        self.log_operation(
            LogLevel::Info,
            format!("Batch downloaded {} files", results.len()),
        )
        .await;

        Ok(results)
    }

    async fn delete_files(&self, paths: Vec<PathBuf>) -> FileStorageResult<Vec<PathBuf>> {
        let mut deleted = Vec::new();

        for path in paths {
            match self.delete_file(&path).await {
                Ok(()) => deleted.push(path),
                Err(e) => {
                    self.log_operation(
                        LogLevel::Error,
                        format!("Failed to delete file in batch: {} - {}", path.display(), e),
                    )
                    .await;
                    return Err(e);
                }
            }
        }

        self.log_operation(
            LogLevel::Info,
            format!("Batch deleted {} files", deleted.len()),
        )
        .await;

        Ok(deleted)
    }

    async fn get_files_info(&self, paths: Vec<PathBuf>) -> FileStorageResult<Vec<FileItem>> {
        let mut results = Vec::new();

        for path in paths {
            match self.get_file_info(&path).await {
                Ok(file_item) => results.push(file_item),
                Err(e) => {
                    self.log_operation(
                        LogLevel::Error,
                        format!(
                            "Failed to get file info in batch: {} - {}",
                            path.display(),
                            e
                        ),
                    )
                    .await;
                    return Err(e);
                }
            }
        }

        Ok(results)
    }
}

#[async_trait]
impl AdvancedFileStoragePort for MinioAdapter {
    async fn generate_upload_url(
        &self,
        path: &Path,
        expires_in: Duration,
        _options: Option<UploadOptions>,
    ) -> FileStorageResult<String> {
        let object_name = self.path_to_object_name(path)?;
        let expires_in_secs = expires_in.as_secs() as u32;

        // Fix: Add the missing 4th parameter (custom query parameters)
        let url = self
            .bucket
            .presign_put(&object_name, expires_in_secs, None, None)
            .await
            .map_err(|e| {
                FileStorageError::IoError(format!("Failed to generate upload URL: {}", e))
            })?;

        Ok(url)
    }

    async fn generate_download_url(
        &self,
        path: &Path,
        expires_in: Duration,
        _options: Option<DownloadOptions>,
    ) -> FileStorageResult<String> {
        let object_name = self.path_to_object_name(path)?;
        let expires_in_secs = expires_in.as_secs() as u32;

        // Fix: Add the missing 4th parameter (custom query parameters)
        let url = self
            .bucket
            .presign_get(&object_name, expires_in_secs, None)
            .await
            .map_err(|e| {
                FileStorageError::IoError(format!("Failed to generate download URL: {}", e))
            })?;

        Ok(url)
    }

    async fn create_multipart_upload(
        &self,
        path: &Path,
        _options: Option<UploadOptions>,
    ) -> FileStorageResult<String> {
        let object_name = self.path_to_object_name(path)?;

        let response = self
            .bucket
            .initiate_multipart_upload(&object_name, "application/octet-stream")
            .await
            .map_err(|e| {
                FileStorageError::IoError(format!("Failed to initiate multipart upload: {}", e))
            })?;

        Ok(response.upload_id)
    }

    async fn upload_part(
        &self,
        _upload_id: &str,
        _part_number: u32,
        _content: &[u8],
    ) -> FileStorageResult<String> {
        // Note: This would require implementing multipart upload with rust-s3
        // The current version might not have direct support, so this is a placeholder
        Err(FileStorageError::Unknown(
            "Multipart upload not fully implemented with rust-s3".to_string(),
        ))
    }

    async fn complete_multipart_upload(
        &self,
        _upload_id: &str,
        _parts: Vec<(u32, String)>,
    ) -> FileStorageResult<FileItem> {
        Err(FileStorageError::Unknown(
            "Multipart upload not fully implemented with rust-s3".to_string(),
        ))
    }

    async fn abort_multipart_upload(&self, _upload_id: &str) -> FileStorageResult<()> {
        Err(FileStorageError::Unknown(
            "Multipart upload not fully implemented with rust-s3".to_string(),
        ))
    }
}

#[async_trait]
impl FileVersioningPort for MinioAdapter {
    async fn upload_file_version(
        &self,
        path: &Path,
        content: &[u8],
        options: Option<UploadOptions>,
    ) -> FileStorageResult<FileItem> {
        // For basic versioning, we can append a timestamp to the filename
        let timestamp = Utc::now().format("%Y%m%d_%H%M%S").to_string();
        let mut versioned_path = path.to_path_buf();

        if let Some(filename) = path.file_stem().and_then(|s| s.to_str()) {
            if let Some(extension) = path.extension().and_then(|s| s.to_str()) {
                let new_filename = format!("{}_{}.{}", filename, timestamp, extension);
                versioned_path.set_file_name(new_filename);
            } else {
                let new_filename = format!("{}_{}", filename, timestamp);
                versioned_path.set_file_name(new_filename);
            }
        }

        self.upload_file(&versioned_path, content, options).await
    }

    async fn list_file_versions(&self, path: &Path) -> FileStorageResult<Vec<FileItem>> {
        let filename_stem = path
            .file_stem()
            .and_then(|s| s.to_str())
            .ok_or_else(|| FileStorageError::InvalidPath("Invalid filename".to_string()))?;

        let prefix = path
            .parent()
            .map(|p| format!("{}/{}", p.display(), filename_stem))
            .unwrap_or_else(|| filename_stem.to_string());

        let list_options = ListOptions {
            prefix: Some(prefix),
            ..Default::default()
        };

        let file_list = self.list_files(Some(list_options)).await?;
        Ok(file_list.files)
    }

    async fn download_file_version(
        &self,
        path: &Path,
        _version_id: &str,
        options: Option<DownloadOptions>,
    ) -> FileStorageResult<Vec<u8>> {
        // For simple versioning, treat version_id as the versioned filename
        self.download_file(path, options).await
    }

    async fn delete_file_version(&self, path: &Path, _version_id: &str) -> FileStorageResult<()> {
        // For simple versioning, treat version_id as the versioned filename
        self.delete_file(path).await
    }

    async fn get_file_version_info(
        &self,
        path: &Path,
        _version_id: &str,
    ) -> FileStorageResult<FileItem> {
        // For simple versioning, treat version_id as the versioned filename
        self.get_file_info(path).await
    }
}

// Implement FullFileStoragePort
impl FullFileStoragePort for MinioAdapter {}

impl MinioAdapter {
    /// Shutdown the adapter and close connections
    pub async fn shutdown(&self) -> FileStorageResult<()> {
        self.log_operation(LogLevel::Info, "Shutting down MinIO adapter".to_string())
            .await;
        // rust-s3 handles connection cleanup automatically
        Ok(())
    }

    /// Get MinIO connection info for debugging
    pub fn get_connection_info(&self) -> String {
        format!(
            "{}://{}/{}",
            if self.config.secure { "https" } else { "http" },
            self.config.endpoint,
            self.config.bucket
        )
    }
}

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

    #[test]
    fn test_minio_config_default() {
        let config = MinioConfig::default();

        assert_eq!(config.endpoint, "localhost:9000");
        assert_eq!(config.access_key, "minioadmin");
        assert_eq!(config.secret_key, "minioadmin");
        assert_eq!(config.bucket, "paladin-files");
        assert_eq!(config.region, Some("us-east-1".to_string()));
        assert!(!config.secure);
        assert!(config.path_style);
        assert_eq!(config.connection_timeout, Duration::from_secs(30));
        assert_eq!(config.request_timeout, Duration::from_secs(300));
        assert_eq!(config.max_retries, 3);
        assert_eq!(config.max_idle_conns, 10);
    }

    #[test]
    fn test_minio_config_custom() {
        let config = MinioConfig {
            endpoint: "s3.amazonaws.com".to_string(),
            access_key: "AKIAIOSFODNN7EXAMPLE".to_string(),
            secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_string(),
            bucket: "my-bucket".to_string(),
            region: Some("us-west-2".to_string()),
            secure: true,
            path_style: false,
            connection_timeout: Duration::from_secs(60),
            request_timeout: Duration::from_secs(600),
            max_retries: 5,
            max_idle_conns: 20,
        };

        assert_eq!(config.endpoint, "s3.amazonaws.com");
        assert_eq!(config.access_key, "AKIAIOSFODNN7EXAMPLE");
        assert_eq!(config.bucket, "my-bucket");
        assert_eq!(config.region, Some("us-west-2".to_string()));
        assert!(config.secure);
        assert!(!config.path_style);
        assert_eq!(config.max_retries, 5);
        assert_eq!(config.max_idle_conns, 20);
    }

    #[test]
    fn test_minio_config_clone() {
        let config1 = MinioConfig::default();
        let config2 = config1.clone();

        assert_eq!(config1.endpoint, config2.endpoint);
        assert_eq!(config1.bucket, config2.bucket);
        assert_eq!(config1.max_retries, config2.max_retries);
    }

    #[test]
    fn test_minio_config_debug_format() {
        let config = MinioConfig::default();
        let debug_str = format!("{:?}", config);

        assert!(debug_str.contains("MinioConfig"));
        assert!(debug_str.contains("endpoint"));
        assert!(debug_str.contains("localhost:9000"));
    }

    #[test]
    fn test_minio_config_serialization() {
        let config = MinioConfig::default();

        // Test that serialization works (actual values would require serde_json)
        let serialized = serde_json::to_string(&config).expect("Should serialize");
        assert!(serialized.contains("localhost:9000"));
        assert!(serialized.contains("paladin-files"));

        // Test deserialization
        let deserialized: MinioConfig =
            serde_json::from_str(&serialized).expect("Should deserialize");
        assert_eq!(deserialized.endpoint, config.endpoint);
        assert_eq!(deserialized.bucket, config.bucket);
    }

    #[test]
    fn test_minio_config_with_optional_region() {
        let config_with_region = MinioConfig {
            region: Some("eu-west-1".to_string()),
            ..Default::default()
        };
        assert_eq!(config_with_region.region, Some("eu-west-1".to_string()));

        let config_without_region = MinioConfig {
            region: None,
            ..Default::default()
        };
        assert_eq!(config_without_region.region, None);
    }

    #[test]
    fn test_minio_config_timeout_values() {
        let config = MinioConfig {
            connection_timeout: Duration::from_secs(10),
            request_timeout: Duration::from_secs(120),
            ..Default::default()
        };

        assert_eq!(config.connection_timeout.as_secs(), 10);
        assert_eq!(config.request_timeout.as_secs(), 120);
    }

    #[test]
    fn test_minio_config_retry_settings() {
        let config = MinioConfig {
            max_retries: 0,
            ..Default::default()
        };
        assert_eq!(config.max_retries, 0);

        let config_with_retries = MinioConfig {
            max_retries: 10,
            ..Default::default()
        };
        assert_eq!(config_with_retries.max_retries, 10);
    }

    #[test]
    fn test_minio_config_secure_https_endpoint() {
        let secure_config = MinioConfig {
            endpoint: "s3.amazonaws.com".to_string(),
            secure: true,
            ..Default::default()
        };
        assert!(secure_config.secure);

        let insecure_config = MinioConfig {
            endpoint: "localhost:9000".to_string(),
            secure: false,
            ..Default::default()
        };
        assert!(!insecure_config.secure);
    }

    #[test]
    fn test_minio_config_path_style_setting() {
        let path_style_config = MinioConfig {
            path_style: true,
            ..Default::default()
        };
        assert!(path_style_config.path_style);

        let virtual_hosted_config = MinioConfig {
            path_style: false,
            ..Default::default()
        };
        assert!(!virtual_hosted_config.path_style);
    }

    // Note: Tests requiring actual MinIO connection are in integration tests
    // The following would require mocking or actual MinIO instance:
    // - new()
    // - upload_file()
    // - download_file()
    // - delete_file()
    // - list_files()
    // - health_check()
}