anytype 0.5.0

An ergonomic Anytype API client in rust
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
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
//! # Anytype Files
//!
//! File transfers use REST when the HTTP API has equivalent functionality.
//! Metadata, search, preload, URL upload, and uploads with rich placement/style
//! options continue to use gRPC.
//!

use std::{
    fmt,
    path::{Path, PathBuf},
    pin::Pin,
};

use anytype_rpc::{
    anytype::rpc::{
        file::{discard_preload, download, upload},
        object::search_with_meta,
    },
    deadline::{GrpcCallOptions, GrpcTimeoutClass, GrpcTimeoutOutcome, with_grpc_call_options},
    model,
};
use bytes::Bytes;
use chrono::{DateTime, FixedOffset, Utc};
use prost_types::{ListValue, Struct, Value};
use reqwest::{
    Method, StatusCode,
    header::{
        ACCEPT_RANGES, CACHE_CONTROL, CONTENT_LENGTH, CONTENT_RANGE, CONTENT_TYPE, ETAG, HeaderMap,
        HeaderName, HeaderValue, IF_MATCH, IF_MODIFIED_SINCE, IF_NONE_MATCH, IF_RANGE,
        IF_UNMODIFIED_SINCE, LAST_MODIFIED, RANGE,
    },
};
use serde::{Deserialize, Serialize};
use serde_json::Number;
use tokio::io::AsyncRead;
use tonic::Request;
use tracing::{debug, error, info};

use crate::{
    Result,
    client::AnytypeClient,
    error::AnytypeError,
    filters::{Filter, Sort, SortDirection},
    grpc_util::{ensure_error_ok, grpc_status, grpc_status_for, with_token_request},
    paged::{PagedResult, PaginatedResponse, PaginationMeta},
};

// ============================================================================
// Public types
// ============================================================================

/// Hard ceiling for retained allowlisted file-response header evidence.
pub const MAX_FILE_HEADER_EVIDENCE_BYTES: u64 = 1024 * 1024;
/// Hard ceiling for physical attempts made by one file request.
pub const MAX_FILE_REQUEST_ATTEMPTS: u32 = 6;

pub(crate) const DEFAULT_FILE_HEADER_EVIDENCE_BYTES: u64 = 64 * 1024;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileObject {
    pub id: String,
    pub space_id: String,
    pub name: Option<String>,
    pub size: Option<i64>,
    pub mime: Option<String>,
    pub added_at: Option<DateTime<FixedOffset>>,
    #[serde(default)]
    pub file_type: FileType,
    pub style: FileStyle,
    pub target_object_id: Option<String>,
    pub details: serde_json::Value,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize, strum::EnumString, strum::Display)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum FileType {
    #[default]
    File,
    Image,
    Video,
    Audio,
    Pdf,
    /// catch-all in case other types added in the future
    #[serde(untagged)]
    Other(String),
}

#[derive(Debug, Clone, Serialize, Deserialize, strum::EnumString, strum::Display)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum FileStyle {
    Auto,
    Link,
    Embed,
}

/// Response from an HTTP file upload (`POST /v1/spaces/{space_id}/files`).
///
/// This is the subset of file metadata the REST upload endpoint returns. The
/// unified [`FilesClient::upload`] builder normalizes this into [`FileObject`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileUploadResponse {
    /// File object ID
    pub object_id: String,
    /// Original file name as stored
    #[serde(default)]
    pub name: Option<String>,
    /// File extension without the leading dot, when known
    #[serde(default)]
    pub extension: Option<String>,
    /// MIME type (for example `image/png`)
    #[serde(default)]
    pub media: Option<String>,
    /// Size of the uploaded file, in bytes
    #[serde(default)]
    pub size_in_bytes: Option<i64>,
}

/// HTTP metadata returned for a REST file download or `HEAD` request.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FileHttpMetadata {
    /// Media type of the selected file or image variant.
    pub content_type: Option<String>,
    /// Response body length. For a ranged response this is the partial length.
    pub content_length: Option<u64>,
    /// Byte range selected by the server, such as `bytes 0-499/1200`.
    pub content_range: Option<String>,
    /// Range units supported by the server, normally `bytes`.
    pub accept_ranges: Option<String>,
    /// Server-provided modification timestamp in HTTP-date form.
    pub last_modified: Option<String>,
    /// Server-provided entity tag, when available.
    pub etag: Option<String>,
    /// Cache policy supplied by the file endpoint.
    pub cache_control: Option<String>,
    /// Total bytes retained across the allowlisted response headers.
    ///
    /// Header names, separators, and values all count toward this total.
    pub retained_header_bytes: u64,
}

/// Result of a configurable REST file download.
#[derive(Debug, Clone)]
pub struct FileContentResponse {
    /// HTTP status, including `206`, `304`, `412`, or `416` control responses.
    pub status: StatusCode,
    /// File-related response headers.
    pub metadata: FileHttpMetadata,
    /// Response body. Conditional and `HEAD` responses normally have no body.
    pub bytes: Bytes,
}

impl FileContentResponse {
    /// Returns true when a conditional request found the cached representation current.
    #[must_use]
    pub fn is_not_modified(&self) -> bool {
        self.status == StatusCode::NOT_MODIFIED
    }

    /// Returns true when the server fulfilled a byte-range request.
    #[must_use]
    pub fn is_partial(&self) -> bool {
        self.status == StatusCode::PARTIAL_CONTENT
    }
}

// ============================================================================
// Client entry point
// ============================================================================

#[derive(Debug)]
pub struct FilesClient<'a> {
    client: &'a AnytypeClient,
}

impl AnytypeClient {
    #[must_use]
    pub fn files(&self) -> FilesClient<'_> {
        FilesClient { client: self }
    }
}

impl<'a> FilesClient<'a> {
    /// Builds a rich file listing. Executing it requires a gRPC backend.
    pub fn list(&self, space_id: impl Into<String>) -> FileListRequest<'a> {
        FileListRequest {
            client: self.client,
            space_id: space_id.into(),
            filters: Vec::new(),
            limit: None,
            offset: None,
        }
    }

    /// Builds a rich file search. Executing it requires a gRPC backend.
    pub fn search(&self, space_id: impl Into<String>) -> FileSearchRequest<'a> {
        FileSearchRequest {
            client: self.client,
            space_id: space_id.into(),
            text: None,
            filters: Vec::new(),
            sorts: Vec::new(),
            limit: None,
            offset: None,
        }
    }

    /// Builds a rich file-object lookup. Executing it requires a gRPC backend.
    pub fn get(
        &self,
        space_id: impl Into<String>,
        object_id: impl Into<String>,
    ) -> FileGetRequest<'a> {
        FileGetRequest {
            client: self.client,
            space_id: space_id.into(),
            object_id: object_id.into(),
        }
    }

    /// Download through the legacy gRPC API.
    ///
    /// New code should prefer [`download_bytes`](Self::download_bytes), which
    /// uses the REST file endpoint. This method remains available for callers
    /// that rely on the server writing directly to a destination path. It
    /// requires a gRPC backend.
    pub fn download(&self, object_id: impl Into<String>) -> FileDownloadRequest<'a> {
        FileDownloadRequest {
            client: self.client,
            object_id: object_id.into(),
            destination: None,
        }
    }

    /// Builds an upload that selects REST or gRPC from its source and options.
    /// URL sources and rich options require a gRPC backend.
    pub fn upload(&self, space_id: impl Into<String>) -> FileUploadRequest<'a> {
        FileUploadRequest {
            client: self.client,
            space_id: space_id.into(),
            source: None,
            file_type: None,
            style: None,
            details: None,
            created_in_context: None,
            created_in_context_ref: None,
            file_name: None,
            mime: None,
            multipart_limit_bytes: None,
            response_limit_bytes: None,
            error_limit_bytes: None,
        }
    }

    /// Builds a preload request. Executing it requires a gRPC backend.
    pub fn preload(&self, space_id: impl Into<String>) -> FilePreloadRequest<'a> {
        FilePreloadRequest {
            client: self.client,
            space_id: space_id.into(),
            source: None,
            file_type: None,
            created_in_context: None,
            created_in_context_ref: None,
        }
    }

    /// Builds a preload-discard request. Executing it requires a gRPC backend.
    pub fn discard_preload(
        &self,
        space_id: impl Into<String>,
        file_id: impl Into<String>,
    ) -> FileDiscardPreloadRequest<'a> {
        FileDiscardPreloadRequest {
            client: self.client,
            space_id: space_id.into(),
            file_id: file_id.into(),
        }
    }
}

// ============================================================================
// HTTP (REST) file transfer
//
// Added in the 2025-11-08 / anytype-heart 0.50.15 REST surface. These wrap the
// REST endpoints directly (no gRPC channel required). See the capability
// mapping and combined-API recommendation in `docs/http-grpc-overlap.md`.
// ============================================================================

impl<'a> FilesClient<'a> {
    /// Download a file's raw bytes over REST.
    pub async fn download_bytes(
        &self,
        space_id: impl Into<String>,
        file_id: impl Into<String>,
    ) -> Result<Bytes> {
        Ok(self
            .download_request(space_id, file_id)
            .download()
            .await?
            .bytes)
    }

    /// Delete a file over REST.
    pub async fn delete(
        &self,
        space_id: impl Into<String>,
        file_id: impl Into<String>,
    ) -> Result<()> {
        self.delete_request(space_id, file_id).delete().await
    }

    /// Configure a REST file download or `HEAD` metadata request.
    #[must_use]
    pub fn download_request(
        &self,
        space_id: impl Into<String>,
        file_id: impl Into<String>,
    ) -> FileContentRequest<'a> {
        FileContentRequest {
            client: self.client,
            space_id: space_id.into(),
            file_id: file_id.into(),
            width: None,
            range: None,
            invalid_range: false,
            if_match: None,
            if_none_match: None,
            if_modified_since: None,
            if_unmodified_since: None,
            if_range: None,
            response_limit_bytes: None,
            error_limit_bytes: None,
            header_evidence_limit_bytes: None,
            max_attempts: None,
        }
    }

    /// Fetch file metadata with an HTTP `HEAD` request.
    ///
    /// Use [`download_request`](Self::download_request) when image width or
    /// conditional headers are needed.
    pub async fn metadata(
        &self,
        space_id: impl Into<String>,
        file_id: impl Into<String>,
    ) -> Result<FileContentResponse> {
        self.download_request(space_id, file_id).head().await
    }

    /// Configure a REST file deletion, including permanent deletion.
    #[must_use]
    pub fn delete_request(
        &self,
        space_id: impl Into<String>,
        file_id: impl Into<String>,
    ) -> FileDeleteRequest<'a> {
        FileDeleteRequest {
            client: self.client,
            space_id: space_id.into(),
            file_id: file_id.into(),
            skip_bin: false,
        }
    }

    /// Upload a file over the REST API (`POST /v1/spaces/{space_id}/files`).
    ///
    /// This is the REST equivalent of the gRPC [`upload`](Self::upload): simpler
    /// (multipart bytes in, minimal metadata out) and it needs no gRPC channel.
    /// For richer uploads (`style`, `details`, created-in-context), use the gRPC
    /// [`upload`](Self::upload) path.
    ///
    /// Provide the bytes with [`FileHttpUploadRequest::bytes`] or a filesystem
    /// path with [`FileHttpUploadRequest::path`]. Callers that already hold an
    /// authorized file handle can use [`FileHttpUploadRequest::reader`] to
    /// avoid reopening a path or buffering the complete payload. Then call
    /// [`FileHttpUploadRequest::upload`].
    #[must_use]
    #[deprecated(since = "0.5.0", note = "use upload for automatic backend selection")]
    pub fn http_upload(&self, space_id: impl Into<String>) -> FileHttpUploadRequest<'a> {
        FileHttpUploadRequest {
            client: self.client,
            space_id: space_id.into(),
            file_name: None,
            mime: None,
            data: None,
            source_path: None,
            source_reader: None,
            multipart_limit_bytes: None,
            response_limit_bytes: None,
            error_limit_bytes: None,
        }
    }

    /// Download a file's raw bytes over the REST API
    /// (`GET /v1/spaces/{space_id}/files/{file_id}`).
    ///
    /// Returns the file contents. This is the REST equivalent of the gRPC
    /// [`download`](Self::download); both stream the same raw bytes.
    #[deprecated(since = "0.5.0", note = "use download_bytes")]
    pub async fn http_download(
        &self,
        space_id: impl Into<String>,
        file_id: impl Into<String>,
    ) -> Result<Bytes> {
        self.download_bytes(space_id, file_id).await
    }

    /// Delete a file over the REST API
    /// (`DELETE /v1/spaces/{space_id}/files/{file_id}`).
    ///
    /// The REST API is the only transport with a first-class file delete; the
    /// gRPC path removes files via generic object deletion.
    #[deprecated(since = "0.5.0", note = "use delete")]
    pub async fn http_delete(
        &self,
        space_id: impl Into<String>,
        file_id: impl Into<String>,
    ) -> Result<()> {
        self.delete(space_id, file_id).await
    }
}

/// Builder for ranged, conditional, resized-image, and metadata file requests.
pub struct FileContentRequest<'a> {
    client: &'a AnytypeClient,
    space_id: String,
    file_id: String,
    width: Option<u32>,
    range: Option<String>,
    invalid_range: bool,
    if_match: Option<String>,
    if_none_match: Option<String>,
    if_modified_since: Option<String>,
    if_unmodified_since: Option<String>,
    if_range: Option<String>,
    response_limit_bytes: Option<u64>,
    error_limit_bytes: Option<u64>,
    header_evidence_limit_bytes: Option<u64>,
    max_attempts: Option<u32>,
}

impl FileContentRequest<'_> {
    /// Select a pre-rendered image variant at the given pixel width.
    ///
    /// The server ignores this option for non-image files. A width of zero
    /// requests the original image.
    #[must_use]
    pub fn width(mut self, width: u32) -> Self {
        self.width = Some(width);
        self
    }

    /// Set an HTTP byte range, for example `bytes=0-499` or `bytes=-500`.
    #[must_use]
    pub fn range(mut self, range: impl Into<String>) -> Self {
        self.range = Some(range.into());
        self.invalid_range = false;
        self
    }

    /// Select a checked inclusive byte range from `offset` for at most `length` bytes.
    ///
    /// A zero length and arithmetic overflow are rejected before network I/O.
    /// The response is still bounded independently with
    /// [`response_limit_bytes`](Self::response_limit_bytes), so callers that
    /// need an overrun sentinel can request `length + 1` body bytes there.
    #[must_use]
    pub fn byte_range(mut self, offset: u64, length: u64) -> Self {
        self.range = offset
            .checked_add(length.saturating_sub(1))
            .filter(|_| length != 0)
            .map(|end| format!("bytes={offset}-{end}"));
        self.invalid_range = self.range.is_none();
        self
    }

    /// Set the maximum successful response-body bytes buffered for this request.
    ///
    /// The value must be nonzero and cannot exceed the client's configured
    /// [`ResponseLimits::file_bytes`](crate::client::ResponseLimits::file_bytes).
    /// It does not change the client-wide default or any other request.
    #[must_use]
    pub const fn response_limit_bytes(mut self, limit: u64) -> Self {
        self.response_limit_bytes = Some(limit);
        self
    }

    /// Set the maximum error-response bytes buffered for this request.
    ///
    /// The value must be nonzero and cannot exceed the client's configured
    /// [`ResponseLimits::error_bytes`](crate::client::ResponseLimits::error_bytes).
    #[must_use]
    pub const fn error_limit_bytes(mut self, limit: u64) -> Self {
        self.error_limit_bytes = Some(limit);
        self
    }

    /// Set the retained evidence ceiling for allowlisted file response headers.
    ///
    /// Values are limited to [`MAX_FILE_HEADER_EVIDENCE_BYTES`]. The ceiling
    /// is enforced independently on every physical response before retry or
    /// body processing. Unrelated headers are never copied into the public
    /// result.
    #[must_use]
    pub const fn header_evidence_limit_bytes(mut self, limit: u64) -> Self {
        self.header_evidence_limit_bytes = Some(limit);
        self
    }

    /// Set the cumulative physical-attempt ceiling for this safe request.
    ///
    /// One through [`MAX_FILE_REQUEST_ATTEMPTS`] attempts are accepted. The
    /// initial send and every 429, retryable-status, connection, or timeout
    /// replay share this one counter. `POST` file uploads are unaffected.
    #[must_use]
    pub const fn max_attempts(mut self, max_attempts: u32) -> Self {
        self.max_attempts = Some(max_attempts);
        self
    }

    /// Set the `If-Match` precondition.
    #[must_use]
    pub fn if_match(mut self, value: impl Into<String>) -> Self {
        self.if_match = Some(value.into());
        self
    }

    /// Set the `If-None-Match` cache validator.
    #[must_use]
    pub fn if_none_match(mut self, value: impl Into<String>) -> Self {
        self.if_none_match = Some(value.into());
        self
    }

    /// Set the `If-Modified-Since` cache validator using an HTTP-date string.
    #[must_use]
    pub fn if_modified_since(mut self, value: impl Into<String>) -> Self {
        self.if_modified_since = Some(value.into());
        self
    }

    /// Set the `If-Unmodified-Since` precondition using an HTTP-date string.
    #[must_use]
    pub fn if_unmodified_since(mut self, value: impl Into<String>) -> Self {
        self.if_unmodified_since = Some(value.into());
        self
    }

    /// Set the `If-Range` validator for a ranged request.
    #[must_use]
    pub fn if_range(mut self, value: impl Into<String>) -> Self {
        self.if_range = Some(value.into());
        self
    }

    /// Execute an HTTP `GET`, preserving range and conditional statuses.
    pub async fn download(self) -> Result<FileContentResponse> {
        self.send(Method::GET).await
    }

    /// Execute an HTTP `HEAD`, returning headers without downloading the body.
    pub async fn head(self) -> Result<FileContentResponse> {
        self.send(Method::HEAD).await
    }

    async fn send(self, method: Method) -> Result<FileContentResponse> {
        let path = file_path(&self.space_id, &self.file_id);
        let query = self
            .width
            .map(|width| vec![("width".to_string(), width.to_string())])
            .unwrap_or_default();
        let mut headers = HeaderMap::new();
        if self.invalid_range {
            return invalid_range();
        }
        let requested_range = self.range.as_deref().map(parse_request_range).transpose()?;
        insert_optional_header(&mut headers, RANGE, self.range)?;
        insert_optional_header(&mut headers, IF_MATCH, self.if_match)?;
        insert_optional_header(&mut headers, IF_NONE_MATCH, self.if_none_match)?;
        insert_optional_header(&mut headers, IF_MODIFIED_SINCE, self.if_modified_since)?;
        insert_optional_header(&mut headers, IF_UNMODIFIED_SINCE, self.if_unmodified_since)?;
        insert_optional_header(&mut headers, IF_RANGE, self.if_range)?;

        let response_limit = self
            .response_limit_bytes
            .unwrap_or_else(|| self.client.client.file_response_limit());
        let error_limit = self
            .error_limit_bytes
            .unwrap_or_else(|| self.client.client.error_response_limit());
        let header_limit = self
            .header_evidence_limit_bytes
            .unwrap_or(DEFAULT_FILE_HEADER_EVIDENCE_BYTES);
        if header_limit == 0 || header_limit > MAX_FILE_HEADER_EVIDENCE_BYTES {
            return Err(AnytypeError::Validation {
                message: format!(
                    "file header evidence limit must be between 1 and {MAX_FILE_HEADER_EVIDENCE_BYTES} bytes"
                ),
            });
        }
        let max_attempts = self.max_attempts.unwrap_or(1);
        if max_attempts == 0 || max_attempts > MAX_FILE_REQUEST_ATTEMPTS {
            return Err(AnytypeError::Validation {
                message: format!(
                    "file request attempts must be between 1 and {MAX_FILE_REQUEST_ATTEMPTS}"
                ),
            });
        }

        let response = self
            .client
            .client
            .file_request_with_limits(
                method.clone(),
                &path,
                &query,
                headers,
                response_limit,
                error_limit,
                header_limit,
                max_attempts,
            )
            .await?;
        let metadata = file_http_metadata(
            &response.headers,
            response.status,
            method,
            requested_range,
            response.body.len() as u64,
            header_limit,
        )?;
        Ok(FileContentResponse {
            status: response.status,
            metadata,
            bytes: response.body,
        })
    }
}

/// Builder for soft or permanent REST file deletion.
pub struct FileDeleteRequest<'a> {
    client: &'a AnytypeClient,
    space_id: String,
    file_id: String,
    skip_bin: bool,
}

impl FileDeleteRequest<'_> {
    /// Set whether deletion bypasses the bin and permanently removes the file.
    #[must_use]
    pub fn skip_bin(mut self, skip_bin: bool) -> Self {
        self.skip_bin = skip_bin;
        self
    }

    /// Permanently remove the file instead of moving it to the bin.
    #[must_use]
    pub fn permanently(mut self) -> Self {
        self.skip_bin = true;
        self
    }

    /// Execute the deletion.
    pub async fn delete(self) -> Result<()> {
        let path = file_path(&self.space_id, &self.file_id);
        let query = if self.skip_bin {
            vec![("skip_bin".to_string(), "true".to_string())]
        } else {
            Vec::new()
        };
        self.client
            .client
            .file_request(Method::DELETE, &path, &query, HeaderMap::new())
            .await?;
        Ok(())
    }
}

fn file_path(space_id: &str, file_id: &str) -> String {
    format!("/v1/spaces/{space_id}/files/{file_id}")
}

fn insert_optional_header(
    headers: &mut HeaderMap,
    name: HeaderName,
    value: Option<String>,
) -> Result<()> {
    if let Some(value) = value {
        let value = HeaderValue::from_str(&value).map_err(|error| AnytypeError::Validation {
            message: format!("invalid {name} header: {error}"),
        })?;
        headers.insert(name, value);
    }
    Ok(())
}

#[derive(Debug, Clone, Copy)]
enum RequestRange {
    From {
        start: u64,
        inclusive_end: Option<u64>,
    },
    Suffix {
        length: u64,
    },
}

fn parse_request_range(value: &str) -> Result<RequestRange> {
    let Some(spec) = value.strip_prefix("bytes=") else {
        return invalid_range();
    };
    if spec.is_empty() || spec.contains(',') || spec.bytes().any(|byte| byte.is_ascii_whitespace())
    {
        return invalid_range();
    }
    let Some((start, end)) = spec.split_once('-') else {
        return invalid_range();
    };
    let range = match (start.is_empty(), end.is_empty()) {
        (false, false) => {
            let start = parse_canonical_u64(start).ok_or_else(invalid_range_error)?;
            let end = parse_canonical_u64(end).ok_or_else(invalid_range_error)?;
            if start > end {
                return invalid_range();
            }
            RequestRange::From {
                start,
                inclusive_end: Some(end),
            }
        }
        (false, true) => RequestRange::From {
            start: parse_canonical_u64(start).ok_or_else(invalid_range_error)?,
            inclusive_end: None,
        },
        (true, false) => {
            let suffix = parse_canonical_u64(end).ok_or_else(invalid_range_error)?;
            if suffix == 0 {
                return invalid_range();
            }
            RequestRange::Suffix { length: suffix }
        }
        (true, true) => return invalid_range(),
    };
    Ok(range)
}

fn invalid_range<T>() -> Result<T> {
    Err(invalid_range_error())
}

fn invalid_range_error() -> AnytypeError {
    AnytypeError::Validation {
        message: "file range must be one canonical bytes range".to_owned(),
    }
}

fn parse_canonical_u64(value: &str) -> Option<u64> {
    if value.is_empty()
        || !value.bytes().all(|byte| byte.is_ascii_digit())
        || (value.len() > 1 && value.starts_with('0'))
    {
        return None;
    }
    value.parse().ok()
}

#[derive(Debug, Clone, Copy)]
struct ParsedContentRange {
    start: u64,
    end: u64,
    total: u64,
}

fn parse_content_range(value: &str) -> Option<ParsedContentRange> {
    let spec = value.strip_prefix("bytes ")?;
    let (range, total) = spec.split_once('/')?;
    let (start, end) = range.split_once('-')?;
    let start = parse_canonical_u64(start)?;
    let end = parse_canonical_u64(end)?;
    let total = parse_canonical_u64(total)?;
    if start > end || end >= total {
        return None;
    }
    Some(ParsedContentRange { start, end, total })
}

fn file_http_metadata(
    headers: &HeaderMap,
    status: StatusCode,
    method: Method,
    requested_range: Option<RequestRange>,
    body_len: u64,
    evidence_limit: u64,
) -> Result<FileHttpMetadata> {
    let retained_header_bytes = retained_file_header_bytes(headers, status, evidence_limit)?;
    let content_type = single_header(headers, status, CONTENT_TYPE, "content-type")?;
    let content_length = single_header(headers, status, CONTENT_LENGTH, "content-length")?
        .map(|value| {
            parse_canonical_u64(&value).ok_or(AnytypeError::InvalidFileResponseHeader {
                status: status.as_u16(),
                header: "content-length",
                issue: "malformed",
            })
        })
        .transpose()?;
    let content_range = single_header(headers, status, CONTENT_RANGE, "content-range")?;
    let accept_ranges = single_header(headers, status, ACCEPT_RANGES, "accept-ranges")?;
    let last_modified = single_header(headers, status, LAST_MODIFIED, "last-modified")?
        .map(|value| {
            httpdate::parse_http_date(&value)
                .map(httpdate::fmt_http_date)
                .map_err(|_| AnytypeError::InvalidFileResponseHeader {
                    status: status.as_u16(),
                    header: "last-modified",
                    issue: "malformed",
                })
        })
        .transpose()?;
    let etag = single_header(headers, status, ETAG, "etag")?
        .map(|value| validate_etag(value, status))
        .transpose()?;
    let cache_control = single_header(headers, status, CACHE_CONTROL, "cache-control")?;

    if let Some(value) = content_type.as_deref()
        && (value.len() > 255
            || !value
                .bytes()
                .all(|byte| byte.is_ascii_graphic() || byte == b' ')
            || value.parse::<mime::Mime>().is_err())
    {
        return Err(AnytypeError::InvalidFileResponseHeader {
            status: status.as_u16(),
            header: "content-type",
            issue: "malformed",
        });
    }
    if let Some(value) = accept_ranges.as_deref()
        && value != "bytes"
        && value != "none"
    {
        return Err(AnytypeError::InvalidFileResponseHeader {
            status: status.as_u16(),
            header: "accept-ranges",
            issue: "unsupported",
        });
    }

    if method == Method::GET && status.is_success() {
        let declared = content_length.ok_or(AnytypeError::InvalidFileResponseHeader {
            status: status.as_u16(),
            header: "content-length",
            issue: "missing",
        })?;
        if declared != body_len {
            return Err(AnytypeError::InvalidFileResponseHeader {
                status: status.as_u16(),
                header: "content-length",
                issue: "body-length-mismatch",
            });
        }
    }

    if status == StatusCode::PARTIAL_CONTENT {
        let parsed = content_range
            .as_deref()
            .and_then(parse_content_range)
            .ok_or(AnytypeError::InvalidFileResponseHeader {
                status: status.as_u16(),
                header: "content-range",
                issue: if content_range.is_some() {
                    "malformed"
                } else {
                    "missing"
                },
            })?;
        let span = parsed
            .end
            .checked_sub(parsed.start)
            .and_then(|value| value.checked_add(1));
        if span != Some(body_len) {
            return Err(AnytypeError::InvalidFileResponseHeader {
                status: status.as_u16(),
                header: "content-range",
                issue: "body-length-mismatch",
            });
        }
        let Some(requested) = requested_range else {
            return Err(AnytypeError::InvalidFileResponseHeader {
                status: status.as_u16(),
                header: "content-range",
                issue: "unexpected",
            });
        };
        let request_matches = match requested {
            RequestRange::From {
                start,
                inclusive_end,
            } => {
                parsed.start == start
                    && inclusive_end.is_none_or(|requested_end| parsed.end <= requested_end)
            }
            RequestRange::Suffix { length } => {
                span.is_some_and(|span| span <= length)
                    && parsed.end.checked_add(1) == Some(parsed.total)
            }
        };
        if !request_matches || parsed.total == 0 {
            return Err(AnytypeError::InvalidFileResponseHeader {
                status: status.as_u16(),
                header: "content-range",
                issue: "request-mismatch",
            });
        }
    } else if content_range.is_some() && status.is_success() {
        return Err(AnytypeError::InvalidFileResponseHeader {
            status: status.as_u16(),
            header: "content-range",
            issue: "unexpected",
        });
    }

    Ok(FileHttpMetadata {
        content_type,
        content_length,
        content_range,
        accept_ranges,
        last_modified,
        etag,
        cache_control,
        retained_header_bytes,
    })
}

fn validate_etag(value: String, status: StatusCode) -> Result<String> {
    let opaque = value.strip_prefix("W/").unwrap_or(&value);
    if opaque.len() < 2
        || !opaque.starts_with('"')
        || !opaque.ends_with('"')
        || opaque[1..opaque.len() - 1]
            .bytes()
            .any(|byte| byte == b'"' || byte < 0x21 || byte == 0x7f)
    {
        return Err(AnytypeError::InvalidFileResponseHeader {
            status: status.as_u16(),
            header: "etag",
            issue: "malformed",
        });
    }
    Ok(value)
}

fn single_header(
    headers: &HeaderMap,
    status: StatusCode,
    name: HeaderName,
    display_name: &'static str,
) -> Result<Option<String>> {
    let values: Vec<_> = headers.get_all(&name).iter().collect();
    if values.len() > 1 {
        return Err(AnytypeError::InvalidFileResponseHeader {
            status: status.as_u16(),
            header: display_name,
            issue: "duplicate",
        });
    }
    values
        .first()
        .map(|value| {
            value
                .to_str()
                .map(str::to_owned)
                .map_err(|_| AnytypeError::InvalidFileResponseHeader {
                    status: status.as_u16(),
                    header: display_name,
                    issue: "non-utf8",
                })
        })
        .transpose()
}

pub(crate) fn retained_file_header_bytes(
    headers: &HeaderMap,
    status: StatusCode,
    limit: u64,
) -> Result<u64> {
    let allowlist = [
        CONTENT_LENGTH,
        CONTENT_RANGE,
        CONTENT_TYPE,
        ETAG,
        LAST_MODIFIED,
        ACCEPT_RANGES,
        CACHE_CONTROL,
    ];
    let mut retained = 0_u64;
    for name in allowlist {
        for value in headers.get_all(&name) {
            retained = retained
                .checked_add(name.as_str().len() as u64)
                .and_then(|value_len| value_len.checked_add(value.as_bytes().len() as u64 + 2))
                .ok_or(AnytypeError::FileHeaderEvidenceTooLarge {
                    limit,
                    status: status.as_u16(),
                })?;
            if retained > limit {
                return Err(AnytypeError::FileHeaderEvidenceTooLarge {
                    limit,
                    status: status.as_u16(),
                });
            }
        }
    }
    Ok(retained)
}

/// Builder for an HTTP (REST) file upload. Created by
/// [`FilesClient::http_upload`].
pub struct FileHttpUploadRequest<'a> {
    client: &'a AnytypeClient,
    space_id: String,
    file_name: Option<String>,
    mime: Option<String>,
    data: Option<Bytes>,
    source_path: Option<PathBuf>,
    source_reader: Option<FileUploadReader>,
    multipart_limit_bytes: Option<u64>,
    response_limit_bytes: Option<u64>,
    error_limit_bytes: Option<u64>,
}

impl FileHttpUploadRequest<'_> {
    /// Set the file name reported to the server. When uploading from a
    /// [`path`](Self::path) this defaults to the path's file name.
    #[must_use]
    pub fn file_name(mut self, name: impl Into<String>) -> Self {
        self.file_name = Some(name.into());
        self
    }

    /// Set an explicit MIME type for the multipart part. When omitted the
    /// server infers it from the content and file name.
    #[must_use]
    pub fn mime(mut self, mime: impl Into<String>) -> Self {
        self.mime = Some(mime.into());
        self
    }

    /// Upload from an in-memory byte buffer.
    #[must_use]
    pub fn bytes(mut self, data: impl Into<Bytes>) -> Self {
        self.data = Some(data.into());
        self.source_path = None;
        self.source_reader = None;
        self
    }

    /// Upload from a file on disk. The bytes are read when
    /// [`upload`](Self::upload) is called.
    #[must_use]
    pub fn path(mut self, path: impl AsRef<Path>) -> Self {
        self.data = None;
        self.source_path = Some(path.as_ref().to_path_buf());
        self.source_reader = None;
        self
    }

    /// Upload from one already-authorized asynchronous reader.
    ///
    /// The declared `length` is used to bound and serialize the multipart
    /// request. The stream fails if fewer bytes are readable; callers should
    /// independently retain and verify the source identity around the upload.
    /// This source never reopens or formats a filesystem path.
    #[must_use]
    pub fn reader<R>(mut self, file: R, length: u64) -> Self
    where
        R: AsyncRead + Send + 'static,
    {
        self.data = None;
        self.source_path = None;
        self.source_reader = Some(FileUploadReader {
            reader: Box::pin(file),
            length,
        });
        self
    }

    /// Set the maximum complete serialized multipart request-body bytes.
    #[must_use]
    pub const fn multipart_limit_bytes(mut self, limit: u64) -> Self {
        self.multipart_limit_bytes = Some(limit);
        self
    }

    /// Set the maximum successful upload response-body bytes.
    #[must_use]
    pub const fn response_limit_bytes(mut self, limit: u64) -> Self {
        self.response_limit_bytes = Some(limit);
        self
    }

    /// Set the maximum definitive-error response-body bytes.
    #[must_use]
    pub const fn error_limit_bytes(mut self, limit: u64) -> Self {
        self.error_limit_bytes = Some(limit);
        self
    }

    /// Perform the upload, returning the server's [`FileUploadResponse`].
    ///
    /// # Errors
    ///
    /// Returns an error if no byte, path, or [`reader`](Self::reader) source
    /// was set, if the source cannot be read, or if the request fails.
    pub async fn upload(self) -> Result<FileUploadResponse> {
        let source = match (self.data, self.source_path, self.source_reader) {
            (Some(data), None, None) => Some(HttpUploadSource::Bytes(data)),
            (None, Some(path), None) => Some(HttpUploadSource::Path(path)),
            (None, None, Some(reader)) => Some(HttpUploadSource::Reader(reader)),
            _ => None,
        };
        http_upload_file(
            self.client,
            &self.space_id,
            source,
            self.file_name,
            self.mime,
            FileHttpUploadLimits {
                multipart: self.multipart_limit_bytes,
                response: self.response_limit_bytes,
                error: self.error_limit_bytes,
            },
        )
        .await
    }
}

// ============================================================================
// Request builders
// ============================================================================

pub struct FileListRequest<'a> {
    client: &'a AnytypeClient,
    space_id: String,
    filters: Vec<Filter>,
    limit: Option<u32>,
    offset: Option<u32>,
}

impl FileListRequest<'_> {
    /// list files with the text in the name
    #[must_use]
    pub fn name_contains(mut self, text: impl Into<String>) -> Self {
        self.filters.push(Filter::Text {
            condition: crate::filters::Condition::Contains,
            property_key: "name".to_string(),
            text: text.into(),
        });
        self
    }

    /// list files of a specific type
    #[must_use]
    pub fn file_type(mut self, file_type: &FileType) -> Self {
        if let Some(filter) = file_type_filter(file_type) {
            self.filters.push(filter);
        }
        self
    }

    /// List files with the extension
    #[must_use]
    pub fn extension(mut self, ext: impl Into<String>) -> Self {
        self.filters.push(Filter::Text {
            condition: crate::filters::Condition::Equal,
            property_key: "fileExt".to_string(),
            text: ext.into(),
        });
        self
    }

    /// List files with one of the extensions
    #[must_use]
    pub fn extension_in(mut self, extensions: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.filters.push(Filter::Select {
            condition: crate::filters::Condition::In,
            property_key: "fileExt".to_string(),
            select: extensions.into_iter().map(Into::into).collect(),
        });
        self
    }

    /// List files that don't have one of these extensions
    #[must_use]
    pub fn extension_not_in(
        mut self,
        extensions: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.filters.push(Filter::Select {
            condition: crate::filters::Condition::NotIn,
            property_key: "fileExt".to_string(),
            select: extensions.into_iter().map(Into::into).collect(),
        });
        self
    }

    /// list files with size
    #[must_use]
    pub fn size_eq(mut self, size: i64) -> Self {
        self.filters
            .push(size_filter(crate::filters::Condition::Equal, size));
        self
    }

    #[must_use]
    pub fn size_neq(mut self, size: i64) -> Self {
        self.filters
            .push(size_filter(crate::filters::Condition::NotEqual, size));
        self
    }

    #[must_use]
    pub fn size_lt(mut self, size: i64) -> Self {
        self.filters
            .push(size_filter(crate::filters::Condition::Less, size));
        self
    }

    #[must_use]
    pub fn size_lte(mut self, size: i64) -> Self {
        self.filters
            .push(size_filter(crate::filters::Condition::LessOrEqual, size));
        self
    }

    #[must_use]
    pub fn size_gt(mut self, size: i64) -> Self {
        self.filters
            .push(size_filter(crate::filters::Condition::Greater, size));
        self
    }

    #[must_use]
    pub fn size_gte(mut self, size: i64) -> Self {
        self.filters
            .push(size_filter(crate::filters::Condition::GreaterOrEqual, size));
        self
    }

    #[must_use]
    pub fn filter(mut self, filter: Filter) -> Self {
        self.filters.push(filter);
        self
    }

    #[must_use]
    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit);
        self
    }

    #[must_use]
    pub fn offset(mut self, offset: u32) -> Self {
        self.offset = Some(offset);
        self
    }

    /// Lists rich file objects through the gRPC backend.
    pub async fn list(self) -> Result<PagedResult<FileObject>> {
        search_files(
            self.client,
            &self.space_id,
            None,
            self.filters,
            Vec::new(),
            self.limit,
            self.offset,
        )
        .await
    }
}

pub struct FileSearchRequest<'a> {
    client: &'a AnytypeClient,
    space_id: String,
    text: Option<String>,
    filters: Vec<Filter>,
    sorts: Vec<Sort>,
    limit: Option<u32>,
    offset: Option<u32>,
}

impl FileSearchRequest<'_> {
    #[must_use]
    pub fn text(mut self, text: impl Into<String>) -> Self {
        self.text = Some(text.into());
        self
    }

    #[must_use]
    pub fn name_contains(mut self, text: impl Into<String>) -> Self {
        self.filters.push(Filter::Text {
            condition: crate::filters::Condition::Contains,
            property_key: "name".to_string(),
            text: text.into(),
        });
        self
    }

    #[must_use]
    pub fn file_type(mut self, file_type: &FileType) -> Self {
        if let Some(filter) = file_type_filter(file_type) {
            self.filters.push(filter);
        }
        self
    }

    #[must_use]
    pub fn extension(mut self, ext: impl Into<String>) -> Self {
        self.filters.push(Filter::Text {
            condition: crate::filters::Condition::Equal,
            property_key: "fileExt".to_string(),
            text: ext.into(),
        });
        self
    }

    #[must_use]
    pub fn extension_in(mut self, extensions: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.filters.push(Filter::Select {
            condition: crate::filters::Condition::In,
            property_key: "fileExt".to_string(),
            select: extensions.into_iter().map(Into::into).collect(),
        });
        self
    }

    #[must_use]
    pub fn extension_not_in(
        mut self,
        extensions: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.filters.push(Filter::Select {
            condition: crate::filters::Condition::NotIn,
            property_key: "fileExt".to_string(),
            select: extensions.into_iter().map(Into::into).collect(),
        });
        self
    }

    #[must_use]
    pub fn size_eq(mut self, size: i64) -> Self {
        self.filters
            .push(size_filter(crate::filters::Condition::Equal, size));
        self
    }

    #[must_use]
    pub fn size_neq(mut self, size: i64) -> Self {
        self.filters
            .push(size_filter(crate::filters::Condition::NotEqual, size));
        self
    }

    #[must_use]
    pub fn size_lt(mut self, size: i64) -> Self {
        self.filters
            .push(size_filter(crate::filters::Condition::Less, size));
        self
    }

    #[must_use]
    pub fn size_lte(mut self, size: i64) -> Self {
        self.filters
            .push(size_filter(crate::filters::Condition::LessOrEqual, size));
        self
    }

    #[must_use]
    pub fn size_gt(mut self, size: i64) -> Self {
        self.filters
            .push(size_filter(crate::filters::Condition::Greater, size));
        self
    }

    #[must_use]
    pub fn size_gte(mut self, size: i64) -> Self {
        self.filters
            .push(size_filter(crate::filters::Condition::GreaterOrEqual, size));
        self
    }

    #[must_use]
    pub fn filter(mut self, filter: Filter) -> Self {
        self.filters.push(filter);
        self
    }

    #[must_use]
    pub fn sort_asc(mut self, key: impl Into<String>) -> Self {
        self.sorts.push(Sort::asc(key));
        self
    }

    #[must_use]
    pub fn sort_desc(mut self, key: impl Into<String>) -> Self {
        self.sorts.push(Sort::desc(key));
        self
    }

    #[must_use]
    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit);
        self
    }

    #[must_use]
    pub fn offset(mut self, offset: u32) -> Self {
        self.offset = Some(offset);
        self
    }

    /// Searches rich file objects through the gRPC backend.
    pub async fn search(self) -> Result<PagedResult<FileObject>> {
        search_files(
            self.client,
            &self.space_id,
            self.text,
            self.filters,
            self.sorts,
            self.limit,
            self.offset,
        )
        .await
    }
}

pub struct FileGetRequest<'a> {
    client: &'a AnytypeClient,
    space_id: String,
    object_id: String,
}

impl FileGetRequest<'_> {
    /// Gets rich file metadata through the gRPC backend.
    pub async fn get(self) -> Result<FileObject> {
        let grpc = self.client.grpc_client().await?;
        let mut commands = grpc.client_commands();
        let request = search_with_meta::Request {
            space_id: self.space_id.clone(),
            filters: vec![filter_id_equal(&self.object_id)],
            sorts: Vec::new(),
            full_text: String::new(),
            offset: 0,
            limit: 1,
            object_type_filter: Vec::new(),
            keys: Vec::new(),
            return_meta: false,
            return_meta_relation_details: false,
            return_html_highlights_instead_of_ranges: false,
        };
        let request = with_token_request(Request::new(request), grpc.token())?;
        let response = commands
            .object_search_with_meta(request)
            .await
            .map_err(grpc_status)?
            .into_inner();
        ensure_error_ok(response.error.as_ref(), "file get")?;
        let result = response
            .results
            .first()
            .ok_or_else(|| AnytypeError::Other {
                message: "file not found".to_string(),
            })?;
        let details = result.details.as_ref().ok_or_else(|| AnytypeError::Other {
            message: "file result missing details".to_string(),
        })?;
        Ok(file_from_details(
            &self.space_id,
            &result.object_id,
            details,
        ))
    }
}

pub struct FileDownloadRequest<'a> {
    client: &'a AnytypeClient,
    object_id: String,
    destination: Option<FileDownloadDestination>,
}

#[derive(Debug, Clone)]
enum FileDownloadDestination {
    Dir(PathBuf),
    File(PathBuf),
}

impl FileDownloadRequest<'_> {
    /// set the destination directory for the download
    #[must_use]
    pub fn to_path(mut self, path: impl AsRef<Path>) -> Self {
        self.destination = Some(FileDownloadDestination::Dir(path.as_ref().to_path_buf()));
        self
    }

    /// set the destination directory for the download
    #[must_use]
    pub fn to_dir(mut self, path: impl AsRef<Path>) -> Self {
        self.destination = Some(FileDownloadDestination::Dir(path.as_ref().to_path_buf()));
        self
    }

    /// set the destination file path for the download
    #[must_use]
    pub fn to_file(mut self, path: impl AsRef<Path>) -> Self {
        self.destination = Some(FileDownloadDestination::File(path.as_ref().to_path_buf()));
        self
    }

    /// Downloads the file through gRPC and returns the server-written path.
    pub async fn download(self) -> Result<PathBuf> {
        debug!("enter download execute");
        let (request_path, target_file) = match self.destination {
            Some(FileDownloadDestination::Dir(path)) => (path, None),
            Some(FileDownloadDestination::File(path)) => {
                if path.is_dir() {
                    return Err(AnytypeError::Validation {
                        message: format!("download destination is a directory: {}", path.display()),
                    });
                }
                let parent = path
                    .parent()
                    .filter(|value| !value.as_os_str().is_empty())
                    .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
                if let Err(err) = std::fs::create_dir_all(&parent) {
                    return Err(AnytypeError::Other {
                        message: format!("create download directory {}: {err}", parent.display()),
                    });
                }
                (parent, Some(path))
            }
            None => (PathBuf::new(), None),
        };
        let grpc = self.client.grpc_client().await?;
        let mut commands = grpc.client_commands();
        let request = download::Request {
            object_id: self.object_id.clone(),
            path: if request_path.as_os_str().is_empty() {
                String::new()
            } else {
                request_path.to_string_lossy().to_string()
            },
        };
        let request = with_token_request(Request::new(request), grpc.token()).map_err(|err| {
            error!("download rpc error: {err}");
            err
        })?;
        let request = with_grpc_call_options(request, GrpcCallOptions::long_read());
        let started = std::time::Instant::now();

        let response = commands
            .file_download(request)
            .await
            .map_err(|err| {
                error!(code = %err.code(), "download gRPC request failed");
                grpc_status_for(
                    err,
                    GrpcTimeoutClass::LongUnary,
                    GrpcTimeoutOutcome::ReadAborted,
                    started.elapsed(),
                )
            })?
            .into_inner();

        // remove partial files if there was an error
        if let Err(err) = ensure_error_ok(response.error.as_ref(), "file download") {
            let local = PathBuf::from(response.local_path);
            if local.is_file() {
                info!("download error {err}. Removing incomplete download {local:?}");
                if let Err(delete_err) = std::fs::remove_file(&local) {
                    error!(
                        "failed to remove incomplete download {local:?} (err={delete_err}) after download error {err}"
                    );
                }
            } else {
                error!("download error {err}");
            }
            return Err(err);
        }
        let mut local_path = PathBuf::from(response.local_path);
        if let Some(target_path) = target_file {
            if target_path.is_dir() {
                return Err(AnytypeError::Validation {
                    message: format!(
                        "download file path points to a directory: {}",
                        target_path.display()
                    ),
                });
            }
            if local_path != target_path {
                if let Err(err) = std::fs::rename(&local_path, &target_path) {
                    if let Err(copy_err) = std::fs::copy(&local_path, &target_path) {
                        return Err(AnytypeError::Other {
                            message: format!(
                                "move download to {}: {err} (copy error: {copy_err})",
                                target_path.display()
                            ),
                        });
                    }
                    if let Err(remove_err) = std::fs::remove_file(&local_path) {
                        error!(
                            "failed to remove original download {local_path:?} after copy: {remove_err}"
                        );
                    }
                }
                local_path = target_path;
            }
        }
        debug!("download complete 536 {}", &local_path.display());
        Ok(local_path)
    }
}

/// Unified file-upload builder.
///
/// Path and byte uploads without rich options use REST. URL uploads and
/// requests with file type, style, details, or creation context use gRPC.
pub struct FileUploadRequest<'a> {
    client: &'a AnytypeClient,
    space_id: String,
    source: Option<FileSource>,
    file_type: Option<FileType>,
    style: Option<FileStyle>,
    details: Option<serde_json::Value>,
    created_in_context: Option<String>,
    created_in_context_ref: Option<String>,
    file_name: Option<String>,
    mime: Option<String>,
    multipart_limit_bytes: Option<u64>,
    response_limit_bytes: Option<u64>,
    error_limit_bytes: Option<u64>,
}

impl FileUploadRequest<'_> {
    #[must_use]
    pub fn from_path(mut self, path: impl AsRef<Path>) -> Self {
        self.source = Some(FileSource::Path(path.as_ref().to_path_buf()));
        self
    }

    /// Selects a remote URL source and therefore the gRPC backend.
    #[must_use]
    pub fn from_url(mut self, url: impl Into<String>) -> Self {
        self.source = Some(FileSource::Url(url.into()));
        self
    }

    /// Upload an in-memory file. Simple byte and path uploads use REST.
    #[must_use]
    pub fn bytes(mut self, file_name: impl Into<String>, data: impl Into<Bytes>) -> Self {
        self.file_name = Some(file_name.into());
        self.source = Some(FileSource::Bytes(data.into()));
        self
    }

    /// Upload from one already-authorized asynchronous reader through REST.
    ///
    /// The source is streamed with the exact declared `length`; no path is
    /// reopened or formatted and the complete payload is not buffered.
    /// Reader uploads do not support gRPC-only rich file options.
    #[must_use]
    pub fn reader<R>(mut self, file_name: impl Into<String>, file: R, length: u64) -> Self
    where
        R: AsyncRead + Send + 'static,
    {
        self.file_name = Some(file_name.into());
        self.source = Some(FileSource::Reader(FileUploadReader {
            reader: Box::pin(file),
            length,
        }));
        self
    }

    /// Set the MIME type used by a REST upload.
    #[must_use]
    pub fn mime(mut self, mime: impl Into<String>) -> Self {
        self.mime = Some(mime.into());
        self
    }

    /// Set the maximum complete serialized multipart request-body bytes.
    #[must_use]
    pub const fn multipart_limit_bytes(mut self, limit: u64) -> Self {
        self.multipart_limit_bytes = Some(limit);
        self
    }

    /// Set the maximum successful upload response-body bytes.
    #[must_use]
    pub const fn response_limit_bytes(mut self, limit: u64) -> Self {
        self.response_limit_bytes = Some(limit);
        self
    }

    /// Set the maximum definitive-error response-body bytes.
    #[must_use]
    pub const fn error_limit_bytes(mut self, limit: u64) -> Self {
        self.error_limit_bytes = Some(limit);
        self
    }

    /// Sets a file type and therefore selects the gRPC backend.
    #[must_use]
    pub fn file_type(mut self, file_type: FileType) -> Self {
        self.file_type = Some(file_type);
        self
    }

    /// Sets a placement style and therefore selects the gRPC backend.
    #[must_use]
    pub fn style(mut self, style: FileStyle) -> Self {
        self.style = Some(style);
        self
    }

    /// Sets rich details and therefore selects the gRPC backend.
    #[must_use]
    pub fn details(mut self, details: serde_json::Value) -> Self {
        self.details = Some(details);
        self
    }

    /// Sets the containing object and therefore selects the gRPC backend.
    #[must_use]
    pub fn created_in_context(mut self, object_id: impl Into<String>) -> Self {
        self.created_in_context = Some(object_id.into());
        self
    }

    /// Sets the containing block and therefore selects the gRPC backend.
    #[must_use]
    pub fn created_in_context_ref(mut self, block_id: impl Into<String>) -> Self {
        self.created_in_context_ref = Some(block_id.into());
        self
    }

    /// Upload the file through the least-capable backend that preserves every
    /// requested option, returning a normalized [`FileObject`]. URL sources
    /// and rich options require a gRPC backend.
    pub async fn upload(self) -> Result<FileObject> {
        if self.uses_rest() {
            let source = match self.source {
                Some(FileSource::Bytes(data)) => Some(HttpUploadSource::Bytes(data)),
                Some(FileSource::Path(path)) => Some(HttpUploadSource::Path(path)),
                Some(FileSource::Reader(reader)) => Some(HttpUploadSource::Reader(reader)),
                Some(FileSource::Url(_)) | None => {
                    return Err(AnytypeError::Validation {
                        message: "REST file upload requires bytes, a path, or a reader".to_string(),
                    });
                }
            };
            let response = http_upload_file(
                self.client,
                &self.space_id,
                source,
                self.file_name,
                self.mime,
                FileHttpUploadLimits {
                    multipart: self.multipart_limit_bytes,
                    response: self.response_limit_bytes,
                    error: self.error_limit_bytes,
                },
            )
            .await?;
            return Ok(file_from_http_upload(&self.space_id, response));
        }

        let result = upload_file(
            self.client,
            &self.space_id,
            self.source,
            self.file_type,
            self.style,
            self.details,
            self.created_in_context,
            self.created_in_context_ref,
            false,
            None,
        )
        .await?;
        Ok(file_from_details(
            &self.space_id,
            &result.object_id,
            &result.details,
        ))
    }

    fn uses_rest(&self) -> bool {
        upload_uses_rest(
            self.source.as_ref(),
            self.file_type.is_some()
                || self.style.is_some()
                || self.details.is_some()
                || self.created_in_context.is_some()
                || self.created_in_context_ref.is_some(),
        )
    }
}

pub struct FilePreloadRequest<'a> {
    client: &'a AnytypeClient,
    space_id: String,
    source: Option<FileSource>,
    file_type: Option<FileType>,
    created_in_context: Option<String>,
    created_in_context_ref: Option<String>,
}

impl FilePreloadRequest<'_> {
    #[must_use]
    pub fn from_path(mut self, path: impl AsRef<Path>) -> Self {
        self.source = Some(FileSource::Path(path.as_ref().to_path_buf()));
        self
    }

    /// Preload a file fetched from a remote URL.
    ///
    /// Preloading always runs over gRPC, so a URL source is uploaded the same
    /// way the unified upload builder handles [`FileUploadRequest::from_url`].
    #[must_use]
    pub fn from_url(mut self, url: impl Into<String>) -> Self {
        self.source = Some(FileSource::Url(url.into()));
        self
    }

    #[must_use]
    pub fn file_type(mut self, file_type: FileType) -> Self {
        self.file_type = Some(file_type);
        self
    }

    #[must_use]
    pub fn created_in_context(mut self, object_id: impl Into<String>) -> Self {
        self.created_in_context = Some(object_id.into());
        self
    }

    #[must_use]
    pub fn created_in_context_ref(mut self, block_id: impl Into<String>) -> Self {
        self.created_in_context_ref = Some(block_id.into());
        self
    }

    /// Preloads the file through the gRPC backend.
    pub async fn preload(self) -> Result<String> {
        let result = upload_file(
            self.client,
            &self.space_id,
            self.source,
            self.file_type,
            None,
            None,
            self.created_in_context,
            self.created_in_context_ref,
            true,
            None,
        )
        .await?;
        Ok(result.preload_file_id)
    }
}

pub struct FileDiscardPreloadRequest<'a> {
    client: &'a AnytypeClient,
    space_id: String,
    file_id: String,
}

impl FileDiscardPreloadRequest<'_> {
    /// Discards the preload through the gRPC backend.
    pub async fn discard(self) -> Result<()> {
        let grpc = self.client.grpc_client().await?;
        let mut commands = grpc.client_commands();
        let request = discard_preload::Request {
            file_id: self.file_id,
            space_id: self.space_id,
        };
        let request = with_token_request(Request::new(request), grpc.token())?;
        let request = with_grpc_call_options(request, GrpcCallOptions::cleanup());
        let started = std::time::Instant::now();
        let response = commands
            .file_discard_preload(request)
            .await
            .map_err(|status| {
                grpc_status_for(
                    status,
                    GrpcTimeoutClass::Cleanup,
                    GrpcTimeoutOutcome::MutationIndeterminate,
                    started.elapsed(),
                )
            })?
            .into_inner();
        ensure_error_ok(response.error.as_ref(), "file discard preload")?;
        Ok(())
    }
}

// ============================================================================
// Internal helpers
// ============================================================================

#[derive(Debug)]
enum FileSource {
    Url(String),
    Path(PathBuf),
    Bytes(Bytes),
    Reader(FileUploadReader),
}

fn upload_uses_rest(source: Option<&FileSource>, has_rich_options: bool) -> bool {
    matches!(
        source,
        Some(FileSource::Path(_) | FileSource::Bytes(_) | FileSource::Reader(_))
    ) && !has_rich_options
}

async fn http_upload_file(
    client: &AnytypeClient,
    space_id: &str,
    source: Option<HttpUploadSource>,
    file_name: Option<String>,
    mime: Option<String>,
    limits: FileHttpUploadLimits,
) -> Result<FileUploadResponse> {
    let (part, name, data_bytes) = match source {
        Some(HttpUploadSource::Bytes(data)) => {
            let name = file_name.unwrap_or_else(|| "file".to_string());
            let length = data.len() as u64;
            (
                reqwest::multipart::Part::bytes(data.to_vec()).file_name(name.clone()),
                name,
                length,
            )
        }
        Some(HttpUploadSource::Path(path)) => {
            let data = tokio::fs::read(&path)
                .await
                .map_err(|_| AnytypeError::Other {
                    message: "failed to read file upload source".to_string(),
                })?;
            let name = file_name.or_else(|| {
                path.file_name()
                    .and_then(|name| name.to_str())
                    .map(String::from)
            });
            let name = name.unwrap_or_else(|| "file".to_string());
            let length = data.len() as u64;
            (
                reqwest::multipart::Part::bytes(data).file_name(name.clone()),
                name,
                length,
            )
        }
        Some(HttpUploadSource::Reader(reader)) => {
            if reader.length == 0 {
                return Err(AnytypeError::Validation {
                    message: "file upload reader length must be nonzero".to_string(),
                });
            }
            let body = reqwest::Body::wrap_stream(tokio_util::io::ReaderStream::new(
                ExactLengthReader::new(reader.reader, reader.length),
            ));
            let name = file_name.unwrap_or_else(|| "file".to_string());
            (
                reqwest::multipart::Part::stream_with_length(body, reader.length)
                    .file_name(name.clone()),
                name,
                reader.length,
            )
        }
        None => {
            return Err(AnytypeError::Validation {
                message: "file upload requires exactly one byte, path, or reader source"
                    .to_string(),
            });
        }
    };

    let mut part = part;
    if let Some(mime) = mime.as_ref() {
        part = part
            .mime_str(mime)
            .map_err(|err| AnytypeError::Validation {
                message: format!("invalid mime type: {err}"),
            })?;
    }
    let form = reqwest::multipart::Form::new().part("file", part);
    let serialized_body_bytes =
        multipart_body_bytes(form.boundary(), &name, mime.as_deref(), data_bytes)?;
    let path = format!("/v1/spaces/{space_id}/files");
    client
        .client
        .post_multipart_with_limits(
            &path,
            form,
            Some(serialized_body_bytes),
            limits.multipart,
            limits.response,
            limits.error,
        )
        .await
}

struct FileUploadReader {
    reader: Pin<Box<dyn AsyncRead + Send>>,
    length: u64,
}

impl fmt::Debug for FileUploadReader {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("FileUploadReader")
            .field("length", &self.length)
            .finish_non_exhaustive()
    }
}

struct ExactLengthReader {
    reader: Pin<Box<dyn AsyncRead + Send>>,
    remaining: u64,
    complete: bool,
}

impl ExactLengthReader {
    fn new(reader: Pin<Box<dyn AsyncRead + Send>>, length: u64) -> Self {
        Self {
            reader,
            remaining: length,
            complete: false,
        }
    }
}

impl AsyncRead for ExactLengthReader {
    fn poll_read(
        self: Pin<&mut Self>,
        context: &mut std::task::Context<'_>,
        buffer: &mut tokio::io::ReadBuf<'_>,
    ) -> std::task::Poll<std::io::Result<()>> {
        let source = self.get_mut();
        if source.complete || buffer.remaining() == 0 {
            return std::task::Poll::Ready(Ok(()));
        }
        if source.remaining == 0 {
            let mut probe = [0_u8; 1];
            let mut probe_buffer = tokio::io::ReadBuf::new(&mut probe);
            return match source.reader.as_mut().poll_read(context, &mut probe_buffer) {
                std::task::Poll::Pending => std::task::Poll::Pending,
                std::task::Poll::Ready(Err(error)) => std::task::Poll::Ready(Err(error)),
                std::task::Poll::Ready(Ok(())) if probe_buffer.filled().is_empty() => {
                    source.complete = true;
                    std::task::Poll::Ready(Ok(()))
                }
                std::task::Poll::Ready(Ok(())) => std::task::Poll::Ready(Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "file upload reader exceeded its declared length",
                ))),
            };
        }
        let available = usize::try_from(source.remaining)
            .unwrap_or(usize::MAX)
            .min(buffer.remaining());
        let destination = buffer.initialize_unfilled_to(available);
        let mut limited = tokio::io::ReadBuf::new(destination);
        match source.reader.as_mut().poll_read(context, &mut limited) {
            std::task::Poll::Pending => std::task::Poll::Pending,
            std::task::Poll::Ready(Err(error)) => std::task::Poll::Ready(Err(error)),
            std::task::Poll::Ready(Ok(())) => {
                let read = limited.filled().len();
                if read == 0 {
                    return std::task::Poll::Ready(Err(std::io::Error::new(
                        std::io::ErrorKind::UnexpectedEof,
                        "file upload reader ended before its declared length",
                    )));
                }
                source.remaining = source.remaining.saturating_sub(read as u64);
                buffer.advance(read);
                std::task::Poll::Ready(Ok(()))
            }
        }
    }
}

enum HttpUploadSource {
    Bytes(Bytes),
    Path(PathBuf),
    Reader(FileUploadReader),
}

#[derive(Clone, Copy, Debug, Default)]
struct FileHttpUploadLimits {
    multipart: Option<u64>,
    response: Option<u64>,
    error: Option<u64>,
}

fn multipart_body_bytes(
    boundary: &str,
    file_name: &str,
    mime: Option<&str>,
    data_bytes: u64,
) -> Result<u64> {
    let escaped_file_name_bytes = file_name
        .bytes()
        .try_fold(0_u64, |length, byte| {
            length.checked_add(if matches!(byte, b'\\' | b'"' | b'\r' | b'\n') {
                2
            } else {
                1
            })
        })
        .ok_or_else(|| AnytypeError::Validation {
            message: "multipart filename length overflowed".to_owned(),
        })?;
    let header_bytes = (b"Content-Disposition: form-data; name=\"file\"; filename=\"".len() as u64)
        .checked_add(escaped_file_name_bytes)
        .and_then(|value| value.checked_add(1))
        .and_then(|value| {
            mime.map_or(Some(value), |mime| {
                value
                    .checked_add(b"\r\nContent-Type: ".len() as u64)
                    .and_then(|value| value.checked_add(mime.len() as u64))
            })
        })
        .ok_or_else(|| AnytypeError::Validation {
            message: "multipart header length overflowed".to_owned(),
        })?;
    let boundary_bytes = boundary.len() as u64;
    2_u64
        .checked_add(boundary_bytes)
        .and_then(|value| value.checked_add(2))
        .and_then(|value| value.checked_add(header_bytes))
        .and_then(|value| value.checked_add(4))
        .and_then(|value| value.checked_add(data_bytes))
        .and_then(|value| value.checked_add(2))
        .and_then(|value| value.checked_add(2))
        .and_then(|value| value.checked_add(boundary_bytes))
        .and_then(|value| value.checked_add(4))
        .ok_or_else(|| AnytypeError::Validation {
            message: "multipart request length overflowed".to_owned(),
        })
}

fn file_from_http_upload(space_id: &str, response: FileUploadResponse) -> FileObject {
    let file_type = response
        .media
        .as_deref()
        .map(file_type_from_mime)
        .unwrap_or_default();
    FileObject {
        id: response.object_id,
        space_id: space_id.to_string(),
        name: response.name,
        size: response.size_in_bytes,
        mime: response.media,
        added_at: None,
        file_type,
        style: FileStyle::Auto,
        target_object_id: None,
        details: serde_json::Value::Null,
    }
}

async fn search_files(
    client: &AnytypeClient,
    space_id: &str,
    text: Option<String>,
    filters: Vec<Filter>,
    sorts: Vec<Sort>,
    limit: Option<u32>,
    offset: Option<u32>,
) -> Result<PagedResult<FileObject>> {
    let grpc = client.grpc_client().await?;
    let mut commands = grpc.client_commands();

    let mut grpc_filters = Vec::with_capacity(filters.len() + 1);
    grpc_filters.push(filter_not_empty("fileId"));
    for filter in filters {
        grpc_filters.push(filter_to_dataview(filter)?);
    }

    let mut grpc_sorts = Vec::with_capacity(sorts.len());
    for sort in sorts {
        grpc_sorts.push(sort_to_dataview(sort));
    }

    #[allow(clippy::cast_possible_wrap)] // u32 to i32 for offset and limit
    let request = search_with_meta::Request {
        space_id: space_id.to_string(),
        filters: grpc_filters,
        sorts: grpc_sorts,
        full_text: text.unwrap_or_default(),
        offset: offset.unwrap_or_default() as i32,
        limit: limit.unwrap_or(100) as i32,
        object_type_filter: Vec::new(),
        keys: Vec::new(),
        return_meta: false,
        return_meta_relation_details: false,
        return_html_highlights_instead_of_ranges: false,
    };

    let request = with_token_request(Request::new(request), grpc.token())?;
    let response = commands
        .object_search_with_meta(request)
        .await
        .map_err(grpc_status)?
        .into_inner();
    ensure_error_ok(response.error.as_ref(), "file search")?;

    let items: Vec<FileObject> = response
        .results
        .into_iter()
        .filter_map(|result| {
            let details = result.details.as_ref()?;
            Some(file_from_details(space_id, &result.object_id, details))
        })
        .collect();

    let limit_value = limit.unwrap_or(100);
    let has_more = items.len() == limit_value as usize;
    let total = offset.unwrap_or_default() as usize + items.len();
    let response = PaginatedResponse {
        items,
        pagination: PaginationMeta {
            has_more,
            limit: limit_value,
            offset: offset.unwrap_or_default(),
            total,
        },
    };
    Ok(PagedResult::from_response(response))
}

struct UploadResult {
    object_id: String,
    preload_file_id: String,
    details: Struct,
}

#[allow(clippy::too_many_arguments)]
async fn upload_file(
    client: &AnytypeClient,
    space_id: &str,
    source: Option<FileSource>,
    file_type: Option<FileType>,
    style: Option<FileStyle>,
    details: Option<serde_json::Value>,
    created_in_context: Option<String>,
    created_in_context_ref: Option<String>,
    preload_only: bool,
    preload_file_id: Option<String>,
) -> Result<UploadResult> {
    let source = source.ok_or_else(|| AnytypeError::Validation {
        message: "file upload requires a source (path or url)".to_string(),
    })?;

    let grpc = client.grpc_client().await?;
    let mut commands = grpc.client_commands();
    let (url, local_path) = match source {
        FileSource::Url(url) => (url, String::new()),
        FileSource::Path(path) => (String::new(), path.to_string_lossy().to_string()),
        FileSource::Bytes(_) => {
            return Err(AnytypeError::Validation {
                message: "in-memory uploads are only supported by the REST backend".to_string(),
            });
        }
        FileSource::Reader(_) => {
            return Err(AnytypeError::Validation {
                message: "reader uploads require REST without rich options".to_string(),
            });
        }
    };

    let request = upload::Request {
        space_id: space_id.to_string(),
        url,
        local_path,
        r#type: grpc_file_type(&file_type.unwrap_or(FileType::File)),
        disable_encryption: false,
        style: grpc_file_style(&style.unwrap_or(FileStyle::Auto)),
        details: details.map(json_to_struct).transpose()?,
        origin: 0,
        image_kind: 0,
        preload_only,
        preload_file_id: preload_file_id.unwrap_or_default(),
        created_in_context: created_in_context.unwrap_or_default(),
        created_in_context_ref: created_in_context_ref.unwrap_or_default(),
    };
    let request = with_token_request(Request::new(request), grpc.token())?;
    let request = with_grpc_call_options(
        request,
        GrpcCallOptions::new(
            GrpcTimeoutClass::LongUnary,
            GrpcTimeoutOutcome::MutationIndeterminate,
        ),
    );
    let started = std::time::Instant::now();
    let response = commands
        .file_upload(request)
        .await
        .map_err(|status| {
            grpc_status_for(
                status,
                GrpcTimeoutClass::LongUnary,
                GrpcTimeoutOutcome::MutationIndeterminate,
                started.elapsed(),
            )
        })?
        .into_inner();
    ensure_error_ok(response.error.as_ref(), "file upload")?;
    let details = response.details.unwrap_or_default();
    Ok(UploadResult {
        object_id: response.object_id,
        preload_file_id: response.preload_file_id,
        details,
    })
}

fn grpc_file_type(file_type: &FileType) -> i32 {
    match file_type {
        &FileType::File | &FileType::Other(_) => model::block::content::file::Type::File as i32,
        &FileType::Image => model::block::content::file::Type::Image as i32,
        &FileType::Video => model::block::content::file::Type::Video as i32,
        &FileType::Audio => model::block::content::file::Type::Audio as i32,
        &FileType::Pdf => model::block::content::file::Type::Pdf as i32,
    }
}

fn grpc_file_style(style: &FileStyle) -> i32 {
    match style {
        FileStyle::Auto => model::block::content::file::Style::Auto as i32,
        FileStyle::Link => model::block::content::file::Style::Link as i32,
        FileStyle::Embed => model::block::content::file::Style::Embed as i32,
    }
}

fn filter_not_empty(key: &str) -> model::block::content::dataview::Filter {
    model::block::content::dataview::Filter {
        id: String::new(),
        operator: model::block::content::dataview::filter::Operator::No as i32,
        relation_key: key.to_string(),
        relation_property: String::new(),
        condition: model::block::content::dataview::filter::Condition::NotEmpty as i32,
        value: None,
        quick_option: model::block::content::dataview::filter::QuickOption::ExactDate as i32,
        format: 0,
        include_time: false,
        nested_filters: Vec::new(),
    }
}

fn filter_id_equal(id: &str) -> model::block::content::dataview::Filter {
    model::block::content::dataview::Filter {
        id: String::new(),
        operator: model::block::content::dataview::filter::Operator::No as i32,
        relation_key: "id".to_string(),
        relation_property: String::new(),
        condition: model::block::content::dataview::filter::Condition::Equal as i32,
        value: Some(value_string(id.to_string())),
        quick_option: model::block::content::dataview::filter::QuickOption::ExactDate as i32,
        format: 0,
        include_time: false,
        nested_filters: Vec::new(),
    }
}

#[allow(clippy::too_many_lines)]
fn filter_to_dataview(filter: Filter) -> Result<model::block::content::dataview::Filter> {
    let (relation_key, condition, value) = match filter {
        Filter::Text {
            condition,
            property_key,
            text: str,
        }
        | Filter::Date {
            condition,
            property_key,
            date: str,
        }
        | Filter::Url {
            condition,
            property_key,
            url: str,
        }
        | Filter::Email {
            condition,
            property_key,
            email: str,
        }
        | Filter::Phone {
            condition,
            property_key,
            phone: str,
        } => (property_key, condition, Some(value_string(str))),
        Filter::Number {
            condition,
            property_key,
            number,
        } => {
            let number = number.as_f64().ok_or_else(|| AnytypeError::Validation {
                message: "number filter must be numeric".to_string(),
            })?;
            (property_key, condition, Some(value_number(number)))
        }
        Filter::Select {
            condition,
            property_key,
            select,
        } => (
            property_key,
            condition,
            Some(value_list(select.into_iter().map(value_string).collect())),
        ),
        Filter::MultiSelect {
            condition,
            property_key,
            multi_select,
        } => (
            property_key,
            condition,
            Some(value_list(
                multi_select.into_iter().map(value_string).collect(),
            )),
        ),
        Filter::Checkbox {
            condition,
            property_key,
            checkbox,
        } => (property_key, condition, Some(value_bool(checkbox))),
        Filter::Files {
            condition,
            property_key,
            files,
        } => (
            property_key,
            condition,
            Some(value_list(files.into_iter().map(value_string).collect())),
        ),
        Filter::Objects {
            condition,
            property_key,
            objects,
        } => (
            property_key,
            condition,
            Some(value_list(objects.into_iter().map(value_string).collect())),
        ),
        Filter::Empty {
            condition,
            property_key,
        }
        | Filter::NotEmpty {
            condition,
            property_key,
        } => (property_key, condition, None),
        Filter::Value {
            condition,
            property_key,
            value,
        } => (
            property_key,
            condition,
            value.map(json_value_to_prost).transpose()?,
        ),
    };

    Ok(model::block::content::dataview::Filter {
        id: String::new(),
        operator: model::block::content::dataview::filter::Operator::No as i32,
        relation_key,
        relation_property: String::new(),
        condition: grpc_filter_condition(condition),
        value,
        quick_option: model::block::content::dataview::filter::QuickOption::ExactDate as i32,
        format: 0,
        include_time: false,
        nested_filters: Vec::new(),
    })
}

fn grpc_filter_condition(condition: crate::filters::Condition) -> i32 {
    use model::block::content::dataview::filter::Condition as GrpcCondition;

    use crate::filters::Condition;

    match condition {
        Condition::None => GrpcCondition::None as i32,
        Condition::Equal => GrpcCondition::Equal as i32,
        Condition::NotEqual => GrpcCondition::NotEqual as i32,
        Condition::Greater => GrpcCondition::Greater as i32,
        Condition::Less => GrpcCondition::Less as i32,
        Condition::GreaterOrEqual => GrpcCondition::GreaterOrEqual as i32,
        Condition::LessOrEqual => GrpcCondition::LessOrEqual as i32,
        Condition::Contains => GrpcCondition::Like as i32,
        Condition::NotContains => GrpcCondition::NotLike as i32,
        Condition::In => GrpcCondition::In as i32,
        Condition::NotIn => GrpcCondition::NotIn as i32,
        Condition::Empty => GrpcCondition::Empty as i32,
        Condition::NotEmpty => GrpcCondition::NotEmpty as i32,
        Condition::All | Condition::AllIn => GrpcCondition::AllIn as i32,
        Condition::NotAllIn => GrpcCondition::NotAllIn as i32,
        Condition::ExactIn => GrpcCondition::ExactIn as i32,
        Condition::NotExactIn => GrpcCondition::NotExactIn as i32,
        Condition::Exists => GrpcCondition::Exists as i32,
    }
}

fn sort_to_dataview(sort: Sort) -> model::block::content::dataview::Sort {
    let sort_type = match sort.direction {
        SortDirection::Asc => model::block::content::dataview::sort::Type::Asc,
        SortDirection::Desc => model::block::content::dataview::sort::Type::Desc,
    };

    model::block::content::dataview::Sort {
        relation_key: sort.property_key,
        r#type: sort_type as i32,
        custom_order: Vec::new(),
        format: 0,
        include_time: false,
        id: String::new(),
        empty_placement: 0,
        no_collate: false,
    }
}

fn file_from_details(space_id: &str, object_id: &str, details: &Struct) -> FileObject {
    let name = string_field(details, "name");
    #[allow(clippy::cast_possible_truncation)]
    let size = number_field(details, "sizeInBytes").map(|val| val as i64);
    let mime = string_field(details, "fileMimeType");
    let added_at = added_date(details);
    let target_object_id = string_field(details, "targetObjectId");
    let file_type = mime.as_deref().map(file_type_from_mime).unwrap_or_default();

    FileObject {
        id: object_id.to_string(),
        space_id: space_id.to_string(),
        name,
        size,
        mime,
        added_at,
        file_type,
        style: FileStyle::Auto,
        target_object_id,
        details: struct_to_json(details),
    }
}

fn added_date(details: &Struct) -> Option<DateTime<FixedOffset>> {
    if let Some(value) = number_field(details, "addedDate") {
        if !value.is_finite() || value.fract() != 0.0 {
            return None;
        }
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let seconds = value as i64;
        return DateTime::<Utc>::from_timestamp(seconds, 0)
            .map(|timestamp| timestamp.fixed_offset());
    }

    string_field(details, "addedDate").and_then(|value| DateTime::parse_from_rfc3339(&value).ok())
}

fn file_type_from_mime(mime: &str) -> FileType {
    if mime.starts_with("image/") {
        return FileType::Image;
    }
    if mime.starts_with("video/") {
        return FileType::Video;
    }
    if mime.starts_with("audio/") {
        return FileType::Audio;
    }
    if mime == "application/pdf" {
        return FileType::Pdf;
    }
    FileType::File
}

fn size_filter(condition: crate::filters::Condition, size: i64) -> Filter {
    Filter::Number {
        condition,
        property_key: "sizeInBytes".to_string(),
        number: serde_json::Number::from(size),
    }
}

fn file_type_filter(file_type: &FileType) -> Option<Filter> {
    let (condition, value) = match file_type {
        FileType::Image => (crate::filters::Condition::Contains, "image/".to_string()),
        FileType::Video => (crate::filters::Condition::Contains, "video/".to_string()),
        FileType::Audio => (crate::filters::Condition::Contains, "audio/".to_string()),
        FileType::Pdf => (
            crate::filters::Condition::Equal,
            "application/pdf".to_string(),
        ),
        FileType::File | FileType::Other(_) => return None,
    };

    Some(Filter::Text {
        condition,
        property_key: "fileMimeType".to_string(),
        text: value,
    })
}

fn string_field(details: &Struct, key: &str) -> Option<String> {
    details.fields.get(key).and_then(|value| match &value.kind {
        Some(prost_types::value::Kind::StringValue(value)) => Some(value.clone()),
        _ => None,
    })
}

fn number_field(details: &Struct, key: &str) -> Option<f64> {
    details.fields.get(key).and_then(|value| match &value.kind {
        Some(prost_types::value::Kind::NumberValue(value)) => Some(*value),
        _ => None,
    })
}

fn struct_to_json(details: &Struct) -> serde_json::Value {
    let mut map = serde_json::Map::new();
    for (key, value) in &details.fields {
        map.insert(key.clone(), prost_value_to_json(value));
    }
    serde_json::Value::Object(map)
}

fn prost_value_to_json(value: &Value) -> serde_json::Value {
    match &value.kind {
        Some(prost_types::value::Kind::NullValue(_)) | None => serde_json::Value::Null,
        Some(prost_types::value::Kind::NumberValue(value)) => {
            Number::from_f64(*value).map_or(serde_json::Value::Null, serde_json::Value::Number)
        }
        Some(prost_types::value::Kind::StringValue(value)) => {
            serde_json::Value::String(value.clone())
        }
        Some(prost_types::value::Kind::BoolValue(value)) => serde_json::Value::Bool(*value),
        Some(prost_types::value::Kind::StructValue(value)) => struct_to_json(value),
        Some(prost_types::value::Kind::ListValue(value)) => {
            serde_json::Value::Array(value.values.iter().map(prost_value_to_json).collect())
        }
    }
}

fn json_to_struct(value: serde_json::Value) -> Result<Struct> {
    match json_value_to_prost(value)? {
        Value {
            kind: Some(prost_types::value::Kind::StructValue(value)),
        } => Ok(value),
        _ => Err(AnytypeError::Validation {
            message: "details must be an object".to_string(),
        }),
    }
}

fn json_value_to_prost(value: serde_json::Value) -> Result<Value> {
    Ok(match value {
        serde_json::Value::Null => Value {
            kind: Some(prost_types::value::Kind::NullValue(0)),
        },
        serde_json::Value::Bool(value) => Value {
            kind: Some(prost_types::value::Kind::BoolValue(value)),
        },
        serde_json::Value::Number(value) => Value {
            kind: Some(prost_types::value::Kind::NumberValue(
                value.as_f64().unwrap_or_default(),
            )),
        },
        serde_json::Value::String(value) => Value {
            kind: Some(prost_types::value::Kind::StringValue(value)),
        },
        serde_json::Value::Array(values) => Value {
            kind: Some(prost_types::value::Kind::ListValue(ListValue {
                values: values
                    .into_iter()
                    .map(json_value_to_prost)
                    .collect::<Result<Vec<_>>>()?,
            })),
        },
        serde_json::Value::Object(map) => Value {
            kind: Some(prost_types::value::Kind::StructValue(Struct {
                fields: map
                    .into_iter()
                    .map(|(key, value)| Ok((key, json_value_to_prost(value)?)))
                    .collect::<Result<_>>()?,
            })),
        },
    })
}

fn value_string(value: impl Into<String>) -> Value {
    Value {
        kind: Some(prost_types::value::Kind::StringValue(value.into())),
    }
}

fn value_number(value: f64) -> Value {
    Value {
        kind: Some(prost_types::value::Kind::NumberValue(value)),
    }
}

fn value_bool(value: bool) -> Value {
    Value {
        kind: Some(prost_types::value::Kind::BoolValue(value)),
    }
}

fn value_list(values: Vec<Value>) -> Value {
    Value {
        kind: Some(prost_types::value::Kind::ListValue(ListValue { values })),
    }
}

#[cfg(test)]
mod tests {
    use std::{
        future::Future,
        path::PathBuf,
        pin::Pin,
        sync::atomic::{AtomicU64, Ordering},
        task::{Context, Poll},
    };

    use bytes::Bytes;
    use reqwest::StatusCode;
    use tokio::{
        io::{AsyncRead, AsyncReadExt, AsyncWriteExt, ReadBuf},
        net::TcpListener,
        sync::{oneshot, watch},
        task::JoinHandle,
    };

    use super::{
        ExactLengthReader, FileSource, FileStyle, FileType, FileUploadResponse, file_from_details,
        file_from_http_upload, multipart_body_bytes, upload_uses_rest,
    };
    use crate::{
        client::{AnytypeClient, ClientConfig},
        keystore::HttpCredentials,
    };

    static NEXT_MOCK_ID: AtomicU64 = AtomicU64::new(1);

    fn detail_value(kind: prost_types::value::Kind) -> prost_types::Value {
        prost_types::Value { kind: Some(kind) }
    }

    #[test]
    fn grpc_file_details_parse_numeric_added_date() {
        let details = prost_types::Struct {
            fields: std::collections::BTreeMap::from([(
                "addedDate".to_owned(),
                detail_value(prost_types::value::Kind::NumberValue(1_708_689_792.0)),
            )]),
        };

        let file = file_from_details("space-id", "file-id", &details);
        assert_eq!(
            file.added_at.map(|timestamp| timestamp.timestamp()),
            Some(1_708_689_792)
        );
    }

    #[test]
    fn grpc_file_details_reject_invalid_numeric_added_dates() {
        for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1.5, f64::MAX] {
            let details = prost_types::Struct {
                fields: std::collections::BTreeMap::from([(
                    "addedDate".to_owned(),
                    detail_value(prost_types::value::Kind::NumberValue(value)),
                )]),
            };

            assert!(
                file_from_details("space-id", "file-id", &details)
                    .added_at
                    .is_none(),
                "invalid timestamp {value}"
            );
        }
    }

    #[test]
    fn grpc_file_target_object_id_is_not_created_in_context() {
        let context_only = prost_types::Struct {
            fields: std::collections::BTreeMap::from([(
                "createdInContext".to_owned(),
                detail_value(prost_types::value::Kind::StringValue(
                    "containing-object".to_owned(),
                )),
            )]),
        };
        assert_eq!(
            file_from_details("space-id", "file-id", &context_only).target_object_id,
            None
        );

        let target = prost_types::Struct {
            fields: std::collections::BTreeMap::from([(
                "targetObjectId".to_owned(),
                detail_value(prost_types::value::Kind::StringValue(
                    "file-block-target".to_owned(),
                )),
            )]),
        };
        assert_eq!(
            file_from_details("space-id", "file-id", &target).target_object_id,
            Some("file-block-target".to_owned())
        );
    }

    struct PauseAfterFirstRead {
        bytes: &'static [u8],
        offset: usize,
        entered: Option<oneshot::Sender<()>>,
        released: watch::Receiver<bool>,
        pause: Option<Pin<Box<dyn Future<Output = bool> + Send>>>,
    }

    impl AsyncRead for PauseAfterFirstRead {
        fn poll_read(
            mut self: Pin<&mut Self>,
            context: &mut Context<'_>,
            buffer: &mut ReadBuf<'_>,
        ) -> Poll<std::io::Result<()>> {
            if self.offset != 0 && !*self.released.borrow() {
                if let Some(entered) = self.entered.take() {
                    let _ = entered.send(());
                }
                if self.pause.is_none() {
                    let mut released = self.released.clone();
                    self.pause = Some(Box::pin(async move {
                        released.changed().await.is_ok() && *released.borrow()
                    }));
                }
                let Some(pause) = self.pause.as_mut() else {
                    return Poll::Ready(Err(std::io::Error::other("pause state missing")));
                };
                match pause.as_mut().poll(context) {
                    Poll::Pending => return Poll::Pending,
                    Poll::Ready(true) => self.pause = None,
                    Poll::Ready(false) => {
                        return Poll::Ready(Err(std::io::Error::other(
                            "pause sender closed before release",
                        )));
                    }
                }
            }
            if self.offset >= self.bytes.len() || buffer.remaining() == 0 {
                return Poll::Ready(Ok(()));
            }
            let remaining = &self.bytes[self.offset..];
            let length = if self.offset == 0 {
                remaining.len().min(3).min(buffer.remaining())
            } else {
                remaining.len().min(buffer.remaining())
            };
            buffer.put_slice(&remaining[..length]);
            self.offset = self.offset.saturating_add(length);
            Poll::Ready(Ok(()))
        }
    }

    #[tokio::test]
    async fn generic_upload_reader_rejects_bytes_beyond_declared_length() {
        let (mut writer, reader) = tokio::io::duplex(16);
        let producer = tokio::spawn(async move {
            writer
                .write_all(b"excess")
                .await
                .expect("write excess input");
            writer.shutdown().await.expect("close excess input");
        });
        let mut exact = ExactLengthReader::new(Box::pin(reader), 3);
        let mut observed = Vec::new();
        let error = exact
            .read_to_end(&mut observed)
            .await
            .expect_err("excess input must fail");
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
        assert_eq!(observed, b"exc");
        producer.await.expect("producer task");
    }

    fn complete_request_length(request: &[u8]) -> Option<usize> {
        let header_end = request
            .windows(4)
            .position(|window| window == b"\r\n\r\n")?;
        let headers = std::str::from_utf8(&request[..header_end]).ok()?;
        let body_length = headers.lines().find_map(|line| {
            let (name, value) = line.split_once(':')?;
            if name.eq_ignore_ascii_case("content-length") {
                value.trim().parse::<usize>().ok()
            } else {
                None
            }
        });
        header_end
            .checked_add(4)?
            .checked_add(body_length.unwrap_or(0))
    }

    async fn mock_file_client(response: &'static str) -> (AnytypeClient, JoinHandle<String>) {
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind mock file server");
        let address = listener.local_addr().expect("mock server address");
        let server = tokio::spawn(async move {
            let (mut stream, _) = listener.accept().await.expect("accept mock request");
            let mut request = Vec::new();
            let mut chunk = [0_u8; 1024];
            loop {
                let read = stream.read(&mut chunk).await.expect("read mock request");
                if read == 0 {
                    break;
                }
                request.extend_from_slice(&chunk[..read]);
                if complete_request_length(&request).is_some_and(|length| request.len() >= length) {
                    break;
                }
            }
            stream
                .write_all(response.as_bytes())
                .await
                .expect("write mock response");
            String::from_utf8(request).expect("HTTP request is UTF-8")
        });

        let id = NEXT_MOCK_ID.fetch_add(1, Ordering::Relaxed);
        let key_path = std::env::temp_dir().join(format!(
            "anytype-file-http-unit-{}-{id}.db",
            std::process::id()
        ));
        let mut config = ClientConfig::default().app_name("file-http-unit");
        config.base_url = Some(format!("http://{address}"));
        config.keystore = Some(format!("file:path={}", key_path.display()));
        config.keystore_service = Some(format!("file-http-unit-{id}"));
        let client = AnytypeClient::with_config(config).expect("create mock client");
        client.set_api_key(HttpCredentials::new("test-token"));
        (client, server)
    }

    async fn mock_file_client_sequence(
        responses: Vec<&'static str>,
    ) -> (AnytypeClient, JoinHandle<Vec<String>>) {
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind mock file server");
        let address = listener.local_addr().expect("mock server address");
        let server = tokio::spawn(async move {
            let mut requests = Vec::with_capacity(responses.len());
            for response in responses {
                let (mut stream, _) = listener.accept().await.expect("accept mock request");
                let mut request = Vec::new();
                let mut chunk = [0_u8; 1024];
                loop {
                    let read = stream.read(&mut chunk).await.expect("read mock request");
                    if read == 0 {
                        break;
                    }
                    request.extend_from_slice(&chunk[..read]);
                    if complete_request_length(&request)
                        .is_some_and(|length| request.len() >= length)
                    {
                        break;
                    }
                }
                stream
                    .write_all(response.as_bytes())
                    .await
                    .expect("write mock response");
                requests.push(String::from_utf8(request).expect("HTTP request is UTF-8"));
            }
            requests
        });

        let id = NEXT_MOCK_ID.fetch_add(1, Ordering::Relaxed);
        let key_path = std::env::temp_dir().join(format!(
            "anytype-file-http-unit-{}-{id}.db",
            std::process::id()
        ));
        let mut config = ClientConfig::default().app_name("file-http-unit");
        config.base_url = Some(format!("http://{address}"));
        config.keystore = Some(format!("file:path={}", key_path.display()));
        config.keystore_service = Some(format!("file-http-unit-{id}"));
        let client = AnytypeClient::with_config(config).expect("create mock client");
        client.set_api_key(HttpCredentials::new("test-token"));
        (client, server)
    }

    #[test]
    fn simple_path_and_byte_uploads_select_rest() {
        let path = FileSource::Path(PathBuf::from("example.txt"));
        let bytes = FileSource::Bytes(Bytes::from_static(b"hello"));

        assert!(upload_uses_rest(Some(&path), false));
        assert!(upload_uses_rest(Some(&bytes), false));
    }

    #[test]
    fn rich_and_url_uploads_select_grpc() {
        let path = FileSource::Path(PathBuf::from("example.txt"));
        let url = FileSource::Url("https://example.invalid/file".to_string());

        assert!(!upload_uses_rest(Some(&path), true));
        assert!(!upload_uses_rest(Some(&url), false));
        assert!(!upload_uses_rest(None, false));
    }

    #[test]
    fn preload_source_tracks_url_and_path() {
        let id = NEXT_MOCK_ID.fetch_add(1, Ordering::Relaxed);
        let key_path = std::env::temp_dir().join(format!(
            "anytype-preload-unit-{}-{id}.db",
            std::process::id()
        ));
        let mut config = ClientConfig::default().app_name("preload-unit");
        config.keystore = Some(format!("file:path={}", key_path.display()));
        config.keystore_service = Some(format!("preload-unit-{id}"));
        let client = AnytypeClient::with_config(config).expect("create client");

        let url_request = client
            .files()
            .preload("space")
            .from_url("https://example.invalid/file");
        assert!(matches!(url_request.source, Some(FileSource::Url(_))));

        let path_request = client.files().preload("space").from_path("example.txt");
        assert!(matches!(path_request.source, Some(FileSource::Path(_))));
    }

    #[test]
    fn rest_upload_response_normalizes_to_file_object() {
        let file = file_from_http_upload(
            "space-id",
            FileUploadResponse {
                object_id: "file-id".to_string(),
                name: Some("report.txt".to_string()),
                extension: Some("txt".to_string()),
                media: Some("text/plain".to_string()),
                size_in_bytes: Some(5),
            },
        );

        assert_eq!(file.id, "file-id");
        assert_eq!(file.space_id, "space-id");
        assert_eq!(file.name.as_deref(), Some("report.txt"));
        assert_eq!(file.mime.as_deref(), Some("text/plain"));
        assert_eq!(file.size, Some(5));
        assert!(matches!(file.file_type, FileType::File));
        assert!(matches!(file.style, FileStyle::Auto));
        assert!(file.details.is_null());
    }

    #[test]
    fn multipart_length_accounts_for_complete_framing_and_escaped_filename() {
        let boundary = "0123456789abcdef0123456789abcdef";
        let plain = multipart_body_bytes(boundary, "a__b.txt", Some("text/plain"), 5)
            .expect("plain multipart length");
        let escaped = multipart_body_bytes(boundary, "a\\\"b.txt", Some("text/plain"), 5)
            .expect("escaped multipart length");
        assert_eq!(escaped, plain + 2);

        let maximum = multipart_body_bytes(
            boundary,
            &"é".repeat(512),
            Some("application/octet-stream"),
            65_536,
        )
        .expect("maximum files-toolset multipart length");
        assert!(maximum <= 71_680);
        assert!(
            multipart_body_bytes(boundary, "file", None, 71_680).expect("over-limit fixture")
                > 71_680
        );
    }

    #[test]
    fn current_http_upload_schema_deserializes() {
        let response: FileUploadResponse = serde_json::from_value(serde_json::json!({
            "object_id": "file-id",
            "name": "photo.png",
            "extension": "png",
            "media": "image/png",
            "size_in_bytes": 42
        }))
        .expect("deserialize current anytype-heart file response");

        assert_eq!(response.object_id, "file-id");
        assert_eq!(response.extension.as_deref(), Some("png"));
    }

    #[tokio::test]
    async fn retained_reader_upload_uses_streamed_multipart_source() {
        let (client, server) = mock_file_client(
            "HTTP/1.1 200 OK\r\n\
             Content-Type: application/json\r\n\
             Connection: close\r\n\r\n\
             {\"object_id\":\"file-id\",\"size_in_bytes\":6}",
        )
        .await;
        let id = NEXT_MOCK_ID.fetch_add(1, Ordering::Relaxed);
        let path = std::env::temp_dir().join(format!(
            "anytype-file-reader-unit-{}-{id}.bin",
            std::process::id()
        ));
        std::fs::write(&path, b"stream").expect("write stream fixture");
        let file = tokio::fs::File::open(&path)
            .await
            .expect("open retained reader");

        let response = client
            .files()
            .upload("space-1")
            .reader("stream.bin", file, 6)
            .mime("application/octet-stream")
            .multipart_limit_bytes(1_024)
            .upload()
            .await
            .expect("stream reader upload");

        assert_eq!(response.id, "file-id");
        assert_eq!(response.size, Some(6));
        let request = server.await.expect("mock server task");
        assert!(request.starts_with("POST /v1/spaces/space-1/files HTTP/1.1"));
        assert!(
            request
                .to_ascii_lowercase()
                .contains("\r\ncontent-length: ")
        );
        std::fs::remove_file(path).expect("cleanup");
    }

    #[tokio::test]
    async fn retained_reader_upload_resumes_after_mid_body_pause() {
        let (client, server) = mock_file_client(
            "HTTP/1.1 200 OK\r\n\
             Content-Type: application/json\r\n\
             Connection: close\r\n\r\n\
             {\"object_id\":\"file-id\",\"size_in_bytes\":6}",
        )
        .await;
        let (entered_tx, entered_rx) = oneshot::channel();
        let (release_tx, release_rx) = watch::channel(false);
        let reader = PauseAfterFirstRead {
            bytes: b"stream",
            offset: 0,
            entered: Some(entered_tx),
            released: release_rx,
            pause: None,
        };
        let upload = tokio::spawn(async move {
            client
                .files()
                .upload("space-1")
                .reader("stream.bin", reader, 6)
                .mime("application/octet-stream")
                .multipart_limit_bytes(1_024)
                .upload()
                .await
        });

        tokio::time::timeout(std::time::Duration::from_secs(2), entered_rx)
            .await
            .expect("upload reaches the mid-body pause")
            .expect("pause signal remains owned");
        release_tx.send(true).expect("release paused upload");
        let response = tokio::time::timeout(std::time::Duration::from_secs(2), upload)
            .await
            .expect("scripted multipart peer settles after release")
            .expect("upload task completes")
            .expect("stream reader upload succeeds");
        assert_eq!(response.id, "file-id");
        assert_eq!(response.size, Some(6));
        let request = server.await.expect("mock server task");
        assert!(request.contains("stream"));
    }

    #[tokio::test]
    async fn ranged_download_sends_width_and_conditional_headers() {
        let (client, server) = mock_file_client(
            "HTTP/1.1 206 Partial Content\r\n\
             Content-Type: text/plain\r\n\
             Content-Length: 5\r\n\
             Content-Range: bytes 0-4/11\r\n\
             Accept-Ranges: bytes\r\n\
             Last-Modified: Sun, 19 Jul 2026 12:00:00 GMT\r\n\
             Cache-Control: max-age=31536000, private\r\n\
             Connection: close\r\n\r\nhello",
        )
        .await;

        let response = client
            .files()
            .download_request("space-1", "file-1")
            .width(320)
            .range("bytes=0-4")
            .if_match("\"current\"")
            .if_none_match("\"stale\"")
            .if_modified_since("Sun, 19 Jul 2026 11:00:00 GMT")
            .if_unmodified_since("Sun, 19 Jul 2026 13:00:00 GMT")
            .if_range("Sun, 19 Jul 2026 12:00:00 GMT")
            .download()
            .await
            .expect("ranged download");

        assert_eq!(response.status, StatusCode::PARTIAL_CONTENT);
        assert!(response.is_partial());
        assert_eq!(response.bytes, Bytes::from_static(b"hello"));
        assert_eq!(response.metadata.content_length, Some(5));
        assert_eq!(
            response.metadata.content_range.as_deref(),
            Some("bytes 0-4/11")
        );
        assert_eq!(response.metadata.accept_ranges.as_deref(), Some("bytes"));
        assert_eq!(
            response.metadata.content_type.as_deref(),
            Some("text/plain")
        );

        let request = server.await.expect("mock server task").to_ascii_lowercase();
        assert!(request.starts_with("get /v1/spaces/space-1/files/file-1?width=320 http/1.1"));
        assert!(request.contains("\r\nrange: bytes=0-4\r\n"));
        assert!(request.contains("\r\nif-match: \"current\"\r\n"));
        assert!(request.contains("\r\nif-none-match: \"stale\"\r\n"));
        assert!(request.contains("\r\nif-modified-since: sun, 19 jul 2026 11:00:00 gmt\r\n"));
        assert!(request.contains("\r\nif-unmodified-since: sun, 19 jul 2026 13:00:00 gmt\r\n"));
        assert!(request.contains("\r\nif-range: sun, 19 jul 2026 12:00:00 gmt\r\n"));
    }

    #[tokio::test]
    async fn head_returns_file_metadata_without_a_body() {
        let (client, server) = mock_file_client(
            "HTTP/1.1 200 OK\r\n\
             Content-Type: image/png\r\n\
             Content-Length: 1234\r\n\
             Accept-Ranges: bytes\r\n\
             ETag: \"image-v1\"\r\n\
             Last-Modified: Sun, 19 Jul 2026 12:00:00 GMT\r\n\
             Connection: close\r\n\r\n",
        )
        .await;

        let response = client
            .files()
            .metadata("space-1", "image-1")
            .await
            .expect("HEAD metadata");

        assert_eq!(response.status, StatusCode::OK);
        assert!(response.bytes.is_empty());
        assert_eq!(response.metadata.content_length, Some(1234));
        assert_eq!(response.metadata.content_type.as_deref(), Some("image/png"));
        assert_eq!(response.metadata.etag.as_deref(), Some("\"image-v1\""));
        assert_eq!(
            response.metadata.last_modified.as_deref(),
            Some("Sun, 19 Jul 2026 12:00:00 GMT")
        );

        let request = server.await.expect("mock server task");
        assert!(request.starts_with("HEAD /v1/spaces/space-1/files/image-1 HTTP/1.1"));
    }

    #[tokio::test]
    async fn conditional_not_modified_status_is_preserved() {
        let (client, server) = mock_file_client(
            "HTTP/1.1 304 Not Modified\r\n\
             Last-Modified: Sun, 19 Jul 2026 12:00:00 GMT\r\n\
             Connection: close\r\n\r\n",
        )
        .await;

        let response = client
            .files()
            .download_request("space-1", "file-1")
            .if_modified_since("Sun, 19 Jul 2026 12:00:00 GMT")
            .download()
            .await
            .expect("conditional response");

        assert_eq!(response.status, StatusCode::NOT_MODIFIED);
        assert!(response.is_not_modified());
        assert!(response.bytes.is_empty());
        server.await.expect("mock server task");
    }

    #[tokio::test]
    async fn per_request_body_limit_accepts_exact_boundary_and_rejects_one_over() {
        let responses = vec![
            "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: 5\r\nConnection: close\r\n\r\nbytes",
            "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: 5\r\nConnection: close\r\n\r\nbytes",
        ];
        let (client, server) = mock_file_client_sequence(responses).await;

        let response = client
            .files()
            .download_request("space-1", "file-1")
            .response_limit_bytes(5)
            .download()
            .await
            .expect("exact limit is accepted");
        assert_eq!(response.bytes, Bytes::from_static(b"bytes"));

        let error = client
            .files()
            .download_request("space-1", "file-1")
            .response_limit_bytes(4)
            .download()
            .await
            .expect_err("one byte over the request limit must fail");
        assert!(matches!(
            error,
            crate::error::AnytypeError::ResponseTooLarge {
                limit: 4,
                declared: Some(5)
            }
        ));
        assert_eq!(server.await.expect("mock server task").len(), 2);
    }

    #[tokio::test]
    async fn malformed_or_contradictory_range_evidence_fails_closed() {
        let responses = vec![
            "HTTP/1.1 206 Partial Content\r\nContent-Type: text/plain\r\nContent-Length: 5\r\nContent-Range: bytes 1-5/11\r\nConnection: close\r\n\r\nhello",
            "HTTP/1.1 206 Partial Content\r\nContent-Type: text/plain\r\nContent-Length: 5\r\nContent-Range: bytes nonsense\r\nConnection: close\r\n\r\nhello",
        ];
        let (client, server) = mock_file_client_sequence(responses).await;

        for expected_issue in ["request-mismatch", "malformed"] {
            let error = client
                .files()
                .download_request("space-1", "file-1")
                .range("bytes=0-4")
                .response_limit_bytes(5)
                .download()
                .await
                .expect_err("bad range evidence must fail");
            assert!(matches!(
                error,
                crate::error::AnytypeError::InvalidFileResponseHeader {
                    header: "content-range",
                    issue,
                    ..
                } if issue == expected_issue
            ));
        }
        assert_eq!(server.await.expect("mock server task").len(), 2);
    }

    #[tokio::test]
    async fn duplicate_validator_and_header_budget_fail_with_typed_evidence() {
        let responses = vec![
            "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 1\r\nETag: \"one\"\r\nETag: \"two\"\r\nConnection: close\r\n\r\nx",
            "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 1\r\nETag: W/\"unterminated\r\nConnection: close\r\n\r\nx",
            "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 1\r\nConnection: close\r\n\r\nx",
        ];
        let (client, server) = mock_file_client_sequence(responses).await;

        let duplicate = client
            .files()
            .download_request("space-1", "file-1")
            .download()
            .await
            .expect_err("duplicate ETag must fail");
        assert!(matches!(
            duplicate,
            crate::error::AnytypeError::InvalidFileResponseHeader {
                status: 200,
                header: "etag",
                issue: "duplicate"
            }
        ));

        let malformed = client
            .files()
            .download_request("space-1", "file-1")
            .download()
            .await
            .expect_err("malformed ETag must fail");
        assert!(matches!(
            malformed,
            crate::error::AnytypeError::InvalidFileResponseHeader {
                status: 200,
                header: "etag",
                issue: "malformed"
            }
        ));

        let bounded = client
            .files()
            .download_request("space-1", "file-1")
            .header_evidence_limit_bytes(8)
            .download()
            .await
            .expect_err("allowlisted headers over their request budget must fail");
        assert!(matches!(
            bounded,
            crate::error::AnytypeError::FileHeaderEvidenceTooLarge {
                limit: 8,
                status: 200
            }
        ));
        assert_eq!(server.await.expect("mock server task").len(), 3);
    }

    #[tokio::test]
    async fn truncated_body_and_malformed_metadata_fail_closed() {
        let responses = vec![
            "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\nConnection: close\r\n\r\nfour",
            "HTTP/1.1 200 OK\r\nContent-Type: not a mime\r\nContent-Length: 1\r\nConnection: close\r\n\r\nx",
            "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 1\r\nLast-Modified: yesterday\r\nConnection: close\r\n\r\nx",
        ];
        let (client, server) = mock_file_client_sequence(responses).await;

        let truncated = client
            .files()
            .download_request("space-1", "file-1")
            .response_limit_bytes(5)
            .download()
            .await
            .expect_err("truncated response must fail");
        assert!(matches!(truncated, crate::error::AnytypeError::Http { .. }));

        for expected_header in ["content-type", "last-modified"] {
            let malformed = client
                .files()
                .download_request("space-1", "file-1")
                .download()
                .await
                .expect_err("malformed metadata must fail");
            assert!(matches!(
                malformed,
                crate::error::AnytypeError::InvalidFileResponseHeader {
                    header,
                    issue: "malformed",
                    ..
                } if header == expected_header
            ));
        }
        assert_eq!(server.await.expect("mock server task").len(), 3);
    }

    #[tokio::test]
    async fn safe_retries_share_one_physical_attempt_ceiling() {
        let responses = vec![
            "HTTP/1.1 429 Too Many Requests\r\nRateLimit-Reset: 0\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
            "HTTP/1.1 504 Gateway Timeout\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok",
        ];
        let (client, server) = mock_file_client_sequence(responses).await;
        let response = client
            .files()
            .download_request("space-1", "file-1")
            .max_attempts(3)
            .response_limit_bytes(2)
            .header_evidence_limit_bytes(128)
            .download()
            .await
            .expect("third and final physical attempt succeeds");
        assert_eq!(response.bytes, Bytes::from_static(b"ok"));
        let requests = server.await.expect("mock server task");
        assert_eq!(requests.len(), 3);
        assert_eq!(client.http_metrics().total_requests, 3);
        assert_eq!(client.http_metrics().logical_operations, 1);
        assert_eq!(client.http_metrics().retries, 2);
    }

    #[tokio::test]
    async fn intermediate_retry_header_evidence_overflow_stops_without_replay() {
        let responses = vec![
            "HTTP/1.1 429 Too Many Requests\r\nRateLimit-Reset: 0\r\nContent-Length: 0\r\nETag: \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\r\nConnection: close\r\n\r\n",
        ];
        let (client, server) = mock_file_client_sequence(responses).await;

        let error = client
            .files()
            .download_request("space-1", "file-1")
            .max_attempts(3)
            .header_evidence_limit_bytes(64)
            .download()
            .await
            .expect_err("intermediate retry headers must be bounded before replay");
        assert!(matches!(
            error,
            crate::error::AnytypeError::FileHeaderEvidenceTooLarge {
                limit: 64,
                status: 429
            }
        ));
        assert_eq!(server.await.expect("mock server task").len(), 1);
        assert_eq!(client.http_metrics().total_requests, 1);
        assert_eq!(client.http_metrics().logical_operations, 1);
        assert_eq!(client.http_metrics().retries, 0);
    }

    #[tokio::test]
    async fn retry_ceiling_never_sends_one_attempt_over() {
        let responses = vec![
            "HTTP/1.1 429 Too Many Requests\r\nRateLimit-Reset: 0\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
            "HTTP/1.1 429 Too Many Requests\r\nRateLimit-Reset: 0\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
        ];
        let (client, server) = mock_file_client_sequence(responses).await;
        let error = client
            .files()
            .download_request("space-1", "file-1")
            .max_attempts(2)
            .download()
            .await
            .expect_err("second physical attempt exhausts the request ceiling");
        assert!(matches!(
            error,
            crate::error::AnytypeError::ApiError { code: 429, .. }
        ));
        assert_eq!(server.await.expect("mock server task").len(), 2);
        assert_eq!(client.http_metrics().total_requests, 2);
        assert_eq!(client.http_metrics().logical_operations, 1);
        assert_eq!(client.http_metrics().retries, 1);
    }

    #[test]
    fn request_range_grammar_is_canonical_and_checked() {
        assert!(super::parse_request_range("bytes=0-4").is_ok());
        assert!(super::parse_request_range("bytes=4-").is_ok());
        assert!(super::parse_request_range("bytes=-4").is_ok());
        for invalid in [
            "bytes=00-4",
            "bytes=4-3",
            "bytes=-0",
            "bytes=0-1,3-4",
            "items=0-4",
            "bytes=0 - 4",
        ] {
            assert!(
                super::parse_request_range(invalid).is_err(),
                "accepted {invalid}"
            );
        }
    }

    #[tokio::test]
    async fn permanent_delete_sets_skip_bin_query() {
        let (client, server) =
            mock_file_client("HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n").await;

        client
            .files()
            .delete_request("space-1", "file-1")
            .permanently()
            .delete()
            .await
            .expect("permanent delete");

        let request = server.await.expect("mock server task");
        assert!(
            request.starts_with("DELETE /v1/spaces/space-1/files/file-1?skip_bin=true HTTP/1.1")
        );
    }
}