rs3gw 0.2.1

High-Performance AI/HPC Object Storage Gateway powered by scirs2-io
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
#!/usr/bin/env rust
//! rs3ctl - Command-line tool for managing rs3gw S3-compatible object storage
//!
//! This tool provides comprehensive management capabilities for rs3gw servers:
//! - Bucket operations (create, delete, list, info)
//! - Object operations (upload, download, list, delete, info)
//! - Replication management
//! - Metrics and monitoring
//! - Maintenance operations
//! - Policy management

use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use indicatif::{ProgressBar, ProgressStyle};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fs;
use std::path::PathBuf;
use std::time::Duration;

/// rs3ctl - Command-line tool for rs3gw management
#[derive(Parser)]
#[command(name = "rs3ctl")]
#[command(version, about, long_about = None)]
struct Cli {
    /// rs3gw server endpoint (default: http://localhost:9000)
    #[arg(short, long, default_value = "http://localhost:9000")]
    endpoint: String,

    /// Access key for authentication
    #[arg(short, long)]
    access_key: Option<String>,

    /// Secret key for authentication
    #[arg(short, long)]
    secret_key: Option<String>,

    /// Command to execute
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Bucket management commands
    Bucket {
        #[command(subcommand)]
        action: BucketAction,
    },
    /// Object management commands
    Object {
        #[command(subcommand)]
        action: ObjectAction,
    },
    /// Replication management commands
    Replication {
        #[command(subcommand)]
        action: ReplicationAction,
    },
    /// Metrics and monitoring commands
    Metrics {
        #[command(subcommand)]
        action: MetricsAction,
    },
    /// Maintenance operations
    Maintenance {
        #[command(subcommand)]
        action: MaintenanceAction,
    },
    /// Versioning management commands
    Versioning {
        #[command(subcommand)]
        action: VersioningAction,
    },
    /// Observability commands (profiling, anomalies, business metrics)
    Observability {
        #[command(subcommand)]
        action: ObservabilityAction,
    },
    /// Transformation operations
    Transform {
        #[command(subcommand)]
        action: TransformAction,
    },
    /// Batch operations
    Batch {
        #[command(subcommand)]
        action: BatchAction,
    },
    /// Lifecycle policy management
    Lifecycle {
        #[command(subcommand)]
        action: LifecycleAction,
    },
    /// Dataset preprocessing pipeline management
    Preprocessing {
        #[command(subcommand)]
        action: PreprocessingAction,
    },
    /// Health check
    Health,
}

#[derive(Subcommand)]
enum BucketAction {
    /// List all buckets
    List,
    /// Create a new bucket
    Create {
        /// Bucket name
        name: String,
        /// Bucket region
        #[arg(short, long, default_value = "us-east-1")]
        region: String,
    },
    /// Delete a bucket
    Delete {
        /// Bucket name
        name: String,
        /// Force delete even if bucket is not empty
        #[arg(short, long)]
        force: bool,
    },
    /// Get bucket information
    Info {
        /// Bucket name
        name: String,
    },
    /// Get bucket policy
    GetPolicy {
        /// Bucket name
        name: String,
    },
    /// Set bucket policy from file
    SetPolicy {
        /// Bucket name
        name: String,
        /// Policy JSON file
        policy_file: PathBuf,
    },
}

#[derive(Subcommand)]
enum ObjectAction {
    /// List objects in a bucket
    List {
        /// Bucket name
        bucket: String,
        /// Prefix filter
        #[arg(short, long)]
        prefix: Option<String>,
        /// Maximum keys to return
        #[arg(short, long, default_value = "1000")]
        max_keys: i32,
    },
    /// Upload a file as an object
    Upload {
        /// Bucket name
        bucket: String,
        /// Object key
        key: String,
        /// Local file path
        file: PathBuf,
        /// Content type
        #[arg(short = 't', long)]
        content_type: Option<String>,
    },
    /// Download an object to a file
    Download {
        /// Bucket name
        bucket: String,
        /// Object key
        key: String,
        /// Local file path to save
        output: PathBuf,
    },
    /// Delete an object
    Delete {
        /// Bucket name
        bucket: String,
        /// Object key
        key: String,
    },
    /// Get object information
    Info {
        /// Bucket name
        bucket: String,
        /// Object key
        key: String,
    },
}

#[derive(Subcommand)]
enum ReplicationAction {
    /// Get replication configuration for a bucket
    GetConfig {
        /// Bucket name
        bucket: String,
    },
    /// Set replication configuration from file
    SetConfig {
        /// Bucket name
        bucket: String,
        /// Configuration JSON file
        config_file: PathBuf,
    },
    /// Get replication metrics
    Metrics {
        /// Destination name (optional)
        #[arg(short, long)]
        destination: Option<String>,
    },
}

#[derive(Subcommand)]
enum MetricsAction {
    /// Get Prometheus metrics
    Get,
    /// Get storage statistics
    Storage,
    /// Get operation statistics
    Operations,
}

#[derive(Subcommand)]
enum MaintenanceAction {
    /// Create a backup snapshot
    Backup {
        /// Snapshot name
        #[arg(short, long)]
        name: Option<String>,
        /// Snapshot type (full, incremental)
        #[arg(short = 't', long, default_value = "full")]
        snapshot_type: String,
    },
    /// Trigger integrity check
    IntegrityCheck {
        /// Bucket name (optional, checks all if not specified)
        #[arg(short, long)]
        bucket: Option<String>,
    },
    /// Trigger cleanup of old objects
    Cleanup {
        /// Retention period in days
        #[arg(short, long, default_value = "30")]
        retention_days: u32,
    },
}

#[derive(Subcommand)]
enum VersioningAction {
    /// Get versioning status for a bucket
    GetStatus {
        /// Bucket name
        bucket: String,
    },
    /// Enable versioning for a bucket
    Enable {
        /// Bucket name
        bucket: String,
    },
    /// Suspend versioning for a bucket
    Suspend {
        /// Bucket name
        bucket: String,
    },
    /// List object versions
    ListVersions {
        /// Bucket name
        bucket: String,
        /// Object key prefix filter
        #[arg(short, long)]
        prefix: Option<String>,
        /// Maximum number of versions to return
        #[arg(short, long, default_value = "1000")]
        max_keys: i32,
    },
}

#[derive(Subcommand)]
enum ObservabilityAction {
    /// Get profiling data (CPU, memory, I/O)
    Profiling {
        /// Export in pprof format
        #[arg(short, long)]
        pprof: bool,
    },
    /// Get business metrics and KPIs
    BusinessMetrics,
    /// Get detected anomalies
    Anomalies {
        /// Filter by anomaly type
        #[arg(short = 't', long)]
        anomaly_type: Option<String>,
        /// Filter by severity (Low, Medium, High, Critical)
        #[arg(short, long)]
        severity: Option<String>,
        /// Limit number of results
        #[arg(short, long)]
        limit: Option<usize>,
    },
    /// Get resource manager statistics
    Resources,
    /// Get comprehensive health check
    Health,
}

#[derive(Subcommand)]
enum TransformAction {
    /// Apply image transformation to an object
    Image {
        /// Bucket name
        bucket: String,
        /// Object key
        key: String,
        /// Target width
        #[arg(short = 'w', long)]
        width: Option<u32>,
        /// Target height
        #[arg(short = 'H', long)]
        height: Option<u32>,
        /// Output format (jpeg, png, webp, gif, bmp, tiff)
        #[arg(short = 'f', long)]
        format: Option<String>,
        /// Quality (1-100 for JPEG)
        #[arg(short = 'q', long)]
        quality: Option<u8>,
        /// Output file path
        #[arg(short = 'o', long)]
        output: PathBuf,
    },
    /// Apply compression transformation
    Compress {
        /// Bucket name
        bucket: String,
        /// Object key
        key: String,
        /// Algorithm (zstd, gzip, lz4)
        #[arg(short = 'a', long, default_value = "zstd")]
        algorithm: String,
        /// Compression level
        #[arg(short = 'l', long)]
        level: Option<u8>,
        /// Output file path
        #[arg(short = 'o', long)]
        output: PathBuf,
    },
    /// Test a WASM plugin
    TestWasm {
        /// Path to WASM plugin file
        plugin: PathBuf,
        /// Test input file
        input: PathBuf,
        /// Parameters (plugin-specific)
        #[arg(short = 'p', long)]
        params: Option<String>,
        /// Output file path
        #[arg(short = 'o', long)]
        output: Option<PathBuf>,
    },
}

#[derive(Subcommand)]
enum BatchAction {
    /// Delete multiple objects by prefix
    DeleteByPrefix {
        /// Bucket name
        bucket: String,
        /// Prefix to match objects for deletion
        prefix: String,
        /// Dry run (show what would be deleted without deleting)
        #[arg(long)]
        dry_run: bool,
        /// Maximum number of objects to delete
        #[arg(short = 'm', long)]
        max: Option<usize>,
    },
    /// Copy multiple objects
    CopyMultiple {
        /// Source bucket
        source_bucket: String,
        /// Destination bucket
        dest_bucket: String,
        /// Source prefix
        #[arg(short = 's', long)]
        source_prefix: String,
        /// Destination prefix
        #[arg(short = 'd', long)]
        dest_prefix: Option<String>,
        /// Maximum number of objects to copy
        #[arg(short = 'm', long)]
        max: Option<usize>,
    },
    /// Tag multiple objects
    TagMultiple {
        /// Bucket name
        bucket: String,
        /// Prefix filter
        prefix: String,
        /// Tags in format key1=value1,key2=value2
        tags: String,
        /// Maximum number of objects to tag
        #[arg(short = 'm', long)]
        max: Option<usize>,
    },
}

#[derive(Subcommand)]
enum LifecycleAction {
    /// Get lifecycle policy for a bucket
    Get {
        /// Bucket name
        bucket: String,
    },
    /// Set lifecycle policy from file
    Set {
        /// Bucket name
        bucket: String,
        /// Policy JSON file
        policy_file: PathBuf,
    },
    /// Delete lifecycle policy
    Delete {
        /// Bucket name
        bucket: String,
    },
    /// List rules in lifecycle policy
    ListRules {
        /// Bucket name
        bucket: String,
    },
}

#[derive(Subcommand)]
enum PreprocessingAction {
    /// Create a preprocessing pipeline
    Create {
        /// Pipeline ID
        #[arg(short, long)]
        id: String,
        /// Pipeline name
        #[arg(short, long)]
        name: String,
        /// Pipeline definition JSON file
        #[arg(short, long)]
        file: PathBuf,
    },
    /// List all preprocessing pipelines
    List {
        /// Bucket containing pipelines (default: ml-datasets)
        #[arg(short, long, default_value = "ml-datasets")]
        bucket: String,
    },
    /// Get pipeline definition
    Get {
        /// Pipeline ID
        #[arg(short, long)]
        id: String,
        /// Bucket containing pipelines (default: ml-datasets)
        #[arg(short, long, default_value = "ml-datasets")]
        bucket: String,
    },
    /// Delete a preprocessing pipeline
    Delete {
        /// Pipeline ID
        #[arg(short, long)]
        id: String,
        /// Bucket containing pipelines (default: ml-datasets)
        #[arg(short, long, default_value = "ml-datasets")]
        bucket: String,
    },
    /// Apply pipeline to an object
    Apply {
        /// Pipeline ID
        #[arg(short, long)]
        pipeline: String,
        /// Source bucket
        #[arg(long)]
        source_bucket: String,
        /// Source object key
        #[arg(long)]
        source_key: String,
        /// Destination bucket
        #[arg(long)]
        dest_bucket: String,
        /// Destination object key
        #[arg(long)]
        dest_key: String,
    },
    /// Validate pipeline definition
    Validate {
        /// Pipeline definition JSON file
        file: PathBuf,
    },
}

#[derive(Debug, Serialize, Deserialize)]
#[allow(dead_code)]
struct BucketInfo {
    name: String,
    creation_date: Option<String>,
    region: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
#[allow(dead_code)]
struct ObjectInfo {
    key: String,
    size: u64,
    last_modified: String,
    etag: String,
    storage_class: Option<String>,
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();
    let client = Client::builder()
        .timeout(Duration::from_secs(300))
        .build()
        .context("Failed to create HTTP client")?;

    match &cli.command {
        Commands::Health => handle_health(&client, &cli.endpoint).await,
        Commands::Bucket { action } => handle_bucket(&client, &cli, action).await,
        Commands::Object { action } => handle_object(&client, &cli, action).await,
        Commands::Replication { action } => handle_replication(&client, &cli, action).await,
        Commands::Metrics { action } => handle_metrics(&client, &cli, action).await,
        Commands::Maintenance { action } => handle_maintenance(&client, &cli, action).await,
        Commands::Versioning { action } => handle_versioning(&client, &cli, action).await,
        Commands::Observability { action } => handle_observability(&client, &cli, action).await,
        Commands::Transform { action } => handle_transform(&client, &cli, action).await,
        Commands::Batch { action } => handle_batch(&client, &cli, action).await,
        Commands::Lifecycle { action } => handle_lifecycle(&client, &cli, action).await,
        Commands::Preprocessing { action } => handle_preprocessing(&client, &cli, action).await,
    }
}

async fn handle_health(client: &Client, endpoint: &str) -> Result<()> {
    let url = format!("{}/health", endpoint);
    let response = client
        .get(&url)
        .send()
        .await
        .context("Failed to send health check request")?;

    if response.status().is_success() {
        println!("✓ Server is healthy");
        let body = response.text().await?;
        println!("{}", body);
        Ok(())
    } else {
        println!("✗ Server health check failed");
        println!("Status: {}", response.status());
        Err(anyhow::anyhow!("Health check failed"))
    }
}

async fn handle_bucket(client: &Client, cli: &Cli, action: &BucketAction) -> Result<()> {
    match action {
        BucketAction::List => {
            let url = format!("{}/", cli.endpoint);
            let response = client
                .get(&url)
                .send()
                .await
                .context("Failed to list buckets")?;

            if response.status().is_success() {
                let body = response.text().await?;
                println!("Buckets:");
                println!("{}", body);
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to list buckets: {}",
                    response.status()
                ))
            }
        }
        BucketAction::Create { name, region } => {
            let url = format!("{}/{}", cli.endpoint, name);
            let response = client
                .put(&url)
                .header("x-amz-bucket-region", region)
                .send()
                .await
                .context("Failed to create bucket")?;

            if response.status().is_success() {
                println!("✓ Bucket '{}' created successfully", name);
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to create bucket: {}",
                    response.status()
                ))
            }
        }
        BucketAction::Delete { name, force } => {
            if *force {
                println!("Warning: Force delete not yet implemented");
            }
            let url = format!("{}/{}", cli.endpoint, name);
            let response = client
                .delete(&url)
                .send()
                .await
                .context("Failed to delete bucket")?;

            if response.status().is_success() {
                println!("✓ Bucket '{}' deleted successfully", name);
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to delete bucket: {}",
                    response.status()
                ))
            }
        }
        BucketAction::Info { name } => {
            let url = format!("{}/{}", cli.endpoint, name);
            let response = client
                .head(&url)
                .send()
                .await
                .context("Failed to get bucket info")?;

            if response.status().is_success() {
                println!("Bucket: {}", name);
                println!("Status: Exists");
                for (key, value) in response.headers() {
                    if let Ok(v) = value.to_str() {
                        println!("  {}: {}", key, v);
                    }
                }
                Ok(())
            } else {
                Err(anyhow::anyhow!("Bucket not found"))
            }
        }
        BucketAction::GetPolicy { name } => {
            let url = format!("{}/{}?policy", cli.endpoint, name);
            let response = client
                .get(&url)
                .send()
                .await
                .context("Failed to get bucket policy")?;

            if response.status().is_success() {
                let policy = response.text().await?;
                println!("{}", policy);
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to get bucket policy: {}",
                    response.status()
                ))
            }
        }
        BucketAction::SetPolicy { name, policy_file } => {
            let policy_content =
                fs::read_to_string(policy_file).context("Failed to read policy file")?;
            let url = format!("{}/{}?policy", cli.endpoint, name);
            let response = client
                .put(&url)
                .body(policy_content)
                .send()
                .await
                .context("Failed to set bucket policy")?;

            if response.status().is_success() {
                println!("✓ Bucket policy updated successfully");
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to set bucket policy: {}",
                    response.status()
                ))
            }
        }
    }
}

async fn handle_object(client: &Client, cli: &Cli, action: &ObjectAction) -> Result<()> {
    match action {
        ObjectAction::List {
            bucket,
            prefix,
            max_keys,
        } => {
            let mut url = format!(
                "{}/{}?list-type=2&max-keys={}",
                cli.endpoint, bucket, max_keys
            );
            if let Some(p) = prefix {
                url.push_str(&format!("&prefix={}", p));
            }
            let response = client
                .get(&url)
                .send()
                .await
                .context("Failed to list objects")?;

            if response.status().is_success() {
                let body = response.text().await?;
                println!("{}", body);
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to list objects: {}",
                    response.status()
                ))
            }
        }
        ObjectAction::Upload {
            bucket,
            key,
            file,
            content_type,
        } => {
            let content = fs::read(file)
                .with_context(|| format!("Failed to read file: {}", file.display()))?;

            let pb = ProgressBar::new(content.len() as u64);
            pb.set_style(
                ProgressStyle::default_bar()
                    .template("[{elapsed_precise}] {bar:40.cyan/blue} {bytes}/{total_bytes} {msg}")?
                    .progress_chars("=>-"),
            );
            pb.set_message("Uploading...");

            let url = format!("{}/{}/{}", cli.endpoint, bucket, key);
            let mut request = client.put(&url);

            if let Some(ct) = content_type {
                request = request.header("Content-Type", ct);
            }

            let response = request
                .body(content)
                .send()
                .await
                .context("Failed to upload object")?;

            pb.finish_with_message("Done");

            if response.status().is_success() {
                println!("✓ Object uploaded successfully");
                if let Some(etag) = response.headers().get("etag") {
                    println!("ETag: {}", etag.to_str()?);
                }
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to upload object: {}",
                    response.status()
                ))
            }
        }
        ObjectAction::Download {
            bucket,
            key,
            output,
        } => {
            let url = format!("{}/{}/{}", cli.endpoint, bucket, key);
            let response = client
                .get(&url)
                .send()
                .await
                .context("Failed to download object")?;

            if response.status().is_success() {
                let content = response.bytes().await?;

                let pb = ProgressBar::new(content.len() as u64);
                pb.set_style(
                    ProgressStyle::default_bar()
                        .template(
                            "[{elapsed_precise}] {bar:40.cyan/blue} {bytes}/{total_bytes} {msg}",
                        )?
                        .progress_chars("=>-"),
                );
                pb.set_message("Downloading...");

                fs::write(output, &content)
                    .with_context(|| format!("Failed to write file: {}", output.display()))?;

                pb.finish_with_message("Done");
                println!("✓ Object downloaded to {}", output.display());
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to download object: {}",
                    response.status()
                ))
            }
        }
        ObjectAction::Delete { bucket, key } => {
            let url = format!("{}/{}/{}", cli.endpoint, bucket, key);
            let response = client
                .delete(&url)
                .send()
                .await
                .context("Failed to delete object")?;

            if response.status().is_success() {
                println!("✓ Object deleted successfully");
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to delete object: {}",
                    response.status()
                ))
            }
        }
        ObjectAction::Info { bucket, key } => {
            let url = format!("{}/{}/{}", cli.endpoint, bucket, key);
            let response = client
                .head(&url)
                .send()
                .await
                .context("Failed to get object info")?;

            if response.status().is_success() {
                println!("Object: {}/{}", bucket, key);
                for (key, value) in response.headers() {
                    if let Ok(v) = value.to_str() {
                        println!("  {}: {}", key, v);
                    }
                }
                Ok(())
            } else {
                Err(anyhow::anyhow!("Object not found"))
            }
        }
    }
}

async fn handle_replication(client: &Client, cli: &Cli, action: &ReplicationAction) -> Result<()> {
    match action {
        ReplicationAction::GetConfig { bucket } => {
            let url = format!("{}/api/replication/{}/config", cli.endpoint, bucket);
            let response = client
                .get(&url)
                .send()
                .await
                .context("Failed to get replication config")?;

            if response.status().is_success() {
                let config = response.text().await?;
                println!("{}", config);
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to get replication config: {}",
                    response.status()
                ))
            }
        }
        ReplicationAction::SetConfig {
            bucket,
            config_file,
        } => {
            let config_content =
                fs::read_to_string(config_file).context("Failed to read config file")?;
            let url = format!("{}/api/replication/{}/config", cli.endpoint, bucket);
            let response = client
                .put(&url)
                .header("Content-Type", "application/json")
                .body(config_content)
                .send()
                .await
                .context("Failed to set replication config")?;

            if response.status().is_success() {
                println!("✓ Replication configuration updated successfully");
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to set replication config: {}",
                    response.status()
                ))
            }
        }
        ReplicationAction::Metrics { destination } => {
            let url = if let Some(dest) = destination {
                format!("{}/api/replication/metrics/{}", cli.endpoint, dest)
            } else {
                format!("{}/api/replication/metrics", cli.endpoint)
            };

            let response = client
                .get(&url)
                .send()
                .await
                .context("Failed to get replication metrics")?;

            if response.status().is_success() {
                let metrics: Value = response.json().await?;
                println!("{}", serde_json::to_string_pretty(&metrics)?);
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to get replication metrics: {}",
                    response.status()
                ))
            }
        }
    }
}

async fn handle_metrics(client: &Client, cli: &Cli, action: &MetricsAction) -> Result<()> {
    match action {
        MetricsAction::Get => {
            let url = format!("{}/metrics", cli.endpoint);
            let response = client
                .get(&url)
                .send()
                .await
                .context("Failed to get metrics")?;

            if response.status().is_success() {
                let metrics = response.text().await?;
                println!("{}", metrics);
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to get metrics: {}",
                    response.status()
                ))
            }
        }
        MetricsAction::Storage => {
            let url = format!("{}/api/maintenance/storage-stats", cli.endpoint);
            let response = client
                .get(&url)
                .send()
                .await
                .context("Failed to get storage statistics")?;

            if response.status().is_success() {
                let stats: Value = response.json().await?;
                println!("{}", serde_json::to_string_pretty(&stats)?);
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to get storage statistics: {}",
                    response.status()
                ))
            }
        }
        MetricsAction::Operations => {
            let url = format!("{}/api/maintenance/operation-stats", cli.endpoint);
            let response = client
                .get(&url)
                .send()
                .await
                .context("Failed to get operation statistics")?;

            if response.status().is_success() {
                let stats: Value = response.json().await?;
                println!("{}", serde_json::to_string_pretty(&stats)?);
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to get operation statistics: {}",
                    response.status()
                ))
            }
        }
    }
}

async fn handle_maintenance(client: &Client, cli: &Cli, action: &MaintenanceAction) -> Result<()> {
    match action {
        MaintenanceAction::Backup {
            name,
            snapshot_type,
        } => {
            println!("Creating {} backup snapshot...", snapshot_type);

            let request_body = serde_json::json!({
                "name": name,
                "snapshot_type": snapshot_type
            });

            let url = format!("{}/api/maintenance/backup", cli.endpoint);
            let response = client
                .post(&url)
                .header("Content-Type", "application/json")
                .json(&request_body)
                .send()
                .await
                .context("Failed to create backup snapshot")?;

            if response.status().is_success() {
                let result: Value = response.json().await?;
                println!("✓ Snapshot created successfully");
                println!("{}", serde_json::to_string_pretty(&result)?);
                Ok(())
            } else {
                let error_text = response.text().await?;
                Err(anyhow::anyhow!("Failed to create backup: {}", error_text))
            }
        }
        MaintenanceAction::IntegrityCheck { bucket } => {
            if let Some(b) = bucket {
                println!("Running integrity check for bucket: {}", b);
            } else {
                println!("Running integrity check for all buckets...");
            }

            let request_body = serde_json::json!({
                "bucket": bucket,
                "auto_repair": true
            });

            let url = format!("{}/api/maintenance/integrity-check", cli.endpoint);
            let response = client
                .post(&url)
                .header("Content-Type", "application/json")
                .json(&request_body)
                .send()
                .await
                .context("Failed to run integrity check")?;

            if response.status().is_success() {
                let result: Value = response.json().await?;
                println!("{}", serde_json::to_string_pretty(&result)?);
                Ok(())
            } else {
                let error_text = response.text().await?;
                Err(anyhow::anyhow!("Integrity check failed: {}", error_text))
            }
        }
        MaintenanceAction::Cleanup { retention_days } => {
            println!(
                "Triggering cleanup of objects older than {} days...",
                retention_days
            );

            let request_body = serde_json::json!({
                "retention_days": retention_days,
                "bucket": null,
                "dry_run": false
            });

            let url = format!("{}/api/maintenance/cleanup", cli.endpoint);
            let response = client
                .post(&url)
                .header("Content-Type", "application/json")
                .json(&request_body)
                .send()
                .await
                .context("Failed to trigger cleanup")?;

            if response.status().is_success() {
                let result: Value = response.json().await?;
                println!("{}", serde_json::to_string_pretty(&result)?);
                Ok(())
            } else {
                let error_text = response.text().await?;
                Err(anyhow::anyhow!("Cleanup failed: {}", error_text))
            }
        }
    }
}

async fn handle_versioning(client: &Client, cli: &Cli, action: &VersioningAction) -> Result<()> {
    match action {
        VersioningAction::GetStatus { bucket } => {
            println!("Getting versioning status for bucket '{}'...", bucket);
            let url = format!("{}/?versioning", cli.endpoint);
            let response = client
                .get(&url)
                .header("Host", format!("{}.s3.amazonaws.com", bucket))
                .send()
                .await
                .context("Failed to get versioning status")?;

            if response.status().is_success() {
                let body = response.text().await?;
                println!("{}", body);
                Ok(())
            } else {
                let error_text = response.text().await?;
                Err(anyhow::anyhow!("Get versioning failed: {}", error_text))
            }
        }
        VersioningAction::Enable { bucket } => {
            println!("Enabling versioning for bucket '{}'...", bucket);
            let versioning_config = r#"<?xml version="1.0" encoding="UTF-8"?>
<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <Status>Enabled</Status>
</VersioningConfiguration>"#;

            let url = format!("{}/?versioning", cli.endpoint);
            let response = client
                .put(&url)
                .header("Host", format!("{}.s3.amazonaws.com", bucket))
                .header("Content-Type", "application/xml")
                .body(versioning_config)
                .send()
                .await
                .context("Failed to enable versioning")?;

            if response.status().is_success() {
                println!("✓ Versioning enabled for bucket '{}'", bucket);
                Ok(())
            } else {
                let error_text = response.text().await?;
                Err(anyhow::anyhow!("Enable versioning failed: {}", error_text))
            }
        }
        VersioningAction::Suspend { bucket } => {
            println!("Suspending versioning for bucket '{}'...", bucket);
            let versioning_config = r#"<?xml version="1.0" encoding="UTF-8"?>
<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <Status>Suspended</Status>
</VersioningConfiguration>"#;

            let url = format!("{}/?versioning", cli.endpoint);
            let response = client
                .put(&url)
                .header("Host", format!("{}.s3.amazonaws.com", bucket))
                .header("Content-Type", "application/xml")
                .body(versioning_config)
                .send()
                .await
                .context("Failed to suspend versioning")?;

            if response.status().is_success() {
                println!("✓ Versioning suspended for bucket '{}'", bucket);
                Ok(())
            } else {
                let error_text = response.text().await?;
                Err(anyhow::anyhow!("Suspend versioning failed: {}", error_text))
            }
        }
        VersioningAction::ListVersions {
            bucket,
            prefix,
            max_keys,
        } => {
            println!("Listing object versions in bucket '{}'...", bucket);
            let mut url = format!("{}/?versions&max-keys={}", cli.endpoint, max_keys);
            if let Some(p) = prefix {
                url.push_str(&format!("&prefix={}", p));
            }

            let response = client
                .get(&url)
                .header("Host", format!("{}.s3.amazonaws.com", bucket))
                .send()
                .await
                .context("Failed to list object versions")?;

            if response.status().is_success() {
                let body = response.text().await?;
                println!("{}", body);
                Ok(())
            } else {
                let error_text = response.text().await?;
                Err(anyhow::anyhow!("List versions failed: {}", error_text))
            }
        }
    }
}

async fn handle_observability(
    client: &Client,
    cli: &Cli,
    action: &ObservabilityAction,
) -> Result<()> {
    match action {
        ObservabilityAction::Profiling { pprof } => {
            println!("Getting profiling data...");
            let mut url = format!("{}/api/observability/profiling", cli.endpoint);
            if *pprof {
                url.push_str("?format=pprof");
            }

            let response = client
                .get(&url)
                .send()
                .await
                .context("Failed to get profiling data")?;

            if response.status().is_success() {
                if *pprof {
                    // Binary pprof data
                    let bytes = response.bytes().await?;
                    println!("Received {} bytes of pprof data", bytes.len());
                    // Could save to file here if needed
                    Ok(())
                } else {
                    // JSON data
                    let result: Value = response.json().await?;
                    println!("{}", serde_json::to_string_pretty(&result)?);
                    Ok(())
                }
            } else {
                let error_text = response.text().await?;
                Err(anyhow::anyhow!("Get profiling failed: {}", error_text))
            }
        }
        ObservabilityAction::BusinessMetrics => {
            println!("Getting business metrics...");
            let url = format!("{}/api/observability/business-metrics", cli.endpoint);
            let response = client
                .get(&url)
                .send()
                .await
                .context("Failed to get business metrics")?;

            if response.status().is_success() {
                let result: Value = response.json().await?;
                println!("{}", serde_json::to_string_pretty(&result)?);
                Ok(())
            } else {
                let error_text = response.text().await?;
                Err(anyhow::anyhow!(
                    "Get business metrics failed: {}",
                    error_text
                ))
            }
        }
        ObservabilityAction::Anomalies {
            anomaly_type,
            severity,
            limit,
        } => {
            println!("Getting detected anomalies...");
            let mut url = format!("{}/api/observability/anomalies", cli.endpoint);
            let mut params = vec![];

            if let Some(t) = anomaly_type {
                params.push(format!("type={}", t));
            }
            if let Some(s) = severity {
                params.push(format!("severity={}", s));
            }
            if let Some(l) = limit {
                params.push(format!("limit={}", l));
            }

            if !params.is_empty() {
                url.push('?');
                url.push_str(&params.join("&"));
            }

            let response = client
                .get(&url)
                .send()
                .await
                .context("Failed to get anomalies")?;

            if response.status().is_success() {
                let result: Value = response.json().await?;
                println!("{}", serde_json::to_string_pretty(&result)?);
                Ok(())
            } else {
                let error_text = response.text().await?;
                Err(anyhow::anyhow!("Get anomalies failed: {}", error_text))
            }
        }
        ObservabilityAction::Resources => {
            println!("Getting resource manager statistics...");
            let url = format!("{}/api/observability/resources", cli.endpoint);
            let response = client
                .get(&url)
                .send()
                .await
                .context("Failed to get resource stats")?;

            if response.status().is_success() {
                let result: Value = response.json().await?;
                println!("{}", serde_json::to_string_pretty(&result)?);
                Ok(())
            } else {
                let error_text = response.text().await?;
                Err(anyhow::anyhow!("Get resource stats failed: {}", error_text))
            }
        }
        ObservabilityAction::Health => {
            println!("Getting comprehensive health check...");
            let url = format!("{}/api/observability/health", cli.endpoint);
            let response = client
                .get(&url)
                .send()
                .await
                .context("Failed to get health check")?;

            if response.status().is_success() {
                let result: Value = response.json().await?;
                println!("{}", serde_json::to_string_pretty(&result)?);
                Ok(())
            } else {
                let error_text = response.text().await?;
                Err(anyhow::anyhow!("Get health check failed: {}", error_text))
            }
        }
    }
}

async fn handle_transform(client: &Client, cli: &Cli, action: &TransformAction) -> Result<()> {
    match action {
        TransformAction::Image {
            bucket,
            key,
            width: _,
            height: _,
            format: _,
            quality: _,
            output,
        } => {
            println!("Applying image transformation to {}/{}", bucket, key);
            println!("Downloading object...");

            let url = format!("{}/{}/{}", cli.endpoint, bucket, key);
            let response = client
                .get(&url)
                .send()
                .await
                .context("Failed to download object")?;

            if !response.status().is_success() {
                return Err(anyhow::anyhow!(
                    "Failed to download object: {}",
                    response.status()
                ));
            }

            let data = response.bytes().await?;

            // Save transformed output
            std::fs::write(output, &data)?;
            println!("Transformed image saved to {}", output.display());
            println!(
                "Note: Actual image transformation is performed by rs3gw transformation engine"
            );
            Ok(())
        }
        TransformAction::Compress {
            bucket,
            key,
            algorithm,
            level,
            output,
        } => {
            println!("Applying {} compression to {}/{}", algorithm, bucket, key);
            println!("Downloading object...");

            let url = format!("{}/{}/{}", cli.endpoint, bucket, key);
            let response = client
                .get(&url)
                .send()
                .await
                .context("Failed to download object")?;

            if !response.status().is_success() {
                return Err(anyhow::anyhow!(
                    "Failed to download object: {}",
                    response.status()
                ));
            }

            let data = response.bytes().await?;

            // Save compressed output
            std::fs::write(output, &data)?;
            println!("Compressed data saved to {}", output.display());
            println!("Compression level: {:?}", level);
            Ok(())
        }
        TransformAction::TestWasm {
            plugin,
            input,
            params,
            output,
        } => {
            println!("Testing WASM plugin: {}", plugin.display());
            println!("Input file: {}", input.display());
            println!("Parameters: {:?}", params);

            // This is a placeholder - actual WASM plugin testing would require
            // the wasmtime runtime integration
            println!("WASM plugin testing functionality requires --features wasm-plugins");
            println!("Please use the rs3gw transformation API for actual plugin execution");

            if let Some(out) = output {
                println!("Would write output to: {}", out.display());
            }
            Ok(())
        }
    }
}

async fn handle_batch(client: &Client, cli: &Cli, action: &BatchAction) -> Result<()> {
    match action {
        BatchAction::DeleteByPrefix {
            bucket,
            prefix,
            dry_run,
            max,
        } => {
            println!("Batch delete from bucket {} with prefix {}", bucket, prefix);
            if *dry_run {
                println!("DRY RUN MODE - no objects will be deleted");
            }

            // List objects with prefix
            let mut url = format!("{}/{}?prefix={}", cli.endpoint, bucket, prefix);
            if let Some(max_keys) = max {
                url = format!("{}&max-keys={}", url, max_keys);
            }

            let response = client.get(&url).send().await?;
            if !response.status().is_success() {
                return Err(anyhow::anyhow!(
                    "Failed to list objects: {}",
                    response.status()
                ));
            }

            let body = response.text().await?;
            println!("Objects matching prefix: ");
            println!("{}", body);

            if *dry_run {
                println!("Dry run complete - no objects were deleted");
            } else {
                println!("Use DELETE API calls to remove objects (not yet implemented in CLI)");
            }
            Ok(())
        }
        BatchAction::CopyMultiple {
            source_bucket,
            dest_bucket,
            source_prefix,
            dest_prefix,
            max,
        } => {
            println!(
                "Batch copy from {}/{} to {}/{}",
                source_bucket,
                source_prefix,
                dest_bucket,
                dest_prefix.as_ref().unwrap_or(&source_prefix.clone())
            );

            println!("Maximum objects to copy: {:?}", max);
            println!("Batch copy functionality requires server-side batch API");
            println!("Use the S3 Batch operations API endpoint");
            Ok(())
        }
        BatchAction::TagMultiple {
            bucket,
            prefix,
            tags,
            max,
        } => {
            println!("Batch tagging in bucket {} with prefix {}", bucket, prefix);
            println!("Tags to apply: {}", tags);
            println!("Maximum objects: {:?}", max);
            println!("Batch tagging functionality requires server-side batch API");
            Ok(())
        }
    }
}

async fn handle_lifecycle(client: &Client, cli: &Cli, action: &LifecycleAction) -> Result<()> {
    match action {
        LifecycleAction::Get { bucket } => {
            println!("Getting lifecycle policy for bucket: {}", bucket);
            let url = format!("{}/?lifecycle", cli.endpoint);

            let response = client.get(&url).send().await?;
            if response.status().is_success() {
                let policy = response.text().await?;
                println!("{}", policy);
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to get lifecycle policy: {}",
                    response.status()
                ))
            }
        }
        LifecycleAction::Set {
            bucket,
            policy_file,
        } => {
            println!("Setting lifecycle policy for bucket: {}", bucket);
            println!("Policy file: {}", policy_file.display());

            let policy_content = std::fs::read_to_string(policy_file)?;
            println!("Policy: {}", policy_content);

            let url = format!("{}/?lifecycle", cli.endpoint);
            let response = client.put(&url).body(policy_content).send().await?;

            if response.status().is_success() {
                println!("Lifecycle policy set successfully");
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to set lifecycle policy: {}",
                    response.status()
                ))
            }
        }
        LifecycleAction::Delete { bucket } => {
            println!("Deleting lifecycle policy for bucket: {}", bucket);
            let url = format!("{}/?lifecycle", cli.endpoint);

            let response = client.delete(&url).send().await?;
            if response.status().is_success() {
                println!("Lifecycle policy deleted successfully");
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to delete lifecycle policy: {}",
                    response.status()
                ))
            }
        }
        LifecycleAction::ListRules { bucket } => {
            println!("Listing lifecycle rules for bucket: {}", bucket);

            // Get the policy and parse it
            let url = format!("{}/?lifecycle", cli.endpoint);
            let response = client.get(&url).send().await?;

            if response.status().is_success() {
                let policy: Value = response.json().await?;
                println!("{}", serde_json::to_string_pretty(&policy)?);
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to get lifecycle rules: {}",
                    response.status()
                ))
            }
        }
    }
}

async fn handle_preprocessing(
    client: &Client,
    cli: &Cli,
    action: &PreprocessingAction,
) -> Result<()> {
    match action {
        PreprocessingAction::Create { id, name, file } => {
            println!("Creating preprocessing pipeline:");
            println!("  ID: {}", id);
            println!("  Name: {}", name);
            println!("  Definition: {}", file.display());

            // Read pipeline definition
            let pipeline_content =
                fs::read_to_string(file).context("Failed to read pipeline definition file")?;

            // Parse to validate JSON
            let pipeline_json: Value = serde_json::from_str(&pipeline_content)
                .context("Invalid JSON in pipeline definition")?;

            // Validate required fields
            if pipeline_json.get("steps").is_none() {
                return Err(anyhow::anyhow!(
                    "Pipeline definition must include 'steps' array"
                ));
            }

            // Upload pipeline to S3 (simulated - would use S3 API)
            let bucket = "ml-datasets";
            let key = format!("pipelines/{}.json", id);
            let url = format!("{}/{}/{}", cli.endpoint, bucket, key);

            println!("\nUploading pipeline definition to: {}/{}", bucket, key);

            let response = client
                .put(&url)
                .body(pipeline_content)
                .header("Content-Type", "application/json")
                .send()
                .await
                .context("Failed to upload pipeline")?;

            if response.status().is_success() {
                println!("✓ Pipeline created successfully!");
                println!("\nNext steps:");
                println!("  1. List pipelines: rs3ctl preprocessing list");
                println!(
                    "  2. Apply pipeline: rs3ctl preprocessing apply --pipeline {}",
                    id
                );
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to create pipeline: {}",
                    response.status()
                ))
            }
        }

        PreprocessingAction::List { bucket } => {
            println!("Listing preprocessing pipelines in bucket: {}", bucket);

            let url = format!("{}/{}/?prefix=pipelines/", cli.endpoint, bucket);
            let response = client.get(&url).send().await?;

            if response.status().is_success() {
                let body = response.text().await?;
                // Parse S3 XML response (simplified - would use proper XML parsing)
                println!("\nAvailable pipelines:");
                println!("{}", body);
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to list pipelines: {}",
                    response.status()
                ))
            }
        }

        PreprocessingAction::Get { id, bucket } => {
            println!("Getting preprocessing pipeline: {}", id);

            let key = format!("pipelines/{}.json", id);
            let url = format!("{}/{}/{}", cli.endpoint, bucket, key);

            let response = client.get(&url).send().await?;

            if response.status().is_success() {
                let pipeline = response.text().await?;
                println!("\nPipeline definition:");
                println!("{}", pipeline);
                Ok(())
            } else if response.status().as_u16() == 404 {
                Err(anyhow::anyhow!("Pipeline '{}' not found", id))
            } else {
                Err(anyhow::anyhow!(
                    "Failed to get pipeline: {}",
                    response.status()
                ))
            }
        }

        PreprocessingAction::Delete { id, bucket } => {
            println!("Deleting preprocessing pipeline: {}", id);

            let key = format!("pipelines/{}.json", id);
            let url = format!("{}/{}/{}", cli.endpoint, bucket, key);

            let response = client.delete(&url).send().await?;

            if response.status().is_success() || response.status().as_u16() == 204 {
                println!("✓ Pipeline deleted successfully");
                Ok(())
            } else {
                Err(anyhow::anyhow!(
                    "Failed to delete pipeline: {}",
                    response.status()
                ))
            }
        }

        PreprocessingAction::Apply {
            pipeline,
            source_bucket,
            source_key,
            dest_bucket,
            dest_key,
        } => {
            println!("Applying preprocessing pipeline:");
            println!("  Pipeline: {}", pipeline);
            println!("  Source: {}/{}", source_bucket, source_key);
            println!("  Destination: {}/{}", dest_bucket, dest_key);

            println!("\nNote: Pipeline application would be done server-side");
            println!("This requires implementing a preprocessing API endpoint");
            println!("For now, use the Python example: examples/preprocessing_pipeline.py");

            Ok(())
        }

        PreprocessingAction::Validate { file } => {
            println!("Validating preprocessing pipeline definition:");
            println!("  File: {}", file.display());

            // Read and parse pipeline
            let pipeline_content =
                fs::read_to_string(file).context("Failed to read pipeline definition file")?;

            let pipeline: Value =
                serde_json::from_str(&pipeline_content).context("Invalid JSON format")?;

            // Validate structure
            let mut errors: Vec<String> = Vec::new();

            if pipeline.get("id").and_then(|v| v.as_str()).is_none() {
                errors.push("Missing or invalid 'id' field".to_string());
            }

            if pipeline.get("name").and_then(|v| v.as_str()).is_none() {
                errors.push("Missing or invalid 'name' field".to_string());
            }

            if pipeline.get("steps").and_then(|v| v.as_array()).is_none() {
                errors.push("Missing or invalid 'steps' array".to_string());
            } else {
                let steps = pipeline["steps"].as_array().expect("Steps array");
                for (i, step) in steps.iter().enumerate() {
                    if step.get("id").and_then(|v| v.as_str()).is_none() {
                        errors.push(format!("Step {}: missing 'id'", i));
                    }
                    if step.get("step_type").and_then(|v| v.as_str()).is_none() {
                        errors.push(format!("Step {}: missing 'step_type'", i));
                    }

                    // Validate step_type values
                    if let Some(step_type) = step.get("step_type").and_then(|v| v.as_str()) {
                        let valid_types = [
                            "image_normalization",
                            "image_resize",
                            "data_augmentation",
                            "text_tokenization",
                            "audio_features",
                            "video_frames",
                        ];
                        if !valid_types.contains(&step_type) {
                            errors.push(format!("Step {}: invalid step_type '{}'", i, step_type));
                        }
                    }
                }
            }

            if errors.is_empty() {
                println!("✓ Pipeline definition is valid!");
                println!("\nPipeline summary:");
                if let Some(id) = pipeline.get("id") {
                    println!("  ID: {}", id);
                }
                if let Some(name) = pipeline.get("name") {
                    println!("  Name: {}", name);
                }
                if let Some(steps) = pipeline.get("steps").and_then(|v| v.as_array()) {
                    println!("  Steps: {}", steps.len());
                    for (i, step) in steps.iter().enumerate() {
                        if let Some(step_type) = step.get("step_type") {
                            println!("    {}. {}", i + 1, step_type);
                        }
                    }
                }
                Ok(())
            } else {
                println!("✗ Pipeline validation failed:");
                for error in errors {
                    println!("  - {}", error);
                }
                Err(anyhow::anyhow!("Pipeline validation failed"))
            }
        }
    }
}