calmlens 0.27.3

Rust SDK for CalmLens moderation, storage and CDN delivery
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
//! The async [`ServerClient`].
use crate::error::{invalid_argument, invalid_config, invalid_payload, ErrorCode};
use crate::models::*;
use crate::transport::{
    decode, execute, read_file_range, stream_error, upload_body, uuid, CallOptions, Deadline,
    Exchange, Prepared, RequestBody, Transport, DEFAULT_MAX_RESPONSE_BYTES,
};
use crate::{Error, Result};
use bytes::Bytes;
use futures_util::{stream::BoxStream, StreamExt, TryStreamExt};
use http::{HeaderMap, HeaderValue, Method, StatusCode};
use serde::Serialize;
use std::{
    collections::HashMap,
    fmt,
    sync::{Arc, Mutex},
    time::{Duration, SystemTime, UNIX_EPOCH},
};

/// The production API base URL.
pub const DEFAULT_BASE_URL: &str = "https://api.calmlens.com/v1";
/// The production CDN base URL.
pub const DEFAULT_CDN_BASE_URL: &str = "https://cdn.calmlens.com/v1";
/// The most lens definitions [`ServerClient::ensure_lenses`] sends in one request.
pub const ENSURE_LENSES_MAX_PER_REQUEST: usize = 100;
/// The longest signed asset URL lifetime the API accepts, in seconds: 24 hours.
pub const MAX_SIGNED_URL_EXPIRES_IN: u64 = 24 * 60 * 60;
/// The default timeout of each API call attempt.
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(120);
/// The default timeout of each binary upload attempt: none.
pub const DEFAULT_UPLOAD_TIMEOUT: Option<Duration> = None;
/// How many times a repeatable request is retried by default.
pub const DEFAULT_MAX_RETRIES: u32 = 2;
/// A signed asset URL's lifetime in seconds when the options give none: 15 minutes.
pub const DEFAULT_SIGNED_URL_EXPIRES_IN: u64 = 15 * 60;
/// An upload token's lifetime in seconds when the options give none: 10 minutes.
pub const DEFAULT_UPLOAD_TOKEN_SECONDS: u32 = 10 * 60;
/// Content larger than this many bytes is uploaded in parts of this size by default: 8 MiB.
pub const DEFAULT_PART_SIZE_BYTES: u64 = 8 * 1024 * 1024;
/// The smallest `part_size_bytes`: every part but the last is at least 5 MiB.
pub const MIN_PART_SIZE_BYTES: u64 = 5 * 1024 * 1024;
/// The largest `part_size_bytes`: 64 MiB.
pub const MAX_PART_SIZE_BYTES: u64 = 64 * 1024 * 1024;
/// The longest `idempotency_key` of an upload sent in parts: each part's key adds `:part-<n>`.
const MAX_SPLIT_IDEMPOTENCY_KEY_LENGTH: usize = 240;
/// How long [`AssetsClient::wait_for_decision`] waits by default.
pub const DEFAULT_DECISION_TIMEOUT: Duration = Duration::from_secs(60);
/// The wait before [`AssetsClient::wait_for_decision`]'s second check.
pub const DECISION_POLL_FIRST_INTERVAL: Duration = Duration::from_millis(500);
/// How much longer each wait between decision checks is than the one before.
pub const DECISION_POLL_INTERVAL_FACTOR: f64 = 1.5;
/// The longest wait between decision checks.
pub const DECISION_POLL_MAX_INTERVAL: Duration = Duration::from_secs(2);

/// Configures a [`ServerClient`]. Create it with [`ServerClient::builder`].
///
/// Defaults: a 120-second `timeout` for API calls (and for the response headers of CDN
/// downloads), no `upload_timeout` for binary uploads, a 10-second `connect_timeout`, a
/// 120-second `read_timeout` between response bytes, 2 retries of repeatable requests, a
/// 32 MiB `max_response_bytes` and an 8 MiB `part_size_bytes`.
#[derive(Clone)]
pub struct ServerClientBuilder {
    api_key: String,
    project_id: String,
    base_url: String,
    cdn_base_url: String,
    timeout: Duration,
    upload_timeout: Option<Duration>,
    connect_timeout: Duration,
    read_timeout: Duration,
    max_retries: u32,
    max_response_bytes: usize,
    part_size_bytes: u64,
    proxy: Option<String>,
    root_certificates: Vec<Vec<u8>>,
    app_info: Option<AppInfo>,
    on_attempt: Option<crate::observe::AttemptHook>,
}

/// Your application's name, version and URL, appended to the SDK's `User-Agent` by
/// [`ServerClientBuilder::app_info`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AppInfo {
    name: String,
    version: Option<String>,
    url: Option<String>,
}
impl AppInfo {
    /// ` name/version (url)`, as appended to the user agent.
    fn suffix(&self) -> String {
        let mut suffix = format!(" {}", self.name);
        if let Some(version) = &self.version {
            suffix.push('/');
            suffix.push_str(version);
        }
        if let Some(url) = &self.url {
            suffix.push_str(&format!(" ({url})"));
        }
        suffix
    }
}

impl fmt::Debug for ServerClientBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ServerClientBuilder")
            .field("api_key", &"[redacted]")
            .field("project_id", &self.project_id)
            .field("base_url", &self.base_url)
            .field("cdn_base_url", &self.cdn_base_url)
            .field("timeout", &self.timeout)
            .field("upload_timeout", &self.upload_timeout)
            .field("connect_timeout", &self.connect_timeout)
            .field("read_timeout", &self.read_timeout)
            .field("max_retries", &self.max_retries)
            .field("max_response_bytes", &self.max_response_bytes)
            .field("part_size_bytes", &self.part_size_bytes)
            .field("proxy", &self.proxy.as_ref().map(|_| "[set]"))
            .field("root_certificates", &self.root_certificates.len())
            .field("app_info", &self.app_info)
            .field("on_attempt", &self.on_attempt.is_some())
            .finish()
    }
}

impl ServerClientBuilder {
    pub(crate) fn new(api_key: String, project_id: String) -> Self {
        Self {
            api_key,
            project_id,
            base_url: DEFAULT_BASE_URL.into(),
            cdn_base_url: DEFAULT_CDN_BASE_URL.into(),
            timeout: DEFAULT_TIMEOUT,
            upload_timeout: DEFAULT_UPLOAD_TIMEOUT,
            connect_timeout: Duration::from_secs(10),
            read_timeout: Duration::from_secs(120),
            max_retries: DEFAULT_MAX_RETRIES,
            max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES,
            part_size_bytes: DEFAULT_PART_SIZE_BYTES,
            proxy: None,
            root_certificates: Vec::new(),
            app_info: None,
            on_attempt: None,
        }
    }
    /// A builder from the environment: `CALMLENS_API_KEY` and `CALMLENS_PROJECT_ID` (both
    /// required, else `sdk/invalid-config`) and `CALMLENS_BASE_URL` when it is set.
    pub fn from_env() -> Result<Self> {
        let var = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty());
        let (Some(api_key), Some(project_id)) =
            (var("CALMLENS_API_KEY"), var("CALMLENS_PROJECT_ID"))
        else {
            return Err(invalid_config(
                "Set CALMLENS_API_KEY and CALMLENS_PROJECT_ID, or pass the API key and project ID",
            ));
        };
        let mut builder = Self::new(api_key, project_id);
        if let Some(base_url) = var("CALMLENS_BASE_URL") {
            builder.base_url = base_url;
        }
        Ok(builder)
    }
    /// The API base URL, e.g. `http://localhost:6110/v1` for a local CalmLens.
    pub fn base_url(mut self, value: impl Into<String>) -> Self {
        self.base_url = value.into();
        self
    }
    /// The CDN base URL.
    pub fn cdn_base_url(mut self, value: impl Into<String>) -> Self {
        self.cdn_base_url = value.into();
        self
    }
    /// The timeout of each API call attempt, response body included (120 seconds by default).
    /// It also covers text uploads and the wait for a CDN download's response headers; binary
    /// uploads use [`upload_timeout`](Self::upload_timeout) instead, and a CDN body streams for
    /// as long as it takes.
    pub fn timeout(mut self, value: Duration) -> Self {
        self.timeout = value;
        self
    }
    /// The timeout of each binary upload attempt (none by default, so large files are not cut
    /// off; `read_timeout` still bounds a stalled connection).
    pub fn upload_timeout(mut self, value: Duration) -> Self {
        self.upload_timeout = Some(value);
        self
    }
    /// The largest API response body the client reads, in bytes (32 MiB by default). A larger
    /// one, or a larger declared `Content-Length`, fails with `sdk/response-too-large` before
    /// it is read. CDN downloads stream and have no limit.
    pub fn max_response_bytes(mut self, value: usize) -> Self {
        self.max_response_bytes = value;
        self
    }
    /// Content larger than this many bytes that the client holds in memory ([`Payload::Bytes`]
    /// and [`Payload::Base64`]) is uploaded by [`AssetsClient::create`] and
    /// [`AssetsClient::classify`] as a multipart upload in parts of this size (8 MiB by default,
    /// from 5 MiB to 64 MiB; anything else fails [`build`](Self::build) with
    /// `sdk/invalid-config`). Each part is retried on its own, and calling again with the same
    /// `idempotency_key` resumes an interrupted upload. Readers, streams and text go in one
    /// request.
    pub fn part_size_bytes(mut self, value: u64) -> Self {
        self.part_size_bytes = value;
        self
    }
    /// The timeout for establishing a connection (10 seconds by default).
    pub fn connect_timeout(mut self, value: Duration) -> Self {
        self.connect_timeout = value;
        self
    }
    /// The longest wait for the next response bytes, for every request including CDN streams
    /// (120 seconds by default).
    pub fn read_timeout(mut self, value: Duration) -> Self {
        self.read_timeout = value;
        self
    }
    /// How many times to retry a repeatable request (2 by default; 0 disables retries).
    ///
    /// GET and HEAD requests and POSTs carrying an `Idempotency-Key` (uploads and parts) are
    /// retried after transport failures and timeouts, `429`, `500`, `502`, `503`, `504` and
    /// `idempotency/request-in-progress`, waiting for `Retry-After` when the server sends one
    /// and otherwise for a jittered exponential backoff. Uploads from readers and streams are
    /// sent once.
    pub fn max_retries(mut self, value: u32) -> Self {
        self.max_retries = value;
        self
    }
    /// Sends every request through this HTTP(S) or SOCKS proxy URL, such as
    /// `http://proxy.internal:3128`. Credentials may be given in the URL.
    pub fn proxy(mut self, url: impl Into<String>) -> Self {
        self.proxy = Some(url.into());
        self
    }
    /// Also trusts the PEM certificates in `pem` (one or more), e.g. a corporate proxy's root.
    /// The operating system's (rustls) or platform library's (native-tls) roots still apply.
    pub fn add_root_certificate(mut self, pem: impl Into<Vec<u8>>) -> Self {
        self.root_certificates.push(pem.into());
        self
    }
    /// Names your application in the `User-Agent` the SDK sends, as ` name/version (url)`
    /// after the SDK's own entry, so CalmLens support can tell integrations apart.
    pub fn app_info(
        mut self,
        name: impl Into<String>,
        version: Option<&str>,
        url: Option<&str>,
    ) -> Self {
        self.app_info = Some(AppInfo {
            name: name.into(),
            version: version.map(str::to_owned),
            url: url.map(str::to_owned),
        });
        self
    }
    /// Calls `hook` after every HTTP attempt, retries included, with its operation, method,
    /// path, attempt number, the delay before it, status, request ID and duration, e.g. to
    /// record metrics. The event never holds the API key, tokens, signed URL grants or bodies.
    /// `CALMLENS_LOG=info` (failures and retries) or `debug` (every attempt) also writes these
    /// to standard error, and the `tracing` feature emits them as `tracing` events with the
    /// target `calmlens`.
    pub fn on_attempt(
        mut self,
        hook: impl Fn(&crate::AttemptEvent) + Send + Sync + 'static,
    ) -> Self {
        self.on_attempt = Some(Arc::new(hook));
        self
    }
    /// Validates the options and creates the client. Fails with `sdk/invalid-config`.
    pub fn build(self) -> Result<ServerClient> {
        let config = self.validate()?;
        // Redirects are never followed: a redirected API call would resend the API key.
        let mut http = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .connect_timeout(self.connect_timeout)
            .read_timeout(self.read_timeout)
            .no_proxy();
        if let Some(url) = &self.proxy {
            let proxy = reqwest::Proxy::all(url.as_str()).map_err(|cause| {
                invalid_config("proxy must be an HTTP(S) or SOCKS proxy URL").with_source(cause)
            })?;
            http = http.proxy(proxy);
        }
        for pem in &self.root_certificates {
            let certificates = reqwest::Certificate::from_pem_bundle(pem).map_err(|cause| {
                invalid_config("add_root_certificate needs PEM certificates").with_source(cause)
            })?;
            if certificates.is_empty() {
                return Err(invalid_config(
                    "add_root_certificate needs PEM certificates",
                ));
            }
            for certificate in certificates {
                http = http.add_root_certificate(certificate);
            }
        }
        let http = http.build().map_err(|cause| {
            invalid_config(format!("Could not create the HTTP client: {cause}")).with_source(cause)
        })?;
        Ok(ServerClient::from_parts(config, Transport::Http(http)))
    }
    /// The API and CDN base URLs, for the mock's recorded request paths.
    #[cfg(feature = "testing")]
    pub(crate) fn base_urls(&self) -> [String; 2] {
        [&self.base_url, &self.cdn_base_url].map(|url| url.trim_end_matches('/').to_owned())
    }
    #[cfg(feature = "testing")]
    pub(crate) fn build_mock(
        self,
        mock: Arc<crate::testing::MockTransport>,
    ) -> Result<ServerClient> {
        Ok(ServerClient::from_parts(
            self.validate()?,
            Transport::Mock(mock),
        ))
    }
    fn validate(&self) -> Result<Config> {
        for (name, value) in [
            ("timeout", Some(self.timeout)),
            ("upload_timeout", self.upload_timeout),
            ("connect_timeout", Some(self.connect_timeout)),
            ("read_timeout", Some(self.read_timeout)),
        ] {
            if value.is_some_and(|value| value.is_zero()) {
                return Err(invalid_config(format!("{name} must be positive")));
            }
        }
        if self.max_response_bytes == 0 {
            return Err(invalid_config("max_response_bytes must be positive"));
        }
        if !(MIN_PART_SIZE_BYTES..=MAX_PART_SIZE_BYTES).contains(&self.part_size_bytes) {
            return Err(invalid_config(format!(
                "part_size_bytes must be from {MIN_PART_SIZE_BYTES} (5 MiB) to {MAX_PART_SIZE_BYTES} (64 MiB)"
            )));
        }
        if self.api_key.is_empty() || self.project_id.is_empty() {
            return Err(invalid_config("API key and project ID are required"));
        }
        id(&self.project_id).map_err(|_| invalid_config("Invalid project ID"))?;
        // Only what can be sent as a header is checked: the API decides whether a key is real.
        if !self.api_key.bytes().all(|byte| matches!(byte, 0x21..=0x7e)) {
            return Err(invalid_config(
                "The API key must be printable ASCII without spaces",
            ));
        }
        let api_key = HeaderValue::from_str(&self.api_key)
            .map_err(|_| invalid_config("The API key contains characters a header cannot"))?;
        let mut api_key = api_key;
        api_key.set_sensitive(true);
        let mut urls = Vec::new();
        for url in [&self.base_url, &self.cdn_base_url] {
            let parsed = reqwest::Url::parse(url).ok().filter(|url| {
                ["http", "https"].contains(&url.scheme())
                    && url.query().is_none()
                    && url.fragment().is_none()
            });
            if parsed.is_none() {
                return Err(invalid_config(format!(
                    "Base URLs must be absolute HTTP(S) URLs without a query: {url:?}"
                )));
            }
            urls.push(url.trim_end_matches('/').to_owned());
        }
        let user_agent = format!(
            "{}{}",
            crate::user_agent(),
            self.app_info
                .as_ref()
                .map(AppInfo::suffix)
                .unwrap_or_default()
        );
        let user_agent = HeaderValue::from_str(&user_agent)
            .map_err(|_| invalid_config("app_info must be printable ASCII"))?;
        Ok(Config {
            observer: crate::observe::Observer {
                hook: self.on_attempt.clone(),
                log: crate::observe::LogLevel::from_env(),
            },
            user_agent,
            api_key,
            project_id: self.project_id.clone(),
            cdn_base_url: urls.pop().unwrap_or_default(),
            base_url: urls.pop().unwrap_or_default(),
            timeout: self.timeout,
            upload_timeout: self.upload_timeout,
            max_retries: self.max_retries,
            max_response_bytes: self.max_response_bytes,
            part_size_bytes: self.part_size_bytes,
        })
    }
}

struct Config {
    observer: crate::observe::Observer,
    user_agent: HeaderValue,
    api_key: HeaderValue,
    project_id: String,
    base_url: String,
    cdn_base_url: String,
    timeout: Duration,
    upload_timeout: Option<Duration>,
    max_retries: u32,
    max_response_bytes: usize,
    part_size_bytes: u64,
}

struct Inner {
    config: Config,
    transport: Transport,
    user_agent: HeaderValue,
    lenses: Mutex<HashMap<String, Lens>>,
    /// Held while lenses are ensured, so concurrent calls for the same definitions send one
    /// request and the others answer from the cache it fills.
    ensuring: tokio::sync::Mutex<()>,
}

/// The async CalmLens client.
///
/// Create one client and reuse it: clones are cheap and share the connection pool and lens
/// cache, so hold it in your application state (or an `Arc`) rather than creating one per
/// request. All methods are `Send`, so they work in Tokio tasks, axum and actix-web handlers.
#[derive(Clone)]
pub struct ServerClient {
    inner: Arc<Inner>,
    timeout: Option<Duration>,
    max_retries: Option<u32>,
    request_options: Option<Arc<RequestOptions>>,
}

/// Options for the calls made through a [`ServerClient::with_options`] handle, such as
/// `client.with_options(RequestOptions::new().header("X-Trace", "1")).assets().retrieve(id)`.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct RequestOptions {
    /// The timeout of each attempt, replacing the client's `timeout` (and `upload_timeout`).
    pub timeout: Option<Duration>,
    /// How many times to retry a repeatable request, replacing the client's `max_retries`.
    pub max_retries: Option<u32>,
    /// The `Idempotency-Key` of POST requests that have none of their own, which also makes them
    /// retryable. Uploads use their `idempotency_key` option first.
    pub idempotency_key: Option<String>,
    /// Extra request headers. The SDK's `X-Api-Key`, `User-Agent` and `Authorization` can't be
    /// replaced.
    pub headers: Vec<(String, String)>,
    /// Extra query parameters, added after the SDK's own.
    pub extra_query: Vec<(String, String)>,
    /// Extra top-level properties for a JSON request body, e.g. an option this SDK version does
    /// not have yet. They replace properties of the same name.
    pub extra_body: serde_json::Map<String, serde_json::Value>,
}
impl RequestOptions {
    /// Options with nothing set.
    pub fn new() -> Self {
        Self::default()
    }
    /// Sets the per-attempt timeout.
    pub fn timeout(mut self, value: Duration) -> Self {
        self.timeout = Some(value);
        self
    }
    /// Sets the retry limit.
    pub fn max_retries(mut self, value: u32) -> Self {
        self.max_retries = Some(value);
        self
    }
    /// Sets the `Idempotency-Key`.
    pub fn idempotency_key(mut self, value: impl Into<String>) -> Self {
        self.idempotency_key = Some(value.into());
        self
    }
    /// Adds a request header.
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }
    /// Adds a query parameter.
    pub fn query(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra_query.push((name.into(), value.into()));
        self
    }
    /// Adds a top-level JSON body property.
    pub fn body_field(
        mut self,
        name: impl Into<String>,
        value: impl Into<serde_json::Value>,
    ) -> Self {
        self.extra_body.insert(name.into(), value.into());
        self
    }
}

impl fmt::Debug for ServerClient {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let config = &self.inner.config;
        f.debug_struct("ServerClient")
            .field("api_key", &"[redacted]")
            .field("project_id", &config.project_id)
            .field("base_url", &config.base_url)
            .field("cdn_base_url", &config.cdn_base_url)
            .field("timeout", &self.timeout.unwrap_or(config.timeout))
            .field(
                "max_retries",
                &self.max_retries.unwrap_or(config.max_retries),
            )
            .finish_non_exhaustive()
    }
}

impl ServerClient {
    /// A client for the production API with default options.
    pub fn new(api_key: impl Into<String>, project_id: impl Into<String>) -> Result<Self> {
        Self::builder(api_key, project_id).build()
    }
    /// A client from the environment; see [`ServerClientBuilder::from_env`].
    pub fn from_env() -> Result<Self> {
        ServerClientBuilder::from_env()?.build()
    }
    /// A builder for a client with custom URLs, timeouts, retries, proxy or certificates.
    pub fn builder(
        api_key: impl Into<String>,
        project_id: impl Into<String>,
    ) -> ServerClientBuilder {
        ServerClientBuilder::new(api_key.into(), project_id.into())
    }
    fn from_parts(config: Config, transport: Transport) -> Self {
        let user_agent = config.user_agent.clone();
        Self {
            inner: Arc::new(Inner {
                config,
                transport,
                user_agent,
                lenses: Mutex::new(HashMap::new()),
                ensuring: tokio::sync::Mutex::new(()),
            }),
            timeout: None,
            max_retries: None,
            request_options: None,
        }
    }
    /// A handle whose calls, including uploads and CDN downloads, time out after `timeout`.
    /// It shares this client's connections.
    pub fn with_timeout(&self, timeout: Duration) -> Self {
        Self {
            timeout: Some(timeout),
            ..self.clone()
        }
    }
    /// A handle whose API calls use `options`: a timeout, retry limit, idempotency key, extra
    /// headers, query parameters and body properties. It shares this client's connections. The
    /// timeout and retry limit also apply to CDN downloads.
    pub fn with_options(&self, options: RequestOptions) -> Self {
        Self {
            timeout: options.timeout.or(self.timeout),
            max_retries: options.max_retries.or(self.max_retries),
            request_options: Some(Arc::new(options)),
            ..self.clone()
        }
    }
    /// Sends any API request with the client's API key, retries and error mapping, for an
    /// endpoint this SDK version has no method for. `path` is relative to the base URL, such
    /// as `/projects/{project_id}/assets`, and may carry a query. The response body is returned
    /// as JSON (`null` when empty).
    pub async fn request(
        &self,
        method: Method,
        path: &str,
        body: Option<&serde_json::Value>,
    ) -> Result<serde_json::Value> {
        if !path.starts_with('/') || path.starts_with("//") {
            return Err(invalid_argument("path must start with a single /"));
        }
        let mut request = self.prepare(method, path, &[])?;
        if let Some(body) = body {
            request = request.json(body)?;
        }
        let (status, headers, body) = self.send(request).await?;
        if body.is_empty() {
            return Ok(serde_json::Value::Null);
        }
        decode(status, &headers, &body)
    }
    /// A handle that retries repeatable requests up to `max_retries` times.
    pub fn with_max_retries(&self, max_retries: u32) -> Self {
        Self {
            max_retries: Some(max_retries),
            ..self.clone()
        }
    }
    /// The project this client works in.
    pub fn project_id(&self) -> &str {
        &self.inner.config.project_id
    }
    /// Asset operations.
    pub fn assets(&self) -> AssetsClient<'_> {
        AssetsClient(self)
    }
    /// Folder operations.
    pub fn folders(&self) -> FoldersClient<'_> {
        FoldersClient(self)
    }
    /// Hash list operations.
    pub fn hash_lists(&self) -> HashListsClient<'_> {
        HashListsClient(self)
    }
    /// Moderation policy operations.
    pub fn policies(&self) -> PoliciesClient<'_> {
        PoliciesClient(self)
    }
    /// The project's upload presets: the rules for uploads from browsers and apps.
    pub fn upload_presets(&self) -> UploadPresetsClient<'_> {
        UploadPresetsClient(self)
    }
    /// The project's settings.
    pub fn project_settings(&self) -> ProjectSettingsClient<'_> {
        ProjectSettingsClient(self)
    }
    /// The project's metadata fields.
    pub fn metadata_fields(&self) -> MetadataFieldsClient<'_> {
        MetadataFieldsClient(self)
    }
    /// Lens operations: the project's named CDN transforms.
    pub fn lenses(&self) -> LensesClient<'_> {
        LensesClient(self)
    }
    /// The project's events feed.
    pub fn events(&self) -> EventsClient<'_> {
        EventsClient(self)
    }
    /// CDN URLs and downloads.
    pub fn cdn(&self) -> CdnClient<'_> {
        CdnClient(self)
    }
    /// Text moderation.
    pub fn text(&self) -> TextClient<'_> {
        TextClient(self)
    }
    /// Upload tokens for upload presets, signed locally.
    pub fn upload_tokens(&self) -> UploadTokensClient<'_> {
        UploadTokensClient(self)
    }

    /// Creates a named lens, or changes it to this definition, and returns it. See
    /// [`ServerClient::ensure_lenses`].
    pub async fn ensure_lens(&self, lens: LensDefinition) -> Result<Lens> {
        let mut lenses = self
            .ensure_lenses(EnsureLenses { lenses: vec![lens] })
            .await?;
        lenses
            .pop()
            .ok_or_else(|| Error::new(ErrorCode::InvalidResponse, "Unexpected lens response"))
    }
    /// Creates each named lens, or changes it to the definition sent, by identifier, and returns
    /// them in request order. An unchanged lens is returned as it is, so applications can send
    /// their lenses every time they start. Definitions this client has already ensured are
    /// answered from its cache without a request, and
    /// concurrent calls wait for each other, so one definition is sent once. More than
    /// [`ENSURE_LENSES_MAX_PER_REQUEST`] new definitions are sent in consecutive requests, in order.
    /// A response that does not return each definition's lens at its position fails with
    /// `sdk/invalid-response`.
    pub async fn ensure_lenses(&self, options: EnsureLenses) -> Result<Vec<Lens>> {
        if options.lenses.is_empty() {
            return Err(invalid_argument("At least one lens is required"));
        }
        let _ensuring = self.inner.ensuring.lock().await;
        let mut keys = Vec::with_capacity(options.lenses.len());
        let mut missing: Vec<(String, &LensDefinition)> = Vec::new();
        let mut resolved = HashMap::new();
        {
            let cache = self.inner.lenses.lock().unwrap_or_else(|e| e.into_inner());
            for lens in &options.lenses {
                id(&lens.identifier)?;
                // A lens sent without `active` is active, so both spellings share a cache entry.
                let key = serde_json::to_string(&LensDefinition {
                    active: Some(lens.active.unwrap_or(true)),
                    ..lens.clone()
                })
                .map_err(|cause| invalid_argument(cause.to_string()).with_source(cause))?;
                match cache.get(&key) {
                    Some(cached) => {
                        resolved.insert(key.clone(), cached.clone());
                    }
                    None if !missing.iter().any(|(k, _)| *k == key) => {
                        missing.push((key.clone(), lens))
                    }
                    None => {}
                }
                keys.push(key);
            }
        }
        #[derive(Serialize)]
        struct Body<'a> {
            lenses: Vec<&'a LensDefinition>,
        }
        #[derive(serde::Deserialize)]
        struct Response {
            lenses: Vec<Lens>,
        }
        impl crate::models::Responded for Response {}
        for chunk in missing.chunks(ENSURE_LENSES_MAX_PER_REQUEST) {
            let request = self.prepare_for(
                "ensureLenses",
                Method::PUT,
                &self.project_path("lenses")?,
                &[],
            )?;
            let request = request.json(&Body {
                lenses: chunk.iter().map(|(_, lens)| *lens).collect(),
            })?;
            let response: Response = self.call(request).await?;
            if response.lenses.len() != chunk.len() {
                return Err(Error::new(
                    ErrorCode::InvalidResponse,
                    format!(
                        "Expected {} lenses but CalmLens returned {}",
                        chunk.len(),
                        response.lenses.len()
                    ),
                ));
            }
            let mut cache = self.inner.lenses.lock().unwrap_or_else(|e| e.into_inner());
            for ((key, definition), lens) in chunk.iter().zip(response.lenses) {
                if lens.identifier != definition.identifier {
                    return Err(Error::new(
                        ErrorCode::InvalidResponse,
                        format!("Expected lens {:?} at its position", definition.identifier),
                    ));
                }
                cache.retain(|_, cached| cached.identifier != lens.identifier);
                cache.insert(key.clone(), lens.clone());
                resolved.insert(key.clone(), lens);
            }
        }
        Ok(keys
            .iter()
            .filter_map(|key| resolved.get(key).cloned())
            .collect())
    }

    fn options(&self) -> CallOptions {
        let config = &self.inner.config;
        CallOptions {
            timeout: config.timeout,
            upload_timeout: config.upload_timeout,
            timeout_override: self.timeout,
            max_retries: self.max_retries.unwrap_or(config.max_retries),
            max_response_bytes: config.max_response_bytes,
        }
    }
    fn project_path(&self, path: &str) -> Result<String> {
        Ok(format!(
            "/projects/{}/{path}",
            id(&self.inner.config.project_id)?
        ))
    }
    /// An API request for `operation`, which accepts JSON.
    fn prepare_for(
        &self,
        operation: &'static str,
        method: Method,
        path: &str,
        query: &[(String, String)],
    ) -> Result<Prepared> {
        let mut request = self.prepare(method, path, query)?;
        request.operation = Some(operation);
        Ok(request)
    }
    fn prepare_url_for(
        &self,
        operation: &'static str,
        method: Method,
        url: &str,
        query: &[(String, String)],
    ) -> Result<Prepared> {
        let mut request = self.prepare_url(method, url, query)?;
        request.operation = Some(operation);
        Ok(request)
    }
    /// The handle's [`RequestOptions::idempotency_key`], for uploads without their own.
    fn call_idempotency_key(&self) -> Option<String> {
        self.request_options
            .as_ref()
            .and_then(|options| options.idempotency_key.clone())
    }
    /// Adds the handle's [`RequestOptions`] to an API request.
    fn with_request_options(&self, mut request: Prepared) -> Result<Prepared> {
        let Some(options) = &self.request_options else {
            return Ok(request);
        };
        for (name, value) in &options.headers {
            let name = http::HeaderName::from_bytes(name.as_bytes())
                .map_err(|_| invalid_argument(format!("Invalid header name {name:?}")))?;
            if [http::header::USER_AGENT, http::header::AUTHORIZATION].contains(&name)
                || name == "x-api-key"
            {
                continue;
            }
            let value = HeaderValue::from_str(value)
                .map_err(|_| invalid_argument(format!("Invalid {name} header value")))?;
            request.headers.append(name, value);
        }
        if !options.extra_query.is_empty() {
            request
                .url
                .query_pairs_mut()
                .extend_pairs(&options.extra_query);
        }
        if let Some(key) = &options.idempotency_key {
            if request.method == Method::POST && !request.headers.contains_key("idempotency-key") {
                request = request.header("idempotency-key", key)?;
            }
        }
        if !options.extra_body.is_empty() {
            request = request.merge_json(&options.extra_body)?;
        }
        Ok(request)
    }
    /// An API request, which accepts JSON.
    fn prepare(&self, method: Method, path: &str, query: &[(String, String)]) -> Result<Prepared> {
        let url = format!("{}{path}", self.inner.config.base_url);
        let mut request = self.prepare_url(method, &url, query)?;
        request.headers.insert(
            http::header::ACCEPT,
            HeaderValue::from_static("application/json"),
        );
        Ok(request)
    }
    fn prepare_url(
        &self,
        method: Method,
        url: &str,
        query: &[(String, String)],
    ) -> Result<Prepared> {
        let mut url = reqwest::Url::parse(url).map_err(|cause| {
            invalid_argument(format!("Invalid URL: {cause}")).with_source(cause)
        })?;
        if !query.is_empty() {
            url.query_pairs_mut().extend_pairs(query);
        }
        let mut request = Prepared::new(method, url);
        request
            .headers
            .insert("x-api-key", self.inner.config.api_key.clone());
        request
            .headers
            .insert(http::header::USER_AGENT, self.inner.user_agent.clone());
        Ok(request)
    }
    async fn send(&self, request: Prepared) -> Result<(u16, HeaderMap, Bytes)> {
        self.send_keyed(request)
            .await
            .map(|(status, headers, body, _)| (status, headers, body))
    }
    /// [`send`](Self::send), with the `Idempotency-Key` the request carried.
    async fn send_keyed(
        &self,
        request: Prepared,
    ) -> Result<(u16, HeaderMap, Bytes, Option<String>)> {
        let options = self.options();
        let request = self.with_request_options(request)?;
        let key = request
            .headers
            .get("idempotency-key")
            .and_then(|value| value.to_str().ok())
            .map(str::to_owned);
        let exchange = execute(
            &self.inner.transport,
            request,
            options,
            true,
            &self.inner.config.observer,
        )
        .await?;
        let (status, headers) = (exchange.status, exchange.headers.clone());
        let body = exchange.read(options.max_response_bytes).await?;
        Ok((status, headers, body, key))
    }
    async fn call<T: serde::de::DeserializeOwned + crate::models::Responded>(
        &self,
        request: Prepared,
    ) -> Result<T> {
        let (status, headers, body, key) = self.send_keyed(request).await?;
        let mut value: T = decode(status, &headers, &body)?;
        value.set_last_response(crate::transport::last_response(status, &headers, key));
        Ok(value)
    }
    async fn call_empty(&self, request: Prepared) -> Result<()> {
        self.send(request).await.map(|_| ())
    }
    /// An upload's response, which must be an asset with an ID.
    async fn call_upload(&self, request: Prepared) -> Result<Asset> {
        let (status, headers, body, key) = self.send_keyed(request).await?;
        let value: serde_json::Value = decode(status, &headers, &body)?;
        if value["id"].as_str().is_none_or(|id| id.is_empty()) {
            return Err(Error::new(
                ErrorCode::InvalidResponse,
                "Expected an uploaded asset response",
            )
            .with_http_status(status));
        }
        let mut asset: Asset = serde_json::from_value(value).map_err(|cause| {
            Error::new(
                ErrorCode::InvalidResponse,
                format!("Invalid asset response: {cause}"),
            )
            .with_http_status(status)
            .with_source(cause)
        })?;
        asset.set_last_response(crate::transport::last_response(status, &headers, key));
        Ok(asset)
    }

    async fn submit(&self, options: SubmitAsset, wait: bool) -> Result<Asset> {
        let operation = if wait {
            "assets.classify"
        } else {
            "assets.create"
        };
        if options.name.is_empty() {
            return Err(invalid_payload("Asset name is required"));
        }
        let sources = [
            options.content.is_some(),
            options.part.is_some(),
            options.url.is_some(),
        ];
        if sources.iter().filter(|present| **present).count() != 1 {
            return Err(invalid_payload(
                "Supply exactly one of content, part, or url; isFinal belongs in part",
            ));
        }
        let idempotency_key = options
            .idempotency_key
            .clone()
            .or_else(|| self.call_idempotency_key())
            .unwrap_or_else(uuid);
        // Only the posts CalmLens uses are sent.
        let context = options
            .context
            .as_ref()
            .map(|context| ModerationContext::new(select_moderation_context_items(&context.items)));
        // The asset's fields go in the body (the JSON body, or an upload form's options part),
        // never the query, which proxies and servers log. Null and unset values are left out.
        let fields = serde_json::to_value(UploadFields {
            name: &options.name,
            description: options.description.as_ref(),
            processing_options: options.processing_options.as_ref(),
            visibility: options.visibility.as_ref(),
            metadata: options.metadata.as_ref(),
            tags: options.tags.as_ref(),
            author_id: options.author_id.as_ref(),
            context: context.as_ref(),
            external_id: options.external_id.as_ref(),
            external_url: options.external_url.as_ref(),
            folder_id: match &options.folder_id {
                Patch::Value(folder) => Some(folder),
                _ => None,
            },
            upload_preset_id: options.upload_preset_id.as_ref(),
        })
        .map_err(|cause| invalid_argument(cause.to_string()).with_source(cause))?;
        let serde_json::Value::Object(fields) = fields else {
            unreachable!("upload fields serialize as an object")
        };
        // The query holds only transport values.
        let mut query = Query::default();
        query.push("wait", wait);
        if let Some(url) = &options.url {
            #[derive(Serialize)]
            #[serde(rename_all = "camelCase")]
            struct UrlBody<'a> {
                name: &'a str,
                url: &'a str,
                #[serde(skip_serializing_if = "Option::is_none")]
                description: Option<&'a String>,
                #[serde(skip_serializing_if = "Option::is_none")]
                processing_options: Option<&'a ProcessingOptions>,
                #[serde(skip_serializing_if = "Option::is_none")]
                visibility: Option<&'a Visibility>,
                #[serde(skip_serializing_if = "Option::is_none")]
                metadata: Option<&'a Vec<MetadataItem>>,
                #[serde(skip_serializing_if = "Option::is_none")]
                tags: Option<&'a Vec<String>>,
                #[serde(skip_serializing_if = "Option::is_none")]
                author_id: Option<&'a String>,
                #[serde(skip_serializing_if = "Option::is_none")]
                context: Option<&'a ModerationContext>,
                #[serde(skip_serializing_if = "Option::is_none")]
                external_id: Option<&'a String>,
                #[serde(skip_serializing_if = "Option::is_none")]
                external_url: Option<&'a String>,
                #[serde(skip_serializing_if = "Patch::is_missing")]
                folder_id: &'a Patch<String>,
                #[serde(skip_serializing_if = "Option::is_none")]
                upload_preset_id: Option<&'a String>,
            }
            let request = self
                .prepare_for(
                    operation,
                    Method::POST,
                    &self.project_path("assets")?,
                    &[("wait".into(), wait.to_string())],
                )?
                .header("idempotency-key", &idempotency_key)?
                .json(&UrlBody {
                    name: &options.name,
                    url,
                    description: options.description.as_ref(),
                    processing_options: options.processing_options.as_ref(),
                    visibility: options.visibility.as_ref(),
                    metadata: options.metadata.as_ref(),
                    tags: options.tags.as_ref(),
                    author_id: options.author_id.as_ref(),
                    context: context.as_ref(),
                    external_id: options.external_id.as_ref(),
                    external_url: options.external_url.as_ref(),
                    folder_id: &options.folder_id,
                    upload_preset_id: options.upload_preset_id.as_ref(),
                })?;
            return self.call_upload(request).await;
        }
        let multipart = options.part.is_some();
        let content = match (options.content, options.part) {
            (Some(content), _) | (None, Some(content)) => content,
            (None, None) => return Err(invalid_payload("Content is required")),
        };
        let mime = crate::contract_checks::normalize_upload_mime_type(&content.mime_type);
        if !crate::contract_checks::is_accepted_upload_mime_type(&content.mime_type) {
            return Err(crate::contract_checks::invalid_upload_mime_type(
                &content.mime_type,
            ));
        }
        if multipart && content.part_number.is_some_and(|number| number != 1) {
            return Err(Error::new(
                ErrorCode::UseUploadPart,
                "Use uploadPart for multipart upload parts after the first part",
            ));
        }
        let is_final = content.is_final.unwrap_or(false);
        let deadline = upload_deadline(&content.payload);
        // Bytes in memory and files can be cut into parts and read again; readers and streams
        // cannot, and text stays one request.
        let part_size = self.inner.config.part_size_bytes;
        let mut text = None;
        let (source, body, size) = match content.payload {
            Payload::Text(value) => {
                let size = value.len() as u64;
                if content
                    .size_in_bytes
                    .is_some_and(|declared| declared != size)
                {
                    return Err(invalid_payload(
                        "sizeInBytes must match the payload byte length",
                    ));
                }
                text = Some(value);
                (None, RequestBody::Empty, Some(size))
            }
            Payload::File { path, size } if !multipart && size > part_size => {
                if content
                    .size_in_bytes
                    .is_some_and(|declared| declared != size)
                {
                    return Err(invalid_payload(
                        "sizeInBytes must match the payload byte length",
                    ));
                }
                (Some(PartSource::File(path)), RequestBody::Empty, Some(size))
            }
            payload => {
                let splittable =
                    !multipart && matches!(payload, Payload::Bytes(_) | Payload::Base64(_));
                match upload_body(payload, multipart, content.size_in_bytes)? {
                    (RequestBody::Bytes(bytes), size)
                        if splittable && bytes.len() as u64 > part_size =>
                    {
                        (Some(PartSource::Bytes(bytes)), RequestBody::Empty, size)
                    }
                    (body, size) => (None, body, size),
                }
            }
        };
        if let (Some(source), Some(total)) = (source, size) {
            if idempotency_key.chars().count() > MAX_SPLIT_IDEMPOTENCY_KEY_LENGTH {
                return Err(invalid_argument(format!(
                    "idempotency_key can be at most {MAX_SPLIT_IDEMPOTENCY_KEY_LENGTH} characters for an upload sent in parts"
                )));
            }
            if !self.inner.transport.defers_upload_checks() {
                if mime.starts_with("image/") {
                    check_image_size(size, false)?;
                } else {
                    check_upload_size(&mime, size, true)?;
                }
            }
            return self
                .submit_in_parts(
                    operation,
                    (query, &fields),
                    &content.mime_type,
                    (source, total),
                    idempotency_key,
                )
                .await;
        }
        if multipart && !self.inner.transport.defers_upload_checks() {
            if mime.starts_with("image/") {
                check_image_size(size, is_final)?;
            } else {
                // A declared whole-file size over the limit for parts can never finish.
                check_upload_size(&mime, options.total_size_in_bytes, true)?;
            }
            check_part_size(size, is_final)?;
        }
        if !multipart && !self.inner.transport.defers_upload_checks() {
            check_upload_size(&mime, size, false)?;
        }
        if let Some(plain_text) = text {
            // Plain text is one JSON body, with the fields beside it.
            let mut body = fields;
            let mut text = serde_json::Map::new();
            text.insert("plainText".into(), plain_text.into());
            text.insert("type".into(), content.mime_type.into());
            if multipart {
                if let Some(number) = content.part_number {
                    text.insert("partNumber".into(), number.into());
                }
                text.insert("isFinal".into(), is_final.into());
                body.insert("part".into(), text.into());
                if let Some(size) = content.size_in_bytes {
                    body.insert("sizeInBytes".into(), size.into());
                }
                if let Some(total) = options.total_size_in_bytes {
                    body.insert("totalSizeInBytes".into(), total.into());
                }
            } else {
                body.insert("content".into(), text.into());
            }
            let mut request = self
                .prepare_for(
                    operation,
                    Method::POST,
                    &self.project_path("assets")?,
                    &query.0,
                )?
                .header("idempotency-key", &idempotency_key)?
                .json(&body)?;
            request.deadline = deadline;
            return self.call_upload(request).await;
        }
        query.push("contentType", &content.mime_type);
        query.opt("sizeInBytes", size);
        if multipart {
            query.push("partNumber", 1);
            query.push("isFinal", is_final);
            query.opt("totalSizeInBytes", options.total_size_in_bytes);
        }
        let (form_type, body) = upload_form(&fields, &content.mime_type, body)?;
        let mut request = self
            .prepare_for(
                operation,
                Method::POST,
                &self.project_path("assets")?,
                &query.0,
            )?
            .header("content-type", &form_type)?
            .header(
                "x-calmlens-upload",
                if multipart { "part" } else { "content" },
            )?
            .header("idempotency-key", &idempotency_key)?;
        request.body = body;
        request.deadline = deadline;
        self.call_upload(request).await
    }

    async fn upload_part(&self, options: UploadPart) -> Result<Asset> {
        let path = format!("/assets/{}/part", id(&options.asset_id)?);
        let part_number = options.part.part_number.unwrap_or(0);
        if part_number < 1 {
            return Err(Error::new(
                ErrorCode::InvalidUploadPartNumber,
                "Multipart upload part number is invalid.",
            ));
        }
        let is_final = options.part.is_final.unwrap_or(false);
        let deadline = upload_deadline(&options.part.payload);
        let (body, size) = upload_body(options.part.payload, true, options.part.size_in_bytes)?;
        if !self.inner.transport.defers_upload_checks() {
            check_part_size(size, is_final)?;
        }
        let idempotency_key = options
            .idempotency_key
            .or_else(|| self.call_idempotency_key())
            .unwrap_or_else(uuid);
        self.send_part(
            &path,
            (part_number, is_final),
            (body, size),
            options.wait,
            &idempotency_key,
            deadline,
        )
        .await
    }

    /// Sends part `number` of a multipart upload to `path` (`/assets/{id}/part`).
    async fn send_part(
        &self,
        path: &str,
        (part_number, is_final): (u32, bool),
        (body, size): (RequestBody, Option<u64>),
        wait: Option<bool>,
        idempotency_key: &str,
        deadline: Deadline,
    ) -> Result<Asset> {
        let mut query = Query::default();
        query.push("partNumber", part_number);
        query.push("isFinal", is_final);
        query.opt("wait", wait);
        query.opt("sizeInBytes", size);
        // Later parts carry no Content-Type: the API reads the upload's saved type.
        let mut request = self
            .prepare_for("assets.uploadPart", Method::POST, path, &query.0)?
            .header("x-calmlens-upload", "part")?
            .header("idempotency-key", idempotency_key)?;
        request.body = body;
        request.deadline = deadline;
        self.call_upload(request).await
    }

    /// Uploads `bytes` as a multipart upload in `part_size_bytes` parts and returns the final
    /// part's asset. The first part goes as an upload form with the upload's `fields` and the
    /// transport values in `query`; part `n` after it
    /// carries the key `<key>:part-<n>`, so each is retried safely and repeating the call with
    /// the same key replays the parts the API already has and sends the rest. A part the API
    /// already has is skipped, and a final part that finds the upload completed reads it back.
    async fn submit_in_parts(
        &self,
        operation: &'static str,
        (mut query, fields): (Query, &serde_json::Map<String, serde_json::Value>),
        mime_type: &str,
        (source, total): (PartSource, u64),
        key: String,
    ) -> Result<Asset> {
        let part_size = self.inner.config.part_size_bytes;
        let count = u32::try_from(total.div_ceil(part_size))
            .map_err(|_| invalid_payload("The content has too many parts"))?;
        let piece = |number: u32| {
            let start = u64::from(number - 1) * part_size;
            let end = (u64::from(number) * part_size).min(total);
            source.read(start, (end - start) as usize)
        };
        let first = piece(1).await?;
        query.push("contentType", mime_type);
        query.push("sizeInBytes", first.len());
        query.push("partNumber", 1);
        query.push("isFinal", false);
        query.push("totalSizeInBytes", total);
        let (form_type, body) = upload_form(fields, mime_type, RequestBody::Bytes(first))?;
        let mut request = self
            .prepare_for(
                operation,
                Method::POST,
                &self.project_path("assets")?,
                &query.0,
            )?
            .header("content-type", &form_type)?
            .header("x-calmlens-upload", "part")?
            .header("idempotency-key", &key)?;
        request.body = body;
        request.deadline = Deadline::Upload;
        let mut asset = self.call_upload(request).await?;
        let path = format!("/assets/{}/part", id(&asset.id)?);
        let mut number = 2;
        while number <= count {
            let is_final = number == count;
            let part = piece(number).await?;
            let size = part.len() as u64;
            let sent = self
                .send_part(
                    &path,
                    (number, is_final),
                    (RequestBody::Bytes(part), Some(size)),
                    None,
                    &format!("{key}:part-{number}"),
                    Deadline::Upload,
                )
                .await;
            match sent {
                Ok(next) => {
                    asset = next;
                    number += 1;
                }
                Err(error) => {
                    let expected = error
                        .details()
                        .get("expectedPartNumber")
                        .and_then(serde_json::Value::as_u64);
                    if *error.code() == ErrorCode::InvalidUploadPartNumber {
                        // The parts before `expected` arrived, but their responses were lost.
                        if let Some(expected) = expected
                            .filter(|expected| *expected > u64::from(number))
                            .and_then(|expected| u32::try_from(expected).ok())
                            .filter(|expected| *expected <= count)
                        {
                            number = expected;
                            continue;
                        }
                    }
                    if is_final && *error.code() == ErrorCode::UploadNotOpen {
                        // The final part completed the upload, but its response was lost.
                        return AssetsClient(self).retrieve(AssetId::new(asset.id)).await;
                    }
                    return Err(error);
                }
            }
        }
        Ok(asset)
    }

    async fn list_page(&self, options: &ListAssets) -> Result<AssetPage> {
        let mut query = Query::default();
        query.opt("cursor", options.cursor.as_deref());
        query.opt("pageSize", options.page_size);
        query.opt("filter", options.filter.as_ref());
        query.opt("sort", options.sort.as_ref());
        self.call(self.prepare_for(
            "assets.list",
            Method::GET,
            &self.project_path("assets")?,
            &query.0,
        )?)
        .await
    }
    async fn children_page(&self, options: &ListChildren) -> Result<AssetPage> {
        let path = format!("/assets/{}/children", id(&options.asset_id)?);
        let mut query = Query::default();
        query.opt("cursor", options.cursor.as_deref());
        query.opt("pageSize", options.page_size);
        query.opt("sort", options.sort.as_ref());
        self.call(self.prepare_for("assets.listChildren", Method::GET, &path, &query.0)?)
            .await
    }
    async fn timeline_page(&self, options: &ListTimeline) -> Result<AssetTimelinePage> {
        let path = self.project_path(&format!("assets/{}/timeline", id(&options.asset_id)?))?;
        let mut query = Query::default();
        query.opt("cursor", options.cursor.as_deref());
        query.opt("pageSize", options.page_size);
        self.call(self.prepare_for("assets.listTimeline", Method::GET, &path, &query.0)?)
            .await
    }
    async fn events_page(&self, options: &ListEvents) -> Result<EventsPage> {
        let mut query = Query::default();
        query.opt("cursor", options.cursor.as_ref());
        query.opt("pageSize", options.page_size);
        // The API takes the types as one comma-separated value.
        if let Some(types) = options.types.as_deref().filter(|types| !types.is_empty()) {
            let types: Vec<&str> = types.iter().map(EventType::as_str).collect();
            query.push("types", types.join(","));
        }
        query.opt("assetId", options.asset_id.as_ref());
        self.call(self.prepare_for(
            "events.list",
            Method::GET,
            &self.project_path("events")?,
            &query.0,
        )?)
        .await
    }
}

/// Content an upload in parts reads each part from, so a part can be sent again.
enum PartSource {
    Bytes(Bytes),
    File(std::path::PathBuf),
}
impl PartSource {
    /// `length` bytes from `offset`.
    async fn read(&self, offset: u64, length: usize) -> Result<Bytes> {
        match self {
            Self::Bytes(bytes) => Ok(bytes.slice(offset as usize..offset as usize + length)),
            Self::File(path) => read_file_range(path.clone(), offset, length).await,
        }
    }
}

/// Refuses a multipart part under 5 MiB that is not the last, before it is sent.
fn check_part_size(size: Option<u64>, is_final: bool) -> Result<()> {
    if !is_final && size.is_some_and(|size| size < 5 * 1024 * 1024) {
        return Err(invalid_payload(
            "Multipart upload parts must be at least 5MiB except the final part.",
        ));
    }
    Ok(())
}

/// Refuses a first multipart image part over 20 MiB before it is sent. Images in parts can be any
/// size below that, down to a single final part.
fn check_image_size(size: Option<u64>, _is_final: bool) -> Result<()> {
    let Some(size) = size else { return Ok(()) };
    if size > 20 * 1024 * 1024 {
        return Err(upload_too_large(
            20 * 1024 * 1024,
            "Multipart image uploads cannot exceed 20 MiB.",
        ));
    }
    Ok(())
}

/// Refuses content whose known size is over the API's limit for its type, before it is sent. In
/// one request, images can be up to 10 MiB (larger ones are uploaded in parts), audio and video up
/// to 50 MiB and other files up to 5,000 MiB. Sent in parts (`in_parts`), audio and video can be
/// up to 2 GiB; the API holds free uploads, made before billing is set up, to 50 MiB itself.
/// Images in parts are checked by `check_image_size`.
fn check_upload_size(mime: &str, size: Option<u64>, in_parts: bool) -> Result<()> {
    let Some(size) = size else { return Ok(()) };
    let (limit, message) = if mime.starts_with("image/") {
        (
            10 * 1024 * 1024,
            "Images uploaded in one request can be at most 10 MiB; upload larger images in parts",
        )
    } else if mime.starts_with("audio/") || mime.starts_with("video/") {
        (
            if in_parts { 2048 } else { 50 } * 1024 * 1024,
            "Audio and video files can be at most 50 MiB in one request, or 2 GiB in parts",
        )
    } else {
        (5000 * 1024 * 1024, "Files can be at most 5,000 MiB")
    };
    if size > limit {
        return Err(upload_too_large(limit, message));
    }
    Ok(())
}

/// The `upload/too-large` error for content over the plan's `limit_bytes`, as the API reports it.
fn upload_too_large(limit_bytes: u64, message: &str) -> Error {
    let mut details = serde_json::Map::new();
    details.insert("limitBytes".into(), limit_bytes.into());
    details.insert("source".into(), "plan".into());
    Error::new(ErrorCode::UploadTooLarge, message).with_details(details)
}

/// Text is small, so it keeps the API timeout; binary files may be arbitrarily large.
fn upload_deadline(payload: &Payload) -> Deadline {
    match payload {
        Payload::Text(_) => Deadline::Api,
        _ => Deadline::Upload,
    }
}

/// The asset fields an upload of content or a first part carries in its body: a plain-text
/// upload's JSON body, or an upload form's `options` part. The API refuses them in the query.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct UploadFields<'a> {
    name: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<&'a String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    processing_options: Option<&'a ProcessingOptions>,
    #[serde(skip_serializing_if = "Option::is_none")]
    visibility: Option<&'a Visibility>,
    #[serde(skip_serializing_if = "Option::is_none")]
    metadata: Option<&'a Vec<MetadataItem>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tags: Option<&'a Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    author_id: Option<&'a String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    context: Option<&'a ModerationContext>,
    #[serde(skip_serializing_if = "Option::is_none")]
    external_id: Option<&'a String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    external_url: Option<&'a String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    folder_id: Option<&'a String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    upload_preset_id: Option<&'a String>,
}

/// An upload form: `multipart/form-data` with the asset's `fields` as the JSON `options` part,
/// then the file as the `file` part with its `mime_type`. Returns the form's Content-Type and
/// body. Bytes are joined with the envelope, so the request can still be retried; a stream is
/// still sent as it is read, with its length grown by the envelope's when it is known.
fn upload_form(
    fields: &serde_json::Map<String, serde_json::Value>,
    mime_type: &str,
    file: RequestBody,
) -> Result<(String, RequestBody)> {
    let boundary = format!("calmlens-{}", uuid());
    let options = serde_json::to_string(fields)
        .map_err(|cause| invalid_argument(cause.to_string()).with_source(cause))?;
    let mime_type: String = mime_type
        .chars()
        .filter(|c| *c != '\r' && *c != '\n')
        .collect();
    let head = Bytes::from(format!(
        "--{boundary}\r\nContent-Disposition: form-data; name=\"options\"\r\nContent-Type: application/json\r\n\r\n{options}\r\n--{boundary}\r\nContent-Disposition: form-data; name=\"file\"\r\nContent-Type: {mime_type}\r\n\r\n"
    ));
    let tail = Bytes::from(format!("\r\n--{boundary}--\r\n"));
    let envelope = (head.len() + tail.len()) as u64;
    let body = match file {
        RequestBody::Empty => RequestBody::Bytes([head, tail].concat().into()),
        RequestBody::Bytes(bytes) => RequestBody::Bytes([head, bytes, tail].concat().into()),
        RequestBody::Stream(stream, size) => {
            let stream = stream.map(|stream| -> crate::ByteStream {
                Box::pin(
                    futures_util::stream::once(async move { Ok(head) })
                        .chain(stream)
                        .chain(futures_util::stream::once(async move { Ok(tail) })),
                )
            });
            RequestBody::Stream(stream, size.map(|size| size + envelope))
        }
    };
    Ok((format!("multipart/form-data; boundary={boundary}"), body))
}

#[derive(Default)]
struct Query(Vec<(String, String)>);
impl Query {
    fn push(&mut self, key: &str, value: impl fmt::Display) {
        self.0.push((key.into(), value.to_string()));
    }
    fn opt(&mut self, key: &str, value: Option<impl fmt::Display>) {
        if let Some(value) = value {
            self.push(key, value);
        }
    }
}

fn percent_encode(value: &str, keep: &[u8]) -> String {
    let mut out = String::with_capacity(value.len());
    for byte in value.bytes() {
        if byte.is_ascii_alphanumeric() || keep.contains(&byte) {
            out.push(byte as char);
        } else {
            out.push_str(&format!("%{byte:02X}"));
        }
    }
    out
}
/// Encodes an identifier as one path segment. "." and ".." are rejected because URL
/// resolution treats them as relative segments, which would reach another route.
/// The most assets one [`AssetsClient::batch`] request takes.
pub const ASSET_BATCH_MAX_ASSETS: usize = 500;

/// Refuses a batch the API would reject for its size or an empty ID.
pub(crate) fn validate_batch(options: &BatchAssets) -> Result<()> {
    if options.asset_ids.is_empty() || options.asset_ids.len() > ASSET_BATCH_MAX_ASSETS {
        return Err(invalid_argument(format!(
            "asset_ids must list 1 to {ASSET_BATCH_MAX_ASSETS} asset IDs"
        )));
    }
    if options.asset_ids.iter().any(String::is_empty) {
        return Err(invalid_argument(
            "Every asset ID must be a non-empty string",
        ));
    }
    Ok(())
}

pub(crate) fn id(value: &str) -> Result<String> {
    if value.is_empty() {
        return Err(invalid_argument("Identifier is required"));
    }
    if value == "." || value == ".." {
        return Err(invalid_argument("Identifier cannot be \".\" or \"..\""));
    }
    Ok(percent_encode(value, b"-_.!~*'()"))
}
/// Encodes a CDN transform selector like JavaScript's encodeURI, keeping its separators and
/// the literal `[` and `]` the CDN matches.
fn encode_selector(value: &str) -> String {
    percent_encode(value, b"-_.!~*'();/:@&=+$,")
}

/// Asset operations. Get it from [`ServerClient::assets`].
#[derive(Debug, Clone, Copy)]
pub struct AssetsClient<'a>(&'a ServerClient);
impl AssetsClient<'_> {
    /// Uploads an asset and returns without waiting for its decision
    /// (`POST /projects/:projectId/assets?wait=false`), with classification status `queued`.
    /// Retries reuse one `Idempotency-Key`, so a retried upload never creates a second asset.
    pub async fn create(&self, options: SubmitAsset) -> Result<Asset> {
        self.0.submit(options, false).await
    }
    /// Uploads an asset and waits for its moderation decision.
    pub async fn classify(&self, options: SubmitAsset) -> Result<Asset> {
        if let Some(Content {
            payload: Payload::Text(text),
            ..
        }) = &options.content
        {
            if text.trim().is_empty() {
                return Err(invalid_payload(
                    "Text to classify must be a non-empty string",
                ));
            }
        }
        self.0.submit(options, true).await
    }
    /// Sends a later multipart part. Whether the final part waits for the decision was chosen
    /// when the upload started; `options.wait` overrides it.
    pub async fn upload_part(&self, options: UploadPart) -> Result<Asset> {
        self.0.upload_part(options).await
    }
    /// Searches accessible assets in natural language, returning the best `page_size` matches.
    pub async fn search(&self, options: SearchAssets) -> Result<AssetSearchResponse> {
        let mut query = Query::default();
        query.push("query", &options.query);
        query.opt("mode", options.mode.as_ref());
        query.opt("pageSize", options.page_size);
        self.0
            .call(self.0.prepare_for(
                "assets.search",
                Method::GET,
                &self.0.project_path("assets/search")?,
                &query.0,
            )?)
            .await
    }
    /// One page of assets.
    pub async fn list(&self, options: ListAssets) -> Result<AssetPage> {
        self.0.list_page(&options).await
    }
    /// Every asset from `options.cursor` on, fetching pages as the stream is read. It ends
    /// at a page without a next cursor, with `has_more: false` or without items, and fails with
    /// `sdk/invalid-response` (`details.cursor`) instead of yielding a page that hands back a
    /// cursor it already sent.
    pub fn iterate(&self, options: ListAssets) -> BoxStream<'static, Result<Asset>> {
        let client = self.0.clone();
        paginate(
            options,
            |options| options.cursor.clone(),
            move |options| {
                let client = client.clone();
                async move {
                    let page = client.list_page(&options).await?;
                    let next =
                        next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
                            ListAssets {
                                cursor: Some(cursor),
                                ..options
                            }
                        });
                    Ok((page.items, next))
                }
            },
        )
    }
    /// One page of an asset's children.
    pub async fn list_children(&self, options: ListChildren) -> Result<AssetPage> {
        self.0.children_page(&options).await
    }
    /// One page of an audio or video asset's findings timeline, in time order, in the client's
    /// project. `classification.moderation.timeline.segment_count` says how many segments there
    /// are; pass each page's `next_cursor` back unchanged, as cursors are opaque.
    pub async fn list_timeline(&self, options: ListTimeline) -> Result<AssetTimelinePage> {
        self.0.timeline_page(&options).await
    }
    /// Every segment of an audio or video asset's findings timeline from `options.cursor` on, in
    /// time order, ending and failing like [`iterate`](Self::iterate).
    pub fn iterate_timeline(
        &self,
        options: ListTimeline,
    ) -> BoxStream<'static, Result<MediaClassificationSegment>> {
        let client = self.0.clone();
        paginate(
            options,
            |options| options.cursor.clone(),
            move |options| {
                let client = client.clone();
                async move {
                    let page = client.timeline_page(&options).await?;
                    let next =
                        next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
                            ListTimeline {
                                cursor: Some(cursor),
                                ..options
                            }
                        });
                    Ok((page.items, next))
                }
            },
        )
    }
    /// Every child of an asset from `options.cursor` on, ending and failing like
    /// [`iterate`](Self::iterate).
    pub fn iterate_children(&self, options: ListChildren) -> BoxStream<'static, Result<Asset>> {
        let client = self.0.clone();
        paginate(
            options,
            |options| options.cursor.clone(),
            move |options| {
                let client = client.clone();
                async move {
                    let page = client.children_page(&options).await?;
                    let next =
                        next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
                            ListChildren {
                                cursor: Some(cursor),
                                ..options
                            }
                        });
                    Ok((page.items, next))
                }
            },
        )
    }
    /// Retrieves an asset's current state.
    pub async fn retrieve(&self, options: AssetId) -> Result<Asset> {
        let path = format!("/assets/{}", id(&options.asset_id)?);
        let query = Query::default();
        self.0
            .call(
                self.0
                    .prepare_for("assets.retrieve", Method::GET, &path, &query.0)?,
            )
            .await
    }
    /// Retrieves the asset until it is settled ([`Asset::is_decided`]: classification status
    /// `completed`, with its decision in `classification.moderation.decision`, or `failed`) and
    /// returns it. A `queued` or `processing` asset is still waiting, even when a reviewer has
    /// already decided it. It checks again after 0.5 seconds, waiting 1.5 times longer each time
    /// up to 2 seconds, and fails with `sdk/timeout` and details
    /// `{assetId, classificationStatus, moderationDecision}` when `options.timeout` (60 seconds by
    /// default) passes before it is settled. Drop the future to stop waiting. Webhooks report
    /// decisions without polling.
    pub async fn wait_for_decision(&self, options: WaitForDecision) -> Result<Asset> {
        let timeout = options.timeout.unwrap_or(DEFAULT_DECISION_TIMEOUT);
        let options_asset_id = options.asset_id;
        let asset_id = AssetId::new(options_asset_id.clone());
        // A timeout too large to add to the clock never runs out.
        let transport = &self.0.inner.transport;
        let deadline = transport.now().checked_add(timeout);
        let mut delay = DECISION_POLL_FIRST_INTERVAL;
        let mut details = serde_json::Map::new();
        details.insert("assetId".into(), options_asset_id.into());
        details.insert("classificationStatus".into(), serde_json::Value::Null);
        details.insert("moderationDecision".into(), serde_json::Value::Null);
        let remaining =
            || deadline.map(|deadline| deadline.saturating_duration_since(transport.now()));
        loop {
            let request = self.retrieve(asset_id.clone());
            let result = match remaining() {
                Some(Duration::ZERO) if !timeout.is_zero() => break,
                Some(left) if !timeout.is_zero() => match tokio::time::timeout(left, request).await
                {
                    Ok(result) => result,
                    Err(_) => break,
                },
                _ => request.await,
            };
            let remaining = remaining();
            if !timeout.is_zero() && remaining == Some(Duration::ZERO) {
                break;
            }
            let asset = result?;
            if asset.is_decided() {
                return Ok(asset);
            }
            details.insert(
                "classificationStatus".into(),
                asset.classification.status.as_str().into(),
            );
            details.insert(
                "moderationDecision".into(),
                serde_json::json!(asset.classification.moderation.decision),
            );
            if remaining == Some(Duration::ZERO) {
                break;
            }
            transport
                .sleep(remaining.map_or(delay, |remaining| remaining.min(delay)))
                .await;
            delay = delay
                .mul_f64(DECISION_POLL_INTERVAL_FACTOR)
                .min(DECISION_POLL_MAX_INTERVAL);
        }
        Err(Error::new(
            ErrorCode::Timeout,
            format!("No moderation decision within {timeout:?}"),
        )
        .with_details(details))
    }
    /// Updates an asset; [`Patch::Missing`] fields are left unchanged.
    pub async fn update(&self, options: UpdateAsset) -> Result<Asset> {
        let path = format!("/assets/{}", id(&options.asset_id)?);
        let request = self
            .0
            .prepare_for("assets.update", Method::PATCH, &path, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Classifies an asset whose processing failed (status `error`) again.
    pub async fn retry(&self, options: AssetId) -> Result<Asset> {
        let path = format!("/assets/{}/retry", id(&options.asset_id)?);
        self.0
            .call(
                self.0
                    .prepare_for("assets.retry", Method::POST, &path, &[])?,
            )
            .await
    }
    /// Records a reviewer's decision, replacing the policy's: the asset's moderation status
    /// becomes `options.decision`, the note joins its review history and the matching
    /// `asset.<status>` event is sent, with the API key as its `actor`. An asset still pending
    /// moderation can only be blocked or purged. Purging needs `confirm_purge` and the
    /// `assets:delete` permission, and permanently deletes the stored content.
    pub async fn decide(&self, options: DecideAsset) -> Result<Asset> {
        let path = format!("/assets/{}/decision", id(&options.asset_id)?);
        let request = self
            .0
            .prepare_for("assets.decide", Method::POST, &path, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Removes the stored content (`DELETE /assets/:assetId/content`), including the content
    /// derived from it in child assets, keeping the asset record, metadata and classification
    /// results. The returned asset's `content.status` is `Removed` with `removal_reason`
    /// `Requested`; the CDN no longer serves it.
    pub async fn remove_content(&self, options: AssetId) -> Result<Asset> {
        let path = format!("/assets/{}/content", id(&options.asset_id)?);
        self.0
            .call(
                self.0
                    .prepare_for("assets.removeContent", Method::DELETE, &path, &[])?,
            )
            .await
    }
    /// Deletes the asset record and its stored content (`DELETE /assets/:assetId`). An asset
    /// extracted from another (one with a `parent_id`) fails with `asset/child-not-deletable`:
    /// delete its parent instead.
    pub async fn delete(&self, options: AssetId) -> Result<()> {
        let path = format!("/assets/{}", id(&options.asset_id)?);
        self.0
            .call_empty(
                self.0
                    .prepare_for("assets.delete", Method::DELETE, &path, &[])?,
            )
            .await
    }
    /// Deletes up to 500 assets ([`AssetBatchOperation::Delete`]) or removes their stored content
    /// ([`AssetBatchOperation::RemoveContent`]) in one request
    /// (`POST /projects/:projectId/assets/batch`). Every asset must exist in the project and the
    /// key needs `assets:delete` for its folder, and a deletion can't name an asset extracted from
    /// another (`asset/child-not-deletable`), or nothing is queued. Returns the operation's
    /// `batch_id` once queued; the work runs in the background and records `asset.deleted` or
    /// `asset.content-removed` for each asset, with a `batch-id` fact naming `batch_id`. Assets
    /// under a safety hold are skipped. Not retried: it carries no `Idempotency-Key`.
    pub async fn batch(&self, options: BatchAssets) -> Result<BatchAssetsResponse> {
        validate_batch(&options)?;
        let path = self.0.project_path("assets/batch")?;
        let request = self
            .0
            .prepare_for("assets.batch", Method::POST, &path, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Moves an asset to a folder, or to the project root.
    pub async fn move_asset(&self, options: MoveAsset) -> Result<Asset> {
        let path = format!("/assets/{}/move", id(&options.asset_id)?);
        let request = self
            .0
            .prepare_for("assets.move", Method::POST, &path, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
}

/// The cursor of the page after a page of `items`, or `None` when the iteration ends there.
fn next_cursor<T>(items: &[T], has_more: bool, next_cursor: &Option<String>) -> Option<String> {
    let more = has_more && !items.is_empty();
    next_cursor.clone().filter(|_| more)
}

/// The error for a page that hands back a cursor the iteration already sent, which would
/// otherwise repeat pages forever.
fn repeated_cursor(cursor: &str) -> Error {
    let mut details = serde_json::Map::new();
    details.insert("cursor".into(), cursor.into());
    Error::new(
        ErrorCode::InvalidResponse,
        "The API returned a cursor it had already returned, with more pages to follow",
    )
    .with_details(details)
}

/// Yields the pages `fetch` returns, each with the next page's options; `cursor` reads the
/// cursor options send. A page whose next cursor was already sent fails, and is not yielded.
fn pages<O, P, C, F, Fut>(first: O, cursor: C, fetch: F) -> BoxStream<'static, Result<P>>
where
    O: Send + 'static,
    P: Send + 'static,
    C: Fn(&O) -> Option<String> + Send + Sync + 'static,
    F: Fn(O) -> Fut + Send + 'static,
    Fut: std::future::Future<Output = Result<(P, Option<O>)>> + Send + 'static,
{
    let mut sent = std::collections::HashSet::new();
    if let Some(first) = cursor(&first) {
        sent.insert(first);
    }
    let cursor = Arc::new(cursor);
    futures_util::stream::try_unfold((Some(first), sent), move |(next, mut sent)| {
        let page = next.map(&fetch);
        let cursor = cursor.clone();
        let checked = page.map(|page| async move {
            let (page, next) = page.await?;
            if let Some(next_cursor) = next.as_ref().and_then(|next| cursor(next)) {
                if !sent.insert(next_cursor.clone()) {
                    return Err(repeated_cursor(&next_cursor));
                }
            }
            Ok((page, (next, sent)))
        });
        async move {
            match checked {
                None => Ok(None),
                Some(checked) => checked.await.map(Some),
            }
        }
    })
    .boxed()
}

/// Yields the items of successive pages, as [`pages`] fetches them.
fn paginate<O, C, F, Fut, T>(first: O, cursor: C, fetch: F) -> BoxStream<'static, Result<T>>
where
    O: Send + 'static,
    T: Send + 'static,
    C: Fn(&O) -> Option<String> + Send + Sync + 'static,
    F: Fn(O) -> Fut + Send + 'static,
    Fut: std::future::Future<Output = Result<(Vec<T>, Option<O>)>> + Send + 'static,
{
    pages(first, cursor, fetch)
        .map_ok(|items| futures_util::stream::iter(items.into_iter().map(Ok)))
        .try_flatten()
        .boxed()
}

/// Folder operations. Get it from [`ServerClient::folders`].
#[derive(Debug, Clone, Copy)]
pub struct FoldersClient<'a>(&'a ServerClient);
impl FoldersClient<'_> {
    /// One page of child folders, sorted by name unless `sort` says otherwise. Pass the page's
    /// `next_cursor` as `cursor` for the next page.
    pub async fn list(&self, options: ListFolders) -> Result<FolderPage> {
        let mut query = Query::default();
        query.opt("parentId", options.parent_id.as_ref());
        query.opt("pageSize", options.page_size);
        query.opt("sort", options.sort.as_ref());
        query.opt("cursor", options.cursor.as_ref());
        query.opt("search", options.search.as_ref());
        let request = self.0.prepare_for(
            "folders.list",
            Method::GET,
            &self.0.project_path("folders")?,
            &query.0,
        )?;
        self.0.call(request).await
    }
    /// Every child folder of `options.parent_id` (or the project root) from `options.cursor` on,
    /// ending and failing like [`AssetsClient::iterate`].
    pub fn iterate(&self, options: ListFolders) -> BoxStream<'static, Result<Folder>> {
        let client = self.0.clone();
        paginate(
            options,
            |options| options.cursor.clone(),
            move |options| {
                let client = client.clone();
                async move {
                    let page = client.folders().list(options.clone()).await?;
                    let next =
                        next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
                            ListFolders {
                                cursor: Some(cursor),
                                ..options
                            }
                        });
                    Ok((page.items, next))
                }
            },
        )
    }
    /// Creates a folder.
    pub async fn create(&self, options: CreateFolder) -> Result<Folder> {
        let request = self
            .0
            .prepare_for(
                "folders.create",
                Method::POST,
                &self.0.project_path("folders")?,
                &[],
            )?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Retrieves a folder.
    pub async fn retrieve(&self, options: FolderId) -> Result<Folder> {
        let path = format!("/folders/{}", id(&options.folder_id)?);
        self.0
            .call(
                self.0
                    .prepare_for("folders.retrieve", Method::GET, &path, &[])?,
            )
            .await
    }
    /// Renames a folder.
    pub async fn update(&self, options: UpdateFolder) -> Result<Folder> {
        let path = format!("/folders/{}", id(&options.folder_id)?);
        let request = self
            .0
            .prepare_for("folders.update", Method::PATCH, &path, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Moves a folder under another folder, or to the project root.
    pub async fn move_folder(&self, options: MoveFolder) -> Result<Folder> {
        let path = format!("/folders/{}/move", id(&options.folder_id)?);
        let request = self
            .0
            .prepare_for("folders.move", Method::POST, &path, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Deletes an empty folder.
    pub async fn delete(&self, options: FolderId) -> Result<()> {
        let path = format!("/folders/{}", id(&options.folder_id)?);
        self.0
            .call_empty(
                self.0
                    .prepare_for("folders.delete", Method::DELETE, &path, &[])?,
            )
            .await
    }
}

/// Hash list operations. Get it from [`ServerClient::hash_lists`].
///
/// Hash lists hold PDQ hashes of images the project never wants again. Image uploads are
/// compared with every list: `flag` lists record matches, `block` lists also block close ones.
#[derive(Debug, Clone, Copy)]
pub struct HashListsClient<'a>(&'a ServerClient);
impl HashListsClient<'_> {
    /// One page of the project's hash lists, newest first unless `sort` says otherwise. Pass
    /// the page's `next_cursor` as `cursor` for the next page.
    pub async fn list(&self, options: ListHashLists) -> Result<HashListPage> {
        let mut query = Query::default();
        query.opt("cursor", options.cursor.as_ref());
        query.opt("pageSize", options.page_size);
        query.opt("sort", options.sort.as_ref());
        let request = self.0.prepare_for(
            "hashLists.list",
            Method::GET,
            &self.0.project_path("hash-lists")?,
            &query.0,
        )?;
        self.0.call(request).await
    }
    /// Every hash list from `options.cursor` on, ending and failing like
    /// [`AssetsClient::iterate`].
    pub fn iterate(&self, options: ListHashLists) -> BoxStream<'static, Result<HashList>> {
        let client = self.0.clone();
        paginate(
            options,
            |options| options.cursor.clone(),
            move |options| {
                let client = client.clone();
                async move {
                    let page = client.hash_lists().list(options.clone()).await?;
                    let next =
                        next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
                            ListHashLists {
                                cursor: Some(cursor),
                                ..options
                            }
                        });
                    Ok((page.items, next))
                }
            },
        )
    }
    /// Retrieves a hash list.
    pub async fn retrieve(&self, options: HashListId) -> Result<HashList> {
        let path = format!("/hash-lists/{}", id(&options.hash_list_id)?);
        self.0
            .call(
                self.0
                    .prepare_for("hashLists.retrieve", Method::GET, &path, &[])?,
            )
            .await
    }
    /// Creates a hash list.
    pub async fn create(&self, options: CreateHashList) -> Result<HashList> {
        let request = self
            .0
            .prepare_for(
                "hashLists.create",
                Method::POST,
                &self.0.project_path("hash-lists")?,
                &[],
            )?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Renames a hash list or changes what its matches do; the new action applies to later
    /// uploads.
    pub async fn update(&self, options: UpdateHashList) -> Result<HashList> {
        let path = format!("/hash-lists/{}", id(&options.hash_list_id)?);
        let request = self
            .0
            .prepare_for("hashLists.update", Method::PATCH, &path, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Deletes a hash list and every entry in it.
    pub async fn delete(&self, options: HashListId) -> Result<()> {
        let path = format!("/hash-lists/{}", id(&options.hash_list_id)?);
        self.0
            .call_empty(
                self.0
                    .prepare_for("hashLists.delete", Method::DELETE, &path, &[])?,
            )
            .await
    }
    /// One page of a hash list's entries, newest first unless `sort` says otherwise.
    pub async fn list_entries(&self, options: ListHashListEntries) -> Result<HashListEntryPage> {
        let path = format!("/hash-lists/{}/entries", id(&options.hash_list_id)?);
        let mut query = Query::default();
        query.opt("cursor", options.cursor.as_ref());
        query.opt("pageSize", options.page_size);
        query.opt("sort", options.sort.as_ref());
        self.0
            .call(
                self.0
                    .prepare_for("hashLists.listEntries", Method::GET, &path, &query.0)?,
            )
            .await
    }
    /// Every entry of a hash list from `options.cursor` on, ending and failing like
    /// [`AssetsClient::iterate`].
    pub fn iterate_entries(
        &self,
        options: ListHashListEntries,
    ) -> BoxStream<'static, Result<HashListEntry>> {
        let client = self.0.clone();
        paginate(
            options,
            |options| options.cursor.clone(),
            move |options| {
                let client = client.clone();
                async move {
                    let page = client.hash_lists().list_entries(options.clone()).await?;
                    let next =
                        next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
                            ListHashListEntries {
                                cursor: Some(cursor),
                                ..options
                            }
                        });
                    Ok((page.items, next))
                }
            },
        )
    }
    /// Adds a hash, or an image asset's perceptual hash, to a hash list. A hash the list
    /// already holds returns its existing entry.
    pub async fn add_entry(&self, options: AddHashListEntry) -> Result<HashListEntry> {
        let path = format!("/hash-lists/{}/entries", id(&options.hash_list_id)?);
        let request = self
            .0
            .prepare_for("hashLists.addEntry", Method::POST, &path, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Removes a hash from its hash list.
    pub async fn remove_entry(&self, options: HashListEntryId) -> Result<()> {
        let path = format!("/hash-list-entries/{}", id(&options.entry_id)?);
        self.0
            .call_empty(
                self.0
                    .prepare_for("hashLists.removeEntry", Method::DELETE, &path, &[])?,
            )
            .await
    }
}

/// Moderation policy operations. Get it from [`ServerClient::policies`].
///
/// Policies belong to the API key's organisation and its projects share them. Every change sends
/// the policy's `revision`, so a policy changed since is refused. Through a project's key you can
/// change only policies no other project uses.
#[derive(Debug, Clone, Copy)]
pub struct PoliciesClient<'a>(&'a ServerClient);
impl PoliciesClient<'_> {
    fn path(policy_id: &str, suffix: &str) -> Result<String> {
        Ok(format!("/policies/{}{suffix}", id(policy_id)?))
    }
    /// One page of the organisation's policies, oldest first unless `sort` says otherwise. Pass
    /// the page's `next_cursor` as `cursor` for the next page.
    pub async fn list(&self, options: ListPolicies) -> Result<PolicyPage> {
        let mut query = Query::default();
        query.opt("cursor", options.cursor.as_ref());
        query.opt("pageSize", options.page_size);
        query.opt("sort", options.sort.as_ref());
        self.0
            .call(
                self.0
                    .prepare_for("policies.list", Method::GET, "/policies", &query.0)?,
            )
            .await
    }
    /// Every policy of the organisation from `options.cursor` on, ending and failing like
    /// [`AssetsClient::iterate`].
    pub fn iterate(&self, options: ListPolicies) -> BoxStream<'static, Result<Policy>> {
        let client = self.0.clone();
        paginate(
            options,
            |options| options.cursor.clone(),
            move |options| {
                let client = client.clone();
                async move {
                    let page = client.policies().list(options.clone()).await?;
                    let next =
                        next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
                            ListPolicies {
                                cursor: Some(cursor),
                                ..options
                            }
                        });
                    Ok((page.items, next))
                }
            },
        )
    }
    /// Retrieves a policy.
    pub async fn retrieve(&self, options: PolicyId) -> Result<Policy> {
        let path = Self::path(&options.policy_id, "")?;
        self.0
            .call(
                self.0
                    .prepare_for("policies.retrieve", Method::GET, &path, &[])?,
            )
            .await
    }
    /// Creates a policy from settings, or a copy of a built-in preset. It moderates nothing until
    /// you assign it to a project or name it on an upload preset.
    pub async fn create(&self, options: CreatePolicy) -> Result<Policy> {
        let request = self
            .0
            .prepare_for("policies.create", Method::POST, "/policies", &[])?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Changes a policy's name, description or settings; later moderation uses them. Saving a
    /// `live` policy pins it as a copy under the same ID.
    pub async fn update(&self, options: UpdatePolicy) -> Result<Policy> {
        let path = Self::path(&options.policy_id, "")?;
        let request = self
            .0
            .prepare_for("policies.update", Method::PATCH, &path, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Restores the settings of the preset release a `pinned` or `copy` policy is pinned to,
    /// discarding its edits.
    pub async fn reset(&self, options: ResetPolicy) -> Result<Policy> {
        let path = Self::path(&options.policy_id, "/reset")?;
        let request = self
            .0
            .prepare_for("policies.reset", Method::POST, &path, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Moves a `pinned` or `copy` policy whose settings are unchanged from its preset release to
    /// the latest release of the preset.
    pub async fn upgrade(&self, options: UpgradePolicy) -> Result<Policy> {
        let path = Self::path(&options.policy_id, "/upgrade")?;
        let request = self
            .0
            .prepare_for("policies.upgrade", Method::POST, &path, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Switches automatic updates on (`live`) or off (`pinned`) for the organisation's own
    /// preset policy.
    pub async fn set_automatic_updates(
        &self,
        options: SetPolicyAutomaticUpdates,
    ) -> Result<Policy> {
        let path = Self::path(&options.policy_id, "/automatic-updates")?;
        let request = self
            .0
            .prepare_for("policies.setAutomaticUpdates", Method::PUT, &path, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Deletes a policy that no project or upload preset uses.
    pub async fn delete(&self, options: PolicyId) -> Result<()> {
        let path = Self::path(&options.policy_id, "")?;
        self.0
            .call_empty(
                self.0
                    .prepare_for("policies.delete", Method::DELETE, &path, &[])?,
            )
            .await
    }
    /// The policy the project moderates with. Uploads through an upload preset that names its
    /// own policy use that one instead.
    pub async fn retrieve_assigned(&self) -> Result<Policy> {
        let path = self.0.project_path("policy")?;
        self.0
            .call(
                self.0
                    .prepare_for("policies.retrieveAssigned", Method::GET, &path, &[])?,
            )
            .await
    }
    /// Chooses the policy the project moderates with.
    pub async fn assign(&self, options: AssignPolicy) -> Result<Policy> {
        let path = self.0.project_path("policy")?;
        let request = self
            .0
            .prepare_for("policies.assign", Method::PUT, &path, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
}

/// The project's upload presets: the rules for uploads from browsers and apps. Get it from
/// [`ServerClient::upload_presets`]. [`UploadPresetsClient::ensure`] creates or replaces presets
/// by key, for deploys that declare them in code; send each preset's `revision` to refuse a change
/// made since you read it.
#[derive(Debug, Clone, Copy)]
pub struct UploadPresetsClient<'a>(&'a ServerClient);
impl UploadPresetsClient<'_> {
    /// One page of the project's upload presets, oldest first unless `sort` says otherwise. Pass
    /// the page's `next_cursor` as `cursor` for the next page.
    pub async fn list(&self, options: ListUploadPresets) -> Result<UploadPresetPage> {
        let mut query = Query::default();
        query.opt("cursor", options.cursor.as_ref());
        query.opt("pageSize", options.page_size);
        query.opt("sort", options.sort.as_ref());
        let path = self.0.project_path("upload-presets")?;
        self.0
            .call(
                self.0
                    .prepare_for("uploadPresets.list", Method::GET, &path, &query.0)?,
            )
            .await
    }
    /// Every upload preset of the project from `options.cursor` on, ending and failing like
    /// [`AssetsClient::iterate`].
    pub fn iterate(&self, options: ListUploadPresets) -> BoxStream<'static, Result<UploadPreset>> {
        let client = self.0.clone();
        paginate(
            options,
            |options| options.cursor.clone(),
            move |options| {
                let client = client.clone();
                async move {
                    let page = client.upload_presets().list(options.clone()).await?;
                    let next =
                        next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
                            ListUploadPresets {
                                cursor: Some(cursor),
                                ..options
                            }
                        });
                    Ok((page.items, next))
                }
            },
        )
    }
    /// Creates each preset, or replaces it with the definition sent, by key. Fields left out take
    /// their defaults. An unchanged preset is returned as it is, with the same revision, so
    /// deploys can send their presets every time. Every preset is checked before any is saved.
    pub async fn ensure(
        &self,
        options: EnsureUploadPresets,
    ) -> Result<EnsureUploadPresetsResponse> {
        let path = self.0.project_path("upload-presets")?;
        let request = self
            .0
            .prepare_for("uploadPresets.ensure", Method::PUT, &path, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Deletes an upload preset. Browsers can no longer upload through it; assets already
    /// uploaded stay.
    pub async fn delete(&self, options: UploadPresetId) -> Result<()> {
        let path = format!("/upload-presets/{}", id(&options.upload_preset_id)?);
        self.0
            .call_empty(
                self.0
                    .prepare_for("uploadPresets.delete", Method::DELETE, &path, &[])?,
            )
            .await
    }
}

/// The project's settings. Get it from [`ServerClient::project_settings`].
#[derive(Debug, Clone, Copy)]
pub struct ProjectSettingsClient<'a>(&'a ServerClient);
impl ProjectSettingsClient<'_> {
    /// The project's settings, with every default filled in, and the revision to send back with
    /// a change.
    pub async fn get(&self) -> Result<ProjectSettingsResource> {
        let path = self.0.project_path("settings")?;
        self.0
            .call(
                self.0
                    .prepare_for("projectSettings.get", Method::GET, &path, &[])?,
            )
            .await
    }
    /// Replaces the project's settings: settings left out return to their defaults. Unchanged
    /// settings keep their revision. Send the `revision` you read to refuse a change made since.
    pub async fn update(&self, options: UpdateProjectSettings) -> Result<ProjectSettingsResource> {
        let path = self.0.project_path("settings")?;
        let request = self
            .0
            .prepare_for("projectSettings.update", Method::PUT, &path, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
}

/// The project's metadata fields, which share the project settings' `revision`. Get it from
/// [`ServerClient::metadata_fields`].
#[derive(Debug, Clone, Copy)]
pub struct MetadataFieldsClient<'a>(&'a ServerClient);
impl MetadataFieldsClient<'_> {
    /// The project's metadata fields in display order, and the revision to send back with a
    /// change.
    pub async fn list(&self) -> Result<MetadataFieldsResource> {
        let path = self.0.project_path("metadata-fields")?;
        self.0
            .call(
                self.0
                    .prepare_for("metadataFields.list", Method::GET, &path, &[])?,
            )
            .await
    }
    /// Creates each field, or replaces it with the definition sent, by ID. Other fields are kept,
    /// and new ones are added at the end. Unchanged fields keep their revision.
    pub async fn ensure(&self, options: EnsureMetadataFields) -> Result<MetadataFieldsResource> {
        let path = self.0.project_path("metadata-fields")?;
        let request = self
            .0
            .prepare_for("metadataFields.ensure", Method::PUT, &path, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Deletes a metadata field definition. Assets keep the metadata values they hold.
    pub async fn delete(&self, options: DeleteMetadataField) -> Result<()> {
        let path = self
            .0
            .project_path(&format!("metadata-fields/{}", id(&options.field_id)?))?;
        let mut query = Query::default();
        query.opt("revision", options.revision);
        self.0
            .call_empty(self.0.prepare_for(
                "metadataFields.delete",
                Method::DELETE,
                &path,
                &query.0,
            )?)
            .await
    }
}

/// The project's lenses: named image transforms the CDN applies at `/@<identifier>`. Get it from
/// [`ServerClient::lenses`]. The CDN serves files made with each lens's current definition;
/// [`ServerClient::ensure_lenses`] creates or changes lenses by identifier, for applications that
/// declare theirs in code.
#[derive(Debug, Clone, Copy)]
pub struct LensesClient<'a>(&'a ServerClient);
impl LensesClient<'_> {
    fn path(lens_id: &str) -> Result<String> {
        Ok(format!("/lenses/{}", id(lens_id)?))
    }
    /// Drops the lenses `ensure_lens` cached that `changed` matches: a lens changed here no
    /// longer has the definition cached for it.
    fn forget(&self, changed: impl Fn(&Lens) -> bool) {
        let mut cache = self
            .0
            .inner
            .lenses
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        cache.retain(|_, cached| !changed(cached));
    }
    /// One page of the project's lenses, newest first unless `sort` says otherwise. The
    /// built-in lenses are always available and aren't listed.
    pub async fn list(&self, options: ListLenses) -> Result<LensPage> {
        let mut query = Query::default();
        query.opt("cursor", options.cursor.as_ref());
        query.opt("pageSize", options.page_size);
        query.opt("sort", options.sort.as_ref());
        let request = self.0.prepare_for(
            "lenses.list",
            Method::GET,
            &self.0.project_path("lenses")?,
            &query.0,
        )?;
        self.0.call(request).await
    }
    /// Every lens of the project from `options.cursor` on, ending and failing like
    /// [`AssetsClient::iterate`].
    pub fn iterate(&self, options: ListLenses) -> BoxStream<'static, Result<Lens>> {
        let client = self.0.clone();
        paginate(
            options,
            |options| options.cursor.clone(),
            move |options| {
                let client = client.clone();
                async move {
                    let page = client.lenses().list(options.clone()).await?;
                    let next =
                        next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
                            ListLenses {
                                cursor: Some(cursor),
                                ..options
                            }
                        });
                    Ok((page.items, next))
                }
            },
        )
    }
    /// Creates a lens; its identifier must be new to the project (`lens/identifier-taken`).
    pub async fn create(&self, options: LensDefinition) -> Result<Lens> {
        id(&options.identifier)?;
        let request = self
            .0
            .prepare_for(
                "lenses.create",
                Method::POST,
                &self.0.project_path("lenses")?,
                &[],
            )?
            .json(&options)?;
        let lens: Lens = self.0.call(request).await?;
        self.forget(|cached| cached.identifier == lens.identifier);
        Ok(lens)
    }
    /// Retrieves one of the project's lenses by ID.
    pub async fn retrieve(&self, options: LensId) -> Result<Lens> {
        let path = Self::path(&options.lens_id)?;
        self.0
            .call(
                self.0
                    .prepare_for("lenses.retrieve", Method::GET, &path, &[])?,
            )
            .await
    }
    /// Changes a lens's name, description, type, transform or whether the CDN serves it. The CDN
    /// serves the new transform from then on.
    pub async fn update(&self, options: UpdateLens) -> Result<Lens> {
        let path = Self::path(&options.lens_id)?;
        let request = self
            .0
            .prepare_for("lenses.update", Method::PATCH, &path, &[])?
            .json(&options)?;
        let lens: Lens = self.0.call(request).await?;
        self.forget(|cached| !cached.id.is_empty() && cached.id == lens.id);
        Ok(lens)
    }
    /// Deletes a lens. URLs that select it stop being served; files the CDN already delivered may
    /// stay in caches until they expire.
    pub async fn delete(&self, options: LensId) -> Result<()> {
        let path = Self::path(&options.lens_id)?;
        self.0
            .call_empty(
                self.0
                    .prepare_for("lenses.delete", Method::DELETE, &path, &[])?,
            )
            .await?;
        self.forget(|cached| cached.id == options.lens_id);
        Ok(())
    }
}

/// The events feed. Get it from [`ServerClient::events`].
#[derive(Debug, Clone, Copy)]
pub struct EventsClient<'a>(&'a ServerClient);
impl EventsClient<'_> {
    /// One page of events after `options.cursor`, oldest first. Without `cursor` the page is
    /// empty and its `next_cursor` marks now. `types` and `asset_id` narrow the feed to some event
    /// types or one asset's events; a cursor belongs to the filters it was issued with, so pass
    /// the same ones with each `cursor`.
    pub async fn list(&self, options: ListEvents) -> Result<EventsPage> {
        self.0.events_page(&options).await
    }
    /// Pages of events from `options.cursor`, following each page's `next_cursor` until a page
    /// has `has_more: false`. Store the last page's `next_cursor` and continue from it later. A page
    /// with more to follow that hands back a cursor already sent fails with
    /// `sdk/invalid-response` (`details.cursor`) and is not yielded.
    /// Yields every event from `options.cursor` on, fetching each page as its first event is
    /// read, until a page has `has_more: false`; see [`pages`](Self::pages) to read the pages and
    /// their cursors.
    pub fn iterate(&self, options: ListEvents) -> BoxStream<'static, Result<Event>> {
        self.pages(options)
            .map_ok(|page| futures_util::stream::iter(page.items.into_iter().map(Ok)))
            .try_flatten()
            .boxed()
    }
    /// Yields each page of the events feed from `options.cursor` on.
    pub fn pages(&self, options: ListEvents) -> BoxStream<'static, Result<EventsPage>> {
        let client = self.0.clone();
        pages(
            options,
            |options| options.cursor.clone(),
            move |options| {
                let client = client.clone();
                async move {
                    let page = client.events_page(&options).await?;
                    let next = page.has_more.then(|| ListEvents {
                        cursor: Some(page.next_cursor.clone()),
                        ..options
                    });
                    Ok((page, next))
                }
            },
        )
    }
}

/// Signs upload tokens, which let a browser upload through an upload preset. Get it from
/// [`ServerClient::upload_tokens`]. Signing happens locally with the API key; no request is made.
#[derive(Debug, Clone, Copy)]
pub struct UploadTokensClient<'a>(&'a ServerClient);
impl UploadTokensClient<'_> {
    /// Signs a single-use token. Hand it to the browser as its bearer token and give each
    /// upload its own.
    pub fn sign(&self, options: SignUploadToken) -> Result<SignedUploadToken> {
        let api_key = String::from_utf8_lossy(self.0.inner.config.api_key.as_bytes()).into_owned();
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_or(0, |elapsed| elapsed.as_millis() as u64);
        sign_upload_token(&api_key, options, now, &uuid())
    }
}

/// Signs an upload token for `api_key` at `now` (epoch milliseconds) with `nonce`.
pub(crate) fn sign_upload_token(
    api_key: &str,
    options: SignUploadToken,
    now: u64,
    nonce: &str,
) -> Result<SignedUploadToken> {
    use base64::Engine;
    use hmac::{Hmac, Mac};
    use sha2::{Digest, Sha256};

    id(&options.upload_preset_id).map_err(|_| invalid_argument("Upload preset ID is required"))?;
    let ttl = options.expires_in.unwrap_or(DEFAULT_UPLOAD_TOKEN_SECONDS);
    if !(1..=3600).contains(&ttl) {
        return Err(invalid_argument(
            "expires_in must be a whole number of seconds from 1 to 3600",
        ));
    }
    if options.external_id.as_deref() == Some("") {
        return Err(invalid_argument("externalId must be a non-empty string"));
    }
    let prefix_length = if api_key.starts_with("clsk_") { 13 } else { 8 };
    let prefix: String = api_key.chars().take(prefix_length).collect();
    let expires_at = now + u64::from(ttl) * 1000;
    // Field order and escaping as JavaScript's JSON.stringify writes them, which serde_json
    // matches: no whitespace, raw UTF-8, and only quotes, backslashes and control characters
    // escaped.
    #[derive(Serialize)]
    struct Claims<'a> {
        v: u8,
        u: &'a str,
        k: &'a str,
        e: u64,
        n: &'a str,
        #[serde(skip_serializing_if = "Option::is_none")]
        x: Option<&'a str>,
    }
    let claims = Claims {
        v: 1,
        u: &options.upload_preset_id,
        k: &prefix,
        e: expires_at,
        n: nonce,
        x: options.external_id.as_deref(),
    };
    let body = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .encode(serde_json::to_vec(&claims).map_err(|e| invalid_argument(e.to_string()))?);
    let secret: String = Sha256::digest(api_key.as_bytes())
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect();
    let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes())
        .map_err(|e| invalid_argument(e.to_string()))?;
    mac.update(format!("calmlens-upload-token:v1:{body}").as_bytes());
    let signature: String = mac
        .finalize()
        .into_bytes()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect();
    Ok(SignedUploadToken {
        token: format!("clut_{body}.{signature}"),
        expires_at,
    })
}

/// Text moderation. Get it from [`ServerClient::text`].
#[derive(Debug, Clone, Copy)]
pub struct TextClient<'a>(&'a ServerClient);
impl TextClient<'_> {
    /// Moderates text as a `text/plain` asset named `text` unless `name` is set.
    pub async fn classify(&self, options: ClassifyText) -> Result<Asset> {
        if options.text.trim().is_empty() {
            return Err(invalid_argument(
                "Text to classify must be a non-empty string",
            ));
        }
        self.0
            .assets()
            .classify(SubmitAsset {
                name: options.name.unwrap_or_else(|| "text".into()),
                content: Some(Content::text(options.text)),
                description: options.description,
                visibility: options.visibility,
                processing_options: options.processing_options,
                metadata: options.metadata,
                tags: options.tags,
                author_id: options.author_id,
                context: options.context,
                external_id: options.external_id,
                external_url: options.external_url,
                folder_id: options.folder_id,
                upload_preset_id: options.upload_preset_id,
                idempotency_key: options.idempotency_key,
                ..SubmitAsset::blank()
            })
            .await
    }
}

/// The resources beneath an asset URL, in the order messages list them, with the path each is
/// served at. The adaptive stream is its HLS master playlist; its media playlists and segments
/// are the other files beneath `hls/`.
const CDN_RESOURCE_PATHS: [(&str, &str); 7] = [
    ("original", "original"),
    ("rendered", "rendered"),
    ("preview", "preview"),
    ("placeholder", "placeholder"),
    ("hls", "hls/index.m3u8"),
    ("embed", "embed"),
    ("info", "info"),
];

/// The asset segment that names an asset by its external ID starts with this.
const EXTERNAL_ID_SEGMENT_PREFIX: &str = "ext:";

/// The ISO 3166-1 alpha-2 countries a viewer's region can be. EU is not a viewer country.
const VIEWER_COUNTRIES: &str = "AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW";

/// The asset segment of an asset URL: the path-encoded asset ID, or `ext:` and the URL-encoded
/// external ID. Exactly one of them must be given.
fn asset_segment(asset_id: Option<&str>, external_id: Option<&str>) -> Result<String> {
    match (asset_id, external_id) {
        (Some(asset_id), None) => id(asset_id),
        (None, Some("")) => Err(invalid_argument("External ID is required")),
        (None, Some(external_id)) => Ok(format!(
            "{EXTERNAL_ID_SEGMENT_PREFIX}{}",
            percent_encode(external_id, b"-_.!~*'()")
        )),
        _ => Err(invalid_argument("Pass either asset_id or external_id")),
    }
}

/// The `?viewerClaims=` query of a URL with these claims, or an empty string for the defaults:
/// no region and an unconfirmed age are left out, so default URLs stay cacheable.
fn viewer_claims_query(claims: Option<&ViewerClaims>) -> Result<String> {
    let Some(claims) = claims else {
        return Ok(String::new());
    };
    let mut sent = Vec::new();
    if let Some(region) = &claims.region {
        if !VIEWER_COUNTRIES.split(' ').any(|country| country == region) {
            return Err(invalid_argument(
                "viewer_claims.region must be an ISO 3166-1 alpha-2 country code, such as DE",
            ));
        }
        // A viewer country needs no JSON escaping.
        sent.push(format!("\"region\":\"{region}\""));
    }
    if claims.age_confirmed == Some(true) {
        sent.push("\"ageConfirmed\":true".to_owned());
    }
    if sent.is_empty() {
        return Ok(String::new());
    }
    let json = format!("{{{}}}", sent.join(","));
    Ok(format!("?viewerClaims={}", percent_encode(&json, b"-._~")))
}

/// What follows an asset URL: a resource, its selector and the viewer claims.
struct AssetLocation<'a> {
    resource: Option<&'a CdnResource>,
    lens: Option<&'a str>,
    transform: Option<&'a CdnTransform>,
    viewer_claims: Option<&'a ViewerClaims>,
}
impl AssetLocation<'_> {
    /// The asset URL (public or signed) with the location appended. Without a resource the URL
    /// stays the asset URL, which takes no selector.
    fn append(&self, asset_url: &str) -> Result<String> {
        let selected = self.lens.is_some() || self.transform.is_some();
        let mut url = asset_url.to_owned();
        match self.resource {
            None if selected => {
                return Err(invalid_argument(
                    "A lens or transform needs a resource, such as rendered",
                ));
            }
            None => {}
            Some(resource) => {
                let resource = resource.as_str();
                let Some((_, path)) = CDN_RESOURCE_PATHS
                    .iter()
                    .find(|(name, _)| *name == resource)
                else {
                    let names: Vec<&str> =
                        CDN_RESOURCE_PATHS.iter().map(|(name, _)| *name).collect();
                    return Err(invalid_argument(format!(
                        "Resource must be one of {}",
                        names.join(", ")
                    )));
                };
                if !matches!(resource, "rendered" | "preview") && selected {
                    return Err(invalid_argument(format!(
                        "The {resource} resource takes no lens or transform"
                    )));
                }
                url.push('/');
                url.push_str(path);
                let mut selector = Vec::new();
                if let Some(lens) = self.lens {
                    selector.push(format!("@{}", id(lens)?));
                }
                if let Some(value) = self.transform.filter(|value| !value.is_empty()) {
                    selector.push(match value {
                        CdnTransform::Selector(_) => encode_selector(&value.selector()?),
                        // Already path-safe: unreserved characters, percent escapes, `=`, `,`
                        // and `.`.
                        CdnTransform::Options(_) => value.selector()?,
                    });
                }
                if !selector.is_empty() {
                    url.push('/');
                    url.push_str(&selector.join(","));
                }
            }
        }
        url.push_str(&viewer_claims_query(self.viewer_claims)?);
        Ok(url)
    }
}

/// CDN URLs, signed asset URLs, display info and downloads. Get it from [`ServerClient::cdn`].
///
/// Every asset has one URL, `{cdn_base_url}/assets/{projectId}/{asset}`, and each resource
/// ([`CdnResource`]) is a path beneath it. The asset segment is the asset ID, or `ext:` and the
/// URL-encoded external ID, for a public asset, or a signed grant for a private one: use
/// [`sign_asset_url`](Self::sign_asset_url) if the asset is private and
/// [`get_asset_url`](Self::get_asset_url) otherwise, and add viewer claims to either.
#[derive(Debug, Clone, Copy)]
pub struct CdnClient<'a>(&'a ServerClient);
impl CdnClient<'_> {
    /// The path-encoded project, the client's when `project_id` is `None`.
    fn project_segment(&self, project_id: Option<&str>) -> Result<String> {
        id(project_id.unwrap_or(&self.0.inner.config.project_id))
    }
    /// Builds an asset's CDN URL without sending a request: the asset URL, which every resource
    /// is a path beneath, or a resource URL when [`CdnRequest::resource`] is set, with its lens
    /// or transform and the viewer claims. Use it for public assets; private ones need
    /// [`sign_asset_url`](Self::sign_asset_url). Only the rendered and preview resources take a
    /// lens or transform; the CDN refuses them on rendered PDFs, video and audio with
    /// `transform/invalid`. Viewer claims are assertions from your app; CalmLens doesn't
    /// verify them.
    pub fn get_asset_url(&self, options: &CdnRequest) -> Result<String> {
        let project = self.project_segment(options.project_id.as_deref())?;
        let asset = asset_segment(options.asset_id.as_deref(), options.external_id.as_deref())?;
        let location = AssetLocation {
            resource: options.resource.as_ref(),
            lens: options.lens.as_deref(),
            transform: options.transform.as_ref(),
            viewer_claims: options.viewer_claims.as_ref(),
        };
        location.append(&format!(
            "{}/assets/{project}/{asset}",
            self.0.inner.config.cdn_base_url
        ))
    }
    /// Signs a private asset's URL on your server (`POST /projects/:projectId/signed-asset-urls`),
    /// so browsers and apps can load it without an API key until it expires (15 minutes by
    /// default). Every resource is a path beneath it, as beneath a public asset URL; the original
    /// only when signed with `original`. With a `resource`, it returns that resource's URL beneath
    /// the grant. The options are checked before anything is sent. Not retried: it carries no
    /// `Idempotency-Key`.
    pub async fn sign_asset_url(&self, options: SignAssetUrlOptions) -> Result<SignedAssetUrl> {
        if options
            .expires_in
            .is_some_and(|seconds| !(1..=MAX_SIGNED_URL_EXPIRES_IN).contains(&seconds))
        {
            return Err(invalid_argument(format!(
                "expires_in must be a whole number of seconds from 1 to {MAX_SIGNED_URL_EXPIRES_IN}"
            )));
        }
        asset_segment(options.asset_id.as_deref(), options.external_id.as_deref())?;
        let location = AssetLocation {
            resource: options.resource.as_ref(),
            lens: options.lens.as_deref(),
            transform: options.transform.as_ref(),
            viewer_claims: options.viewer_claims.as_ref(),
        };
        // The location is appended to the signed URL: check it before signing.
        location.append("")?;
        let project = self.project_segment(options.project_id.as_deref())?;
        let mut body = serde_json::Map::new();
        match (&options.asset_id, &options.external_id) {
            (Some(asset_id), _) => body.insert("assetId".into(), asset_id.clone().into()),
            (_, external_id) => body.insert("externalId".into(), external_id.clone().into()),
        };
        body.insert(
            "expiresIn".into(),
            options
                .expires_in
                .unwrap_or(DEFAULT_SIGNED_URL_EXPIRES_IN)
                .into(),
        );
        body.insert("original".into(), options.original.unwrap_or(false).into());
        let path = format!("/projects/{project}/signed-asset-urls");
        let request = self
            .0
            .prepare_for("cdn.signAssetUrl", Method::POST, &path, &[])?
            .json(&body)?;
        let signed: SignedAssetUrl = self.0.call(request).await?;
        if signed.url.is_empty() {
            return Err(Error::new(
                ErrorCode::InvalidResponse,
                "The API returned no signed asset URL",
            ));
        }
        Ok(SignedAssetUrl {
            url: location.append(&signed.url)?,
            ..signed
        })
    }
    /// Fetches the display info of an asset URL, public or signed (`{url}/info`): its type,
    /// size, rendered file, preview and stream, and whether the viewer its claims describe can see
    /// it ([`AssetInfo::availability`]). The claims are `options.viewer_claims`, else those the
    /// URL carries. It sends no API key, as a browser would. A refusal fails with the CDN's code,
    /// such as `signed-url/expired` or `asset/not-available`.
    pub async fn get_asset_info(
        &self,
        url: &str,
        options: GetAssetInfoOptions,
    ) -> Result<AssetInfo> {
        let parsed = reqwest::Url::parse(url)
            .ok()
            .filter(|parsed| parsed.has_host())
            .ok_or_else(|| invalid_argument("url must be an absolute asset URL"))?;
        let without_fragment = url.split('#').next().unwrap_or_default();
        let base = without_fragment.split('?').next().unwrap_or_default();
        let claims = match options.viewer_claims {
            Some(claims) => Some(claims),
            None => match parsed.query_pairs().find(|(key, _)| key == "viewerClaims") {
                Some((_, raw)) => {
                    Some(serde_json::from_str::<ViewerClaims>(&raw).map_err(|cause| {
                        invalid_argument("The asset URL's viewerClaims are not valid JSON")
                            .with_source(cause)
                    })?)
                }
                None => None,
            },
        };
        let info_url = format!(
            "{}/info{}",
            base.trim_end_matches('/'),
            viewer_claims_query(claims.as_ref())?
        );
        let mut request =
            self.0
                .prepare_url_for("cdn.getAssetInfo", Method::GET, &info_url, &[])?;
        request.headers.remove("x-api-key");
        request.headers.insert(
            http::header::ACCEPT,
            HeaderValue::from_static("application/json"),
        );
        let options = self.0.options();
        let exchange = execute(
            &self.0.inner.transport,
            request,
            options,
            true,
            &self.0.inner.config.observer,
        )
        .await?;
        let (status, headers) = (exchange.status, exchange.headers.clone());
        let body = exchange.read(options.max_response_bytes).await?;
        let mut info: AssetInfo = decode(status, &headers, &body)?;
        info.set_last_response(crate::transport::last_response(status, &headers, None));
        if info.id.is_empty() || info.project_id.is_empty() || !info.availability.is_known() {
            return Err(
                Error::new(ErrorCode::InvalidResponse, "The CDN returned no asset info")
                    .with_http_status(status),
            );
        }
        Ok(info)
    }
    /// Fetches an asset through the CDN with the API key, returning the response whatever
    /// its status. The resource defaults to [`CdnResource::Rendered`]. The body streams; it is
    /// not subject to the API call timeout.
    pub async fn serve(&self, options: CdnRequest) -> Result<CdnResponse> {
        let options = CdnRequest {
            resource: Some(options.resource.clone().unwrap_or(CdnResource::Rendered)),
            ..options
        };
        let url = self.get_asset_url(&options)?;
        let init = options.init.unwrap_or_default();
        let method = Method::from_bytes(init.method.as_deref().unwrap_or("GET").as_bytes())
            .map_err(|_| invalid_argument("Invalid HTTP method"))?;
        let mut request = self.0.prepare_url_for("cdn.serve", method, &url, &[])?;
        for (name, value) in &init.headers {
            if name.eq_ignore_ascii_case("x-api-key") {
                continue;
            }
            let name = http::HeaderName::from_bytes(name.as_bytes())
                .map_err(|_| invalid_argument(format!("Invalid header name {name:?}")))?;
            let value = HeaderValue::from_str(value)
                .map_err(|_| invalid_argument(format!("Invalid {name} header value")))?;
            request.headers.insert(name, value);
        }
        self.fetch(request).await
    }
    /// Fetches a CDN URL with a GET and without the API key, as a browser would.
    #[cfg(feature = "testing")]
    pub(crate) async fn fetch_unauthenticated(&self, url: &str) -> Result<CdnResponse> {
        let mut request =
            self.0
                .prepare_url_for("cdn.fetchUnauthenticated", Method::GET, url, &[])?;
        request.headers.remove("x-api-key");
        self.fetch(request).await
    }
    async fn fetch(&self, mut request: Prepared) -> Result<CdnResponse> {
        request.deadline = Deadline::Headers;
        let exchange: Exchange = execute(
            &self.0.inner.transport,
            request,
            self.0.options(),
            false,
            &self.0.inner.config.observer,
        )
        .await?;
        Ok(CdnResponse {
            status: StatusCode::from_u16(exchange.status)
                .map_err(|_| Error::new(ErrorCode::InvalidResponse, "Invalid status"))?,
            headers: exchange.headers.clone(),
            body: exchange.stream(),
        })
    }
}

/// A streaming CDN response. Drop it to close an unfinished download.
pub struct CdnResponse {
    status: StatusCode,
    headers: HeaderMap,
    body: crate::ByteStream,
}
impl fmt::Debug for CdnResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CdnResponse")
            .field("status", &self.status)
            .field("headers", &self.headers)
            .finish_non_exhaustive()
    }
}
impl CdnResponse {
    /// The HTTP status.
    pub fn status(&self) -> StatusCode {
        self.status
    }
    /// The response headers.
    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }
    /// Reads served image dimensions from the headers without consuming the body.
    pub fn get_asset_info(&self) -> Option<crate::ServedAssetInfo> {
        crate::ServedAssetInfo::from_headers(&self.headers)
    }
    /// The next chunk of the body, or `None` at the end.
    pub async fn chunk(&mut self) -> Result<Option<Bytes>> {
        match self.body.next().await {
            None => Ok(None),
            Some(chunk) => chunk.map(Some).map_err(stream_error),
        }
    }
    /// The whole body in memory. Prefer [`CdnResponse::chunk`] or
    /// [`CdnResponse::into_stream`] for large files.
    pub async fn bytes(mut self) -> Result<Bytes> {
        let mut body = Vec::new();
        while let Some(chunk) = self.chunk().await? {
            body.extend_from_slice(&chunk);
        }
        Ok(body.into())
    }
    /// The whole body as UTF-8 text.
    pub async fn text(self) -> Result<String> {
        String::from_utf8(self.bytes().await?.to_vec()).map_err(|cause| {
            Error::new(ErrorCode::InvalidResponse, "Invalid UTF-8 response").with_source(cause)
        })
    }
    /// The body as a stream of chunks.
    pub fn into_stream(self) -> BoxStream<'static, Result<Bytes>> {
        self.body.map_err(stream_error).boxed()
    }
}