lake-pulse 0.2.2

A Rust library for analyzing data lake table health across multiple formats and storage providers.
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
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
// Copyright 2025 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.
//
// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.

use super::config::{StorageConfig, StorageType};
use super::error::{StorageError, StorageResult};
use super::provider::{string_to_path, FileMetadata, StorageProvider};
use crate::util::retry::retry_with_max_retries;
use async_trait::async_trait;
use bytes::Bytes;
use futures::stream::StreamExt;
use hdfs_native_object_store::HdfsObjectStoreBuilder;
use object_store::{
    aws::AmazonS3Builder, azure::MicrosoftAzureBuilder, gcp::GoogleCloudStorageBuilder,
    http::HttpBuilder, local::LocalFileSystem, ClientOptions, ObjectStore, ObjectStoreExt,
    RetryConfig,
};
use std::collections::HashMap;
use std::fmt::{Debug, Formatter};
use std::future::Future;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tracing::info;

/// Generic storage provider that works with any object_store backend
pub struct ObjectStoreProvider {
    pub config: StorageConfig,
    pub store: Arc<dyn ObjectStore>,
    pub base_path: String,
}

impl ObjectStoreProvider {
    /// Create a new generic storage provider from configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - Storage configuration specifying the storage type and options
    ///
    /// # Returns
    ///
    /// A `Result` containing:
    /// * `Ok(GenericStorageProvider)` - A configured storage provider ready to use
    /// * `Err(StorageError)` - If the storage backend cannot be initialized
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// * The storage configuration is invalid
    /// * Required configuration options are missing
    /// * The storage backend cannot be created (e.g., invalid credentials, network issues)
    pub async fn new(config: StorageConfig) -> StorageResult<Self> {
        let (store, base_path) = Self::build_store(&config).await?;

        Ok(Self {
            config,
            store: Arc::new(store),
            base_path,
        })
    }

    /// Build the appropriate object store based on configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - Storage configuration specifying the storage type and options
    ///
    /// # Returns
    ///
    /// A `Result` containing:
    /// * `Ok((Box<dyn ObjectStore>, String))` - A tuple of the object store and base path/URL
    /// * `Err(StorageError)` - If the object store cannot be built
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// * The storage type is not supported
    /// * Required configuration options are missing for the storage type
    /// * The object store backend cannot be initialized
    async fn build_store(config: &StorageConfig) -> StorageResult<(Box<dyn ObjectStore>, String)> {
        match config.storage_type {
            StorageType::Local => Self::build_local_store(config),
            StorageType::Aws => Self::build_aws_store(config),
            StorageType::Azure => Self::build_azure_store(config),
            StorageType::Gcs => Self::build_gcs_store(config),
            StorageType::Hdfs => Self::build_hdfs_store(config),
            StorageType::Http => Self::build_http_store(config),
        }
    }

    /// Build a local filesystem store.
    ///
    /// # Arguments
    ///
    /// * `config` - Storage configuration with 'path' option specifying the local directory
    ///
    /// # Returns
    ///
    /// A `Result` containing:
    /// * `Ok((Box<dyn ObjectStore>, String))` - A tuple of the local filesystem store and canonical path
    /// * `Err(StorageError)` - If the local store cannot be created
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// * The 'path' option is missing from configuration
    /// * The path cannot be canonicalized (doesn't exist or permission denied)
    /// * The path is not a directory
    /// * The local filesystem store cannot be created
    fn build_local_store(config: &StorageConfig) -> StorageResult<(Box<dyn ObjectStore>, String)> {
        let path = config.options.get("path").ok_or_else(|| {
            StorageError::ConfigError("Local storage requires 'path' option".to_string())
        })?;
        let base_path = PathBuf::from(path);

        // Canonicalize the path (handles both relative and absolute paths, resolves symlinks)
        let canonical_path = base_path.canonicalize().map_err(|e| {
            StorageError::ConfigError(format!(
                "Failed to resolve path '{}': {} (path must exist)",
                path, e
            ))
        })?;

        if !canonical_path.is_dir() {
            return Err(StorageError::ConfigError(format!(
                "Base path is not a directory: {}",
                canonical_path.display()
            )));
        }

        let store = LocalFileSystem::new_with_prefix(&canonical_path).map_err(|e| {
            StorageError::ConfigError(format!("Failed to create local store: {}", e))
        })?;

        let base_path_str = canonical_path.to_string_lossy().to_string();
        Ok((Box::new(store), base_path_str))
    }

    /// Build connection options from configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - Storage configuration with optional timeout and connection settings
    ///
    /// # Returns
    ///
    /// A `ClientOptions` instance configured with timeout and connection settings from the config.
    fn build_connection_options(config: &StorageConfig) -> ClientOptions {
        let mut client_options = ClientOptions::default();
        if let Some(timeout_str) = config.options.get("timeout") {
            if timeout_str == "0" || timeout_str == "disabled" {
                client_options = client_options.with_timeout_disabled();
            } else if let Ok(sec) = timeout_str.parse::<u64>() {
                client_options = client_options.with_timeout(Duration::from_secs(sec))
            }
        };
        if let Some(connect_timeout_str) = config.options.get("connect_timeout") {
            if connect_timeout_str == "0" || connect_timeout_str == "disabled" {
                client_options = client_options.with_connect_timeout_disabled();
            } else if let Ok(ms) = connect_timeout_str.parse::<u64>() {
                client_options = client_options.with_connect_timeout(Duration::from_secs(ms))
            }
        }
        if let Some(pool_idle_timeout_str) = config.options.get("pool_idle_timeout") {
            if let Ok(sec) = pool_idle_timeout_str.parse::<u64>() {
                client_options = client_options.with_pool_idle_timeout(Duration::from_secs(sec))
            }
        }
        if let Some(pool_max_idle_per_host_str) = config.options.get("pool_max_idle_per_host") {
            if let Ok(max_idle) = pool_max_idle_per_host_str.parse::<usize>() {
                client_options = client_options.with_pool_max_idle_per_host(max_idle)
            }
        }
        client_options
    }

    /// Build retry options from configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - Storage configuration with optional max_retries and retry_timeout settings
    ///
    /// # Returns
    ///
    /// A `RetryConfig` instance configured with retry settings from the config.
    fn build_retry_options(config: &StorageConfig) -> RetryConfig {
        let default_retry_config = RetryConfig::default();
        let max_retries = config
            .options
            .get("max_retries")
            .and_then(|s| s.parse::<usize>().ok())
            .unwrap_or(default_retry_config.max_retries);
        let retry_timeout = config
            .options
            .get("retry_timeout")
            .and_then(|s| Some(Duration::from_secs(s.parse::<u64>().ok()?)))
            .unwrap_or(default_retry_config.retry_timeout);
        RetryConfig {
            backoff: Default::default(),
            max_retries,
            retry_timeout,
        }
    }

    /// Get max retries from config.
    ///
    /// # Arguments
    ///
    /// * `config` - Storage configuration with optional max_retries setting
    ///
    /// # Returns
    ///
    /// The maximum number of retries (defaults to 10 if not specified).
    fn get_max_retries(config: &StorageConfig) -> usize {
        config
            .options
            .get("max_retries")
            .and_then(|s| s.parse::<usize>().ok())
            .unwrap_or(10)
    }

    /// Retry wrapper for operations that may fail due to transient network errors.
    ///
    /// # Arguments
    ///
    /// * `operation_name` - Name of the operation for logging purposes
    /// * `operation` - The async operation to retry
    ///
    /// # Returns
    ///
    /// A `Result` containing:
    /// * `Ok(T)` - The successful result from the operation
    /// * `Err(StorageError)` - If all retry attempts fail
    async fn retry_operation<F, Fut, T>(
        &self,
        operation_name: &str,
        operation: F,
    ) -> StorageResult<T>
    where
        F: FnMut() -> Fut,
        Fut: Future<Output = StorageResult<T>>,
    {
        let max_retries = Self::get_max_retries(&self.config);
        retry_with_max_retries(max_retries, operation_name, operation).await
    }

    /// Build an AWS S3 store.
    ///
    /// # Arguments
    ///
    /// * `config` - Storage configuration with AWS S3 options (bucket, region, credentials, etc.)
    ///
    /// # Returns
    ///
    /// A `Result` containing:
    /// * `Ok((Box<dyn ObjectStore>, String))` - A tuple of the S3 store and base S3 URL
    /// * `Err(StorageError)` - If the S3 store cannot be created
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// * Required S3 configuration options are missing
    /// * AWS credentials are invalid
    /// * The S3 store cannot be initialized
    fn build_aws_store(config: &StorageConfig) -> StorageResult<(Box<dyn ObjectStore>, String)> {
        let mut builder = AmazonS3Builder::new()
            .with_client_options(Self::build_connection_options(config))
            .with_retry(Self::build_retry_options(config));
        let mut bucket: Option<&String> = None;
        let mut endpoint: Option<&String> = None;

        // Apply configuration options
        for (key, value) in &config.options {
            match key.as_str() {
                "bucket" => {
                    bucket = Some(value);
                    builder = builder.with_bucket_name(value);
                }
                "region" => builder = builder.with_region(value),
                "access_key_id" => builder = builder.with_access_key_id(value),
                "secret_access_key" => builder = builder.with_secret_access_key(value),
                "session_token" | "token" => builder = builder.with_token(value),
                "endpoint" => {
                    endpoint = Some(value);
                    builder = builder.with_endpoint(value);
                }
                "allow_http" => {
                    if value.to_lowercase() == "true" {
                        builder = builder.with_allow_http(true);
                    }
                }
                // Already handled by `build_connection_options` and `build_retry_options`
                "timeout"
                | "connect_timeout"
                | "max_retries"
                | "retry_timeout"
                | "pool_idle_timeout"
                | "pool_max_idle_per_host" => (),
                _ => {
                    // Ignore unknown options or log a warning
                    tracing::warn!("Unknown AWS S3 option: {}", key);
                }
            }
        }

        let store = builder
            .build()
            .map_err(|e| StorageError::ConfigError(format!("Failed to create S3 store: {}", e)))?;

        // Construct base URL
        let base_url = if let Some(endpoint_url) = endpoint {
            // If custom endpoint is provided, use it
            endpoint_url.trim_end_matches('/').to_string()
        } else if let Some(bucket_name) = bucket {
            // Standard S3 URL format
            format!("s3://{}", bucket_name)
        } else {
            // No bucket specified (unusual but possible)
            "s3://".to_string()
        };

        Ok((Box::new(store), base_url))
    }

    /// Build an Azure store.
    ///
    /// # Arguments
    ///
    /// * `config` - Storage configuration with Azure options (account, container, credentials, etc.)
    ///
    /// # Returns
    ///
    /// A `Result` containing:
    /// * `Ok((Box<dyn ObjectStore>, String))` - A tuple of the Azure store and base Azure URL
    /// * `Err(StorageError)` - If the Azure store cannot be created
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// * Required Azure configuration options are missing
    /// * Azure credentials are invalid
    /// * The Azure store cannot be initialized
    fn build_azure_store(config: &StorageConfig) -> StorageResult<(Box<dyn ObjectStore>, String)> {
        let mut builder = MicrosoftAzureBuilder::new()
            .with_client_options(Self::build_connection_options(config))
            .with_retry(Self::build_retry_options(config));

        // Account name is required for Azure
        let mut account_name = config.get_option("account_name").ok_or_else(|| {
            StorageError::ConfigError("Azure requires 'account_name' option".to_string())
        })?;
        let mut container = config.get_option("container").ok_or_else(|| {
            StorageError::ConfigError("Azure requires 'container' option".to_string())
        })?;

        builder = builder.with_account(account_name);

        // Track if we should use fabric endpoint
        let mut use_fabric_endpoint = false;
        let mut custom_endpoint: Option<&String> = None;

        // Apply configuration options
        for (key, value) in &config.options {
            match key.as_str() {
                "container" => {
                    container = value;
                    builder = builder.with_container_name(value)
                }
                "account_name" => {
                    account_name = value;
                    builder = builder.with_account(value)
                }
                "access_key" | "account_key" => builder = builder.with_access_key(value),
                "sas_token" => {
                    // Parse SAS token query parameters
                    let pairs: Vec<(String, String)> = value
                        .trim_start_matches('?')
                        .split('&')
                        .filter_map(|pair| {
                            let mut parts = pair.split('=');
                            match (parts.next(), parts.next()) {
                                (Some(k), Some(v)) => Some((k.to_string(), v.to_string())),
                                _ => None,
                            }
                        })
                        .collect();
                    builder = builder.with_sas_authorization(pairs);
                }
                "tenant_id" => builder = builder.with_tenant_id(value),
                "client_id" => builder = builder.with_client_id(value),
                "client_secret" => builder = builder.with_client_secret(value),
                "use_fabric_endpoint" => {
                    use_fabric_endpoint = value.to_lowercase() == "true";
                    builder = builder.with_use_fabric_endpoint(use_fabric_endpoint);
                }
                "endpoint" => {
                    custom_endpoint = Some(value);
                    builder = builder.with_endpoint(value.clone());
                }
                // Already handled by `build_connection_options` and `build_retry_options`
                "timeout"
                | "connect_timeout"
                | "max_retries"
                | "retry_timeout"
                | "pool_idle_timeout"
                | "pool_max_idle_per_host" => (),
                _ => {
                    // Ignore unknown options or log a warning
                    tracing::info!("Unknown Azure option: {}", key);
                }
            }
        }

        let store = builder.build().map_err(|e| {
            StorageError::ConfigError(format!("Failed to create Azure store: {}", e))
        })?;

        // Construct base URL
        // Format: abfss://<container>@<account>.<endpoint>/
        let base_url = if let Some(endpoint) = custom_endpoint {
            // If custom endpoint is provided, use it
            endpoint.trim_end_matches('/').to_string()
        } else {
            // Determine the endpoint based on configuration
            let endpoint_domain = if use_fabric_endpoint {
                "dfs.fabric.microsoft.com"
            } else {
                "dfs.core.windows.net"
            };

            // Use abfss:// (secure) protocol with fully qualified domain
            format!("abfss://{}@{}.{}", container, account_name, endpoint_domain)
        };

        Ok((Box::new(store), base_url))
    }

    /// Build a GCS store.
    ///
    /// # Arguments
    ///
    /// * `config` - Storage configuration with GCS options (bucket, credentials, etc.)
    ///
    /// # Returns
    ///
    /// A `Result` containing:
    /// * `Ok((Box<dyn ObjectStore>, String))` - A tuple of the GCS store and base GCS URL
    /// * `Err(StorageError)` - If the GCS store cannot be created
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// * Required GCS configuration options are missing
    /// * GCS credentials are invalid
    /// * The GCS store cannot be initialized
    fn build_gcs_store(config: &StorageConfig) -> StorageResult<(Box<dyn ObjectStore>, String)> {
        let mut builder = GoogleCloudStorageBuilder::new()
            .with_client_options(Self::build_connection_options(config))
            .with_retry(Self::build_retry_options(config));
        let mut bucket: Option<&String> = None;

        // Apply configuration options
        for (key, value) in &config.options {
            match key.as_str() {
                "bucket" => {
                    bucket = Some(value);
                    builder = builder.with_bucket_name(value);
                }
                "service_account_key_path" => builder = builder.with_service_account_path(value),
                "service_account_key" => builder = builder.with_service_account_key(value),
                // Already handled by `build_connection_options` and `build_retry_options`
                "timeout"
                | "connect_timeout"
                | "max_retries"
                | "retry_timeout"
                | "pool_idle_timeout"
                | "pool_max_idle_per_host" => (),
                _ => {
                    // Ignore unknown options or log a warning
                    tracing::warn!("Unknown GCS option: {}", key);
                }
            }
        }

        let store = builder
            .build()
            .map_err(|e| StorageError::ConfigError(format!("Failed to create GCS store: {}", e)))?;

        // Construct base URL
        let base_url = if let Some(bucket_name) = bucket {
            format!("gs://{}", bucket_name)
        } else {
            // No bucket specified (unusual but possible)
            "gs://".to_string()
        };

        Ok((Box::new(store), base_url))
    }

    /// Build an HDFS store.
    ///
    /// # Arguments
    ///
    /// * `config` - Storage configuration with HDFS options (url)
    ///
    /// # Returns
    ///
    /// A `Result` containing:
    /// * `Ok((Box<dyn ObjectStore>, String))` - A tuple of the HDFS store and base HDFS URL
    /// * `Err(StorageError)` - If the HDFS store cannot be created
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// * The 'url' option is missing from configuration
    /// * The HDFS store cannot be initialized (e.g., invalid URL, connection issues)
    fn build_hdfs_store(config: &StorageConfig) -> StorageResult<(Box<dyn ObjectStore>, String)> {
        let url = config.options.get("url").ok_or_else(|| {
            StorageError::ConfigError("HDFS storage requires 'url' option".to_string())
        })?;

        let store = HdfsObjectStoreBuilder::new()
            .with_url(url)
            .build()
            .map_err(|e| {
                StorageError::ConfigError(format!("Failed to create HDFS store: {}", e))
            })?;

        Ok((Box::new(store), url.clone()))
    }

    /// Build an HTTP/WebDAV store.
    ///
    /// # Arguments
    ///
    /// * `config` - Storage configuration with HTTP options (url)
    ///
    /// # Returns
    ///
    /// A `Result` containing:
    /// * `Ok((Box<dyn ObjectStore>, String))` - A tuple of the HTTP store and base URL
    /// * `Err(StorageError)` - If the HTTP store cannot be created
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// * The 'url' option is missing from configuration
    /// * The HTTP store cannot be initialized (e.g., invalid URL)
    ///
    /// # Notes
    ///
    /// This store supports both basic HTTP servers (read-only via GET) and
    /// WebDAV-compliant servers (full read/write/list operations via RFC 2518).
    fn build_http_store(config: &StorageConfig) -> StorageResult<(Box<dyn ObjectStore>, String)> {
        let url = config.options.get("url").ok_or_else(|| {
            StorageError::ConfigError("HTTP storage requires 'url' option".to_string())
        })?;

        let builder = HttpBuilder::new()
            .with_url(url)
            .with_client_options(Self::build_connection_options(config))
            .with_retry(Self::build_retry_options(config));

        let store = builder.build().map_err(|e| {
            StorageError::ConfigError(format!("Failed to create HTTP store: {}", e))
        })?;

        Ok((Box::new(store), url.clone()))
    }

    /// List multiple partitions in parallel with bounded concurrency.
    ///
    /// This method lists each partition concurrently, which can provide significant
    /// speedup for tables with many partitions.
    ///
    /// # Arguments
    ///
    /// * `partitions` - Vector of partition paths to list
    /// * `parallelism` - Maximum number of concurrent partition listing operations
    ///
    /// # Returns
    ///
    /// A `Result` containing:
    /// * `Ok(Vec<FileMetadata>)` - All files from all partitions combined
    /// * `Err(StorageError)` - If any partition listing fails
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// * Any partition cannot be listed
    /// * Network or storage access errors occur
    /// * File metadata cannot be retrieved
    async fn list_partitions_parallel(
        &self,
        partitions: Vec<String>,
        parallelism: usize,
    ) -> StorageResult<Vec<FileMetadata>> {
        use futures::stream;

        let parallelism = parallelism.max(1);

        let store = Arc::clone(&self.store);
        let config = self.config.clone();

        // List each partition in parallel
        let results: Vec<StorageResult<Vec<FileMetadata>>> = stream::iter(partitions)
            .map(|partition_path| {
                info!("Listing partition={}", &partition_path);
                let store_clone = Arc::clone(&store);
                let max_retries = Self::get_max_retries(&config);
                async move {
                    // Use the retry helper function
                    retry_with_max_retries(
                        max_retries,
                        &format!("list_partition({})", partition_path),
                        || async {
                            let mut files = Vec::new();
                            let path = string_to_path(&partition_path);
                            let mut stream = store_clone.list(Some(&path));

                            while let Some(meta) = stream.next().await {
                                let meta = meta?;
                                files.push(FileMetadata {
                                    path: meta.location.to_string(),
                                    size: meta.size,
                                    last_modified: Some(meta.last_modified),
                                });
                            }

                            info!(
                                "Listed partition={}, found count={} files",
                                string_to_path(&partition_path),
                                files.len()
                            );

                            Ok(files)
                        },
                    )
                    .await
                }
            })
            .buffer_unordered(parallelism)
            .collect()
            .await;

        info!(
            "Collected count={} first level partitions, parallelism={}",
            results.len(),
            parallelism
        );

        // Flatten results and handle errors
        let mut all_files = Vec::new();
        for result in results {
            all_files.extend(result?);
        }

        info!(
            "Found count={} total files across all partitions, parallelism={}",
            all_files.len(),
            parallelism,
        );

        Ok(all_files)
    }
}

#[async_trait]
impl StorageProvider for ObjectStoreProvider {
    fn base_path(&self) -> &str {
        &self.base_path
    }

    async fn validate_connection(&self, path: &str) -> StorageResult<()> {
        // For local filesystem, check if the base path is accessible
        if self.config.storage_type == StorageType::Local {
            let mut path_url = PathBuf::from(&self.base_path);
            path_url.push(path);
            return if path_url.exists() && path_url.is_dir() {
                Ok(())
            } else {
                Err(StorageError::ConnectionError(format!(
                    "Base path is not accessible: {}",
                    path
                )))
            };
        }

        // For cloud providers, try to list objects at the root to validate connection
        self.store.list_with_delimiter(None).await?;
        Ok(())
    }

    async fn list_files(&self, path: &str, recursive: bool) -> StorageResult<Vec<FileMetadata>> {
        let path_str = path.to_string();
        let store = Arc::clone(&self.store);

        self.retry_operation(&format!("list_files({})", path), || async {
            let object_path = if path_str.is_empty() {
                None
            } else {
                Some(string_to_path(&path_str))
            };

            let mut files = Vec::new();

            if recursive {
                let mut stream = store.list(object_path.as_ref());

                while let Some(meta) = stream.next().await {
                    let meta = meta?;
                    files.push(FileMetadata {
                        path: meta.location.to_string(),
                        size: meta.size,
                        last_modified: Some(meta.last_modified),
                    });
                }
            } else {
                let list_result = store.list_with_delimiter(object_path.as_ref()).await?;

                for meta in list_result.objects {
                    files.push(FileMetadata {
                        path: meta.location.to_string(),
                        size: meta.size,
                        last_modified: Some(meta.last_modified),
                    });
                }
            }

            Ok(files)
        })
        .await
    }

    async fn discover_partitions(
        &self,
        path: &str,
        exclude_prefixes: Vec<&str>,
    ) -> StorageResult<Vec<String>> {
        let path_str = path.to_string();
        let exclude_prefixes_owned: Vec<String> =
            exclude_prefixes.iter().map(|s| s.to_string()).collect();
        let store = Arc::clone(&self.store);

        self.retry_operation(&format!("discover_partitions({})", path), || async {
            let object_path = if path_str.is_empty() {
                None
            } else {
                Some(string_to_path(&path_str))
            };

            let list_result = store.list_with_delimiter(object_path.as_ref()).await?;

            // Extract directory paths from common_prefixes
            let partitions: Vec<String> = list_result
                .common_prefixes
                .iter()
                .map(|prefix| prefix.to_string())
                .filter(|prefix| !exclude_prefixes_owned.iter().any(|p| prefix.contains(p)))
                .collect();

            Ok(partitions)
        })
        .await
    }

    async fn list_files_parallel(
        &self,
        path: &str,
        partitions: Vec<String>,
        parallelism: usize,
    ) -> StorageResult<Vec<FileMetadata>> {
        let path_str = path.to_string();
        let store = Arc::clone(&self.store);

        // List files at the root path with retry
        let mut all_files: Vec<FileMetadata> = self
            .retry_operation(&format!("list_files_parallel_root({})", path), || async {
                let object_path = if path_str.is_empty() {
                    None
                } else {
                    Some(string_to_path(&path_str))
                };

                let list_result = store.list_with_delimiter(object_path.as_ref()).await?;

                let files: Vec<FileMetadata> = list_result
                    .objects
                    .into_iter()
                    .map(|meta| FileMetadata {
                        path: meta.location.to_string(),
                        size: meta.size,
                        last_modified: Some(meta.last_modified),
                    })
                    .collect();

                Ok(files)
            })
            .await?;

        if !partitions.is_empty() {
            info!(
                "Found count={} first level partitions at location={}, now listing with parallelism={}",
                partitions.len(),
                path,
                parallelism
            );

            // Parallel listing of partitions (already has retry logic)
            let partition_files = self
                .list_partitions_parallel(partitions.clone(), parallelism)
                .await?;
            all_files.extend(partition_files);
        } else {
            // No partitions found, use standard recursive list with retry
            tracing::debug!(
                "No partitions found at location={}, using standard recursive listing",
                path
            );

            let recursive_files = self
                .retry_operation(
                    &format!("list_files_parallel_recursive({})", path),
                    || async {
                        let object_path = if path_str.is_empty() {
                            None
                        } else {
                            Some(string_to_path(&path_str))
                        };

                        let mut files = Vec::new();
                        let mut stream = store.list(object_path.as_ref());
                        while let Some(meta) = stream.next().await {
                            let meta = meta?;
                            files.push(FileMetadata {
                                path: meta.location.to_string(),
                                size: meta.size,
                                last_modified: Some(meta.last_modified),
                            });
                        }
                        Ok(files)
                    },
                )
                .await?;

            all_files.extend(recursive_files);
        }

        info!(
            "Found count={} partitions and file_count={} at location={}",
            partitions.len(),
            all_files.len(),
            path
        );

        Ok(all_files)
    }

    async fn read_file(&self, path: &str) -> StorageResult<Vec<u8>> {
        let object_path = string_to_path(path);
        let result = self.store.get(&object_path).await?;
        let bytes: Bytes = result.bytes().await?;
        Ok(bytes.to_vec())
    }

    async fn exists(&self, path: &str) -> StorageResult<bool> {
        let object_path = string_to_path(path);
        match self.store.head(&object_path).await {
            Ok(_) => Ok(true),
            Err(object_store::Error::NotFound { .. }) => Ok(false),
            Err(e) => Err(e.into()),
        }
    }

    async fn get_metadata(&self, path: &str) -> StorageResult<FileMetadata> {
        let object_path = string_to_path(path);
        let meta = self.store.head(&object_path).await?;

        Ok(FileMetadata {
            path: meta.location.to_string(),
            size: meta.size as u64,
            last_modified: Some(meta.last_modified),
        })
    }

    fn options(&self) -> &HashMap<String, String> {
        &self.config.options
    }

    fn clean_options(&self) -> HashMap<String, String> {
        self.config
            .options
            .clone()
            .into_iter()
            .filter(|(k, _)| {
                ![
                    "retry_timeout",
                    "timeout",
                    "connect_timeout",
                    "max_retries",
                    "pool_idle_timeout",
                    "pool_max_idle_per_host",
                ]
                .contains(&k.as_str())
            })
            .collect::<HashMap<_, _>>()
    }

    fn uri_from_path(&self, path: &str) -> String {
        fn fix_uri(storage_type: &StorageType, path: &str) -> String {
            if storage_type == &StorageType::Local {
                // Normalize file:// URIs to canonical format
                // Handle paths like "file:///path", "file://path", "file:/path", or "/path"
                // Also convert backslashes to forward slashes for Windows compatibility
                let path = path.replace('\\', "/");

                // Remove Windows extended-length path prefix (\\?\ or //?/)
                // This prefix is added by canonicalize() on Windows
                let path = path.strip_prefix("//?/").unwrap_or(&path).to_string();

                let path_without_scheme = if let Some(without_scheme) = path.strip_prefix("file:") {
                    // Had file: prefix - strip it and any leading slashes
                    without_scheme.trim_start_matches('/').to_string()
                } else if path.starts_with('/') {
                    // Unix absolute path - remove leading slash, we'll add it back
                    path.trim_start_matches('/').to_string()
                } else {
                    // Windows absolute path (C:/...) or relative path
                    path.to_string()
                };

                // file:// URIs require three slashes before the path:
                // - Unix: file:///home/user/... (file:// + / + home/user/...)
                // - Windows: file:///C:/Users/... (file:// + / + C:/Users/...)
                format!("file:///{}", path_without_scheme)
            } else {
                path.to_string()
            }
        }

        let fp = if path.contains(&self.base_path) {
            path.to_string()
        } else {
            format!("{}/{}", self.base_path, path.trim_start_matches('/'))
        };

        fix_uri(&self.config.storage_type, fp.as_str())
    }
}

impl Debug for ObjectStoreProvider {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "StorageProvider(type=generic, cloud_provider={}, config={:?})",
            self.config.storage_type_str(),
            self.config
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_build_connection_options_default() {
        let config = StorageConfig::local();
        let _options = ObjectStoreProvider::build_connection_options(&config);
        // No assertion, just make sure is does not panic
    }

    #[test]
    fn test_build_connection_options_with_timeout() {
        let config = StorageConfig::local()
            .with_option("timeout", "60")
            .with_option("connect_timeout", "10");

        let _options = ObjectStoreProvider::build_connection_options(&config);
        // No assertion, just make sure is does not panic
    }

    #[test]
    fn test_build_connection_options_disabled_timeout() {
        let config = StorageConfig::local()
            .with_option("timeout", "disabled")
            .with_option("connect_timeout", "0");

        let _options = ObjectStoreProvider::build_connection_options(&config);
        // No assertion, just make sure is does not panic
    }

    #[test]
    fn test_build_connection_options_with_pool_settings() {
        let config = StorageConfig::local()
            .with_option("pool_idle_timeout", "30")
            .with_option("pool_max_idle_per_host", "10");

        let _options = ObjectStoreProvider::build_connection_options(&config);
        // No assertion, just make sure is does not panic
    }

    #[test]
    fn test_build_connection_options_invalid_values() {
        let config = StorageConfig::local()
            .with_option("timeout", "invalid")
            .with_option("pool_max_idle_per_host", "not_a_number");

        // Should handle invalid values gracefully
        let _options = ObjectStoreProvider::build_connection_options(&config);
        // No assertion, just make sure is does not panic
    }

    #[test]
    fn test_build_retry_options_default() {
        let config = StorageConfig::local();
        let retry_config = ObjectStoreProvider::build_retry_options(&config);

        // Should use default values from config
        assert!(retry_config.max_retries > 0);
    }

    #[test]
    fn test_build_retry_options_custom() {
        let config = StorageConfig::local()
            .with_option("max_retries", "5")
            .with_option("retry_timeout", "300");

        let retry_config = ObjectStoreProvider::build_retry_options(&config);
        assert_eq!(retry_config.max_retries, 5);
        assert_eq!(retry_config.retry_timeout, Duration::from_secs(300));
    }

    #[test]
    fn test_build_retry_options_invalid_values() {
        let config = StorageConfig::local()
            .with_option("max_retries", "invalid")
            .with_option("retry_timeout", "not_a_number");

        let retry_config = ObjectStoreProvider::build_retry_options(&config);
        // Should fall back to defaults
        assert!(retry_config.max_retries > 0);
    }

    #[test]
    fn test_get_max_retries_default() {
        let config = StorageConfig::local();
        let max_retries = ObjectStoreProvider::get_max_retries(&config);

        // Should return default value from config (20) or fallback (10)
        // StorageConfig::local() sets default_options which includes max_retries=20
        assert_eq!(max_retries, 20);
    }

    #[test]
    fn test_get_max_retries_custom() {
        let config = StorageConfig::local().with_option("max_retries", "15");
        let max_retries = ObjectStoreProvider::get_max_retries(&config);

        assert_eq!(max_retries, 15);
    }

    #[test]
    fn test_get_max_retries_invalid() {
        let config = StorageConfig::local().with_option("max_retries", "invalid");
        let max_retries = ObjectStoreProvider::get_max_retries(&config);

        // Should fall back to default
        assert_eq!(max_retries, 10);
    }

    #[tokio::test]
    async fn test_new_local_provider() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await;

        assert!(provider.is_ok());
        let provider = provider.unwrap();
        // On Windows, canonicalize() adds \\?\ prefix and converts 8.3 short names to long names
        // (e.g., RUNNER~1 -> runneradmin), so we need to canonicalize both paths for comparison
        let base_path = provider.base_path.replace("\\\\?\\", "").replace('\\', "/");
        let canonical_temp = temp_dir
            .path()
            .canonicalize()
            .unwrap()
            .to_str()
            .unwrap()
            .replace("\\\\?\\", "")
            .replace('\\', "/");
        assert!(
            base_path.contains(&canonical_temp),
            "base_path '{}' should contain '{}'",
            base_path,
            canonical_temp
        );
        assert_eq!(provider.config.storage_type, StorageType::Local);
    }

    #[tokio::test]
    async fn test_new_local_provider_invalid_path() {
        let config = StorageConfig::local().with_option("path", "/nonexistent/invalid/path");
        let provider = ObjectStoreProvider::new(config).await;

        assert!(provider.is_err());
        match provider {
            Err(StorageError::ConfigError(msg)) => {
                assert!(msg.contains("Failed to resolve path"));
            }
            _ => panic!("Expected ConfigError"),
        }
    }

    #[tokio::test]
    async fn test_new_local_provider_missing_path() {
        let config = StorageConfig::local();
        let provider = ObjectStoreProvider::new(config).await;

        assert!(provider.is_err());
        match provider {
            Err(StorageError::ConfigError(msg)) => {
                assert!(msg.contains("path"));
            }
            _ => panic!("Expected ConfigError for missing path"),
        }
    }

    #[tokio::test]
    async fn test_new_local_provider_file_not_directory() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test_file.txt");
        fs::write(&file_path, "test content").unwrap();

        let config = StorageConfig::local().with_option("path", file_path.to_str().unwrap());
        let provider = ObjectStoreProvider::new(config).await;

        assert!(provider.is_err());
        match provider {
            Err(StorageError::ConfigError(msg)) => {
                assert!(msg.contains("not a directory"));
            }
            _ => panic!("Expected ConfigError for file instead of directory"),
        }
    }

    #[tokio::test]
    async fn test_provider_base_path() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        let base_path = provider.base_path();
        assert!(!base_path.is_empty());
        // On Windows, canonicalize() adds \\?\ prefix and converts 8.3 short names to long names
        // (e.g., RUNNER~1 -> runneradmin), so we need to canonicalize both paths for comparison
        let normalized_base_path = base_path.replace("\\\\?\\", "").replace('\\', "/");
        let canonical_temp = temp_dir
            .path()
            .canonicalize()
            .unwrap()
            .to_str()
            .unwrap()
            .replace("\\\\?\\", "")
            .replace('\\', "/");
        assert!(
            normalized_base_path.contains(&canonical_temp),
            "base_path '{}' should contain '{}'",
            normalized_base_path,
            canonical_temp
        );
    }

    #[tokio::test]
    async fn test_provider_options() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        let config = StorageConfig::local()
            .with_option("path", temp_path)
            .with_option("custom_option", "custom_value");
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        let options = provider.options();
        assert!(options.contains_key("path"));
        assert!(options.contains_key("custom_option"));
        assert_eq!(options.get("custom_option").unwrap(), "custom_value");
    }

    #[tokio::test]
    async fn test_provider_clean_options() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        let config = StorageConfig::local()
            .with_option("path", temp_path)
            .with_option("timeout", "60")
            .with_option("max_retries", "10")
            .with_option("custom_option", "custom_value");
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        let clean_options = provider.clean_options();

        // Clean options should exclude internal retry/timeout options
        assert!(!clean_options.contains_key("timeout"));
        assert!(!clean_options.contains_key("max_retries"));
        assert!(!clean_options.contains_key("retry_timeout"));
        assert!(!clean_options.contains_key("connect_timeout"));

        // But should include custom options
        assert!(clean_options.contains_key("path"));
        assert!(clean_options.contains_key("custom_option"));
    }

    #[tokio::test]
    async fn test_uri_from_path_local() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        let uri = provider.uri_from_path("test/file.txt");
        assert!(uri.starts_with("file://"));
        assert!(uri.contains("test"));
        assert!(uri.contains("file.txt"));

        // Verify the URI format is valid for delta-rs
        // On Unix: file:///tmp/... (file:// + /tmp/...)
        // On Windows: file:///C:/... (file:// + / + C:/...)
        #[cfg(unix)]
        {
            // Unix absolute paths start with /, so URI should have file:// followed by /
            assert!(
                uri.starts_with("file:///"),
                "Unix absolute path URI should start with file:/// but got: {}",
                uri
            );
        }

        // URIs should never contain backslashes (even on Windows)
        assert!(
            !uri.contains('\\'),
            "URI should use forward slashes only, but got: {}",
            uri
        );
    }

    #[tokio::test]
    async fn test_uri_from_path_with_base_path() {
        use std::path::MAIN_SEPARATOR;

        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        // Test with path that already contains base_path (using platform-native separator)
        let full_path = format!(
            "{}{}test{}file.txt",
            provider.base_path, MAIN_SEPARATOR, MAIN_SEPARATOR
        );
        let uri = provider.uri_from_path(&full_path);

        assert!(
            uri.starts_with("file://"),
            "URI should start with file:// but got: {}",
            uri
        );

        // URIs should never contain backslashes (even on Windows)
        assert!(
            !uri.contains('\\'),
            "URI should use forward slashes only, but got: {}",
            uri
        );

        #[cfg(unix)]
        assert!(
            uri.starts_with("file:///"),
            "Unix absolute path URI should start with file:/// but got: {}",
            uri
        );
    }

    #[tokio::test]
    async fn test_uri_from_path_with_leading_slash() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        let uri = provider.uri_from_path("/test/file.txt");
        assert!(uri.starts_with("file://"));
        assert!(uri.contains("test"));
        assert!(uri.contains("file.txt"));

        // URIs should never contain backslashes
        assert!(
            !uri.contains('\\'),
            "URI should use forward slashes only, but got: {}",
            uri
        );

        #[cfg(unix)]
        assert!(
            uri.starts_with("file:///"),
            "Unix absolute path URI should start with file:/// but got: {}",
            uri
        );
    }

    /// Test that fix_uri produces valid URIs for various input formats.
    /// This test specifically catches the bug where absolute paths without
    /// file: prefix would produce file://path instead of file:///path.
    #[tokio::test]
    async fn test_uri_from_path_format_validation() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        // Test various input formats
        let test_cases = vec![
            ("relative/path.txt", "relative path"),
            ("/absolute/path.txt", "absolute path with leading slash"),
        ];

        for (input, description) in test_cases {
            let uri = provider.uri_from_path(input);

            // All URIs should start with file://
            assert!(
                uri.starts_with("file://"),
                "{}: URI should start with file:// but got: {}",
                description,
                uri
            );

            // The path component should be present
            let path_part = input.trim_start_matches('/');
            assert!(
                uri.contains(path_part),
                "{}: URI should contain path '{}' but got: {}",
                description,
                path_part,
                uri
            );

            // URIs should never contain backslashes (even on Windows)
            assert!(
                !uri.contains('\\'),
                "{}: URI should use forward slashes only, but got: {}",
                description,
                uri
            );

            #[cfg(unix)]
            {
                // On Unix, the base_path is absolute (starts with /), so all URIs
                // should have file:// followed by an absolute path (starting with /)
                assert!(
                    uri.starts_with("file:///"),
                    "{}: Unix URI should start with file:/// but got: {}",
                    description,
                    uri
                );

                // Verify no double slashes in the path (except after file:)
                let after_scheme = &uri[7..]; // Skip "file://"
                assert!(
                    !after_scheme.contains("//"),
                    "{}: URI should not have double slashes in path: {}",
                    description,
                    uri
                );
            }
        }
    }

    /// Test that fix_uri correctly handles Windows extended-length path prefix.
    /// On Windows, canonicalize() adds \\?\ prefix to paths, which must be
    /// stripped when creating file:// URIs.
    #[test]
    fn test_fix_uri_windows_extended_path_prefix() {
        // Simulate what fix_uri does internally for testing the Windows prefix handling
        fn fix_uri_for_test(path: &str) -> String {
            let path = path.replace('\\', "/");
            let path = path.strip_prefix("//?/").unwrap_or(&path).to_string();

            let path_without_scheme = if let Some(without_scheme) = path.strip_prefix("file:") {
                without_scheme.trim_start_matches('/').to_string()
            } else if path.starts_with('/') {
                path.trim_start_matches('/').to_string()
            } else {
                path.to_string()
            };

            format!("file:///{}", path_without_scheme)
        }

        // Test Windows extended-length path prefix (\\?\C:\...)
        let windows_path = "\\\\?\\C:\\Users\\test\\data";
        let uri = fix_uri_for_test(windows_path);
        assert_eq!(uri, "file:///C:/Users/test/data");
        assert!(!uri.contains("?"), "URI should not contain ? from prefix");

        // Test already forward-slash version (//?/C:/...)
        let windows_path_fwd = "//?/C:/Users/test/data";
        let uri = fix_uri_for_test(windows_path_fwd);
        assert_eq!(uri, "file:///C:/Users/test/data");

        // Test normal Windows path without prefix
        let normal_windows = "C:\\Users\\test\\data";
        let uri = fix_uri_for_test(normal_windows);
        assert_eq!(uri, "file:///C:/Users/test/data");

        // Test Unix path (should not be affected)
        let unix_path = "/home/user/data";
        let uri = fix_uri_for_test(unix_path);
        assert_eq!(uri, "file:///home/user/data");
    }

    #[tokio::test]
    async fn test_validate_connection_local_valid() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        // Create a subdirectory for validation
        let sub_dir = temp_dir.path().join("subdir");
        fs::create_dir(&sub_dir).unwrap();

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        let result = provider.validate_connection("subdir").await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_validate_connection_local_invalid() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        let result = provider.validate_connection("nonexistent").await;
        assert!(result.is_err());
    }

    #[test]
    fn test_debug_implementation() {
        let config = StorageConfig::local()
            .with_option("path", "/tmp")
            .with_option("timeout", "60");

        let debug_str = format!("{:?}", config);
        assert!(debug_str.contains("StorageConfig"));
    }

    #[tokio::test]
    async fn test_read_file() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        // Create a test file
        let file_path = temp_dir.path().join("test.txt");
        let test_content = b"Hello, World!";
        fs::write(&file_path, test_content).unwrap();

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        let content = provider.read_file("test.txt").await.unwrap();
        assert_eq!(content, test_content);
    }

    #[tokio::test]
    async fn test_read_file_nonexistent() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        let result = provider.read_file("nonexistent.txt").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_exists_file() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        // Create a test file
        let file_path = temp_dir.path().join("exists.txt");
        fs::write(&file_path, "content").unwrap();

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        let exists = provider.exists("exists.txt").await.unwrap();
        assert!(exists);
    }

    #[tokio::test]
    async fn test_exists_nonexistent() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        let exists = provider.exists("nonexistent.txt").await.unwrap();
        assert!(!exists);
    }

    #[tokio::test]
    async fn test_get_metadata() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        // Create a test file
        let file_path = temp_dir.path().join("metadata.txt");
        let test_content = b"Test content for metadata";
        fs::write(&file_path, test_content).unwrap();

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        let metadata = provider.get_metadata("metadata.txt").await.unwrap();
        assert_eq!(metadata.path, "metadata.txt");
        assert_eq!(metadata.size, test_content.len() as u64);
        assert!(metadata.last_modified.is_some());
    }

    #[tokio::test]
    async fn test_list_files_non_recursive() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        // Create test files
        fs::write(temp_dir.path().join("file1.txt"), "content1").unwrap();
        fs::write(temp_dir.path().join("file2.txt"), "content2").unwrap();

        // Create subdirectory with file (should not be listed in non-recursive mode)
        let sub_dir = temp_dir.path().join("subdir");
        fs::create_dir(&sub_dir).unwrap();
        fs::write(sub_dir.join("file3.txt"), "content3").unwrap();

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        let files = provider.list_files("", false).await.unwrap();

        // Should only list files in root directory
        assert_eq!(files.len(), 2);
        let file_names: Vec<String> = files.iter().map(|f| f.path.clone()).collect();
        assert!(file_names.iter().any(|name| name.contains("file1.txt")));
        assert!(file_names.iter().any(|name| name.contains("file2.txt")));
    }

    #[tokio::test]
    async fn test_list_files_recursive() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        // Create test files
        fs::write(temp_dir.path().join("file1.txt"), "content1").unwrap();

        // Create subdirectory with file
        let sub_dir = temp_dir.path().join("subdir");
        fs::create_dir(&sub_dir).unwrap();
        fs::write(sub_dir.join("file2.txt"), "content2").unwrap();

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        let files = provider.list_files("", true).await.unwrap();

        // Should list all files recursively
        assert!(files.len() >= 2);
        let file_names: Vec<String> = files.iter().map(|f| f.path.clone()).collect();
        assert!(file_names.iter().any(|name| name.contains("file1.txt")));
        assert!(file_names.iter().any(|name| name.contains("file2.txt")));
    }

    #[tokio::test]
    async fn test_discover_partitions() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        // Create partition directories
        fs::create_dir(temp_dir.path().join("partition1")).unwrap();
        fs::create_dir(temp_dir.path().join("partition2")).unwrap();
        fs::create_dir(temp_dir.path().join("_metadata")).unwrap(); // Should be excluded

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        let partitions = provider
            .discover_partitions("", vec!["_metadata"])
            .await
            .unwrap();

        // Should find partitions but exclude _metadata
        assert!(partitions.len() >= 2);
        assert!(partitions.iter().any(|p| p.contains("partition1")));
        assert!(partitions.iter().any(|p| p.contains("partition2")));
        assert!(!partitions.iter().any(|p| p.contains("_metadata")));
    }

    #[tokio::test]
    async fn test_provider_debug_format() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();

        let config = StorageConfig::local().with_option("path", temp_path);
        let provider = ObjectStoreProvider::new(config).await.unwrap();

        let debug_str = format!("{:?}", provider);
        assert!(debug_str.contains("StorageProvider"));
        assert!(debug_str.contains("local"));
    }

    #[tokio::test]
    async fn test_hdfs_provider_missing_url() {
        // HDFS requires a 'url' option - test that missing URL returns appropriate error
        let config = StorageConfig::hdfs();
        let provider = ObjectStoreProvider::new(config).await;

        assert!(provider.is_err());
        match provider {
            Err(StorageError::ConfigError(msg)) => {
                assert!(
                    msg.contains("HDFS storage requires 'url' option"),
                    "Expected error about missing URL, got: {}",
                    msg
                );
            }
            _ => panic!("Expected ConfigError for missing HDFS URL"),
        }
    }

    #[tokio::test]
    async fn test_hdfs_provider_invalid_url() {
        // Test with an invalid HDFS URL format
        let config = StorageConfig::hdfs().with_option("url", "not-a-valid-hdfs-url");
        let provider = ObjectStoreProvider::new(config).await;

        assert!(provider.is_err());
        match provider {
            Err(StorageError::ConfigError(msg)) => {
                assert!(
                    msg.contains("Failed to create HDFS store"),
                    "Expected error about HDFS store creation failure, got: {}",
                    msg
                );
            }
            _ => panic!("Expected ConfigError for invalid HDFS URL"),
        }
    }

    #[tokio::test]
    async fn test_hdfs_provider_unreachable_namenode() {
        // Test with a valid URL format but unreachable namenode
        // This tests the error handling when HDFS connection fails
        let config = StorageConfig::hdfs().with_option("url", "hdfs://nonexistent-namenode:8020");
        let provider = ObjectStoreProvider::new(config).await;

        // The provider creation may succeed (lazy connection) or fail immediately
        // depending on the hdfs-native-object-store implementation
        // Either outcome is acceptable - we're testing that it doesn't panic
        match provider {
            Ok(_) => {
                // Lazy connection - provider created but will fail on first operation
                // This is acceptable behavior
            }
            Err(StorageError::ConfigError(msg)) => {
                // Eager connection failure - also acceptable
                assert!(
                    msg.contains("Failed to create HDFS store"),
                    "Expected HDFS store creation error, got: {}",
                    msg
                );
            }
            Err(e) => panic!("Unexpected error type: {:?}", e),
        }
    }

    #[test]
    fn test_build_hdfs_store_missing_url() {
        // Direct test of build_hdfs_store with missing URL
        let config = StorageConfig::hdfs();
        let result = ObjectStoreProvider::build_hdfs_store(&config);

        assert!(result.is_err());
        match result {
            Err(StorageError::ConfigError(msg)) => {
                assert!(msg.contains("HDFS storage requires 'url' option"));
            }
            _ => panic!("Expected ConfigError for missing URL"),
        }
    }

    #[test]
    fn test_build_hdfs_store_invalid_url() {
        // Direct test of build_hdfs_store with invalid URL
        let config = StorageConfig::hdfs().with_option("url", "invalid://not-hdfs");
        let result = ObjectStoreProvider::build_hdfs_store(&config);

        assert!(result.is_err());
        match result {
            Err(StorageError::ConfigError(msg)) => {
                assert!(
                    msg.contains("Failed to create HDFS store"),
                    "Expected HDFS creation error, got: {}",
                    msg
                );
            }
            _ => panic!("Expected ConfigError for invalid URL"),
        }
    }

    #[test]
    fn test_build_hdfs_store_empty_url() {
        // Test with empty URL string
        let config = StorageConfig::hdfs().with_option("url", "");
        let result = ObjectStoreProvider::build_hdfs_store(&config);

        // Empty URL should fail during HDFS store creation
        assert!(result.is_err());
        match result {
            Err(StorageError::ConfigError(msg)) => {
                assert!(
                    msg.contains("Failed to create HDFS store"),
                    "Expected HDFS creation error for empty URL, got: {}",
                    msg
                );
            }
            _ => panic!("Expected ConfigError for empty URL"),
        }
    }

    #[test]
    fn test_build_http_store_missing_url() {
        // Direct test of build_http_store with missing URL
        let config = StorageConfig::http();
        let result = ObjectStoreProvider::build_http_store(&config);

        assert!(result.is_err());
        match result {
            Err(StorageError::ConfigError(msg)) => {
                assert!(msg.contains("HTTP storage requires 'url' option"));
            }
            _ => panic!("Expected ConfigError for missing URL"),
        }
    }

    #[test]
    fn test_build_http_store_valid_url() {
        // Test with valid HTTP URL
        let config = StorageConfig::http().with_option("url", "https://example.com/files");
        let result = ObjectStoreProvider::build_http_store(&config);

        assert!(result.is_ok());
        let (_, base_url) = result.unwrap();
        assert_eq!(base_url, "https://example.com/files");
    }

    #[test]
    fn test_build_http_store_webdav_url() {
        // Test with WebDAV URL
        let config = StorageConfig::http().with_option("url", "https://webdav.example.com/dav");
        let result = ObjectStoreProvider::build_http_store(&config);

        assert!(result.is_ok());
        let (_, base_url) = result.unwrap();
        assert_eq!(base_url, "https://webdav.example.com/dav");
    }
}