cloudreve-api 0.8.4

A Rust library for interacting with Cloudreve API
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
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
//! File operations for CloudreveAPI

use crate::Error;
use crate::api::v3::models as v3_models;
use crate::api::v4::models as v4_models;
use crate::api::v4::uri::path_to_uri;
use crate::client::UnifiedClient;
use log::debug;

/// How many matches a search returns before stopping, absent an explicit limit
const SEARCH_DEFAULT_LIMIT: usize = 1000;
/// Page size for server-side search
const SEARCH_PAGE_SIZE: u32 = 500;
/// Hard stop on paging, so a server that keeps handing out tokens can't spin us
const SEARCH_MAX_PAGES: u32 = 100;

/// Joins a v3 object's parent path and name into a full path
fn join_v3_path(parent: &str, name: &str) -> String {
    if parent == "/" {
        format!("/{}", name)
    } else {
        format!("{}/{}", parent.trim_end_matches('/'), name)
    }
}

/// One match from a server-side search
///
/// Normalized across API versions so callers need not branch on v3 vs v4.
#[derive(Debug, Clone)]
pub struct SearchHit {
    pub name: String,
    /// Full path of the item, ready to hand to delete/move/download
    pub path: String,
    pub is_folder: bool,
    pub size: i64,
    /// Last modification time exactly as the server reported it
    pub updated_at: String,
}

/// A single item that a batch operation could not process
#[derive(Debug, Clone)]
pub struct ItemFailure {
    /// Path as the caller submitted it
    pub path: String,
    /// Per-item business code, when the server reported one
    ///
    /// A `Some(40073)` here means the file is locked and `data` carries the
    /// tokens needed to force-unlock it.
    pub code: Option<i32>,
    pub message: String,
    /// Per-item payload, when the server attached one
    pub data: Option<serde_json::Value>,
}

impl ItemFailure {
    /// Record a failure the server did not itemize, e.g. a transport error.
    pub fn new(path: &str, message: String) -> Self {
        Self {
            path: path.to_string(),
            code: None,
            message,
            data: None,
        }
    }

    fn from_aggregated(path: &str, item: &v4_models::AggregatedItemError) -> Self {
        Self {
            path: path.to_string(),
            code: Some(item.code),
            message: item.msg.clone(),
            data: item.data.clone(),
        }
    }
}

/// Alias kept for callers written against the delete-specific name
pub type DeleteFailure = ItemFailure;

/// Result of batch delete operation
#[derive(Debug, Default)]
pub struct DeleteResult {
    pub deleted: usize,
    pub failed: usize,
    pub errors: Vec<ItemFailure>,
}

/// Result of a batch move or copy operation
#[derive(Debug, Default)]
pub struct TransferResult {
    pub succeeded: usize,
    pub failed: usize,
    pub errors: Vec<ItemFailure>,
}

/// Entries of a lock-conflict payload, which is an array of conflict details.
fn conflict_entries(data: &serde_json::Value) -> &[serde_json::Value] {
    match data.as_array() {
        Some(items) => items.as_slice(),
        None => std::slice::from_ref(data),
    }
}

/// URIs the server named as locked in a 40073 payload.
fn locked_uris(data: &serde_json::Value) -> std::collections::HashSet<&str> {
    conflict_entries(data)
        .iter()
        .filter_map(|item| item.get("path").and_then(|path| path.as_str()))
        .collect()
}

/// The single conflict detail describing `uri`, so a per-item failure carries
/// only its own unlock token rather than the whole batch's.
fn locked_entry(data: &serde_json::Value, uri: &str) -> Option<serde_json::Value> {
    conflict_entries(data)
        .iter()
        .find(|item| item.get("path").and_then(|path| path.as_str()) == Some(uri))
        .cloned()
}

/// Split submitted paths into successes and failures using the server's
/// per-item error map.
///
/// Items absent from `errors` succeeded. A key that matches nothing we sent is
/// still counted as a failure — the server normalizes URIs, and trusting its
/// tally over ours is safer than reporting an item as done.
fn partition_aggregated(
    paths: &[&str],
    uris: &[String],
    errors: &std::collections::HashMap<String, v4_models::AggregatedItemError>,
    succeeded: &mut usize,
    failures: &mut Vec<ItemFailure>,
) {
    let mut reported = std::collections::HashSet::new();
    for (path, uri) in paths.iter().zip(uris.iter()) {
        match errors.get(uri) {
            Some(item) => {
                reported.insert(uri.as_str());
                failures.push(ItemFailure::from_aggregated(path, item));
            }
            None => *succeeded += 1,
        }
    }
    for (uri, item) in errors.iter() {
        if reported.contains(uri.as_str()) {
            continue;
        }
        *succeeded = succeeded.saturating_sub(1);
        failures.push(ItemFailure::from_aggregated(uri, item));
    }
}

/// File operation methods for CloudreveAPI
impl super::CloudreveAPI {
    /// List files in a directory
    ///
    /// Returns a unified file list regardless of API version.
    pub async fn list_files(
        &self,
        path: &str,
        page: Option<u32>,
        page_size: Option<u32>,
    ) -> Result<FileList, Error> {
        debug!("Listing files in: {}", path);

        match &self.inner {
            UnifiedClient::V3(client) => {
                // V3 doesn't support pagination in list_directory
                let dir_list = client.list_directory(path).await?;
                Ok(FileList::V3(dir_list))
            }
            UnifiedClient::V4(client) => {
                let page_size = page_size.unwrap_or(100);

                // First, fetch the first page to check pagination mode (cursor vs offset)
                let first_request = v4_models::ListFilesRequest {
                    path,
                    page: Some(0),
                    page_size: Some(page_size),
                    order_by: None,
                    order_direction: None,
                    next_page_token: None,
                };
                let first_response = client.list_files(&first_request).await?;

                // If no page specified or requesting page 0, return the first page
                if page.is_none() || page == Some(0) {
                    return Ok(FileList::V4(Box::new(first_response)));
                }

                let target_page = page.unwrap();
                let is_cursor = first_response.pagination.is_cursor;

                if is_cursor {
                    // Cursor pagination: need to fetch pages sequentially to get next_page_token
                    let mut next_token = first_response.pagination.next_token.clone();
                    let mut current_response = first_response;

                    for current_page in 1..=target_page {
                        // Check if we have more pages
                        if next_token.is_none()
                            || next_token.as_ref().map(|t| t.is_empty()).unwrap_or(true)
                        {
                            return Err(Error::InvalidResponse(format!(
                                "Page {} does not exist (only {} pages available)",
                                target_page, current_page
                            )));
                        }

                        // Fetch next page using the token
                        let request = v4_models::ListFilesRequest {
                            path,
                            page: Some(current_page),
                            page_size: Some(page_size),
                            order_by: None,
                            order_direction: None,
                            next_page_token: next_token.as_deref(),
                        };
                        current_response = client.list_files(&request).await?;

                        // If this is the target page, return it
                        if current_page == target_page {
                            return Ok(FileList::V4(Box::new(current_response)));
                        }

                        // Get next token for next iteration
                        next_token = current_response.pagination.next_token.clone();
                    }

                    // Should not reach here, but handle the case
                    Ok(FileList::V4(Box::new(current_response)))
                } else {
                    // Offset pagination: can directly request the target page
                    let request = v4_models::ListFilesRequest {
                        path,
                        page: Some(target_page),
                        page_size: Some(page_size),
                        order_by: None,
                        order_direction: None,
                        next_page_token: None,
                    };
                    let list_response = client.list_files(&request).await?;
                    Ok(FileList::V4(Box::new(list_response)))
                }
            }
        }
    }

    /// List all files in a directory with automatic pagination
    ///
    /// This method automatically fetches all pages for V4 API and combines them.
    /// For V3 API, it returns the single page result (no pagination support).
    pub async fn list_files_all(
        &self,
        path: &str,
        page_size: Option<u32>,
    ) -> Result<FileListAll, Error> {
        debug!("Listing all files in: {} (with pagination)", path);

        let page_size = page_size.unwrap_or(500); // Default to 500 items per page

        match &self.inner {
            UnifiedClient::V3(client) => {
                // V3 doesn't support pagination
                let dir_list = client.list_directory(path).await?;
                Ok(FileListAll::V3(dir_list))
            }
            UnifiedClient::V4(client) => {
                let mut all_files = Vec::new();
                let mut parent: Option<v4_models::File> = None;
                let mut storage_policy: Option<v4_models::StoragePolicy> = None;
                #[allow(unused_assignments)]
                let mut pagination: Option<v4_models::PaginationResults> = None;
                let mut next_token: Option<String> = None;
                let mut page_num = 1;

                loop {
                    let request = v4_models::ListFilesRequest {
                        path,
                        page: Some(page_num),
                        page_size: Some(page_size),
                        order_by: None,
                        order_direction: None,
                        next_page_token: next_token.as_deref(),
                    };
                    let list_response = client.list_files(&request).await?;

                    // Store parent and storage_policy from first response
                    if parent.is_none() {
                        parent = Some(list_response.parent.clone());
                        storage_policy = list_response.storage_policy.clone();
                    }

                    // Collect files
                    all_files.extend(list_response.files);

                    // Check if there are more pages (before moving pagination)
                    next_token = list_response.pagination.next_token.clone();
                    let has_more = next_token.is_some();

                    // Store pagination info from last response
                    pagination = Some(list_response.pagination);

                    if !has_more {
                        break;
                    }

                    page_num += 1;
                    debug!(
                        "Fetching page {} (next_token: {})",
                        page_num,
                        next_token.as_ref().unwrap()
                    );
                }

                let parent = parent.expect("parent should always be set after first API call");
                let pagination = pagination.expect("should have at least one response");
                let combined_response = v4_models::ListResponse {
                    files: all_files,
                    parent,
                    pagination,
                    props: v4_models::NavigatorProps {
                        capability: String::new(),
                        max_page_size: page_size as i32,
                        order_by_options: Vec::new(),
                        order_direction_options: Vec::new(),
                    },
                    context_hint: String::new(),
                    mixed_type: false,
                    storage_policy,
                    view: None,
                };

                Ok(FileListAll::V4(Box::new(combined_response)))
            }
        }
    }

    /// Create a directory
    ///
    /// Creates a new directory at the specified path.
    pub async fn create_directory(&self, path: &str) -> Result<(), Error> {
        debug!("Creating directory: {}", path);

        match &self.inner {
            UnifiedClient::V3(client) => {
                let request = v3_models::CreateDirectoryRequest { path };
                client.create_directory(&request).await?;
                Ok(())
            }
            UnifiedClient::V4(client) => {
                client.create_directory(path).await?;
                Ok(())
            }
        }
    }

    /// Delete a file or directory
    ///
    /// Accepts either a path or URI for deletion.
    pub async fn delete(&self, target: DeleteTarget) -> Result<(), Error> {
        debug!("Deleting target: {:?}", target);

        match &self.inner {
            UnifiedClient::V3(client) => {
                // V3 requires IDs, not paths. Need to get the ID from the parent directory listing.
                let path = match &target {
                    DeleteTarget::Path(p) => p.as_str(),
                    DeleteTarget::Uri(u) => u.as_str(),
                };

                // Get the parent directory to find the object's ID
                let normalized_path = if path.ends_with('/') && path != "/" {
                    &path[..path.len() - 1]
                } else {
                    path
                };

                let parent_path = if normalized_path == "/" {
                    return Err(Error::InvalidResponse(
                        "Cannot delete root directory".to_string(),
                    ));
                } else {
                    let pos = normalized_path.rfind('/');
                    match pos {
                        Some(0) => "/",
                        Some(p) => &normalized_path[..p],
                        None => "/",
                    }
                };

                let file_name = normalized_path.rsplit('/').next().unwrap_or("");

                // List parent directory to find the object
                let dir_list = client.list_directory(parent_path).await?;

                // Find the object by name to get its ID and type
                let obj = dir_list
                    .objects
                    .iter()
                    .find(|obj| obj.name == file_name)
                    .ok_or_else(|| Error::InvalidResponse(format!("File not found: {}", path)))?;

                // Separate into files and folders based on object type
                let (folders, files) = if obj.object_type == "dir" {
                    (vec![obj.id.as_str()], Vec::<&str>::new())
                } else {
                    (Vec::<&str>::new(), vec![obj.id.as_str()])
                };

                let request = v3_models::DeleteObjectRequest {
                    items: files,
                    dirs: folders,
                    force: true,
                    unlink: false,
                };
                client.delete_object(&request).await?;
                Ok(())
            }
            UnifiedClient::V4(client) => {
                let path = match &target {
                    DeleteTarget::Path(p) => p.as_str(),
                    DeleteTarget::Uri(u) => u.as_str(),
                };
                client.delete_file(path).await?;
                Ok(())
            }
        }
    }

    /// Batch delete multiple files and/or folders
    ///
    /// This method accepts multiple paths and deletes them all in a single API call.
    /// Files and folders can be mixed in the same request. The server handles
    /// recursive deletion of folder contents automatically.
    ///
    /// # Arguments
    /// * `paths` - Slice of paths to delete (can mix files and folders)
    ///
    /// # Example
    /// ```no_run
    /// # use cloudreve_api::CloudreveAPI;
    /// # async fn example(api: &CloudreveAPI) -> cloudreve_api::Result<()> {
    /// // Delete multiple items at once
    /// api.batch_delete(&[
    ///     "/folder/file1.txt",
    ///     "/folder/file2.txt",
    ///     "/another_folder",  // folder will be deleted recursively
    /// ]).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn batch_delete(&self, paths: &[&str]) -> Result<DeleteResult, Error> {
        debug!("Batch deleting {} paths", paths.len());

        if paths.is_empty() {
            return Ok(DeleteResult::default());
        }

        match &self.inner {
            UnifiedClient::V3(client) => self.batch_delete_v3(client, paths).await,
            UnifiedClient::V4(client) => self.batch_delete_v4(client, paths).await,
        }
    }

    /// Search the server for files whose name contains `keyword`.
    ///
    /// This is the server's own index doing the work, not a client-side walk of
    /// the tree — one request per page instead of one per folder.
    ///
    /// # Arguments
    /// * `keyword` - Name fragment to look for
    /// * `path` - Folder to search under; "/" or "" covers the whole drive
    /// * `limit` - Stop after this many matches (default 1000)
    pub async fn search_files(
        &self,
        keyword: &str,
        path: &str,
        limit: Option<usize>,
    ) -> Result<Vec<SearchHit>, Error> {
        let limit = limit.unwrap_or(SEARCH_DEFAULT_LIMIT);
        debug!(
            "Searching for '{}' under {} (limit {})",
            keyword, path, limit
        );

        match &self.inner {
            UnifiedClient::V3(client) => {
                let list = client.search_files(keyword, path).await?;
                Ok(list
                    .objects
                    .into_iter()
                    .take(limit)
                    .map(|object| SearchHit {
                        path: join_v3_path(&object.path, &object.name),
                        name: object.name,
                        is_folder: object.object_type == "dir",
                        size: object.size,
                        updated_at: object.date,
                    })
                    .collect())
            }
            UnifiedClient::V4(client) => {
                let mut hits: Vec<SearchHit> = Vec::new();
                // Paging can repeat an entry across page boundaries; without this
                // the same file would surface twice.
                let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
                let mut next_token: Option<String> = None;
                let mut page = 0u32;

                while hits.len() < limit && page < SEARCH_MAX_PAGES {
                    let response = client
                        .search_files(&v4_models::SearchFilesRequest {
                            path,
                            keyword,
                            case_folding: true,
                            page: Some(page),
                            page_size: Some(SEARCH_PAGE_SIZE),
                            next_page_token: next_token.as_deref(),
                        })
                        .await?;

                    let before = hits.len();
                    let returned = response.files.len();
                    for file in response.files {
                        // 解码后再交出去:URI 里的路径段是编码过的,直接用会显示成
                        // /photos/Screenshot%20-%20%E5%89%AF%E6%9C%AC.png
                        let path = crate::api::v4::uri::uri_to_decoded_path(&file.path)
                            .unwrap_or_else(|_| file.path.clone());
                        if !seen.insert(path.clone()) {
                            continue;
                        }
                        hits.push(SearchHit {
                            name: file.name,
                            path,
                            is_folder: matches!(file.r#type, v4_models::FileType::Folder),
                            size: file.size,
                            updated_at: file.updated_at,
                        });
                        if hits.len() >= limit {
                            break;
                        }
                    }

                    next_token = response.pagination.next_token.clone();
                    // A short page, or one that added nothing new, means the end —
                    // trusting next_token alone can loop forever.
                    if next_token.is_none()
                        || (returned as u32) < SEARCH_PAGE_SIZE
                        || hits.len() == before
                    {
                        break;
                    }
                    page += 1;
                }

                Ok(hits)
            }
        }
    }

    /// Move any number of items into a destination directory.
    ///
    /// Unlike [`CloudreveAPI::move_file`], which resolves one source and can
    /// double as a rename, this always targets a directory — which lets V4
    /// send the whole set in a single request and report per-item failures
    /// instead of costing one round trip per file.
    pub async fn batch_move(&self, srcs: &[&str], dest_dir: &str) -> Result<TransferResult, Error> {
        self.batch_transfer(srcs, dest_dir, false).await
    }

    /// Copy any number of items into a destination directory.
    ///
    /// Batches the same way [`CloudreveAPI::batch_move`] does.
    pub async fn batch_copy(&self, srcs: &[&str], dest_dir: &str) -> Result<TransferResult, Error> {
        self.batch_transfer(srcs, dest_dir, true).await
    }

    async fn batch_transfer(
        &self,
        srcs: &[&str],
        dest_dir: &str,
        copy: bool,
    ) -> Result<TransferResult, Error> {
        let mut result = TransferResult::default();
        if srcs.is_empty() {
            return Ok(result);
        }
        debug!(
            "Batch {} of {} item(s) to {}",
            if copy { "copy" } else { "move" },
            srcs.len(),
            dest_dir
        );

        match &self.inner {
            UnifiedClient::V4(client) => {
                let dst = crate::api::v4::uri::path_to_uri(dest_dir);
                let mut pending: Vec<(&str, String)> = srcs
                    .iter()
                    .map(|p| (*p, crate::api::v4::uri::path_to_uri(p)))
                    .collect();

                loop {
                    let (batch_srcs, batch_uris): (Vec<&str>, Vec<String>) =
                        pending.iter().cloned().unzip();
                    let request = v4_models::MoveFileRequest {
                        uris: batch_uris.iter().map(|s| s.as_str()).collect(),
                        dst: &dst,
                        copy: if copy { Some(true) } else { None },
                    };
                    match client.move_file(&request).await {
                        Ok(()) => {
                            result.succeeded += pending.len();
                            break;
                        }
                        Err(Error::Aggregate { errors, .. }) => {
                            partition_aggregated(
                                &batch_srcs,
                                &batch_uris,
                                &errors,
                                &mut result.succeeded,
                                &mut result.errors,
                            );
                            break;
                        }
                        // As with delete, the server locks all targets at once,
                        // so one locked item aborts the request having moved
                        // nothing. Set the named ones aside and retry the rest
                        // as a batch.
                        Err(Error::ApiWithData { code, data, .. })
                            if code == v4_models::CODE_LOCK_CONFLICT =>
                        {
                            let locked = locked_uris(&data);
                            let before = pending.len();
                            pending.retain(|(src, uri)| {
                                if !locked.contains(uri.as_str()) {
                                    return true;
                                }
                                result.errors.push(ItemFailure {
                                    path: src.to_string(),
                                    code: Some(code),
                                    message: "Lock conflict".to_string(),
                                    data: locked_entry(&data, uri),
                                });
                                false
                            });

                            if pending.len() == before {
                                for (src, _) in &pending {
                                    result.errors.push(ItemFailure {
                                        path: src.to_string(),
                                        code: Some(code),
                                        message: "Lock conflict".to_string(),
                                        data: None,
                                    });
                                }
                                break;
                            }
                            if pending.is_empty() {
                                break;
                            }
                        }
                        // A whole-request failure says nothing about individual
                        // items, and retrying them one by one risks repeating
                        // work that may already have landed — report them all
                        // as failed and let the caller decide.
                        Err(e) => {
                            for (src, _) in &pending {
                                result.errors.push(ItemFailure {
                                    path: src.to_string(),
                                    code: e.code(),
                                    message: e.message().unwrap_or("transfer failed").to_string(),
                                    data: e.data().cloned(),
                                });
                            }
                            break;
                        }
                    }
                }
                result.failed = result.errors.len();
            }
            // V3 addresses objects by ID, so each source needs its own lookup
            // regardless; there is no batch to win here.
            UnifiedClient::V3(_) => {
                for src in srcs {
                    let outcome = if copy {
                        self.copy_file(src, dest_dir).await
                    } else {
                        self.move_file(src, dest_dir).await
                    };
                    match outcome {
                        Ok(()) => result.succeeded += 1,
                        Err(e) => {
                            result.failed += 1;
                            result.errors.push(ItemFailure::new(src, e.to_string()));
                        }
                    }
                }
            }
        }

        Ok(result)
    }

    /// Get file information by path or URI
    ///
    /// Returns unified file information regardless of API version.
    pub async fn get_file_info(&self, path: &str) -> Result<FileInfo, Error> {
        debug!("Getting file info for: {}", path);

        match &self.inner {
            UnifiedClient::V3(client) => {
                // V3: Use object property (requires ID) or get from directory listing
                // For simplicity, list the parent directory and find the object

                // Normalize path: remove trailing slash unless it's the root directory
                let normalized_path = if path.ends_with('/') && path != "/" {
                    &path[..path.len() - 1]
                } else {
                    path
                };

                let parent_path = if normalized_path == "/" {
                    "/"
                } else {
                    let pos = normalized_path.rfind('/');
                    match pos {
                        Some(0) => "/",
                        Some(p) => &normalized_path[..p],
                        None => "/",
                    }
                };

                let dir_list = client.list_directory(parent_path).await?;

                // Find the object by name
                let file_name = if normalized_path == "/" {
                    ""
                } else {
                    normalized_path.rsplit('/').next().unwrap_or("")
                };

                for obj in &dir_list.objects {
                    if obj.name == file_name {
                        return Ok(FileInfo::V3(obj.clone()));
                    }
                }

                Err(Error::InvalidResponse(format!("File not found: {}", path)))
            }
            UnifiedClient::V4(client) => {
                let request = v4_models::GetFileInfoRequest {
                    uri: path,
                    include_extended_info: Some(false),
                };
                let file = client.get_file_info_extended(&request).await?;
                Ok(FileInfo::V4(file))
            }
        }
    }

    /// Rename a file or directory
    ///
    /// Renames a file or directory at the given path to a new name.
    pub async fn rename(&self, path: &str, new_name: &str) -> Result<(), Error> {
        debug!("Renaming {} to {}", path, new_name);

        match &self.inner {
            UnifiedClient::V3(client) => {
                // V3 needs object ID, not path. Get the ID from parent directory listing.
                let normalized_path = if path.ends_with('/') && path != "/" {
                    &path[..path.len() - 1]
                } else {
                    path
                };

                let parent_path = if normalized_path == "/" {
                    return Err(Error::InvalidResponse(
                        "Cannot rename root directory".to_string(),
                    ));
                } else {
                    let pos = normalized_path.rfind('/');
                    match pos {
                        Some(0) => "/",
                        Some(p) => &normalized_path[..p],
                        None => "/",
                    }
                };

                let file_name = normalized_path.rsplit('/').next().unwrap_or("");

                debug!(
                    "V3 rename: parent_path={}, file_name={}, new_name={}",
                    parent_path, file_name, new_name
                );

                // List parent directory to find the object ID
                let dir_list = client.list_directory(parent_path).await?;

                debug!(
                    "V3 rename: found {} objects in parent directory",
                    dir_list.objects.len()
                );

                // Find the object by name to get its ID
                let obj = dir_list
                    .objects
                    .iter()
                    .find(|obj| obj.name == file_name)
                    .ok_or_else(|| {
                        // Provide helpful error message showing available files
                        let available_files: Vec<String> = dir_list.objects
                            .iter()
                            .filter(|obj| obj.object_type == "file")
                            .map(|obj| obj.name.clone())
                            .take(10)
                            .collect();
                        Error::InvalidResponse(format!(
                            "File not found: '{}'. Did you mean:\n  - {}\nAvailable files in {}: {}",
                            path,
                            available_files.join("\n  - "),
                            parent_path,
                            available_files.len()
                        ))
                    })?;

                debug!(
                    "V3 rename: found object id={}, type={}",
                    obj.id, obj.object_type
                );

                // Use object ID for rename
                let request = v3_models::RenameObjectRequest {
                    action: "rename",
                    src: v3_models::SourceItems {
                        dirs: if obj.object_type == "dir" {
                            vec![obj.id.as_str()]
                        } else {
                            vec![]
                        },
                        items: if obj.object_type != "dir" {
                            vec![obj.id.as_str()]
                        } else {
                            vec![]
                        },
                    },
                    new_name,
                };
                client.rename_object(&request).await?;
                Ok(())
            }
            UnifiedClient::V4(client) => {
                let uri = path_to_uri(path);
                let request = v4_models::RenameFileRequest {
                    uri: uri.as_str(),
                    new_name,
                };
                let _ = client.rename_file(&request).await?;
                Ok(())
            }
        }
    }

    /// Move a file or directory
    ///
    /// Moves a file or directory from source path to destination path.
    pub async fn move_file(&self, src: &str, dest: &str) -> Result<(), Error> {
        debug!("Moving {} to {}", src, dest);

        match &self.inner {
            UnifiedClient::V3(client) => {
                // V3 needs object ID, not path. Get the ID from parent directory listing.
                let normalized_path = if src.ends_with('/') && src != "/" {
                    &src[..src.len() - 1]
                } else {
                    src
                };

                // Normalize destination path - remove trailing slash unless it's root
                let normalized_dest = if dest.ends_with('/') && dest != "/" {
                    &dest[..dest.len() - 1]
                } else {
                    dest
                };

                let src_dir = if let Some(pos) = normalized_path.rfind('/') {
                    if pos == 0 {
                        "/"
                    } else {
                        &normalized_path[..pos]
                    }
                } else {
                    "/"
                };

                let file_name = normalized_path.rsplit('/').next().unwrap_or("");

                debug!(
                    "V3 move: src_dir={}, file_name={}, dest={}",
                    src_dir, file_name, normalized_dest
                );

                // List parent directory to find the object ID
                let dir_list = client.list_directory(src_dir).await?;

                // Find the object by name to get its ID
                let obj = dir_list
                    .objects
                    .iter()
                    .find(|obj| obj.name == file_name)
                    .ok_or_else(|| Error::InvalidResponse(format!("File not found: {}", src)))?;

                debug!(
                    "V3 move: found object id={}, type={}",
                    obj.id, obj.object_type
                );

                // Verify destination directory exists
                match client.list_directory(normalized_dest).await {
                    Ok(_) => {
                        debug!("V3 move: destination directory exists");
                    }
                    Err(e) => {
                        return Err(Error::InvalidResponse(format!(
                            "Destination directory '{}' does not exist or is not accessible: {}",
                            normalized_dest, e
                        )));
                    }
                }

                let request = v3_models::MoveObjectRequest {
                    action: "move",
                    src_dir,
                    src: v3_models::SourceItems {
                        dirs: if obj.object_type == "dir" {
                            vec![obj.id.as_str()]
                        } else {
                            vec![]
                        },
                        items: if obj.object_type != "dir" {
                            vec![obj.id.as_str()]
                        } else {
                            vec![]
                        },
                    },
                    dst: normalized_dest,
                };
                client.move_object(&request).await?;
                Ok(())
            }
            UnifiedClient::V4(client) => {
                // V4 API: Check if this is a rename operation (same directory)
                // Extract source directory and filename
                let src_normalized = if src.ends_with('/') && src != "/" {
                    &src[..src.len() - 1]
                } else {
                    src
                };

                let dest_normalized = if dest.ends_with('/') && dest != "/" {
                    &dest[..dest.len() - 1]
                } else {
                    dest
                };

                let src_dir = if let Some(pos) = src_normalized.rfind('/') {
                    if pos == 0 {
                        "/"
                    } else {
                        &src_normalized[..pos]
                    }
                } else {
                    "/"
                };

                let dest_dir = if let Some(pos) = dest_normalized.rfind('/') {
                    if pos == 0 {
                        "/"
                    } else {
                        &dest_normalized[..pos]
                    }
                } else {
                    "/"
                };

                let src_name = src_normalized.rsplit('/').next().unwrap_or("");
                let dest_name = dest_normalized.rsplit('/').next().unwrap_or("");

                // Same parent directory is ambiguous: dest may be a new name
                // (rename) or an existing sibling folder to move into. Ask the
                // server which it is before treating it as a rename.
                let is_rename = src_dir == dest_dir && src_name != dest_name && {
                    !matches!(
                        client.get_file_info(dest_normalized).await,
                        Ok(info) if matches!(info.r#type, v4_models::FileType::Folder)
                    )
                };

                if is_rename {
                    debug!(
                        "Detected rename operation within same directory: {} -> {}",
                        src, dest
                    );
                    let src_uri = path_to_uri(src);
                    let request = v4_models::RenameFileRequest {
                        uri: src_uri.as_str(),
                        new_name: dest_name,
                    };
                    let _ = client.rename_file(&request).await?;
                    Ok(())
                } else {
                    // dest is a directory (existing sibling folder or a
                    // cross-directory target); move into it
                    let src_uri = path_to_uri(src);
                    let dest_uri = path_to_uri(dest);
                    let request = v4_models::MoveFileRequest {
                        uris: vec![src_uri.as_str()],
                        dst: dest_uri.as_str(),
                        copy: None,
                    };
                    client.move_file(&request).await?;
                    Ok(())
                }
            }
        }
    }

    /// Copy a file or directory
    ///
    /// Copies a file or directory from source path to destination path.
    pub async fn copy_file(&self, src: &str, dest: &str) -> Result<(), Error> {
        debug!("Copying {} to {}", src, dest);

        match &self.inner {
            UnifiedClient::V3(client) => {
                // V3 needs object ID, not path. Get the ID from parent directory listing.
                let normalized_path = if src.ends_with('/') && src != "/" {
                    &src[..src.len() - 1]
                } else {
                    src
                };

                let src_dir = if let Some(pos) = normalized_path.rfind('/') {
                    if pos == 0 {
                        "/"
                    } else {
                        &normalized_path[..pos]
                    }
                } else {
                    "/"
                };

                let file_name = normalized_path.rsplit('/').next().unwrap_or("");

                // List parent directory to find the object ID
                let dir_list = client.list_directory(src_dir).await?;

                // Find the object by name to get its ID
                let obj = dir_list
                    .objects
                    .iter()
                    .find(|obj| obj.name == file_name)
                    .ok_or_else(|| Error::InvalidResponse(format!("File not found: {}", src)))?;

                let request = v3_models::CopyObjectRequest {
                    src_dir,
                    src: v3_models::SourceItems {
                        dirs: if obj.object_type == "dir" {
                            vec![obj.id.as_str()]
                        } else {
                            vec![]
                        },
                        items: if obj.object_type != "dir" {
                            vec![obj.id.as_str()]
                        } else {
                            vec![]
                        },
                    },
                    dst: dest,
                };
                client.copy_object(&request).await?;
                Ok(())
            }
            UnifiedClient::V4(client) => {
                // Parse source and destination paths
                let src_normalized = if src.ends_with('/') && src != "/" {
                    &src[..src.len() - 1]
                } else {
                    src
                };
                let dest_normalized = if dest.ends_with('/') && dest != "/" {
                    &dest[..dest.len() - 1]
                } else {
                    dest
                };

                // Extract source directory and file name
                let src_dir = if let Some(pos) = src_normalized.rfind('/') {
                    if pos == 0 {
                        "/"
                    } else {
                        &src_normalized[..pos]
                    }
                } else {
                    "/"
                };
                let src_name = src_normalized.rsplit('/').next().unwrap_or("");

                // Extract destination directory and file name
                // For V4 API, the dst parameter should be the target directory URI
                // If dest ends with a filename (different from src), we need to handle it specially
                let dest_dir = if let Some(pos) = dest_normalized.rfind('/') {
                    if pos == 0 {
                        "/"
                    } else {
                        &dest_normalized[..pos]
                    }
                } else {
                    "/"
                };
                let dest_name = dest_normalized.rsplit('/').next().unwrap_or("");

                let src_uri = path_to_uri(src);
                let dest_dir_uri = path_to_uri(dest_dir);

                // If dest is an existing folder, this is a plain "copy into
                // directory" — not a copy+rename (sibling folder case) nor a
                // copy into dest's parent (standard case below).
                if matches!(
                    client.get_file_info(dest_normalized).await,
                    Ok(info) if matches!(info.r#type, v4_models::FileType::Folder)
                ) {
                    let dest_uri = path_to_uri(dest_normalized);
                    let request = v4_models::CopyFileRequest {
                        uris: vec![src_uri.as_str()],
                        dst: dest_uri.as_str(),
                    };
                    client.copy_file(&request).await?;
                    return Ok(());
                }

                // Check if this is a "copy and rename" operation (same directory, different name)
                if src_dir == dest_dir && src_name != dest_name && !dest_name.is_empty() {
                    // V4 API doesn't support copy+rename in one operation
                    // Strategy: Use a temporary directory as an intermediate step
                    debug!(
                        "Detected copy+rename operation in same directory: {} -> {}",
                        src, dest
                    );

                    // Step 0: If destination file exists, delete it first
                    let dest_path = format!("{}/{}", dest_dir.trim_end_matches('/'), dest_name);
                    let dest_uri = path_to_uri(&dest_path);
                    if client.get_file_info(dest_uri.as_str()).await.is_err() {
                        // File doesn't exist, continue
                    } else {
                        // File exists, delete it
                        debug!("Destination file exists, deleting: {}", dest_path);
                        let delete_request = v4_models::DeleteFileRequest {
                            uris: vec![dest_uri.as_str()],
                            unlink: None,
                            skip_soft_delete: None,
                        };
                        let _: Result<v4_models::ApiResponse<()>, _> =
                            client.delete_with_body("/file", &delete_request).await;
                    }

                    // Step 1: Create a temporary directory
                    let temp_dir_name = format!(".temp_copy_{}", std::process::id());
                    let temp_dir_path =
                        format!("{}/{}", dest_dir.trim_end_matches('/'), temp_dir_name);
                    let _ = client.create_directory(&temp_dir_path).await;

                    // Step 2: Copy to the temporary directory
                    let temp_dir_uri = path_to_uri(&temp_dir_path);
                    let copy_request = v4_models::CopyFileRequest {
                        uris: vec![src_uri.as_str()],
                        dst: temp_dir_uri.as_str(),
                    };
                    client.copy_file(&copy_request).await?;

                    // Step 3: Rename the file in temporary directory to a unique name
                    let temp_file_old_uri = path_to_uri(&format!(
                        "{}/{}",
                        temp_dir_path.trim_end_matches('/'),
                        src_name
                    ));
                    let temp_file_new_name = format!("{}_copy", src_name);
                    let rename_request = v4_models::RenameFileRequest {
                        uri: temp_file_old_uri.as_str(),
                        new_name: temp_file_new_name.as_str(),
                    };
                    let _ = client.rename_file(&rename_request).await?;

                    // Step 4: Move from temp directory to destination directory
                    let temp_file_new_uri = path_to_uri(&format!(
                        "{}/{}",
                        temp_dir_path.trim_end_matches('/'),
                        temp_file_new_name
                    ));
                    let move_request = v4_models::MoveFileRequest {
                        uris: vec![temp_file_new_uri.as_str()],
                        dst: dest_dir_uri.as_str(),
                        copy: None,
                    };
                    client.move_file(&move_request).await?;

                    // Step 5: Rename to the final destination name
                    let moved_uri = path_to_uri(&format!(
                        "{}/{}",
                        dest_dir.trim_end_matches('/'),
                        temp_file_new_name
                    ));
                    let final_rename_request = v4_models::RenameFileRequest {
                        uri: moved_uri.as_str(),
                        new_name: dest_name,
                    };
                    let _ = client.rename_file(&final_rename_request).await?;

                    // Step 6: Clean up temporary directory
                    let temp_dir_uri_for_delete = path_to_uri(&temp_dir_path);
                    let delete_request = v4_models::DeleteFileRequest {
                        uris: vec![temp_dir_uri_for_delete.as_str()],
                        unlink: None,
                        skip_soft_delete: None,
                    };
                    let _: Result<v4_models::ApiResponse<()>, _> =
                        client.delete_with_body("/file", &delete_request).await;

                    Ok(())
                } else {
                    // Standard copy operation to different directory
                    let request = v4_models::CopyFileRequest {
                        uris: vec![src_uri.as_str()],
                        dst: dest_dir_uri.as_str(),
                    };
                    client.copy_file(&request).await?;
                    Ok(())
                }
            }
        }
    }

    /// Download a file
    ///
    /// Returns the download URL for the file.
    pub async fn download_file(&self, path: &str) -> Result<String, Error> {
        debug!("Downloading file: {}", path);

        match &self.inner {
            UnifiedClient::V3(client) => {
                // V3: Need file ID, not path
                // Parse path to get parent directory and filename
                let normalized_path = if path.ends_with('/') && path != "/" {
                    &path[..path.len() - 1]
                } else {
                    path
                };

                let parent_path = if normalized_path == "/" {
                    "/"
                } else {
                    let pos = normalized_path.rfind('/');
                    match pos {
                        Some(0) => "/",
                        Some(p) => &normalized_path[..p],
                        None => "/",
                    }
                };

                let file_name = normalized_path.rsplit('/').next().unwrap_or("");

                debug!(
                    "V3: Looking for file '{}' in parent directory '{}'",
                    file_name, parent_path
                );

                // List directory to find file ID
                let dir_list = client.list_directory(parent_path).await?;
                let file_id = dir_list
                    .objects
                    .iter()
                    .find(|obj| obj.name == file_name)
                    .ok_or_else(|| Error::InvalidResponse(format!("File not found: {}", path)))?
                    .id
                    .clone();

                debug!("V3: Found file ID: {}", file_id);

                // Download using file ID
                let url_info = client.download_file(&file_id).await?;
                // Construct full URL from base_url and relative path
                let full_url = format!("{}{}", self.base_url.trim_end_matches('/'), url_info.url);
                Ok(full_url)
            }
            UnifiedClient::V4(client) => {
                let request = v4_models::CreateDownloadUrlRequest {
                    uris: vec![path],
                    download: Some(true),
                    redirect: Some(false), // 不自动重定向,返回 JSON 响应
                    entity: None,
                    use_primary_site_url: None,
                    skip_error: None,
                    archive: None,
                    no_cache: None,
                };
                let response = client.create_download_url(&request).await?;
                if let Some(first_url) = response.urls.first() {
                    Ok(first_url.url.clone())
                } else {
                    Err(Error::InvalidResponse(
                        "No download URL returned".to_string(),
                    ))
                }
            }
        }
    }

    /// Restore a file from trash
    ///
    /// Restores a file or directory from the trash. Only available in V4.
    pub async fn restore_file(&self, path: &str) -> Result<(), Error> {
        debug!("Restoring file: {}", path);

        match &self.inner {
            UnifiedClient::V3(_) => Err(Error::UnsupportedFeature(
                "restore from trash".to_string(),
                "v3".to_string(),
            )),
            UnifiedClient::V4(client) => {
                let request = v4_models::RestoreFileRequest { uris: vec![path] };
                client.restore_from_trash(&request).await?;
                Ok(())
            }
        }
    }

    /// Preview a file
    ///
    /// Returns preview information for the file. For V3, requires file ID.
    pub async fn preview_file(&self, file_id: &str) -> Result<String, Error> {
        debug!("Previewing file: {}", file_id);

        match &self.inner {
            UnifiedClient::V3(client) => {
                // V3: Get preview info
                let _preview = client.preview_file(file_id).await?;
                // Return preview URL or info
                Ok(format!("Preview available for file: {}", file_id))
            }
            UnifiedClient::V4(_client) => {
                // V4 preview implementation would go here
                Err(Error::UnsupportedFeature(
                    "preview".to_string(),
                    "v4".to_string(),
                ))
            }
        }
    }

    /// Get thumbnail for a file
    ///
    /// Returns thumbnail information for the file. For V3, requires file ID.
    pub async fn get_thumbnail(&self, file_id: &str) -> Result<String, Error> {
        debug!("Getting thumbnail for file: {}", file_id);

        match &self.inner {
            UnifiedClient::V3(client) => {
                // V3: Get thumbnail info
                let _thumbnail = client.get_thumbnail(file_id).await?;
                Ok(format!("Thumbnail available for file: {}", file_id))
            }
            UnifiedClient::V4(_client) => {
                // V4 thumbnail implementation would go here
                Err(Error::UnsupportedFeature(
                    "thumbnail".to_string(),
                    "v4".to_string(),
                ))
            }
        }
    }
}

/// Unified file list response
///
/// Wraps both V3 and V4 directory listing responses.
#[derive(Debug)]
pub enum FileList {
    V3(v3_models::DirectoryList),
    V4(Box<v4_models::ListResponse>),
}

impl FileList {
    /// Get parent directory name
    pub fn parent_name(&self) -> String {
        match self {
            FileList::V3(d) => d.parent.clone(), // V3: parent field is the parent ID
            FileList::V4(r) => r.parent.name.clone(),
        }
    }

    /// Get parent directory ID
    pub fn parent_id(&self) -> String {
        match self {
            FileList::V3(d) => d.parent.clone(), // V3: parent field is the parent ID
            FileList::V4(r) => r.parent.id.clone(),
        }
    }

    /// Get parent directory path
    pub fn parent_path(&self) -> String {
        match self {
            FileList::V3(_) => String::new(), // V3 doesn't provide parent path
            FileList::V4(r) => r.parent.path.clone(),
        }
    }

    /// Get storage policy ID (V4 only)
    pub fn storage_policy_id(&self) -> Option<String> {
        match self {
            FileList::V3(_) => None,
            FileList::V4(r) => r.storage_policy.as_ref().map(|p| p.id.clone()),
        }
    }

    /// Get storage policy name (V4 only)
    pub fn storage_policy_name(&self) -> Option<String> {
        match self {
            FileList::V3(_) => None,
            FileList::V4(r) => r.storage_policy.as_ref().map(|p| p.name.clone()),
        }
    }

    /// Get files and folders
    pub fn items(&self) -> Vec<FileItem> {
        match self {
            FileList::V3(d) => d
                .objects
                .iter()
                .map(|obj| FileItem {
                    name: obj.name.clone(),
                    is_folder: obj.object_type == "dir",
                    size: obj.size,
                })
                .collect(),
            FileList::V4(r) => r
                .files
                .iter()
                .map(|file| FileItem {
                    name: file.name.clone(),
                    is_folder: matches!(file.r#type, v4_models::FileType::Folder),
                    size: file.size,
                })
                .collect(),
        }
    }

    /// Get total count
    pub fn total_count(&self) -> usize {
        self.items().len()
    }

    /// Get next page token (V4 only)
    pub fn next_token(&self) -> Option<String> {
        match self {
            FileList::V3(_) => None,
            FileList::V4(r) => r.pagination.next_token.clone(),
        }
    }

    /// Get total items count from pagination (V4 only)
    pub fn total_items(&self) -> Option<i64> {
        match self {
            FileList::V3(_) => None,
            FileList::V4(r) => r.pagination.total_items,
        }
    }

    /// Check if there are more pages (V4 only)
    pub fn has_more_pages(&self) -> bool {
        self.next_token().is_some()
    }
}

/// Unified file list with automatic pagination support
///
/// This variant contains all pages combined for V4 API.
pub enum FileListAll {
    V3(v3_models::DirectoryList),
    V4(Box<v4_models::ListResponse>),
}

impl FileListAll {
    /// Get parent directory name
    pub fn parent_name(&self) -> String {
        match self {
            FileListAll::V3(d) => d.parent.clone(),
            FileListAll::V4(r) => r.parent.name.clone(),
        }
    }

    /// Get parent directory ID
    pub fn parent_id(&self) -> String {
        match self {
            FileListAll::V3(d) => d.parent.clone(),
            FileListAll::V4(r) => r.parent.id.clone(),
        }
    }

    /// Get parent directory path
    pub fn parent_path(&self) -> String {
        match self {
            FileListAll::V3(_) => String::new(),
            FileListAll::V4(r) => r.parent.path.clone(),
        }
    }

    /// Get storage policy ID (V4 only)
    pub fn storage_policy_id(&self) -> Option<String> {
        match self {
            FileListAll::V3(_) => None,
            FileListAll::V4(r) => r.storage_policy.as_ref().map(|p| p.id.clone()),
        }
    }

    /// Get storage policy name (V4 only)
    pub fn storage_policy_name(&self) -> Option<String> {
        match self {
            FileListAll::V3(_) => None,
            FileListAll::V4(r) => r.storage_policy.as_ref().map(|p| p.name.clone()),
        }
    }

    /// Get files and folders (all pages combined)
    pub fn items(&self) -> Vec<FileItem> {
        match self {
            FileListAll::V3(d) => d
                .objects
                .iter()
                .map(|obj| FileItem {
                    name: obj.name.clone(),
                    is_folder: obj.object_type == "dir",
                    size: obj.size,
                })
                .collect(),
            FileListAll::V4(r) => r
                .files
                .iter()
                .map(|file| FileItem {
                    name: file.name.clone(),
                    is_folder: matches!(file.r#type, v4_models::FileType::Folder),
                    size: file.size,
                })
                .collect(),
        }
    }

    /// Get total count (all items)
    pub fn total_count(&self) -> usize {
        self.items().len()
    }

    /// Get total items count from pagination (V4 only)
    pub fn total_items(&self) -> Option<i64> {
        match self {
            FileListAll::V3(_) => None,
            FileListAll::V4(r) => r.pagination.total_items,
        }
    }
}

/// Unified file/folder item
#[derive(Debug, Clone)]
pub struct FileItem {
    pub name: String,
    pub is_folder: bool,
    pub size: i64,
}

/// Target for delete operation
///
/// Accepts either a path or URI to provide flexibility.
#[derive(Debug, Clone)]
pub enum DeleteTarget {
    Path(String),
    Uri(String),
}

impl From<&str> for DeleteTarget {
    fn from(s: &str) -> Self {
        if s.starts_with("cloudreve://") {
            DeleteTarget::Uri(s.to_string())
        } else {
            DeleteTarget::Path(s.to_string())
        }
    }
}

impl From<String> for DeleteTarget {
    fn from(s: String) -> Self {
        if s.starts_with("cloudreve://") {
            DeleteTarget::Uri(s)
        } else {
            DeleteTarget::Path(s)
        }
    }
}

/// Unified file information response
///
/// Wraps both V3 and V4 file information responses.
#[derive(Debug, Clone)]
pub enum FileInfo {
    V3(v3_models::Object),
    V4(v4_models::File),
}

impl FileInfo {
    /// Get file name
    pub fn name(&self) -> String {
        match self {
            FileInfo::V3(obj) => obj.name.clone(),
            FileInfo::V4(file) => file.name.clone(),
        }
    }

    /// Get file size
    pub fn size(&self) -> i64 {
        match self {
            FileInfo::V3(obj) => obj.size,
            FileInfo::V4(file) => file.size,
        }
    }

    /// Check if it's a folder
    pub fn is_folder(&self) -> bool {
        match self {
            FileInfo::V3(obj) => obj.object_type == "dir",
            FileInfo::V4(file) => matches!(file.r#type, v4_models::FileType::Folder),
        }
    }

    /// Get file path
    pub fn path(&self) -> String {
        match self {
            FileInfo::V3(obj) => obj.path.clone(),
            FileInfo::V4(file) => file.path.clone(),
        }
    }

    /// Get created date
    pub fn created_at(&self) -> String {
        match self {
            FileInfo::V3(obj) => obj.create_date.clone(),
            FileInfo::V4(file) => file.created_at.clone(),
        }
    }

    /// Get updated date
    pub fn updated_at(&self) -> String {
        match self {
            FileInfo::V3(obj) => obj.date.clone(),
            FileInfo::V4(file) => file.updated_at.clone(),
        }
    }
}

// Private methods for batch_delete
impl super::CloudreveAPI {
    async fn batch_delete_v3(
        &self,
        client: &crate::api::v3::ApiV3Client,
        paths: &[&str],
    ) -> Result<DeleteResult, Error> {
        let mut result = DeleteResult::default();

        // Group paths by parent directory to minimize API calls
        use std::collections::HashMap;
        let mut parent_groups: HashMap<&str, Vec<&str>> = HashMap::new();

        for path in paths {
            // Normalize path
            let normalized = if path.ends_with('/') && *path != "/" {
                &path[..path.len() - 1]
            } else {
                *path
            };

            // Get parent directory
            let parent = if normalized == "/" {
                return Err(Error::InvalidResponse(
                    "Cannot delete root directory".to_string(),
                ));
            } else {
                let pos = normalized.rfind('/');
                match pos {
                    Some(0) => "/",
                    Some(p) => &normalized[..p],
                    None => "/",
                }
            };

            parent_groups.entry(parent).or_default().push(normalized);
        }

        // For each parent directory, list once and delete all items
        for (parent_dir, items) in parent_groups {
            let dir_list = match client.list_directory(parent_dir).await {
                Ok(list) => list,
                Err(e) => {
                    // All items in this group failed
                    result.failed += items.len();
                    for item in &items {
                        result.errors.push(DeleteFailure::new(item, e.to_string()));
                    }
                    continue;
                }
            };

            // Find IDs for all items and separate into files and folders
            let mut file_ids = Vec::new();
            let mut folder_ids = Vec::new();

            for item_path in &items {
                let file_name = item_path.rsplit('/').next().unwrap_or("");

                match dir_list.objects.iter().find(|obj| obj.name == file_name) {
                    Some(obj) => {
                        if obj.object_type == "dir" {
                            folder_ids.push(obj.id.as_str());
                        } else {
                            file_ids.push(obj.id.as_str());
                        }
                    }
                    None => {
                        result.failed += 1;
                        result
                            .errors
                            .push(DeleteFailure::new(item_path, "File not found".to_string()));
                    }
                }
            }

            // Delete all files and folders in one API call
            if !file_ids.is_empty() || !folder_ids.is_empty() {
                let item_count = file_ids.len() + folder_ids.len();
                let request = v3_models::DeleteObjectRequest {
                    items: file_ids,
                    dirs: folder_ids,
                    force: true,
                    unlink: false,
                };

                match client.delete_object(&request).await {
                    Ok(_) => {
                        result.deleted += item_count;
                    }
                    Err(e) => {
                        result.failed += item_count;
                        for item_path in &items {
                            result
                                .errors
                                .push(DeleteFailure::new(item_path, e.to_string()));
                        }
                    }
                }
            }
        }

        Ok(result)
    }

    async fn batch_delete_v4(
        &self,
        client: &crate::api::v4::ApiV4Client,
        paths: &[&str],
    ) -> Result<DeleteResult, Error> {
        let mut result = DeleteResult::default();

        // Everything still awaiting an answer, as (caller path, URI) pairs.
        let mut pending: Vec<(&str, String)> = paths
            .iter()
            .map(|p| (*p, crate::api::v4::uri::path_to_uri(p)))
            .collect();

        loop {
            let (batch_paths, batch_uris): (Vec<&str>, Vec<String>) =
                pending.iter().cloned().unzip();
            let request = v4_models::DeleteFileRequest {
                uris: batch_uris.iter().map(|s| s.as_str()).collect(),
                unlink: None,
                skip_soft_delete: None,
            };

            match client.delete_files(&request).await {
                Ok(()) => {
                    result.deleted += pending.len();
                    break;
                }
                // A partial failure already names every item that failed, so
                // the successful ones need no second look: they are the
                // submitted URIs minus these keys.
                Err(Error::Aggregate { errors, .. }) => {
                    partition_aggregated(
                        &batch_paths,
                        &batch_uris,
                        &errors,
                        &mut result.deleted,
                        &mut result.errors,
                    );
                    break;
                }
                // The server locks every target at once, so one locked file
                // aborts the whole request without deleting anything — but it
                // names the offenders. Drop those and resend the rest as a
                // batch; retrying item by item here would undo the round-trip
                // saving that batching exists for.
                Err(Error::ApiWithData { code, data, .. })
                    if code == v4_models::CODE_LOCK_CONFLICT =>
                {
                    let locked = locked_uris(&data);
                    let before = pending.len();
                    pending.retain(|(path, uri)| {
                        if !locked.contains(uri.as_str()) {
                            return true;
                        }
                        result.errors.push(ItemFailure {
                            path: path.to_string(),
                            code: Some(code),
                            message: "Lock conflict".to_string(),
                            data: locked_entry(&data, uri),
                        });
                        false
                    });

                    // Nothing identifiable was peeled off — without progress
                    // this would loop forever, so fall back to per-item probing.
                    if pending.len() == before {
                        debug!("Lock conflict named no submitted URI, probing individually");
                        Self::probe_individually(client, &pending, &mut result).await;
                        break;
                    }
                    if pending.is_empty() {
                        break;
                    }
                    debug!(
                        "Lock conflict on {} item(s), resending the remaining {}",
                        before - pending.len(),
                        pending.len()
                    );
                }
                // Anything else is an outcome for the request as a whole, which
                // says nothing about the individual items — retry them one by
                // one to find out where the failure actually lies.
                Err(e) => {
                    debug!(
                        "Batch delete failed ({}), falling back to individual deletion",
                        e
                    );
                    Self::probe_individually(client, &pending, &mut result).await;
                    break;
                }
            }
        }

        result.failed = result.errors.len();
        Ok(result)
    }

    /// Delete one URI at a time to attribute a whole-request failure.
    async fn probe_individually(
        client: &crate::api::v4::ApiV4Client,
        pending: &[(&str, String)],
        result: &mut DeleteResult,
    ) {
        for (path, uri) in pending {
            let request = v4_models::DeleteFileRequest {
                uris: vec![uri.as_str()],
                unlink: None,
                skip_soft_delete: None,
            };
            match client.delete_files(&request).await {
                Ok(()) => result.deleted += 1,
                Err(e) => result.errors.push(ItemFailure {
                    path: path.to_string(),
                    code: e.code(),
                    message: e.message().unwrap_or("delete failed").to_string(),
                    data: e.data().cloned(),
                }),
            }
        }
    }
}