calmlens 0.19.0

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
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
//! Typed request options and response models.
//!
//! Rust fields are snake_case; the wire JSON is camelCase. Response models are
//! `#[non_exhaustive]` and keep fields this SDK version does not know in `extra`, and enums
//! keep values it does not know in an `Unknown` variant, so new API fields and values never
//! fail decoding. Only metadata values, event fact values and the options of transform types
//! this SDK does not know use JSON values.
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{collections::HashMap, fmt};

/// A field in an update: leave it unchanged, clear it, or set it.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
#[serde(untagged)]
pub enum Patch<T> {
    /// Leaves the field unchanged (omitted from the request).
    #[default]
    Missing,
    /// Clears the field (sent as `null`).
    Null,
    /// Replaces the field.
    Value(T),
}
impl<T> Patch<T> {
    /// Whether the field is left unchanged.
    pub fn is_missing(&self) -> bool {
        matches!(self, Self::Missing)
    }
}
impl<'de, T: Deserialize<'de>> Deserialize<'de> for Patch<T> {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> std::result::Result<Self, D::Error> {
        Ok(Option::<T>::deserialize(deserializer)?.map_or(Self::Null, Self::Value))
    }
}
impl<T> From<T> for Patch<T> {
    fn from(value: T) -> Self {
        Self::Value(value)
    }
}

/// Reads a model's `extra` map: the fields `T` does not type.
#[cfg_attr(
    not(feature = "strict-contract"),
    allow(clippy::extra_unused_type_parameters)
)]
fn extra_fields<'de, T, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> std::result::Result<HashMap<String, Value>, D::Error> {
    let extra = HashMap::<String, Value>::deserialize(deserializer)?;
    #[cfg(feature = "strict-contract")]
    for key in extra.keys() {
        let name = std::any::type_name::<T>()
            .rsplit("::")
            .next()
            .unwrap_or_default();
        strict::record(name, strict::Finding::Field(key.clone()));
    }
    Ok(extra)
}

/// Contract-test support, not part of the public API: records what decoding kept untyped, an
/// `extra` field or an `Unknown` enum value, so a fixture of a full model can check that every
/// field and value it holds has a typed home.
#[cfg(feature = "strict-contract")]
#[doc(hidden)]
pub mod strict {
    use std::cell::RefCell;

    /// What a model kept untyped.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub enum Finding {
        /// A wire field the model has no field for, kept in its `extra` map.
        Field(String),
        /// A wire value the enum has no variant for, kept as `Unknown`.
        Value(String),
    }

    thread_local! {
        static FINDINGS: RefCell<Option<Vec<(&'static str, Finding)>>> = const { RefCell::new(None) };
    }

    /// Starts recording on this thread, discarding anything recorded before.
    pub fn start() {
        FINDINGS.with(|findings| *findings.borrow_mut() = Some(Vec::new()));
    }

    /// Stops recording and returns each type with what it kept untyped since [`start`].
    pub fn finish() -> Vec<(&'static str, Finding)> {
        FINDINGS.with(|findings| findings.borrow_mut().take().unwrap_or_default())
    }

    pub(crate) fn record(model: &'static str, finding: Finding) {
        FINDINGS.with(|findings| {
            if let Some(findings) = findings.borrow_mut().as_mut() {
                findings.push((model, finding));
            }
        });
    }
}

macro_rules! string_enum {
    ($(#[$meta:meta])* $name:ident { $( $(#[$vmeta:meta])* $variant:ident = $value:literal ),* $(,)? }) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
        #[non_exhaustive]
        pub enum $name {
            $( $(#[$vmeta])* $variant, )*
            /// A value this SDK version does not know.
            Unknown(String),
        }
        impl $name {
            /// The wire value.
            pub fn as_str(&self) -> &str {
                match self {
                    $(Self::$variant => $value,)*
                    Self::Unknown(value) => value,
                }
            }
        }
        impl From<&str> for $name {
            fn from(value: &str) -> Self {
                match value {
                    $($value => Self::$variant,)*
                    other => Self::Unknown(other.to_owned()),
                }
            }
        }
        impl Default for $name {
            /// An empty `Unknown` value, used only when the API omits a required field.
            fn default() -> Self {
                Self::Unknown(String::new())
            }
        }
        impl From<String> for $name {
            fn from(value: String) -> Self {
                Self::from(value.as_str())
            }
        }
        impl PartialEq<&str> for $name {
            fn eq(&self, other: &&str) -> bool {
                self.as_str() == *other
            }
        }
        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(self.as_str())
            }
        }
        impl Serialize for $name {
            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                serializer.serialize_str(self.as_str())
            }
        }
        impl<'de> Deserialize<'de> for $name {
            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                let value = Self::from(String::deserialize(deserializer)?.as_str());
                #[cfg(feature = "strict-contract")]
                if let Self::Unknown(unknown) = &value {
                    strict::record(stringify!($name), strict::Finding::Value(unknown.clone()));
                }
                Ok(value)
            }
        }
    };
}

string_enum! {
    /// Where an asset is in the pipeline.
    AssetClassificationStatus {
        /// The content is still arriving, e.g. a multipart upload receiving parts.
        Pending = "pending",
        /// The content is being processed and classified.
        Processing = "processing",
        /// Processing finished.
        Completed = "completed",
        /// Processing failed; the asset can be retried.
        Failed = "failed",
    }
}

string_enum! {
    /// The moderation decision in force, which also decides delivery: `pending` until
    /// classification decides, then a reviewer's decision when there is one, else the policy's.
    AssetModerationStatus {
        /// Waiting for classification or review; not delivered.
        Pending = "pending",
        /// Delivered according to the asset's visibility.
        Allowed = "allowed",
        /// Delivered like `allowed`, but marked so your app can reduce its reach, such as
        /// keeping it out of recommendations, trending and notifications, ranking it lower or
        /// collapsing it.
        Limited = "limited",
        /// Delivered only through signed URLs or with an API key, like a private asset.
        AgeRestricted = "age-restricted",
        /// Not delivered; the content is kept.
        Blocked = "blocked",
        /// Not delivered, and the stored content is deleted.
        Purged = "purged",
    }
}

string_enum! {
    /// A reviewer's decision on an asset.
    AssetModerationDecision {
        /// Deliver the asset according to its visibility.
        Allowed = "allowed",
        /// Deliver the asset like `allowed`, marked so your app can reduce its reach.
        Limited = "limited",
        /// Deliver the asset only through signed URLs or with an API key.
        AgeRestricted = "age-restricted",
        /// Stop delivering the asset and keep its content.
        Blocked = "blocked",
        /// Stop delivering the asset and delete its stored content.
        Purged = "purged",
    }
}

string_enum! {
    /// Whether CalmLens holds an asset's content (source, preview and extracted text).
    AssetContentStatus {
        /// Held only until processing finishes.
        Temporary = "temporary",
        /// Retained.
        Stored = "stored",
        /// Deleted; [`AssetContent::removal_reason`] says why.
        Removed = "removed",
    }
}

string_enum! {
    /// Why an asset's content was removed.
    AssetContentRemovalReason {
        /// The moderation policy purged it.
        Policy = "policy",
        /// `keepContentAfterProcessing` was off, so it was removed after processing.
        Retention = "retention",
        /// Removed through the API or portal.
        Requested = "requested",
        /// Removed with its parent asset's content.
        ParentRemoved = "parent-removed",
        /// Disposed of after a safety hold.
        Disposed = "disposed",
    }
}

string_enum! {
    /// Why an asset's processing failed.
    AssetFailureReason {
        /// The file is larger than processing allows.
        FileTooLarge = "file-too-large",
        /// The audio or video is longer than processing allows.
        DurationLimit = "duration-limit",
        /// The video is larger than 4096 × 2160 pixels.
        ResolutionLimit = "resolution-limit",
        /// The file format is not supported.
        UnsupportedFormat = "unsupported-format",
        /// The content could not be decoded.
        UndecodableContent = "undecodable-content",
        /// The audio or video has more than one audio or video track.
        MultipleTracks = "multiple-tracks",
        /// The content does not match the asset's type.
        TypeMismatch = "type-mismatch",
        /// The upload has more text than free uploads allow before billing is set up.
        FreeUploadLimit = "free-upload-limit",
        /// A part of the asset, such as an embedded image, failed.
        ChildFailed = "child-failed",
        /// Processing failed for another reason; retrying may succeed.
        ProcessingError = "processing-error",
    }
}

string_enum! {
    /// Whether the CDN serves an asset without a signed URL.
    Visibility {
        /// Served to anyone with the URL once its moderation status is `allowed`.
        Public = "public",
        /// Served only through signed URLs or with an API key.
        Private = "private",
    }
}

string_enum! {
    /// The kind of content an asset holds, detected from its MIME type.
    AssetType {
        /// An image.
        Image = "image",
        /// A video.
        Video = "video",
        /// An audio file.
        Audio = "audio",
        /// A plain-text document.
        PlaintextDocument = "plaintext-document",
        /// A document with text and embedded media, such as a PDF.
        MultimediaDocument = "multimedia-document",
        /// A captured website.
        Website = "website",
        /// Any other file.
        File = "file",
    }
}

string_enum! {
    /// What happens to content that crosses a moderation threshold.
    FlaggedContentAction {
        /// Take no action.
        Allow = "allow",
        /// Deliver normally, but mark the asset `limited` so your app can reduce its reach.
        Limit = "limit",
        /// Deliver only through signed URLs or with an API key, so your backend can limit it to
        /// adults.
        AgeRestrict = "age-restrict",
        /// Block delivery while keeping the content.
        Block = "block",
        /// Delete the content.
        Purge = "purge",
    }
}

string_enum! {
    /// Why an asset is under a safety hold.
    SafetyHoldReason {
        /// The content is suspected to be illegal.
        SuspectedIllegalContent = "suspected-illegal-content",
    }
}

string_enum! {
    /// Where extracted text is stored.
    ExtractedTextType {
        /// Inline, in [`ExtractedText::content`].
        String = "string",
        /// In a separate document, identified by [`ExtractedText::id`].
        Document = "document",
    }
}

string_enum! {
    /// Whether a moderation category or qualifier was assessed.
    EvaluationStatus {
        /// Fully assessed.
        Evaluated = "evaluated",
        /// Assessed from part of the content, e.g. some video frames.
        Partial = "partial",
        /// Not assessed; `reason` says why.
        NotEvaluated = "not-evaluated",
    }
}

string_enum! {
    /// Why a moderation category or qualifier was not assessed.
    NotEvaluatedReason {
        /// This kind of content cannot be assessed for it.
        NotSupported = "not-supported",
        /// Assessment was attempted but produced no usable result.
        Unavailable = "unavailable",
    }
}

string_enum! {
    /// How likely a category, qualifier or label applies.
    Likelihood {
        /// Very unlikely.
        VeryUnlikely = "very-unlikely",
        /// Unlikely.
        Unlikely = "unlikely",
        /// Possible.
        Possible = "possible",
        /// Likely.
        Likely = "likely",
        /// Very likely.
        VeryLikely = "very-likely",
    }
}

string_enum! {
    /// A moderation policy category, the key of [`AssetModeration::categories`].
    ClassificationCategory {
        /// Private personal information (Preview).
        PersonalInformation = "personal-information",
        /// Profanity.
        Profanity = "profanity",
        /// Sexual content.
        Sexual = "sexual",
        /// Violence.
        Violence = "violence",
        /// Self-harm.
        SelfHarm = "self-harm",
        /// Harassment and bullying.
        Harassment = "harassment",
        /// Hate and identity abuse.
        Hate = "hate",
        /// Criminal and dangerous activity.
        CriminalActivity = "criminal-activity",
    }
}

// The moderation qualifiers, generated from the shared registry.
include!("qualifiers.rs");

string_enum! {
    /// What a media segment's scores come from.
    MediaSegmentSource {
        /// A sampled video frame.
        Frame = "frame",
        /// Transcribed speech.
        Speech = "speech",
        /// Text read from a frame.
        FrameText = "frame-text",
        /// A video clip.
        Clip = "clip",
    }
}

string_enum! {
    /// An event type.
    EventType {
        /// `asset.uploaded`.
        AssetUploaded = "asset.uploaded",
        /// `asset.classified`.
        AssetClassified = "asset.classified",
        /// `asset.allowed`.
        AssetAllowed = "asset.allowed",
        /// `asset.limited`.
        AssetLimited = "asset.limited",
        /// `asset.age-restricted`.
        AssetAgeRestricted = "asset.age-restricted",
        /// `asset.blocked`.
        AssetBlocked = "asset.blocked",
        /// `asset.purged`.
        AssetPurged = "asset.purged",
        /// `asset.failed`.
        AssetFailed = "asset.failed",
        /// `asset.deleted`.
        AssetDeleted = "asset.deleted",
        /// `asset.content-removed`.
        AssetContentRemoved = "asset.content-removed",
        /// `asset.retried`.
        AssetRetried = "asset.retried",
        /// `asset.review-requested`.
        AssetReviewRequested = "asset.review-requested",
        /// `usage.limit-reached`.
        UsageLimitReached = "usage.limit-reached",
        /// `usage.spend-limit-reached`.
        UsageSpendLimitReached = "usage.spend-limit-reached",
        /// `upload-preset.daily-limit-reached`.
        UploadPresetDailyLimitReached = "upload-preset.daily-limit-reached",
        /// `project.member-joined`.
        ProjectMemberJoined = "project.member-joined",
        /// `project.member-removed`.
        ProjectMemberRemoved = "project.member-removed",
        /// `project.member-role-changed`.
        ProjectMemberRoleChanged = "project.member-role-changed",
        /// `project.invitation-sent`.
        ProjectInvitationSent = "project.invitation-sent",
        /// `api-key.created`.
        ApiKeyCreated = "api-key.created",
        /// `api-key.revoked`.
        ApiKeyRevoked = "api-key.revoked",
        /// `connector.failing`.
        ConnectorFailing = "connector.failing",
        /// `appeal.submitted`.
        AppealSubmitted = "appeal.submitted",
        /// `appeal.resolved`.
        AppealResolved = "appeal.resolved",
    }
}

string_enum! {
    /// An event's severity.
    EventSeverity {
        /// Informational.
        Low = "low",
        /// Needs attention.
        High = "high",
    }
}

string_enum! {
    /// The asset type a lens applies to.
    LensType {
        /// Images.
        Image = "image",
        /// Videos.
        Video = "video",
        /// Audio.
        Audio = "audio",
        /// Documents.
        Document = "document",
        /// Websites.
        Website = "website",
    }
}

string_enum! {
    /// How asset search matches the query.
    SearchMode {
        /// Keyword and semantic matching combined (the default).
        Hybrid = "hybrid",
        /// Keyword matching only.
        Keyword = "keyword",
        /// Semantic matching only.
        Semantic = "semantic",
    }
}

string_enum! {
    /// Whether semantic search is available for the project.
    SemanticStatus {
        /// Semantic search is turned off.
        Disabled = "disabled",
        /// The semantic index is ready.
        Ready = "ready",
        /// The semantic index is still being built.
        Indexing = "indexing",
        /// Semantic search could not run this time.
        Unavailable = "unavailable",
    }
}

string_enum! {
    /// A field a search result matched on.
    SearchMatchField {
        /// The name.
        Name = "name",
        /// The asset ID.
        Id = "id",
        /// Your ID for the asset.
        ExternalId = "externalId",
        /// The description.
        Description = "description",
        /// The tags.
        Tags = "tags",
        /// The asset type.
        Type = "type",
        /// The content format.
        ContentFormat = "content.format",
        /// The content's file extension.
        ContentExtension = "content.extension",
        /// The moderation status.
        ModerationStatus = "classification.moderation.status",
        /// The visual content.
        Visual = "visual",
        /// The audio transcript.
        Transcript = "transcript",
    }
}

string_enum! {
    /// A sort direction.
    SortDirection {
        /// Ascending.
        Asc = "asc",
        /// Descending.
        Desc = "desc",
    }
}

string_enum! {
    /// Which CDN resource of an asset to serve or sign.
    CdnResource {
        /// The asset's original file. It takes no lens or transform.
        Original = "original",
        /// The asset rendered through a lens or transform, or its default rendition (the default).
        Rendered = "rendered",
        /// A small blurred PNG, public whatever the asset's visibility or moderation. Only
        /// for CDN URLs, without a lens or transform; it needs no age confirmation.
        Placeholder = "placeholder",
    }
}

string_enum! {
    /// Which CDN resource of an asset a signed URL serves. Placeholders need no signature.
    SignedUrlResource {
        /// The asset's original file. It takes no lens or transform.
        Original = "original",
        /// The asset rendered through a lens or transform, or its default rendition (the default).
        Rendered = "rendered",
    }
}

/// Processing options for an asset.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingOptions {
    /// Keep the stored content after classification.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub keep_content_after_processing: Option<bool>,
    /// Overrides the project's `storeSensitiveMetadata` setting for this upload. When false,
    /// embedded image metadata (EXIF, XMP and IPTC) is removed from the file before it is stored,
    /// and `file_metadata` leaves out the creator and location. When true, the image is stored as
    /// uploaded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub store_sensitive_metadata: Option<bool>,
    /// Optional analyses to run, keyed by feature. Link detection runs unless turned off; every
    /// other feature is off unless enabled.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub features: Option<ProcessingFeatures>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<ProcessingOptions, _>")]
    pub extra: HashMap<String, Value>,
}

/// Optional analyses to run on an asset, keyed by feature. The API rejects unknown features.
/// Results of person and face detection are in [`AssetClassification::face_detection`].
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingFeatures {
    /// Extract image text onto the image asset and add a text moderation pass to its report.
    /// Applies to images, including those extracted from documents and websites.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ocr: Option<FeatureOptions>,
    /// Preview. Locate people in images, including people whose faces are not visible. Results
    /// are informational and never change the moderation decision.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub person_detection: Option<FeatureOptions>,
    /// Preview. Locate faces in images and optionally estimate an age range for each. Faces are
    /// not identified. Results are informational and never change the moderation decision.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub face_detection: Option<FaceDetectionOptions>,
    /// Find QR codes and web links in images, and moderate QR code text with the image. Runs
    /// unless `enabled` is false. With OCR on, links in the extracted text are listed too.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub link_detection: Option<FeatureOptions>,
    /// Preview. Read provenance metadata, such as C2PA, that marks an image as AI-generated or
    /// AI-edited. Results are informational and never change the moderation decision.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ai_generated_detection: Option<FeatureOptions>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<ProcessingFeatures, _>")]
    pub extra: HashMap<String, Value>,
}

/// Options for a feature that only needs turning on.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FeatureOptions {
    /// Whether to run the feature.
    pub enabled: bool,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<FeatureOptions, _>")]
    pub extra: HashMap<String, Value>,
}
impl FeatureOptions {
    /// Options that turn the feature on.
    pub fn enabled() -> Self {
        Self {
            enabled: true,
            ..Self::default()
        }
    }
}

/// Face detection options.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FaceDetectionOptions {
    /// Whether to run face detection.
    pub enabled: bool,
    /// Also estimate an age range for each face. Defaults to `false`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub age_estimation: Option<bool>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<FaceDetectionOptions, _>")]
    pub extra: HashMap<String, Value>,
}
impl FaceDetectionOptions {
    /// Options that turn face detection on, without age estimation.
    pub fn enabled() -> Self {
        Self {
            enabled: true,
            ..Self::default()
        }
    }
}

/// The bytes of an upload or multipart part.
///
/// `Text` and `Bytes` are sent as they are and can be retried. `Reader`, `Stream` and
/// `UnsizedStream` are read once while the request is sent, so the whole file never needs to be
/// in memory; the SDK does not retry them. `Reader` and `Stream` need the exact `size`.
///
/// `Bytes`, `Base64` and `File` can be read again, so [`AssetsClient::create`] and
/// [`AssetsClient::classify`] upload them in parts when they are larger than the client's
/// [`part_size_bytes`](crate::ServerClientBuilder::part_size_bytes).
///
/// [`AssetsClient::create`]: crate::AssetsClient::create
/// [`AssetsClient::classify`]: crate::AssetsClient::classify
#[non_exhaustive]
pub enum Payload {
    /// UTF-8 text.
    Text(String),
    /// Bytes. Cloning [`Bytes`] does not copy them.
    Bytes(Bytes),
    /// Base64 bytes, optionally as a `data:` URL. Split multipart files before encoding parts.
    Base64(String),
    /// A blocking reader with its exact length, read on Tokio's blocking thread pool.
    #[cfg(feature = "async")]
    Reader {
        /// The source, e.g. a [`std::fs::File`].
        reader: Box<dyn std::io::Read + Send + 'static>,
        /// The exact number of bytes the reader yields.
        size: u64,
    },
    /// A file on disk with its length, read while it is uploaded. Content larger than one
    /// part is read again part by part, so each part can be retried. Create it with
    /// [`Content::file`].
    #[cfg(feature = "async")]
    File {
        /// The file's path.
        path: std::path::PathBuf,
        /// The file's length in bytes.
        size: u64,
    },
    /// An async byte stream with its exact length.
    #[cfg(feature = "async")]
    Stream {
        /// The chunks.
        stream: crate::ByteStream,
        /// The exact total number of bytes.
        size: u64,
    },
    /// An async byte stream whose length is not known in advance. It is sent with chunked
    /// transfer encoding and no `sizeInBytes`, unless the content declares `size_in_bytes`.
    #[cfg(feature = "async")]
    UnsizedStream(crate::ByteStream),
}
impl Default for Payload {
    fn default() -> Self {
        Self::Bytes(Bytes::new())
    }
}
impl fmt::Debug for Payload {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Text(text) => f.debug_struct("Text").field("len", &text.len()).finish(),
            Self::Bytes(bytes) => f.debug_struct("Bytes").field("len", &bytes.len()).finish(),
            Self::Base64(text) => f.debug_struct("Base64").field("len", &text.len()).finish(),
            #[cfg(feature = "async")]
            Self::Reader { size, .. } => f.debug_struct("Reader").field("size", size).finish(),
            #[cfg(feature = "async")]
            Self::File { path, size } => f
                .debug_struct("File")
                .field("path", path)
                .field("size", size)
                .finish(),
            #[cfg(feature = "async")]
            Self::Stream { size, .. } => f.debug_struct("Stream").field("size", size).finish(),
            #[cfg(feature = "async")]
            Self::UnsizedStream(_) => f.debug_struct("UnsizedStream").finish_non_exhaustive(),
        }
    }
}

/// Upload content (`content`) or a multipart part (`part`): a concrete MIME type and the bytes.
#[derive(Debug, Default)]
pub struct Content {
    /// The file's MIME type, such as `image/png` (`type` on the wire). A multipart part sent
    /// with [`AssetsClient::upload_part`](crate::AssetsClient::upload_part) may leave it empty.
    pub mime_type: String,
    /// The bytes.
    pub payload: Payload,
    /// Optional declared byte length. Uploads reject a value that differs from the payload size.
    pub size_in_bytes: Option<u64>,
    /// The multipart part number, starting at 1. Only for parts.
    pub part_number: Option<u32>,
    /// Whether this is the last multipart part. Only for parts.
    pub is_final: Option<bool>,
}

impl Content {
    /// `text/plain` content.
    pub fn text(text: impl Into<String>) -> Self {
        Self::new(Payload::Text(text.into()), "text/plain")
    }
    /// Binary content. Pass a `Vec<u8>`, `Bytes` or `&'static [u8]` to avoid a copy.
    pub fn bytes(bytes: impl Into<Bytes>, mime_type: impl Into<String>) -> Self {
        Self::new(Payload::Bytes(bytes.into()), mime_type)
    }
    /// Content read from `reader`, which yields exactly `size` bytes, while it is uploaded.
    #[cfg(feature = "async")]
    pub fn reader(
        reader: impl std::io::Read + Send + 'static,
        size: u64,
        mime_type: impl Into<String>,
    ) -> Self {
        Self::new(
            Payload::Reader {
                reader: Box::new(reader),
                size,
            },
            mime_type,
        )
    }
    /// Content streamed from `stream`, which yields exactly `size` bytes, while it is uploaded.
    #[cfg(feature = "async")]
    pub fn stream<S, E>(stream: S, size: u64, mime_type: impl Into<String>) -> Self
    where
        S: futures_util::Stream<Item = std::result::Result<Bytes, E>> + Send + 'static,
        E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
    {
        use futures_util::TryStreamExt;
        Self::new(
            Payload::Stream {
                stream: Box::pin(stream.map_err(Into::into)),
                size,
            },
            mime_type,
        )
    }
    /// Content streamed from `stream`, whose length is not known in advance, while it is
    /// uploaded. Set [`size_in_bytes`](Self::size_in_bytes) when you know it.
    #[cfg(feature = "async")]
    pub fn unsized_stream<S, E>(stream: S, mime_type: impl Into<String>) -> Self
    where
        S: futures_util::Stream<Item = std::result::Result<Bytes, E>> + Send + 'static,
        E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
    {
        use futures_util::TryStreamExt;
        Self::new(
            Payload::UnsizedStream(Box::pin(stream.map_err(Into::into))),
            mime_type,
        )
    }
    /// Streams the file at `path` without reading it into memory. A file larger than the
    /// client's [`part_size_bytes`](crate::ServerClientBuilder::part_size_bytes) is uploaded in
    /// parts, so it must stay unchanged until the upload finishes.
    #[cfg(feature = "async")]
    pub fn file(
        path: impl AsRef<std::path::Path>,
        mime_type: impl Into<String>,
    ) -> std::io::Result<Self> {
        let path = path.as_ref();
        let size = std::fs::File::open(path)?.metadata()?.len();
        Ok(Self::new(
            Payload::File {
                path: path.to_owned(),
                size,
            },
            mime_type,
        ))
    }
    fn new(payload: Payload, mime_type: impl Into<String>) -> Self {
        Self {
            mime_type: mime_type.into(),
            payload,
            size_in_bytes: None,
            part_number: None,
            is_final: None,
        }
    }
    /// Marks the content as multipart part `part_number`, the last part when `is_final`.
    pub fn part(mut self, part_number: u32, is_final: bool) -> Self {
        self.part_number = Some(part_number);
        self.is_final = Some(is_final);
        self
    }
}

/// Reads the JSON request shape `{type, plainText | base64 | bytes, partNumber?, isFinal?}`.
impl<'de> Deserialize<'de> for Content {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase", deny_unknown_fields)]
        struct Wire {
            #[serde(default, rename = "type")]
            mime_type: String,
            plain_text: Option<String>,
            base64: Option<String>,
            bytes: Option<Vec<u8>>,
            size_in_bytes: Option<u64>,
            part_number: Option<u32>,
            is_final: Option<bool>,
        }
        use serde::de::Error;
        let wire = Wire::deserialize(deserializer)?;
        let payload = match (wire.plain_text, wire.base64, wire.bytes) {
            (Some(text), None, None) => Payload::Text(text),
            (None, Some(base64), None) => Payload::Base64(base64),
            (None, None, Some(bytes)) => Payload::Bytes(bytes.into()),
            _ => {
                return Err(D::Error::custom(
                    "Supply exactly one payload representation",
                ))
            }
        };
        if let (Some(size), Payload::Text(_) | Payload::Bytes(_)) = (wire.size_in_bytes, &payload) {
            let length = match &payload {
                Payload::Text(text) => text.len(),
                Payload::Bytes(bytes) => bytes.len(),
                _ => 0,
            };
            if size != length as u64 {
                return Err(D::Error::custom(
                    "sizeInBytes must match the payload byte length",
                ));
            }
        }
        Ok(Self {
            mime_type: wire.mime_type,
            payload,
            size_in_bytes: wire.size_in_bytes,
            part_number: wire.part_number,
            is_final: wire.is_final,
        })
    }
}

/// Options for [`AssetsClient::create`](crate::AssetsClient::create) and
/// [`classify`](crate::AssetsClient::classify). Supply exactly one of `content`, `part` (the
/// first part of a multipart upload) or `url`.
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubmitAsset {
    /// The asset name, such as a file name.
    pub name: String,
    /// The whole file.
    #[serde(default)]
    pub content: Option<Content>,
    /// The first part of a multipart upload; continue with `upload_part`.
    #[serde(default)]
    pub part: Option<Content>,
    /// A URL CalmLens downloads the file from.
    #[serde(default)]
    pub url: Option<String>,
    /// A description.
    #[serde(default)]
    pub description: Option<String>,
    /// Processing options.
    #[serde(default)]
    pub processing_options: Option<ProcessingOptions>,
    /// CDN visibility.
    #[serde(default)]
    pub visibility: Option<Visibility>,
    /// Metadata items.
    #[serde(default)]
    pub metadata: Option<Vec<MetadataItem>>,
    /// Your identifier for who wrote the content. CalmLens only compares it with the author IDs
    /// in `context`, to tell which posts share a speaker.
    #[serde(default)]
    pub author_id: Option<String>,
    /// Earlier posts in the conversation, oldest first. The SDK sends only the posts CalmLens
    /// uses; see [`select_moderation_context_items`].
    #[serde(default)]
    pub context: Option<ModerationContext>,
    /// Your ID for the asset, unique within the project.
    #[serde(default)]
    pub external_id: Option<String>,
    /// A link to the asset in your system.
    #[serde(default)]
    pub external_url: Option<String>,
    /// The folder to put the asset in.
    #[serde(default)]
    pub folder_id: Patch<String>,
    /// The upload preset to apply: its folder, visibility, file types and size limit.
    #[serde(default)]
    pub upload_preset_id: Option<String>,
    /// For a multipart upload, the size of the whole file; CalmLens then refuses an upload
    /// that could never finish, and parts that overshoot or fall short.
    #[serde(default)]
    pub total_size_in_bytes: Option<u64>,
    /// The `Idempotency-Key` for this upload. The SDK generates one when it is `None`.
    #[serde(default)]
    pub idempotency_key: Option<String>,
}

impl SubmitAsset {
    /// Text named `text`.
    pub fn text(text: impl Into<String>) -> Self {
        Self::new("text", Content::text(text))
    }
    /// An asset named `name` with `content`.
    pub fn new(name: impl Into<String>, content: Content) -> Self {
        Self {
            name: name.into(),
            content: Some(content),
            ..Self::default()
        }
    }
    /// An asset CalmLens downloads from `url`.
    pub fn from_url(name: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            url: Some(url.into()),
            ..Self::default()
        }
    }
    /// The first part of a multipart upload of the file `name`.
    pub fn multipart(name: impl Into<String>, part: Content) -> Self {
        Self {
            name: name.into(),
            part: Some(part),
            ..Self::default()
        }
    }
}

/// The most recent earlier posts CalmLens uses.
pub const MODERATION_CONTEXT_USED_ITEMS: usize = 5;
/// The most characters (Unicode code points) of earlier posts CalmLens uses. The newest post
/// always fits, since no post may be longer.
pub const MODERATION_CONTEXT_USED_CHARACTERS: usize = 2_000;

/// Earlier posts in a conversation, oldest first, that CalmLens reads to understand the content
/// it moderates.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModerationContext {
    /// The posts, oldest first.
    pub items: Vec<ModerationContextItem>,
}
impl ModerationContext {
    /// Context of `items`, oldest first.
    pub fn new(items: impl IntoIterator<Item = ModerationContextItem>) -> Self {
        Self {
            items: items.into_iter().collect(),
        }
    }
}

/// An earlier post in the conversation.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModerationContextItem {
    /// The post's text.
    pub text: String,
    /// Your identifier for who wrote the post.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub author_id: Option<String>,
}
impl ModerationContextItem {
    /// A post with `text` and no author.
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            author_id: None,
        }
    }
    /// Sets who wrote the post.
    pub fn author_id(mut self, author_id: impl Into<String>) -> Self {
        self.author_id = Some(author_id.into());
        self
    }
}

/// The earlier posts CalmLens uses: the most recent ones, newest first, while at most
/// [`MODERATION_CONTEXT_USED_ITEMS`] posts and [`MODERATION_CONTEXT_USED_CHARACTERS`]
/// characters allow, returned oldest first. Characters are Unicode code points. The newest post
/// is always kept, so an over-long one is left for the API to reject.
pub fn select_moderation_context_items(
    items: &[ModerationContextItem],
) -> Vec<ModerationContextItem> {
    let mut kept = 0;
    let mut characters = 0;
    for item in items.iter().rev() {
        if kept == MODERATION_CONTEXT_USED_ITEMS {
            break;
        }
        let length = item.text.chars().count();
        if kept > 0 && characters + length > MODERATION_CONTEXT_USED_CHARACTERS {
            break;
        }
        kept += 1;
        characters += length;
    }
    items[items.len() - kept..].to_vec()
}

/// A metadata item.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MetadataItem {
    /// The metadata field ID.
    pub id: String,
    /// The value.
    pub value: Value,
}
impl MetadataItem {
    /// A metadata item.
    pub fn new(id: impl Into<String>, value: impl Into<Value>) -> Self {
        Self {
            id: id.into(),
            value: value.into(),
        }
    }
}

/// Identifies an asset.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AssetId {
    /// The asset ID.
    pub asset_id: String,
}
impl AssetId {
    /// Identifies asset `asset_id`.
    pub fn new(asset_id: impl Into<String>) -> Self {
        Self {
            asset_id: asset_id.into(),
        }
    }
}

/// Options for [`AssetsClient::wait_for_decision`](crate::AssetsClient::wait_for_decision).
#[derive(Debug, Clone, Default)]
pub struct WaitForDecision {
    /// The asset ID.
    pub asset_id: String,
    /// How long to wait for a decision; 60 seconds when `None`.
    pub timeout: Option<std::time::Duration>,
}
impl WaitForDecision {
    /// Waits for asset `asset_id` with the default 60-second timeout.
    pub fn new(asset_id: impl Into<String>) -> Self {
        Self {
            asset_id: asset_id.into(),
            timeout: None,
        }
    }
    /// Sets how long to wait for a decision.
    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }
}

/// Identifies a folder.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FolderId {
    /// The folder ID.
    pub folder_id: String,
}
impl FolderId {
    /// Identifies folder `folder_id`.
    pub fn new(folder_id: impl Into<String>) -> Self {
        Self {
            folder_id: folder_id.into(),
        }
    }
}

/// A sort order.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Order {
    /// The field, e.g. `createdAt`.
    pub field: String,
    /// The direction.
    pub direction: SortDirection,
}

/// Options for listing assets.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListAssets {
    /// The cursor returned by the previous page.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    /// Items per page, 1 to 100.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub page_size: Option<u32>,
    /// A filter such as `classification.moderation.status==allowed`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub filter: Option<String>,
    /// Sort orders.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ordering: Option<Vec<Order>>,
    /// Lists only the assets directly in this folder.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub folder_id: Option<String>,
}

/// Options for listing an asset's children.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListChildren {
    /// The parent asset ID.
    pub asset_id: String,
    /// The cursor returned by the previous page.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    /// Items per page, 1 to 100.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub page_size: Option<u32>,
    /// A filter such as `classification.moderation.status==allowed`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub filter: Option<String>,
    /// Sort orders.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ordering: Option<Vec<Order>>,
}

/// Changes to an asset. [`Patch::Missing`] fields are left unchanged.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateAsset {
    /// The asset ID.
    #[serde(skip_serializing)]
    pub asset_id: String,
    /// The name.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub name: Patch<String>,
    /// The description.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub description: Patch<String>,
    /// The tags.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub tags: Patch<Vec<String>>,
    /// The metadata items.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub metadata: Patch<Vec<MetadataItem>>,
    /// The folder.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub folder_id: Patch<String>,
    /// Your ID for the asset.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub external_id: Patch<String>,
    /// A link to the asset in your system.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub external_url: Patch<String>,
    /// CDN visibility.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub visibility: Patch<Visibility>,
    /// Processing options.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub processing_options: Patch<ProcessingOptions>,
}

/// Options for [`AssetsClient::explain`](crate::AssetsClient::explain).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExplainAsset {
    /// The asset ID.
    #[serde(skip_serializing)]
    pub asset_id: String,
    /// Moderates the asset again with the project's current policy instead of explaining the
    /// decision as made.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub rerun: bool,
}

/// A reviewer's decision for [`AssetsClient::decide`](crate::AssetsClient::decide).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DecideAsset {
    /// The asset ID.
    #[serde(skip_serializing)]
    pub asset_id: String,
    /// The moderation status to set.
    pub decision: AssetModerationDecision,
    /// Why the reviewer made this decision, 1 to 1499 characters after trimming. It is kept in
    /// the asset's review history.
    pub note: String,
    /// Must be `true` to purge: purging permanently deletes the stored content.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub confirm_purge: bool,
}
impl DecideAsset {
    /// Records `decision` on asset `asset_id` with `note`. To purge, also set `confirm_purge`.
    pub fn new(
        asset_id: impl Into<String>,
        decision: AssetModerationDecision,
        note: impl Into<String>,
    ) -> Self {
        Self {
            asset_id: asset_id.into(),
            decision,
            note: note.into(),
            confirm_purge: false,
        }
    }
}

/// Moves an asset to a folder, or to the project root with `folder_id: None`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MoveAsset {
    /// The asset ID.
    #[serde(skip_serializing)]
    pub asset_id: String,
    /// The destination folder.
    pub folder_id: Option<String>,
}

/// What [`crate::AssetsClient::batch`] does to every asset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum AssetBatchOperation {
    /// Deletes each asset with its child assets and stored content.
    Delete,
    /// Removes each asset's stored content and keeps the record, metadata and report.
    RemoveContent,
}
impl AssetBatchOperation {
    /// The wire value.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Delete => "delete",
            Self::RemoveContent => "remove-content",
        }
    }
}
impl fmt::Display for AssetBatchOperation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Deletes up to 500 assets, or removes their stored content, in one request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BatchAssets {
    /// IDs of 1 to 500 assets in the project.
    pub asset_ids: Vec<String>,
    /// What to do to every asset.
    pub operation: AssetBatchOperation,
}

/// The response of [`crate::AssetsClient::batch`]: the operation is queued.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct BatchAssetsResponse {
    /// Always `true`: the operation is queued.
    pub queued: bool,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<BatchAssetsResponse, _>")]
    pub extra: HashMap<String, Value>,
}

/// A later part of a multipart upload.
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UploadPart {
    /// The asset returned when the upload started.
    pub asset_id: String,
    /// The part, with `part_number` set.
    pub part: Content,
    /// Overrides the `queue` choice saved when the upload started, for the final part.
    #[serde(default)]
    pub queue: Option<bool>,
    /// The `Idempotency-Key` for this part. The SDK generates one when it is `None`.
    #[serde(default)]
    pub idempotency_key: Option<String>,
}

/// Options for a signed asset URL.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignedUrlOptions {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional customer assertions for this CDN request.
    pub viewer_claims: Option<ViewerClaims>,
    /// The asset ID.
    #[serde(skip_serializing)]
    pub asset_id: String,
    /// `rendered` (the API's default) or `original`, which takes no lens or transform.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resource: Option<SignedUrlResource>,
    /// A lens identifier.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lens: Option<String>,
    /// A transform: a selector string or structured options, sent as a selector string.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transform: Option<CdnTransform>,
    /// Lifetime in seconds; defaults to 900.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_in_seconds: Option<u64>,
}

/// Options for creating a folder.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateFolder {
    /// The name, unique among folders with the same parent.
    pub name: String,
    /// The parent folder, or the project root when missing or null.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub parent_id: Patch<String>,
}

/// Changes to a folder.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateFolder {
    /// The folder ID.
    #[serde(skip_serializing)]
    pub folder_id: String,
    /// The new name.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub name: Patch<String>,
}

/// Moves a folder under another, or to the project root with `parent_id: None`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MoveFolder {
    /// The folder ID.
    #[serde(skip_serializing)]
    pub folder_id: String,
    /// The new parent.
    pub parent_id: Option<String>,
}

/// Options for one page of the events feed.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListEvents {
    /// A previous page's `next_cursor`. Without it, the page is empty and its `next_cursor`
    /// marks now.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    /// Events per page, 1 to 100 (the API's default is 50).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub page_size: Option<u32>,
}

/// A named lens definition.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LensDefinition {
    /// The lens identifier used in CDN URLs as `@identifier`.
    pub identifier: String,
    /// The display name.
    pub name: String,
    /// A description.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub description: Patch<String>,
    /// The asset type the lens applies to.
    #[serde(rename = "type")]
    pub lens_type: LensType,
    /// Whether the lens is active.
    pub active: bool,
    /// The definition version; bump it to change an existing lens.
    pub version: u32,
    /// The image transform options the lens applies.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub transform: Patch<ImageTransformOptions>,
}

/// Options for [`ServerClient::ensure_lenses`](crate::ServerClient::ensure_lenses).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnsureLenses {
    /// The lenses, returned in the same order.
    pub lenses: Vec<LensDefinition>,
}

/// A CDN request for an asset's rendered, original or placeholder resource.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CdnRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional customer assertions for this CDN request.
    pub viewer_claims: Option<ViewerClaims>,
    /// The asset ID or external ID.
    pub asset_identifier: String,
    /// `rendered` (default), `original` or `placeholder`. Only `rendered` takes a lens or transform.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resource: Option<CdnResource>,
    /// A lens identifier.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lens: Option<String>,
    /// A transform: a selector such as `width=320` or structured options.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transform: Option<CdnTransform>,
    /// The HTTP method and headers, e.g. `HEAD` or a `Range` header.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub init: Option<HttpOptions>,
}

/// HTTP method and headers for a CDN request. The SDK always sends its own API key.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HttpOptions {
    /// The method; defaults to `GET`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
    /// Extra request headers.
    #[serde(default)]
    pub headers: HashMap<String, String>,
}

/// An asset.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Asset {
    /// Effective action and age assurance for the requested viewer country.

    /// The asset ID.
    pub id: String,
    /// The owning project.
    #[serde(default)]
    pub project_id: Option<String>,
    /// The parent asset, for child assets CalmLens extracts during processing.
    #[serde(default)]
    pub parent_id: Option<String>,
    /// The folder, or `None` at the project root.
    #[serde(default)]
    pub folder_id: Option<String>,
    /// The upload preset the asset was uploaded through.
    #[serde(default)]
    pub upload_preset_id: Option<String>,
    /// Milliseconds since the Unix epoch.
    #[serde(default)]
    pub created_at: Option<u64>,
    /// Milliseconds since the Unix epoch.
    #[serde(default)]
    pub updated_at: Option<u64>,
    /// The asset type (`type` on the wire).
    #[serde(default, rename = "type")]
    pub asset_type: Option<AssetType>,
    /// The name.
    #[serde(default)]
    pub name: Option<String>,
    /// The description.
    #[serde(default)]
    pub description: Option<String>,
    /// Your ID for the asset.
    #[serde(default)]
    pub external_id: Option<String>,
    /// A link to the asset in your system.
    #[serde(default)]
    pub external_url: Option<String>,
    /// Metadata items.
    #[serde(default)]
    pub metadata: Option<Vec<MetadataItem>>,
    /// Your identifier for who wrote the content.
    #[serde(default)]
    pub author_id: Option<String>,
    /// The earlier posts CalmLens used, oldest first; `None` once the content is removed.
    #[serde(default)]
    pub context: Option<ModerationContext>,
    /// Tags.
    #[serde(default)]
    pub tags: Option<Vec<String>>,
    /// Processing options.
    #[serde(default)]
    pub processing_options: Option<ProcessingOptions>,
    /// CDN visibility.
    #[serde(default)]
    pub visibility: Option<Visibility>,
    /// Where the asset is in the pipeline.
    #[serde(default)]
    pub upload: AssetUpload,
    /// Classification progress, the moderation status and report.
    #[serde(default)]
    pub classification: AssetClassification,
    /// Whether CalmLens holds the content, and its details.
    #[serde(default)]
    pub content: AssetContent,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<Asset, _>")]
    pub extra: HashMap<String, Value>,
}
impl Asset {
    /// An asset with `id`, classification status `processing` and moderation status `moderation`,
    /// e.g. for a mock response.
    pub fn new(
        id: impl Into<String>,
        processing: AssetClassificationStatus,
        moderation: AssetModerationStatus,
    ) -> Self {
        Self {
            id: id.into(),
            upload: AssetUpload {
                status: "completed".into(),
                ..AssetUpload::default()
            },
            classification: AssetClassification {
                status: processing,
                moderation: AssetModeration {
                    status: moderation,
                    ..AssetModeration::default()
                },
                ..AssetClassification::default()
            },
            ..Self::default()
        }
    }
    /// Whether moderation has finished: the moderation status is no longer `pending`, or
    /// processing failed.
    pub fn is_decided(&self) -> bool {
        self.classification.moderation.status != AssetModerationStatus::Pending
            || self.classification.status == AssetClassificationStatus::Failed
    }
}

/// Source upload progress.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AssetUpload {
    /// Classification or upload progress.
    #[serde(default)]
    pub status: String,
    /// When the state last changed, in milliseconds since the Unix epoch.
    #[serde(default)]
    pub updated_at: Option<u64>,
    /// Number of multipart parts received; absent for other uploads.
    #[serde(default)]
    pub parts_received: Option<u32>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<AssetUpload, _>")]
    pub extra: HashMap<String, Value>,
}

/// Classification progress and capability results.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AssetClassification {
    /// Classification or upload progress.
    #[serde(default)]
    pub status: AssetClassificationStatus,
    /// Why processing failed, while `status` is `failed`; otherwise `None`.
    #[serde(default)]
    pub failure_reason: Option<AssetFailureReason>,
    /// When the state last changed, in milliseconds since the Unix epoch.
    #[serde(default)]
    pub updated_at: Option<u64>,
    /// When classification completed, in milliseconds since the Unix epoch.
    #[serde(default)]
    pub completed_at: Option<u64>,
    /// Content-safety findings and the decision in force.
    #[serde(default)]
    pub moderation: AssetModeration,
    /// Person detections when requested.
    #[serde(default)]
    pub person_detection: Option<PersonDetectionResult>,
    /// Face detections when requested.
    #[serde(default)]
    pub face_detection: Option<FaceDetectionResult>,
    /// Links and QR codes found when requested.
    #[serde(default)]
    pub link_detection: Option<LinkDetectionResult>,
    /// Preview. Every link found in the asset, where it leads and its verdict. Present when the
    /// project's policy acts on links; it is not requested through
    /// [`ProcessingOptions::features`].
    #[serde(default)]
    pub link_safety: Option<LinkSafetyResult>,
    /// AI-generation provenance when requested.
    #[serde(default)]
    pub ai_generated_detection: Option<AiGeneratedDetectionResult>,
    /// Text regions found in the image, which image transforms can redact.
    #[serde(default)]
    pub text_regions: Option<Vec<TextRegion>>,
    /// Detected content labels.
    #[serde(default)]
    pub labels: Option<Vec<ClassificationLabel>>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<AssetClassification, _>")]
    pub extra: HashMap<String, Value>,
}

/// One reviewer decision in an asset's review history.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AssetReview {
    /// Unique identifier for this review.
    pub id: String,
    /// The reviewer’s decision.
    pub decision: AssetModerationDecision,
    /// The reviewer’s explanation; required for an override.
    pub note: Option<String>,
    /// The reviewing user's name, when known.
    #[serde(default)]
    pub reviewer_name: Option<String>,
    /// The reviewing user's email address, when known.
    #[serde(default)]
    pub reviewer_email: Option<String>,
    /// Review time in milliseconds since the Unix epoch.
    pub reviewed_at: u64,
    /// Whether this review changed the asset's moderation status.
    pub applied_to_asset: bool,
}

/// Content-safety findings and decision.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AssetModeration {
    /// Category outcomes supplied by an authenticated test input.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub test_category_actions: Option<HashMap<ClassificationCategory, String>>,
    /// Regional restrictions supplied by an authenticated test input.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub test_regional_actions: Option<Vec<TestRegionalAction>>,
    /// Reviews in chronological order.
    #[serde(default)]
    pub manual_reviews: Vec<AssetReview>,
    /// The moderation decision in force, which also decides delivery, with reviewer decisions
    /// taking precedence.
    #[serde(default)]
    pub status: AssetModerationStatus,
    /// The original automated action, before manual reviews.
    #[serde(default)]
    pub automated_action: Option<String>,
    /// What determined the automated action.
    #[serde(default)]
    pub source: Option<String>,
    /// Mandatory rule that determined the automated action.
    #[serde(default)]
    pub rule: Option<String>,
    /// Categories acted on by automation.
    #[serde(default)]
    pub flagged_categories: Vec<ClassificationCategory>,
    /// Stricter regional outcomes.
    #[serde(default)]
    pub regions: Vec<RegionalDecision>,
    /// Whether the saved decision has a complete explanation.
    #[serde(default)]
    pub explanation_complete: Option<bool>,
    /// Policy-adjusted category results.
    #[serde(default)]
    pub categories: HashMap<ClassificationCategory, CategoryPolicyScore>,
    /// Detection findings before policy evaluation.
    #[serde(default)]
    pub raw: Option<ModerationRaw>,
    /// Preview. What the policy's link-safety section made of the asset's links; `None` when
    /// the policy doesn't act on links.
    #[serde(default)]
    pub link_safety: Option<LinkSafetyDecision>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<AssetModeration, _>")]
    pub extra: HashMap<String, Value>,
}

/// A regional restriction supplied by an authenticated test input.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct TestRegionalAction {
    /// The jurisdiction receiving the restriction.
    pub region: String,
    /// The delivery restriction.
    pub action: String,
}

/// Whether CalmLens holds an asset's content, and the content's details.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AssetContent {
    /// `temporary` until processing finishes, `stored`, or `removed`.
    #[serde(default)]
    pub status: AssetContentStatus,
    /// Why the content was removed; `None` while it is held.
    #[serde(default)]
    pub removal_reason: Option<AssetContentRemovalReason>,
    /// When the content status last changed, in milliseconds since the Unix epoch.
    #[serde(default)]
    pub updated_at: Option<u64>,
    /// A safety hold restricting access.
    #[serde(default)]
    pub safety_hold: Option<SafetyHold>,
    /// The MIME type.
    #[serde(default)]
    pub format: Option<String>,
    /// The file extension.
    #[serde(default)]
    pub extension: Option<String>,
    /// The uploaded size in bytes.
    #[serde(default)]
    pub size_in_bytes: Option<u64>,
    /// Digests of the uploaded content.
    #[serde(default)]
    pub checksums: Option<Checksums>,
    /// The picture served at the rendered resource, `None` when the asset has none.
    #[serde(default)]
    pub image: Option<AssetImage>,
    /// Text extracted from the content.
    #[serde(default)]
    pub extracted_text: Option<ExtractedText>,
    /// Metadata embedded in an uploaded image, such as its capture time, camera and software.
    /// Read-only and separate from the asset's own `metadata`; `None` when the image declares
    /// none, for other asset types, once the content is removed and while the asset is held.
    #[serde(default)]
    pub file_metadata: Option<FileMetadata>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<AssetContent, _>")]
    pub extra: HashMap<String, Value>,
}

/// Detection findings before policy evaluation.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ModerationRaw {
    /// Raw category scores, qualifiers and conditions.
    #[serde(default)]
    pub categories: HashMap<ClassificationCategory, CategoryResult>,
    /// Timed findings from audio or video.
    #[serde(default)]
    pub timeline: Option<MediaClassificationReport>,
    /// Matches against project hash lists.
    #[serde(default)]
    pub hash_matches: Option<Vec<HashMatch>>,
}

/// How strongly a category meets the policy, from 0 to 1, and what the policy does with it.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CategoryPolicyScore {
    /// The policy score.
    #[serde(default)]
    pub score: f64,
    /// `allow`, `limit`, `age-restrict`, `block` or `purge`.
    #[serde(default)]
    pub action: String,
    /// The rule that decided the category, or that its policy score stayed below 50%.
    #[serde(default)]
    pub source: Option<CategoryPolicySource>,
    /// Settings at decision time, independent of subsequent policy edits.
    #[serde(default)]
    pub settings: Option<CategoryPolicySettingsSnapshot>,
}

/// The rule that decided the outcome, or that the policy score stayed below 50%.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CategoryPolicySource {
    /// Saved kind.
    #[serde(default)]
    pub kind: String,
    /// Saved index.
    #[serde(default)]
    pub index: Option<usize>,
    /// Indexes of allowances contributing combined coverage.
    #[serde(default)]
    pub indexes: Option<Vec<usize>>,
}

/// A named rule in force when the asset was decided.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct PolicyRuleSnapshot {
    /// Saved name.
    #[serde(default)]
    pub name: Option<String>,
    /// Saved when.
    #[serde(default)]
    pub when: Vec<String>,
    /// Fixed all tag: selected qualifiers apply to the same instance.
    #[serde(default)]
    pub r#match: Option<String>,
    /// Same-instance exclusions.
    #[serde(default)]
    pub unless: Option<Vec<String>>,
    /// Saved action.
    #[serde(default)]
    pub action: String,
}

/// Historical category settings for explaining the decision.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CategoryPolicySettingsSnapshot {
    /// Saved category action.
    #[serde(default)]
    pub category_action: String,
    /// Saved allowances.
    #[serde(default)]
    pub allowances: Vec<PolicyRuleSnapshot>,
    /// Saved restrictions.
    #[serde(default)]
    pub restrictions: Vec<PolicyRuleSnapshot>,
}

/// The final automatic action, its source and flagged categories.
/// A recorded regional decision.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RegionalDecision {
    /// Viewer country or rule jurisdiction.
    pub region: String,
    /// Regional moderation action.
    pub action: String,
    /// Stable mandatory rule key.
    pub rule: String,
    /// Category matched by the rule; absent for explicit test regional outcomes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub category: Option<ClassificationCategory>,
}

/// One category's result.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CategoryResult {
    /// Whether the category was assessed.
    #[serde(default)]
    pub status: Option<EvaluationStatus>,
    /// The score from 0 to 1, unless `status` is `NotEvaluated`.
    #[serde(default)]
    pub score: Option<f64>,
    /// The likelihood, unless `status` is `NotEvaluated`.
    #[serde(default)]
    pub likelihood: Option<Likelihood>,
    /// Why the category was not assessed.
    #[serde(default)]
    pub reason: Option<NotEvaluatedReason>,
    /// Qualifier results.
    #[serde(default)]
    pub qualifiers: Option<HashMap<ModerationQualifier, QualifierResult>>,
    /// Direct condition evidence, keyed by opaque condition identifiers.
    #[serde(default)]
    pub policy_conditions: Option<HashMap<String, PolicyConditionResult>>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<CategoryResult, _>")]
    pub extra: HashMap<String, Value>,
}

/// Direct assessment of a same-instance or combined-coverage policy condition.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct PolicyConditionResult {
    /// Whether the condition was assessed.
    #[serde(default)]
    pub status: Option<EvaluationStatus>,
    /// Assessed score, absent when unassessed.
    #[serde(default)]
    pub score: Option<f64>,
    /// Why the condition was not assessed.
    #[serde(default)]
    pub reason: Option<NotEvaluatedReason>,
}

/// A qualifier's result.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct QualifierResult {
    /// Confidence that the content is only this qualifier, from 0 to 1; never above `some_score`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub all_score: Option<f64>,
    /// Whether the qualifier was assessed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<EvaluationStatus>,
    /// Confidence that some of the content is this qualifier, from 0 to 1, when evaluated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub some_score: Option<f64>,
    /// The likelihood, when evaluated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub likelihood: Option<Likelihood>,
    /// Why the qualifier was not assessed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<NotEvaluatedReason>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<QualifierResult, _>")]
    pub extra: HashMap<String, Value>,
}

string_enum! {
    /// Whether a feature produced a result.
    FeatureResultStatus {
        /// The feature ran; its results are present.
        Evaluated = "evaluated",
        /// The feature did not run; `reason` says why.
        NotEvaluated = "not-evaluated",
    }
}

string_enum! {
    /// How mature a feature is. Beta results may change shape.
    FeatureStage {
        /// Beta.
        Beta = "beta",
        /// Generally available.
        Ga = "ga",
    }
}

string_enum! {
    /// Why a requested feature did not run.
    FeatureNotEvaluatedReason {
        /// The feature does not apply to this asset, e.g. a text asset.
        NotSupported = "not-supported",
        /// The feature could not run this time.
        Unavailable = "unavailable",
    }
}

/// Results of the features requested in [`ProcessingOptions::features`], keyed by feature.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProcessingFeatureResults {
    /// Person detection results.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub person_detection: Option<PersonDetectionResult>,
    /// Face detection results.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub face_detection: Option<FaceDetectionResult>,
    /// Fields this SDK version does not know.
    #[serde(
        flatten,
        deserialize_with = "extra_fields::<ProcessingFeatureResults, _>"
    )]
    pub extra: HashMap<String, Value>,
}

/// Person detection's result. `people` is present when `status` is `Evaluated`, and `reason`
/// when it is `NotEvaluated`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct PersonDetectionResult {
    /// Whether the feature ran.
    #[serde(default)]
    pub status: Option<FeatureResultStatus>,
    /// The feature's stage.
    #[serde(default)]
    pub stage: Option<FeatureStage>,
    /// Why the feature did not run.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<FeatureNotEvaluatedReason>,
    /// The people found.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub people: Option<Vec<DetectedPerson>>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<PersonDetectionResult, _>")]
    pub extra: HashMap<String, Value>,
}

/// Face detection's result. `faces` is present when `status` is `Evaluated`, and `reason`
/// when it is `NotEvaluated`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct FaceDetectionResult {
    /// Whether the feature ran.
    #[serde(default)]
    pub status: Option<FeatureResultStatus>,
    /// The feature's stage.
    #[serde(default)]
    pub stage: Option<FeatureStage>,
    /// Why the feature did not run.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<FeatureNotEvaluatedReason>,
    /// The faces found.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub faces: Option<Vec<DetectedFace>>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<FaceDetectionResult, _>")]
    pub extra: HashMap<String, Value>,
}

/// Link detection's result. `qr_codes` and `links` are present when `status` is `Evaluated`,
/// and `reason` when it is `NotEvaluated`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LinkDetectionResult {
    /// Whether the feature ran.
    #[serde(default)]
    pub status: Option<FeatureResultStatus>,
    /// The feature's stage.
    #[serde(default)]
    pub stage: Option<FeatureStage>,
    /// Why the feature did not run.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<FeatureNotEvaluatedReason>,
    /// The QR codes found.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub qr_codes: Option<Vec<DetectedQrCode>>,
    /// The links found in QR codes and text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<DetectedLink>>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<LinkDetectionResult, _>")]
    pub extra: HashMap<String, Value>,
}

/// A detected QR code.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct DetectedQrCode {
    /// The decoded value.
    #[serde(default)]
    pub value: String,
    /// Where the QR code is (`box` on the wire).
    #[serde(default, rename = "box")]
    pub bounding_box: BoundingBox,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<DetectedQrCode, _>")]
    pub extra: HashMap<String, Value>,
}

string_enum! {
    /// Where a detected link was found.
    LinkSource {
        /// In a QR code.
        QrCode = "qr-code",
        /// In the image's text.
        Text = "text",
    }
}

/// A detected link.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct DetectedLink {
    /// The URL.
    #[serde(default)]
    pub url: String,
    /// Where it was found.
    #[serde(default)]
    pub source: LinkSource,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<DetectedLink, _>")]
    pub extra: HashMap<String, Value>,
}

/// Preview. Link safety's result. `links` is present when `status` is `Evaluated`, and `reason`
/// when it is `NotEvaluated`. Link checks never change a moderation category's score.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LinkSafetyResult {
    /// Whether the feature ran.
    #[serde(default)]
    pub status: Option<FeatureResultStatus>,
    /// The feature's stage.
    #[serde(default)]
    pub stage: Option<FeatureStage>,
    /// Why the feature did not run.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<FeatureNotEvaluatedReason>,
    /// Every link found in the asset and what its destination is.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<CheckedLink>>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<LinkSafetyResult, _>")]
    pub extra: HashMap<String, Value>,
}

string_enum! {
    /// Preview. What a link's destination is.
    LinkSafetyVerdict {
        /// Every reputation check passed.
        Safe = "safe",
        /// The domain's content categories mark it as adult.
        Adult = "adult",
        /// The domain's content categories mark it as gambling.
        Gambling = "gambling",
        /// A threat list or the domain's security risks mark it as phishing.
        Phishing = "phishing",
        /// A threat list or the domain's security risks mark it as malware.
        Malware = "malware",
        /// A short link or redirect chain could not be followed, or a check failed.
        Unresolved = "unresolved",
    }
}

string_enum! {
    /// Preview. What happens to an asset over its links. Purging content over a link is never
    /// offered.
    LinkSafetyAction {
        /// Take no action.
        Allow = "allow",
        /// Deliver normally, but mark the asset `limited` so your app can reduce its reach.
        Limit = "limit",
        /// Deliver only through signed URLs or with an API key, so your backend can limit it to
        /// adults.
        AgeRestrict = "age-restrict",
        /// Block delivery while keeping the content.
        Block = "block",
    }
}

string_enum! {
    /// Preview. A reputation check of a link, every address it redirects through and its
    /// destination.
    LinkSafetyCheck {
        /// The content categories and security risks of every domain on the way.
        DomainCategories = "domain-categories",
        /// A threat-list lookup of every URL on the way.
        ThreatLists = "threat-lists",
    }
}

string_enum! {
    /// Preview. Whether a link check answered.
    LinkSafetyCheckStatus {
        /// The check answered.
        Checked = "checked",
        /// The check could not answer, which makes the link `unresolved`.
        Failed = "failed",
    }
}

/// Preview. A link in the asset and what its destination is.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CheckedLink {
    /// The link as found, with `https://` added when it was left out.
    #[serde(default)]
    pub url: String,
    /// Where the link leads after following its redirects; `None` when a short link or
    /// redirect chain could not be followed.
    #[serde(default)]
    pub final_url: Option<String>,
    /// How many redirects were followed to reach `final_url`.
    #[serde(default)]
    pub redirects: u32,
    /// Where it was found.
    #[serde(default)]
    pub source: LinkSource,
    /// What its destination is: the most severe finding of any address on the way.
    #[serde(default)]
    pub verdict: LinkSafetyVerdict,
    /// The reputation checks of the link, its redirects and its destination.
    #[serde(default)]
    pub evidence: Vec<LinkSafetyEvidence>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<CheckedLink, _>")]
    pub extra: HashMap<String, Value>,
}

/// Preview. One reputation check of a link, every address it redirects through and its
/// destination.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LinkSafetyEvidence {
    /// Which check this is.
    #[serde(default)]
    pub check: LinkSafetyCheck,
    /// Whether the check answered.
    #[serde(default)]
    pub status: LinkSafetyCheckStatus,
    /// What the check reported for any of the addresses, such as the domains' content categories
    /// and security risks or the threat types listed.
    #[serde(default)]
    pub labels: Vec<String>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<LinkSafetyEvidence, _>")]
    pub extra: HashMap<String, Value>,
}

/// Preview. What a policy's link-safety section made of an asset's links.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LinkSafetyDecision {
    /// The strongest action the asset's links take under the policy's link-safety settings.
    #[serde(default)]
    pub action: LinkSafetyAction,
    /// Indexes into [`LinkSafetyResult::links`] of the links that take that action.
    #[serde(default)]
    pub links: Vec<u32>,
    /// The link-safety settings in force at decision time.
    #[serde(default)]
    pub settings: LinkSafetySettings,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<LinkSafetyDecision, _>")]
    pub extra: HashMap<String, Value>,
}

/// Preview. What happens to assets that link to unsafe destinations. Link checks never change a
/// moderation category's score.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LinkSafetySettings {
    /// What happens to an asset with a link of each verdict. A verdict left out is allowed;
    /// `safe` is never a key.
    #[serde(default)]
    pub verdict_actions: HashMap<LinkSafetyVerdict, LinkSafetyAction>,
    /// Acts on every link whose destination is outside the allowed domains, whatever its
    /// verdict.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub off_platform_links: Option<OffPlatformLinks>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<LinkSafetySettings, _>")]
    pub extra: HashMap<String, Value>,
}

/// Preview. The action for links that lead outside the allowed domains.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct OffPlatformLinks {
    /// What happens to an asset with such a link; never `Allow`.
    #[serde(default)]
    pub action: LinkSafetyAction,
    /// Bare lowercase domains, such as `example.com`, whose links are on platform. A domain
    /// also covers its subdomains.
    #[serde(default)]
    pub allowed_domains: Vec<String>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<OffPlatformLinks, _>")]
    pub extra: HashMap<String, Value>,
}

string_enum! {
    /// What provenance metadata says about how an image was made.
    AiProvenance {
        /// Generated by AI.
        AiGenerated = "ai-generated",
        /// Edited with AI.
        AiEdited = "ai-edited",
        /// No provenance metadata says either way.
        Undetermined = "unknown",
    }
}

string_enum! {
    /// The kind of provenance metadata a signal came from.
    AiSignalKind {
        /// A C2PA manifest.
        C2pa = "c2pa",
        /// An IPTC digital source type.
        IptcDigitalSourceType = "iptc-digital-source-type",
        /// Metadata naming a generator.
        GeneratorMetadata = "generator-metadata",
    }
}

/// AI-generation detection's result. `provenance` and `signals` are present when `status` is
/// `Evaluated`, and `reason` when it is `NotEvaluated`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AiGeneratedDetectionResult {
    /// Whether the feature ran.
    #[serde(default)]
    pub status: Option<FeatureResultStatus>,
    /// The feature's stage.
    #[serde(default)]
    pub stage: Option<FeatureStage>,
    /// Why the feature did not run.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<FeatureNotEvaluatedReason>,
    /// What the metadata says.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provenance: Option<AiProvenance>,
    /// The metadata found.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signals: Option<Vec<AiGeneratedSignal>>,
    /// Fields this SDK version does not know.
    #[serde(
        flatten,
        deserialize_with = "extra_fields::<AiGeneratedDetectionResult, _>"
    )]
    pub extra: HashMap<String, Value>,
}

/// One piece of provenance metadata.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AiGeneratedSignal {
    /// The kind of metadata.
    #[serde(default)]
    pub kind: AiSignalKind,
    /// Its value.
    #[serde(default)]
    pub value: String,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<AiGeneratedSignal, _>")]
    pub extra: HashMap<String, Value>,
}

/// A region of text found in an image.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct TextRegion {
    /// Where the text is (`box` on the wire).
    #[serde(default, rename = "box")]
    pub bounding_box: BoundingBox,
    /// Whether the text holds personal information.
    #[serde(default)]
    pub personal_information: bool,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<TextRegion, _>")]
    pub extra: HashMap<String, Value>,
}

/// A hash list entry an image matched.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct HashMatch {
    /// Where the match came from: `hash-list`.
    #[serde(default)]
    pub source: String,
    /// The hash list.
    #[serde(default)]
    pub list_id: String,
    /// The matched entry.
    #[serde(default)]
    pub entry_id: String,
    /// The Hamming distance between the hashes; lower is closer.
    #[serde(default)]
    pub distance: f64,
    /// What the list does with matches.
    #[serde(default)]
    pub action: HashListAction,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<HashMatch, _>")]
    pub extra: HashMap<String, Value>,
}

/// A detected person.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct DetectedPerson {
    /// Where the person is (`box` on the wire).
    #[serde(default, rename = "box")]
    pub bounding_box: BoundingBox,
    /// Detection confidence from 0 to 1.
    #[serde(default)]
    pub confidence: f64,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<DetectedPerson, _>")]
    pub extra: HashMap<String, Value>,
}

/// A detected face.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct DetectedFace {
    /// Where the face is (`box` on the wire).
    #[serde(default, rename = "box")]
    pub bounding_box: BoundingBox,
    /// Detection confidence from 0 to 1.
    #[serde(default)]
    pub confidence: f64,
    /// The estimated age range, when age estimation was requested.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub age_range: Option<AgeRange>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<DetectedFace, _>")]
    pub extra: HashMap<String, Value>,
}

/// Position and size as fractions of the image width and height, from 0 to 1. `left` and
/// `top` can be slightly negative when the subject extends past the edge.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct BoundingBox {
    /// The left edge.
    #[serde(default)]
    pub left: f64,
    /// The top edge.
    #[serde(default)]
    pub top: f64,
    /// The width.
    #[serde(default)]
    pub width: f64,
    /// The height.
    #[serde(default)]
    pub height: f64,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<BoundingBox, _>")]
    pub extra: HashMap<String, Value>,
}

/// An estimated age range in years. Estimates can be off by several years.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AgeRange {
    /// The lowest estimated age.
    #[serde(default)]
    pub low: u32,
    /// The highest estimated age.
    #[serde(default)]
    pub high: u32,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<AgeRange, _>")]
    pub extra: HashMap<String, Value>,
}

/// A classification label.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ClassificationLabel {
    /// The label.
    #[serde(default)]
    pub description: String,
    /// The score.
    #[serde(default)]
    pub score: f64,
    /// The topicality score.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub topicality_score: Option<f64>,
    /// The likelihood.
    #[serde(default)]
    pub likelihood: Likelihood,
    /// A knowledge base ID.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub knowledge_base_id: Option<String>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<ClassificationLabel, _>")]
    pub extra: HashMap<String, Value>,
}

/// Audio and video moderation results.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct MediaClassificationReport {
    /// The media duration.
    #[serde(default)]
    pub duration_seconds: f64,
    /// The interval between sampled frames.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub frame_interval_seconds: Option<f64>,
    /// The number of sampled frames.
    #[serde(default)]
    pub sampled_frames: u32,
    /// Whether the audio was transcribed.
    #[serde(default)]
    pub audio_transcribed: bool,
    /// Results by time segment.
    #[serde(default)]
    pub segments: Vec<MediaClassificationSegment>,
    /// Fields this SDK version does not know.
    #[serde(
        flatten,
        deserialize_with = "extra_fields::<MediaClassificationReport, _>"
    )]
    pub extra: HashMap<String, Value>,
}

/// A time segment's results.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct MediaClassificationSegment {
    /// What the scores come from.
    #[serde(default)]
    pub source: MediaSegmentSource,
    /// The segment start.
    #[serde(default)]
    pub start_seconds: f64,
    /// The segment end.
    #[serde(default)]
    pub end_seconds: f64,
    /// Results by category.
    #[serde(default)]
    pub categories: HashMap<ClassificationCategory, CategoryResult>,
    /// Fields this SDK version does not know.
    #[serde(
        flatten,
        deserialize_with = "extra_fields::<MediaClassificationSegment, _>"
    )]
    pub extra: HashMap<String, Value>,
}

/// A page of assets.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AssetPage {
    /// The assets on this page.
    #[serde(default)]
    pub items: Vec<Asset>,
    /// The cursor for the next page, or None.
    #[serde(default)]
    pub next_cursor: Option<String>,
    /// The page size.
    #[serde(default)]
    pub page_size: Option<u32>,
    /// Whether another page follows.
    #[serde(default)]
    pub has_more: Option<bool>,
    /// The sort orders applied.
    #[serde(default)]
    pub ordering: Option<Vec<Order>>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<AssetPage, _>")]
    pub extra: HashMap<String, Value>,
}
impl AssetPage {
    /// A page of `items`, with `has_more`, e.g. for a mock response.
    pub fn new(items: Vec<Asset>, has_more: bool) -> Self {
        Self {
            items,
            has_more: Some(has_more),
            ..Self::default()
        }
    }
}

/// A folder.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Folder {
    /// The folder ID.
    pub id: String,
    /// The name.
    #[serde(default)]
    pub name: Option<String>,
    /// The parent folder, or `None` at the project root.
    #[serde(default)]
    pub parent_id: Option<String>,
    /// The owning project.
    #[serde(default)]
    pub project_id: Option<String>,
    /// Milliseconds since the Unix epoch.
    #[serde(default)]
    pub created_at: Option<u64>,
    /// Milliseconds since the Unix epoch.
    #[serde(default)]
    pub updated_at: Option<u64>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<Folder, _>")]
    pub extra: HashMap<String, Value>,
}
impl Folder {
    /// A folder with `id`, `name` and `parent_id`, e.g. for a mock response.
    pub fn new(id: impl Into<String>, name: impl Into<String>, parent_id: Option<String>) -> Self {
        Self {
            id: id.into(),
            name: Some(name.into()),
            parent_id,
            ..Self::default()
        }
    }
}

/// An event fact registered for the event type.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EventFact {
    /// The registered fact key, e.g. `reviewer`.
    pub key: String,
    /// The value.
    pub value: Value,
    /// A link for the fact.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<EventFact, _>")]
    pub extra: HashMap<String, Value>,
}

/// An event from the events feed.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Event {
    /// The event ID.
    pub id: String,
    /// The event type (`type` on the wire).
    #[serde(default, rename = "type")]
    pub event_type: Option<EventType>,
    /// Milliseconds since the Unix epoch.
    #[serde(default)]
    pub created_at: Option<u64>,
    /// The owning project.
    #[serde(default)]
    pub project_id: Option<String>,
    /// The severity.
    #[serde(default)]
    pub severity: Option<EventSeverity>,
    /// The title.
    #[serde(default)]
    pub title: Option<String>,
    /// The description.
    #[serde(default)]
    pub description: Option<String>,
    /// The asset the event concerns.
    #[serde(default)]
    pub asset_id: Option<String>,
    /// Snapshot of the asset's state when the event was created. Retrieve the
    /// asset for its current state.
    #[serde(default)]
    pub asset: Option<EventAsset>,
    /// The event's facts.
    #[serde(default)]
    pub facts: Vec<EventFact>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<Event, _>")]
    pub extra: HashMap<String, Value>,
}
impl Event {
    /// An event with `id` and `event_type`, e.g. for a mock response.
    pub fn new(id: impl Into<String>, event_type: impl Into<EventType>) -> Self {
        Self {
            id: id.into(),
            event_type: Some(event_type.into()),
            ..Self::default()
        }
    }
}

/// The JSON body of a webhook delivery: the event in the same shape as an [`Event`] from the
/// events feed. Read it with [`crate::construct_webhook_event`], which checks the fields' types
/// first; [`json`](Self::json) returns the body as received, including fields this SDK version
/// does not model.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct WebhookEventPayload {
    /// The event ID; deduplicate deliveries with it.
    pub id: String,
    /// The event type (`type` on the wire).
    #[serde(rename = "type")]
    pub event_type: EventType,
    /// Milliseconds since the Unix epoch.
    pub created_at: u64,
    /// The owning project.
    pub project_id: String,
    /// The severity.
    #[serde(default)]
    pub severity: Option<EventSeverity>,
    /// The title.
    #[serde(default)]
    pub title: Option<String>,
    /// The description, or `None` when the event has none.
    #[serde(default)]
    pub description: Option<String>,
    /// The asset the event concerns, or `None`.
    #[serde(default)]
    pub asset_id: Option<String>,
    /// Snapshot of the asset's state when the event was created, or `None`. Retrieve the asset
    /// for its current state.
    #[serde(default)]
    pub asset: Option<EventAsset>,
    /// The event's facts.
    #[serde(default)]
    pub facts: Vec<EventFact>,
    /// The body this payload was parsed from.
    #[serde(skip)]
    received: Option<Value>,
}
impl WebhookEventPayload {
    /// The delivery body CalmLens sends for `event`, e.g. to test a webhook handler.
    pub fn from_event(event: &Event) -> Self {
        Self {
            id: event.id.clone(),
            event_type: event.event_type.clone().unwrap_or_default(),
            created_at: event.created_at.unwrap_or_default(),
            project_id: event.project_id.clone().unwrap_or_default(),
            severity: event.severity.clone(),
            title: event.title.clone(),
            description: event.description.clone(),
            asset_id: event.asset_id.clone(),
            asset: event.asset.clone(),
            facts: event.facts.clone(),
            received: None,
        }
    }
    /// Whether this is a test send from the portal or API: its facts include `test` with the
    /// value `true`. Handle test sends without acting on the asset they name.
    pub fn is_test(&self) -> bool {
        self.facts
            .iter()
            .any(|fact| fact.key == "test" && fact.value == Value::Bool(true))
    }
    /// The delivery as JSON: the body exactly as received for a parsed delivery (unknown fields
    /// included), otherwise this payload serialized.
    pub fn json(&self) -> Value {
        self.received
            .clone()
            .unwrap_or_else(|| serde_json::to_value(self).unwrap_or(Value::Null))
    }
    pub(crate) fn received(mut self, body: Value) -> Self {
        self.received = Some(body);
        self
    }
}

/// Snapshot of an asset's state when an event was created, holding the fields CalmLens sent
/// (fields this SDK version does not know included). Read them with the accessors, or
/// [`get`](Self::get) for any other field; retrieve the asset for its current state.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct EventAsset(serde_json::Map<String, Value>);
impl EventAsset {
    /// A snapshot of asset `id` with classification status `processing`, moderation status
    /// `moderation`, content status `content` and a completed upload, e.g. for a mock event.
    pub fn new(
        id: impl Into<String>,
        processing: AssetClassificationStatus,
        moderation: AssetModerationStatus,
        content: AssetContentStatus,
    ) -> Self {
        let value = serde_json::json!({
            "id": id.into(),
            "upload": {"status": "completed"},
            "classification": {"status": processing, "moderation": {"status": moderation}},
            "content": {"status": content},
        });
        match value {
            Value::Object(map) => Self(map),
            _ => Self::default(),
        }
    }
    /// The snapshot's fields.
    pub fn from_json(fields: serde_json::Map<String, Value>) -> Self {
        Self(fields)
    }
    /// The asset ID.
    pub fn id(&self) -> &str {
        self.text(&["id"]).unwrap_or_default()
    }
    /// Your ID for the asset, if you set one.
    pub fn external_id(&self) -> Option<&str> {
        self.text(&["externalId"])
    }
    /// The upload preset used to create the asset, if any.
    pub fn upload_preset_id(&self) -> Option<&str> {
        self.text(&["uploadPresetId"])
    }
    /// The upload status, such as `completed`.
    pub fn upload_status(&self) -> Option<&str> {
        self.text(&["upload", "status"])
    }
    /// The classification status when the event was created.
    pub fn classification_status(&self) -> Option<AssetClassificationStatus> {
        self.text(&["classification", "status"]).map(Into::into)
    }
    /// The moderation status when the event was created, which also decides delivery.
    pub fn moderation_status(&self) -> Option<AssetModerationStatus> {
        self.text(&["classification", "moderation", "status"])
            .map(Into::into)
    }
    /// Whether CalmLens held the content when the event was created.
    pub fn content_status(&self) -> Option<AssetContentStatus> {
        self.text(&["content", "status"]).map(Into::into)
    }
    /// A top-level field of the snapshot.
    pub fn get(&self, field: &str) -> Option<&Value> {
        self.0.get(field)
    }
    /// The snapshot's fields.
    pub fn as_json(&self) -> &serde_json::Map<String, Value> {
        &self.0
    }
    fn text(&self, path: &[&str]) -> Option<&str> {
        let (last, parents) = path.split_last()?;
        let mut object = &self.0;
        for parent in parents {
            object = object.get(*parent)?.as_object()?;
        }
        object.get(*last)?.as_str()
    }
}

/// A page of the events feed.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct EventsPage {
    /// The events, oldest first.
    #[serde(default)]
    pub items: Vec<Event>,
    /// Pass as `cursor` to continue. Unlike other pages it is always set: store it between
    /// polls to receive later events.
    #[serde(default)]
    pub next_cursor: String,
    /// Whether more events are available now.
    #[serde(default)]
    pub has_more: bool,
    /// Event types this feed never includes, because the API key lacks the permission to see
    /// them. Give the key that permission to receive them.
    #[serde(default)]
    pub excluded_types: Vec<EventType>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<EventsPage, _>")]
    pub extra: HashMap<String, Value>,
}
impl EventsPage {
    /// A page of `items`, e.g. for a mock response.
    pub fn new(items: Vec<Event>, next_cursor: impl Into<String>, has_more: bool) -> Self {
        Self {
            items,
            next_cursor: next_cursor.into(),
            has_more,
            excluded_types: Vec::new(),
            extra: HashMap::new(),
        }
    }
}

/// A lens.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Lens {
    /// The lens ID.
    #[serde(default)]
    pub id: Option<String>,
    /// The identifier.
    pub identifier: String,
    /// The display name.
    #[serde(default)]
    pub name: Option<String>,
    /// The asset type the lens applies to (`type` on the wire).
    #[serde(default, rename = "type")]
    pub lens_type: Option<LensType>,
    /// Whether the lens is active.
    #[serde(default)]
    pub active: Option<bool>,
    /// The definition version.
    #[serde(default)]
    pub version: Option<u32>,
    /// The owning project.
    #[serde(default)]
    pub project_id: Option<String>,
    /// The user who created the lens.
    #[serde(default)]
    pub user_id: Option<String>,
    /// Milliseconds since the Unix epoch.
    #[serde(default)]
    pub created_at: Option<u64>,
    /// Milliseconds since the Unix epoch.
    #[serde(default)]
    pub updated_at: Option<u64>,
    /// The description.
    #[serde(default)]
    pub description: Option<String>,
    /// The image transform options the lens applies.
    #[serde(default)]
    pub transform: Option<ImageTransformOptions>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<Lens, _>")]
    pub extra: HashMap<String, Value>,
}

/// A signed URL.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct SignedUrl {
    /// The URL.
    pub url: String,
    /// When it expires, in milliseconds since the Unix epoch.
    #[serde(default)]
    pub expires_at: Option<u64>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<SignedUrl, _>")]
    pub extra: HashMap<String, Value>,
}

/// The picture CalmLens can show for an asset: the original for image assets, or a generated
/// image for documents and websites. It remains after the content is removed, so check the content
/// `status` before loading it.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AssetImage {
    /// The width in pixels: the original's for image assets (a converted HEIC is served smaller at
    /// the same aspect ratio), and the generated image's for documents and websites.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub width: Option<u32>,
    /// The height in pixels, like `width`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub height: Option<u32>,
    /// A ThumbHash placeholder to render while the image loads; `None` once it is removed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thumbhash: Option<String>,
    /// The average colour; `None` once the image is removed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub average_color: Option<String>,
    /// The perceptual hash, for matching similar image assets.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub perceptual_hash: Option<String>,
    /// The perceptual hash's quality from 0 to 100; low values match less reliably.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub perceptual_hash_quality: Option<i64>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<AssetImage, _>")]
    pub extra: HashMap<String, Value>,
}

/// Digests of an asset's uploaded content.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Checksums {
    /// The MD5 digest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub md5: Option<String>,
    /// The SHA-1 digest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sha1: Option<String>,
    /// The SHA-256 digest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sha256: Option<String>,
    /// The SHA-384 digest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sha384: Option<String>,
    /// The SHA-512 digest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sha512: Option<String>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<Checksums, _>")]
    pub extra: HashMap<String, Value>,
}

/// A safety hold.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct SafetyHold {
    /// Why the asset is held.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<SafetyHoldReason>,
    /// Milliseconds since the Unix epoch.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub placed_at: Option<u64>,
    /// Milliseconds since the Unix epoch.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disposed_at: Option<u64>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<SafetyHold, _>")]
    pub extra: HashMap<String, Value>,
}

/// Extracted text.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ExtractedText {
    /// `String` (inline `content`) or `Document` (stored separately under `id`).
    #[serde(default, rename = "type")]
    pub extraction_type: ExtractedTextType,
    /// The text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    /// The document ID.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<ExtractedText, _>")]
    pub extra: HashMap<String, Value>,
}

/// Descriptive metadata embedded in an uploaded image. Each text field is `None` when the file
/// doesn't record it.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct FileMetadata {
    /// When the picture was taken, as the file records it: an ISO 8601 date and time, such as
    /// `2026-05-01T12:30:00+01:00`. It includes the UTC offset only when the file records one;
    /// without it, the time is the camera's local time.
    #[serde(default)]
    pub captured_at: Option<String>,
    /// The camera manufacturer, such as `Canon`.
    #[serde(default)]
    pub camera_make: Option<String>,
    /// The camera or phone model, such as `EOS R5`.
    #[serde(default)]
    pub camera_model: Option<String>,
    /// The lens model.
    #[serde(default)]
    pub lens_model: Option<String>,
    /// The software that created or last edited the file.
    #[serde(default)]
    pub software: Option<String>,
    /// The creator or artist the file names. Sensitive: recorded only when
    /// `store_sensitive_metadata` is on.
    #[serde(default)]
    pub creator: Option<String>,
    /// The copyright notice the file declares.
    #[serde(default)]
    pub copyright: Option<String>,
    /// The IPTC digital source type the file declares, such as `digitalCapture` for a camera
    /// photo or `trainedAlgorithmicMedia` for generated media. Files can declare any value, so
    /// treat it as a claim.
    #[serde(default)]
    pub digital_source_type: Option<String>,
    /// Whether the uploaded file embedded GPS coordinates, whatever `store_sensitive_metadata` is
    /// set to.
    #[serde(default)]
    pub contains_location: bool,
    /// Where the picture was taken, from its GPS coordinates. Sensitive: recorded only when
    /// `store_sensitive_metadata` is on.
    #[serde(default)]
    pub location: Option<FileMetadataLocation>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<FileMetadata, _>")]
    pub extra: HashMap<String, Value>,
}

/// A GPS position in decimal degrees.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct FileMetadataLocation {
    /// The latitude, from -90 to 90.
    #[serde(default)]
    pub latitude: f64,
    /// The longitude, from -180 to 180.
    #[serde(default)]
    pub longitude: f64,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<FileMetadataLocation, _>")]
    pub extra: HashMap<String, Value>,
}

/// A direct CDN transform, applied in one pass: a selector string or structured
/// [`ImageTransformOptions`]. With a lens, its options replace the lens's.
///
/// `"width=320".into()` and `ImageTransformOptions { .. }.into()` both convert into it.
/// Structured options serialize to a selector such as `fit=cover,width=640`: option keys
/// sorted, nested objects as dotted keys (`border.color`), hex colours without `#` and values
/// percent-encoded, so equal transforms share a URL.
#[derive(Debug, Clone, PartialEq)]
pub enum CdnTransform {
    /// Comma-separated options, such as `fit=cover,width=1024`.
    Selector(String),
    /// Structured options (boxed, as they are large). At least one is required.
    Options(Box<ImageTransformOptions>),
}
impl CdnTransform {
    /// Whether this is an empty selector string, which means no transform.
    pub fn is_empty(&self) -> bool {
        matches!(self, Self::Selector(value) if value.is_empty())
    }
    /// The selector string the API and CDN accept. Fails with `sdk/invalid-argument` for a
    /// selector containing `/`, `..`, `?` or `#` or starting with `@`, for no options, option
    /// names that aren't camelCase letters and digits, or option values that are arrays.
    pub fn selector(&self) -> crate::Result<String> {
        let options = match self {
            Self::Selector(value) => {
                // A transform is one path segment of options: it must not add a segment, lens,
                // query or fragment.
                if value.contains(['/', '?', '#']) || value.contains("..") || value.starts_with('@')
                {
                    return Err(transform_error(
                        "Transform cannot contain \"/\", \"..\", \"?\" or \"#\", or start with \"@\"",
                    ));
                }
                return Ok(value.clone());
            }
            Self::Options(options) => options,
        };
        let mut pairs = Vec::new();
        match serde_json::to_value(options.as_ref())
            .map_err(|cause| transform_error(&cause.to_string()))?
        {
            Value::Object(options) => append_transform_options(&mut pairs, None, &options)?,
            _ => return Err(transform_error("Transform options must be an object")),
        }
        if pairs.is_empty() {
            return Err(transform_error("A transform needs at least one option"));
        }
        Ok(pairs.join(","))
    }
}
impl From<&str> for CdnTransform {
    fn from(value: &str) -> Self {
        Self::Selector(value.into())
    }
}
impl From<String> for CdnTransform {
    fn from(value: String) -> Self {
        Self::Selector(value)
    }
}
impl From<ImageTransformOptions> for CdnTransform {
    fn from(value: ImageTransformOptions) -> Self {
        Self::Options(Box::new(value))
    }
}
impl Serialize for CdnTransform {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let selector = self.selector().map_err(serde::ser::Error::custom)?;
        serializer.serialize_str(&selector)
    }
}
impl<'de> Deserialize<'de> for CdnTransform {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Repr {
            Selector(String),
            Options(Box<ImageTransformOptions>),
        }
        Ok(match Repr::deserialize(deserializer)? {
            Repr::Selector(value) => Self::Selector(value),
            Repr::Options(options) => Self::Options(options),
        })
    }
}

fn transform_error(message: &str) -> crate::Error {
    crate::Error::new(crate::ErrorCode::InvalidArgument, message)
}
/// Options that hold colours, written as hex without `#` in a selector.
// <generated: image-transform-colours>
// Generated by packages/sdk-contract/generate.ts from IMAGE_TRANSFORM_OPTIONS_SCHEMA; do not edit.
/// Options that hold colours, written as hex without `#` in a selector.
const TRANSFORM_COLOUR_KEYS: &[&str] = &["background", "border.color", "trim.border.color"];
// </generated: image-transform-colours>

/// Whether `name` is a transform option name: a lower-case letter, then letters and digits.
fn is_transform_option_name(name: &str) -> bool {
    let mut bytes = name.bytes();
    bytes.next().is_some_and(|b| b.is_ascii_lowercase()) && bytes.all(|b| b.is_ascii_alphanumeric())
}

/// A colour option's hex value without `#`, in lower case, or `None` if it is not `#` and 3, 4,
/// 6 or 8 hex digits.
fn hex_colour(value: &str) -> Option<String> {
    let digits = value.strip_prefix('#')?;
    (matches!(digits.len(), 3 | 4 | 6 | 8) && digits.bytes().all(|b| b.is_ascii_hexdigit()))
        .then(|| digits.to_ascii_lowercase())
}

/// Appends `key=value` pairs, keys sorted at every level.
fn append_transform_options(
    pairs: &mut Vec<String>,
    parent: Option<&str>,
    options: &serde_json::Map<String, Value>,
) -> crate::Result<()> {
    let mut keys: Vec<&String> = options.keys().collect();
    // Option names are ASCII, so byte order is JavaScript's UTF-16 order.
    keys.sort();
    for key in keys {
        let full = match parent {
            Some(parent) => format!("{parent}.{key}"),
            None => key.clone(),
        };
        if !is_transform_option_name(key) {
            return Err(transform_error(&format!(
                "Transform option \"{full}\" is not a valid name"
            )));
        }
        let text = match &options[key] {
            Value::Null => continue,
            Value::Object(child) => {
                append_transform_options(pairs, Some(&full), child)?;
                continue;
            }
            Value::String(value) if TRANSFORM_COLOUR_KEYS.contains(&full.as_str()) => {
                hex_colour(value).unwrap_or_else(|| value.clone())
            }
            Value::String(value) => value.clone(),
            Value::Bool(value) => value.to_string(),
            Value::Number(value) => js_number(value),
            Value::Array(_) => {
                return Err(transform_error(&format!(
                    "Transform option \"{full}\" must be a string, number, boolean or object"
                )))
            }
        };
        pairs.push(format!("{full}={}", encode_transform_component(&text)));
    }
    Ok(())
}
/// Percent-encodes everything except RFC 3986 unreserved characters (`A-Z a-z 0-9 - . _ ~`).
fn encode_transform_component(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for byte in value.bytes() {
        if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
            out.push(byte as char);
        } else {
            out.push_str(&format!("%{byte:02X}"));
        }
    }
    out
}
/// Formats a number as JavaScript's `String(number)` does.
fn js_number(value: &serde_json::Number) -> String {
    let float = match value.as_f64() {
        Some(float) if value.is_f64() => float,
        _ => return value.to_string(),
    };
    if float == 0.0 {
        return "0".into();
    }
    // `{:e}` gives the shortest round-trip digits, e.g. `1.5e0`.
    let exp_form = format!("{:e}", float.abs());
    let (mantissa, exponent) = exp_form.split_once('e').unwrap_or((&exp_form, "0"));
    let digits: String = mantissa.chars().filter(|c| *c != '.').collect();
    let exponent: i32 = exponent.parse().unwrap_or(0);
    let (k, n) = (digits.len() as i32, exponent + 1);
    let body = if k <= n && n <= 21 {
        format!("{digits}{}", "0".repeat((n - k) as usize))
    } else if 0 < n && n <= 21 {
        format!("{}.{}", &digits[..n as usize], &digits[n as usize..])
    } else if -6 < n && n <= 0 {
        format!("0.{}{digits}", "0".repeat((-n) as usize))
    } else {
        let sign = if n - 1 < 0 { '-' } else { '+' };
        let rest = if k > 1 {
            format!("{}.{}", &digits[..1], &digits[1..])
        } else {
            digits.clone()
        };
        format!("{rest}e{sign}{}", (n - 1).abs())
    };
    if float < 0.0 {
        format!("-{body}")
    } else {
        body
    }
}

/// An image quality: a number from 1 to 100 or a level.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ImageQuality {
    /// A number from 1 to 100.
    Value(u32),
    /// A level, such as `High`.
    Level(ImageQualityLevel),
}
impl From<u32> for ImageQuality {
    fn from(value: u32) -> Self {
        Self::Value(value)
    }
}
impl From<ImageQualityLevel> for ImageQuality {
    fn from(value: ImageQualityLevel) -> Self {
        Self::Level(value)
    }
}

/// Where to crop from: a named position or a point.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Gravity {
    /// A named position, such as `Face`.
    Position(GravityPosition),
    /// A point.
    Point(GravityPoint),
}
impl From<GravityPosition> for Gravity {
    fn from(value: GravityPosition) -> Self {
        Self::Position(value)
    }
}

/// A crop gravity point.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GravityPoint {
    /// How `x` and `y` are interpreted.
    pub mode: GravityMode,
    /// The horizontal position from 0 to 1.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub x: Option<f64>,
    /// The vertical position from 0 to 1.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub y: Option<f64>,
}

/// A border drawn around the image.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ImageBorder {
    /// The colour, e.g. `#fff`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color: Option<String>,
    /// The width in pixels.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub width: Option<f64>,
}

/// Regions found when the image was processed, blurred before any other option applies.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ImageRedaction {
    /// Blur text regions. Text regions need OCR on the upload.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub text: Option<bool>,
    /// Blur regions holding personal information.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub personal_information: Option<bool>,
    /// Preview. Blur the faces face detection found. Face boxes need face detection on the upload.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub faces: Option<bool>,
}

string_enum! {
    /// A named trim mode.
    TrimMode {
        /// Trim a uniform border.
        Border = "border",
    }
}

/// What to trim from the image edges.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Trim {
    /// A named mode, such as `Border`.
    Mode(TrimMode),
    /// Pixels to trim from each edge, or the size to trim to.
    Edges(TrimEdges),
}
impl From<TrimMode> for Trim {
    fn from(value: TrimMode) -> Self {
        Self::Mode(value)
    }
}
impl From<TrimEdges> for Trim {
    fn from(value: TrimEdges) -> Self {
        Self::Edges(value)
    }
}

/// Pixels to trim from each edge.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TrimEdges {
    /// Pixels from the top.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub top: Option<f64>,
    /// Pixels from the bottom.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bottom: Option<f64>,
    /// Pixels from the left.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub left: Option<f64>,
    /// Pixels from the right.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub right: Option<f64>,
    /// The width to trim to.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub width: Option<f64>,
    /// The height to trim to.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub height: Option<f64>,
    /// Also trim a uniform border.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub border: Option<TrimBorder>,
}

/// Whether and how to trim a uniform border.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum TrimBorder {
    /// Trim it (`true`) or not.
    Enabled(bool),
    /// Trim it with these settings.
    Options(TrimBorderOptions),
}

/// How to detect and keep a uniform border.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TrimBorderOptions {
    /// The border colour; detected when unset.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color: Option<String>,
    /// How far colours may differ from it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tolerance: Option<f64>,
    /// Pixels of border to keep.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub keep: Option<f64>,
}

// <generated: image-transform-options>
// Generated by packages/sdk-contract/generate.ts from IMAGE_TRANSFORM_OPTIONS_SCHEMA; do not edit.
string_enum! {
    /// The output format. Leave it out to serve the best format the browser accepts.
    ImageFormat {
        /// JPEG.
        Jpg = "jpg",
        /// PNG.
        Png = "png",
        /// WebP.
        Webp = "webp",
        /// AVIF.
        Avif = "avif",
        /// GIF.
        Gif = "gif",
    }
}

string_enum! {
    /// A named image quality.
    ImageQualityLevel {
        /// Low quality, the smallest files.
        Low = "low",
        /// Medium quality.
        Medium = "medium",
        /// High quality.
        High = "high",
    }
}

string_enum! {
    /// How the image fits the `width` and `height`.
    ImageFit {
        /// Shrink to fit, never enlarge.
        ScaleDown = "scale-down",
        /// Fit inside the box, keeping the aspect ratio.
        Contain = "contain",
        /// Fit inside the box and pad to fill it with `background`.
        Pad = "pad",
        /// Stretch to fill the box.
        Squeeze = "squeeze",
        /// Fill the box, cropping the overflow.
        Cover = "cover",
        /// Crop to the box without enlarging.
        Crop = "crop",
    }
}

string_enum! {
    /// Flips the image horizontally (`h`), vertically (`v`) or both (`hv`).
    ImageFlip {
        /// Horizontally.
        H = "h",
        /// Vertically.
        V = "v",
        /// Both.
        Hv = "hv",
    }
}

string_enum! {
    /// `foreground` removes the background.
    ImageSegment {
        /// Keep the foreground and remove the background.
        Foreground = "foreground",
    }
}

string_enum! {
    /// A named crop position.
    GravityPosition {
        /// Centre on detected faces.
        Face = "face",
        /// The left edge.
        Left = "left",
        /// The right edge.
        Right = "right",
        /// The top edge.
        Top = "top",
        /// The bottom edge.
        Bottom = "bottom",
        /// The centre.
        Center = "center",
        /// Chosen automatically.
        Auto = "auto",
        /// The most detailed area.
        Entropy = "entropy",
    }
}

string_enum! {
    /// How `x` and `y` place the point.
    GravityMode {
        /// `x` and `y` are fractions of the space left over after resizing.
        Remainder = "remainder",
        /// `x` and `y` are the centre of the crop box, as fractions of the image.
        BoxCenter = "box-center",
    }
}

/// Image transform options; set only what you need.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ImageTransformOptions {
    /// The output format. Leave it out to serve the best format the browser accepts.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<ImageFormat>,
    /// The width in pixels, 1 to 10,000 after `dpr`. With a size and no `fit`, the image scales down.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub width: Option<u32>,
    /// The height in pixels, 1 to 10,000 after `dpr`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub height: Option<u32>,
    /// The pixel density, 1 to 3: multiplies the width, height and border width.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dpr: Option<f64>,
    /// `false` serves the first frame of an animated GIF or WebP.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub anim: Option<bool>,
    /// The background colour, such as `#ffffff`, for padding and transparency.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub background: Option<String>,
    /// The blur radius.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub blur: Option<f64>,
    /// Blurs regions found when the image was processed, before any other option applies. Text regions need OCR on the upload. An image without such regions is served unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub redact: Option<ImageRedaction>,
    /// A border drawn around the image.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub border: Option<ImageBorder>,
    /// The brightness factor.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub brightness: Option<f64>,
    /// The contrast factor.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub contrast: Option<f64>,
    /// The quality: 1 to 100, or a level. Lossy output defaults to `high`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quality: Option<ImageQuality>,
    /// How the image fits the `width` and `height`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fit: Option<ImageFit>,
    /// Flips the image horizontally (`h`), vertically (`v`) or both (`hv`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flip: Option<ImageFlip>,
    /// The gamma.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gamma: Option<f64>,
    /// `foreground` removes the background.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub segment: Option<ImageSegment>,
    /// Where to keep when cropping: a side, `face`, `auto`, or a point.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gravity: Option<Gravity>,
    /// The clockwise rotation in degrees.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rotate: Option<u32>,
    /// The saturation factor.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub saturation: Option<f64>,
    /// The sharpen amount.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sharpen: Option<f64>,
    /// Trims the edges: `border` trims a detected border, or give edges and sizes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trim: Option<Trim>,
    /// Options this SDK version does not know, as received in a lens.
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}
// </generated: image-transform-options>

/// Options for [`TextClient::classify`](crate::TextClient::classify).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClassifyText {
    /// The text; must not be blank.
    pub text: String,
    /// The asset name; defaults to `text`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// A description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Processing options.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub processing_options: Option<ProcessingOptions>,
    /// Metadata items.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Vec<MetadataItem>>,
    /// Your identifier for who wrote the text. CalmLens only compares it with the author IDs in
    /// `context`, to tell which posts share a speaker.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub author_id: Option<String>,
    /// Earlier posts in the conversation, oldest first. The SDK sends only the posts CalmLens
    /// uses; see [`select_moderation_context_items`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context: Option<ModerationContext>,
    /// Your ID for the asset.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub external_id: Option<String>,
    /// A link to the asset in your system.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub external_url: Option<String>,
    /// The folder.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub folder_id: Patch<String>,
    /// The upload preset to apply.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub upload_preset_id: Option<String>,
    /// The `Idempotency-Key`. The SDK generates one when it is `None`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<String>,
}
impl ClassifyText {
    /// Moderates `text`.
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            ..Self::default()
        }
    }
}

/// Options for [`UploadTokensClient::sign`](crate::UploadTokensClient::sign).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignUploadToken {
    /// The upload preset the token may upload through.
    pub upload_preset_id: String,
    /// The external ID the uploaded asset gets. Must not be empty.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub external_id: Option<String>,
    /// The token's lifetime, from 1 to 3600 seconds. Defaults to 600.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_in_seconds: Option<u32>,
}
impl SignUploadToken {
    /// A token for `upload_preset_id` with the default lifetime.
    pub fn new(upload_preset_id: impl Into<String>) -> Self {
        Self {
            upload_preset_id: upload_preset_id.into(),
            ..Self::default()
        }
    }
}

/// A signed upload token.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignedUploadToken {
    /// The token, to hand to the browser as its bearer token.
    pub token: String,
    /// When the token expires, in milliseconds since the Unix epoch.
    pub expires_at: u64,
}

/// Options for asset search.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SearchAssets {
    /// The natural-language query.
    pub query: String,
    /// How to match; defaults to `Hybrid`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mode: Option<SearchMode>,
    /// The maximum number of results.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// One search result.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AssetSearchMatch {
    /// The asset.
    pub asset: Asset,
    /// The relevance score.
    #[serde(default)]
    pub score: f64,
    /// The fields that matched.
    #[serde(default)]
    pub matched_fields: Vec<SearchMatchField>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<AssetSearchMatch, _>")]
    pub extra: HashMap<String, Value>,
}

/// Search results.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AssetSearchResponse {
    /// The query.
    #[serde(default)]
    pub query: String,
    /// The results.
    #[serde(default)]
    pub items: Vec<AssetSearchMatch>,
    /// Whether semantic search is available.
    #[serde(default)]
    pub semantic_status: SemanticStatus,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<AssetSearchResponse, _>")]
    pub extra: HashMap<String, Value>,
}

/// One page of child folders, with the folders above them.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct FolderPage {
    /// The folders on this page.
    #[serde(default)]
    pub items: Vec<Folder>,
    /// Folders above the listed or requested folders, for showing their paths.
    #[serde(default)]
    pub ancestors: Vec<Folder>,
    /// The cursor for the next page, or None.
    #[serde(default)]
    pub next_cursor: Option<String>,
    /// The page size.
    #[serde(default)]
    pub page_size: Option<u32>,
    /// Whether another page follows.
    #[serde(default)]
    pub has_more: Option<bool>,
    /// The sort orders applied.
    #[serde(default)]
    pub ordering: Option<Vec<Order>>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<FolderPage, _>")]
    pub extra: HashMap<String, Value>,
}

/// Options for browsing folders.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListFolders {
    /// Lists immediate children of this folder; omit for project root.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent_id: Option<String>,
    /// The previous page's `next_cursor`; omit for the first page.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    /// Page size from 1 to 100 (the API's default is 50).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub page_size: Option<u32>,
    /// At most one sort order, by `name` (the default, ascending) or `createdAt`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ordering: Option<Vec<Order>>,
    /// Literal folder-name substring.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub search: Option<String>,
}

string_enum! {
    /// What a hash list does with an image upload that matches one of its entries.
    HashListAction {
        /// Record the match.
        Flag = "flag",
        /// Record the match and block close matches.
        Block = "block",
    }
}

/// A hash list: PDQ hashes of images the project never wants again.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct HashList {
    /// The hash list ID.
    pub id: String,
    /// The owning project.
    #[serde(default)]
    pub project_id: String,
    /// The name.
    #[serde(default)]
    pub name: String,
    /// The description.
    #[serde(default)]
    pub description: Option<String>,
    /// What matches do.
    #[serde(default)]
    pub action: HashListAction,
    /// Milliseconds since the Unix epoch.
    #[serde(default)]
    pub created_at: u64,
    /// Milliseconds since the Unix epoch.
    #[serde(default)]
    pub updated_at: Option<u64>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<HashList, _>")]
    pub extra: HashMap<String, Value>,
}
impl HashList {
    /// A hash list with `id`, `name` and `action`, e.g. for a mock response.
    pub fn new(id: impl Into<String>, name: impl Into<String>, action: HashListAction) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            action,
            ..Self::default()
        }
    }
}

/// One hash in a hash list.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct HashListEntry {
    /// The entry ID.
    pub id: String,
    /// The owning project.
    #[serde(default)]
    pub project_id: String,
    /// The hash list.
    #[serde(default)]
    pub hash_list_id: String,
    /// The PDQ hash: 64 hexadecimal characters.
    #[serde(default)]
    pub hash: String,
    /// The hash's quality from 0 to 100, when known.
    #[serde(default)]
    pub quality: Option<i64>,
    /// A label, such as a report reference.
    #[serde(default)]
    pub label: Option<String>,
    /// The asset the hash was taken from.
    #[serde(default)]
    pub source_asset_id: Option<String>,
    /// Milliseconds since the Unix epoch.
    #[serde(default)]
    pub created_at: u64,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<HashListEntry, _>")]
    pub extra: HashMap<String, Value>,
}

/// A page of a project's hash lists, newest first.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct HashListPage {
    /// The hash lists on this page.
    #[serde(default)]
    pub items: Vec<HashList>,
    /// The cursor for the next page, or None.
    #[serde(default)]
    pub next_cursor: Option<String>,
    /// The page size.
    #[serde(default)]
    pub page_size: Option<u32>,
    /// Whether another page follows.
    #[serde(default)]
    pub has_more: Option<bool>,
    /// The sort orders applied.
    #[serde(default)]
    pub ordering: Option<Vec<Order>>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<HashListPage, _>")]
    pub extra: HashMap<String, Value>,
}

/// Options for one page of a project's hash lists.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListHashLists {
    /// The previous page's `next_cursor`; omit for the first page.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    /// Hash lists per page, 1 to 100 (the API's default is 50).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub page_size: Option<u32>,
}

/// A page of hash list entries, newest first.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct HashListEntryPage {
    /// The entries on this page.
    #[serde(default)]
    pub items: Vec<HashListEntry>,
    /// The cursor for the next page, or None.
    #[serde(default)]
    pub next_cursor: Option<String>,
    /// The page size.
    #[serde(default)]
    pub page_size: Option<u32>,
    /// Whether another page follows.
    #[serde(default)]
    pub has_more: Option<bool>,
    /// The sort orders applied.
    #[serde(default)]
    pub ordering: Option<Vec<Order>>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<HashListEntryPage, _>")]
    pub extra: HashMap<String, Value>,
}

/// Identifies a hash list.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HashListId {
    /// The hash list ID.
    pub hash_list_id: String,
}
impl HashListId {
    /// Identifies hash list `hash_list_id`.
    pub fn new(hash_list_id: impl Into<String>) -> Self {
        Self {
            hash_list_id: hash_list_id.into(),
        }
    }
}

/// Identifies a hash list entry.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HashListEntryId {
    /// The entry ID.
    pub entry_id: String,
}
impl HashListEntryId {
    /// Identifies entry `entry_id`.
    pub fn new(entry_id: impl Into<String>) -> Self {
        Self {
            entry_id: entry_id.into(),
        }
    }
}

/// Options for creating a hash list.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateHashList {
    /// The name.
    pub name: String,
    /// A description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// What matches do: `Flag` records them, `Block` also blocks close matches.
    pub action: HashListAction,
}

/// Changes to a hash list. The new action applies to later uploads.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateHashList {
    /// The hash list ID.
    #[serde(skip_serializing)]
    pub hash_list_id: String,
    /// The new name.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub name: Patch<String>,
    /// The new description; `Patch::Null` clears it.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub description: Patch<String>,
    /// The new action.
    #[serde(default, skip_serializing_if = "Patch::is_missing")]
    pub action: Patch<HashListAction>,
}

/// Options for one page of a hash list's entries.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListHashListEntries {
    /// The hash list ID.
    pub hash_list_id: String,
    /// The cursor from a previous page.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    /// The page size.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub page_size: Option<u32>,
}

/// Adds a hash to a hash list: set `hash` (and optionally `quality`), or `asset_id` to use an
/// image asset's perceptual hash.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AddHashListEntry {
    /// The hash list ID.
    #[serde(skip_serializing)]
    pub hash_list_id: String,
    /// A PDQ hash: 64 hexadecimal characters.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hash: Option<String>,
    /// The hash's quality from 0 to 100.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quality: Option<i64>,
    /// An image asset whose perceptual hash to add.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub asset_id: Option<String>,
    /// A label, such as a report reference.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
}

/// Optional customer assertions for CDN delivery. Neither assertion is verified by CalmLens.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ViewerClaims {
    /// Viewer country; otherwise inferred from the connection reaching CalmLens.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,
    /// Your platform's confirmation that the viewer passed its age check. Defaults to false,
    /// including authenticated requests. Your platform confirms the viewer's age; CalmLens does
    /// not verify this claim. Anyone requesting a public asset's URL can set it, so it doesn't
    /// restrict access: to control who loads an age-restricted asset, make it private and include
    /// the claim in a signed URL, whose signature covers it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub age_confirmed: Option<bool>,
}

string_enum! {
    /// A built-in moderation policy preset.
    PolicyPresetId {
        /// General.
        General = "general-community",
        /// Kids.
        Kids = "children-platform",
        /// Learning and support.
        LearningAndSupport = "education-support",
        /// Teen-safe.
        TeenSafe = "wholesome-community",
    }
}

string_enum! {
    /// How a policy rule's qualifiers combine.
    PolicyRuleMatch {
        /// Every qualifier applies to the same qualifying instance.
        All = "all",
    }
}

string_enum! {
    /// What `policies().apply_preset` does.
    PolicyPresetOperation {
        /// Restores the settings of the pinned preset version, discarding edits.
        Reset = "reset",
        /// Moves an unchanged copy to the latest preset release.
        Update = "update",
    }
}

/// A moderation policy. Policies belong to the project's organisation and its projects share
/// them; each project moderates with one, and an upload preset can name another for its own
/// uploads. `revision` counts saved changes and guards every change, separately from the preset
/// release in `preset.version`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Policy {
    /// The policy ID.
    pub id: String,
    /// The display name.
    #[serde(default)]
    pub name: String,
    /// What the policy is for.
    #[serde(default)]
    pub description: String,
    /// What the policy does with each category, its allowances and restrictions.
    #[serde(default)]
    pub settings: PolicySettings,
    /// Changes with every saved change. Send it with each change; a policy changed since is
    /// refused with `policy/revision-conflict`.
    #[serde(default)]
    pub revision: u64,
    /// Whether the policy follows its preset: it has the latest preset settings until its first
    /// saved change pins a copy.
    #[serde(default)]
    pub automatic_updates: bool,
    /// Where the policy started from a built-in preset, or `None`.
    #[serde(default)]
    pub preset: Option<PolicyPresetOrigin>,
    /// Projects this policy moderates, as their policy or through one of their upload presets.
    #[serde(default)]
    pub project_ids: Vec<String>,
    /// Milliseconds since the Unix epoch.
    #[serde(default)]
    pub created_at: u64,
    /// Milliseconds since the Unix epoch.
    #[serde(default)]
    pub updated_at: u64,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<Policy, _>")]
    pub extra: HashMap<String, Value>,
}

/// The built-in preset a policy started from.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct PolicyPresetOrigin {
    /// The preset.
    #[serde(default)]
    pub id: PolicyPresetId,
    /// The preset release the policy is pinned to; resetting restores its settings.
    #[serde(default)]
    pub version: u64,
    /// The newest release of the preset. A newer one than `version` can be applied with
    /// [`PolicyPresetOperation::Update`].
    #[serde(default)]
    pub latest_version: u64,
    /// The project whose preset policy this is, or `None` for a copy. Only a project's preset
    /// policy can follow automatic updates.
    #[serde(default)]
    pub project_id: Option<String>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<PolicyPresetOrigin, _>")]
    pub extra: HashMap<String, Value>,
}

/// What a policy does with each moderation category. Settings you send must define every
/// category.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct PolicySettings {
    /// Each category's settings.
    #[serde(default)]
    pub category_settings: HashMap<ClassificationCategory, CategoryPolicySettings>,
    /// Preview. What happens to assets that link to unsafe destinations; `None` when off.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub link_safety: Option<LinkSafetySettings>,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<PolicySettings, _>")]
    pub extra: HashMap<String, Value>,
}
impl PolicySettings {
    /// These settings with `category` set to `settings`.
    pub fn category(
        mut self,
        category: ClassificationCategory,
        settings: CategoryPolicySettings,
    ) -> Self {
        self.category_settings.insert(category, settings);
        self
    }
}

/// One category's action, allowances and restrictions.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CategoryPolicySettings {
    /// What happens when the category's policy score reaches 0.5; `None` leaves the API's
    /// default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub action: Option<FlaggedContentAction>,
    /// Contexts that let content through, or act on it more softly, when all of the category's
    /// content is one of their qualifiers.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allowances: Option<Vec<PolicyRule>>,
    /// Conditions that act on at least one matching qualifying instance. They outweigh
    /// allowances.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub restrictions: Option<Vec<PolicyRule>>,
    /// Fields this SDK version does not know.
    #[serde(
        flatten,
        deserialize_with = "extra_fields::<CategoryPolicySettings, _>"
    )]
    pub extra: HashMap<String, Value>,
}
impl CategoryPolicySettings {
    /// Settings that take `action`, with no allowances or restrictions.
    pub fn new(action: FlaggedContentAction) -> Self {
        Self {
            action: Some(action),
            ..Self::default()
        }
    }
}

/// An allowance or restriction: its `when` qualifiers apply to the same instance, excluding
/// instances that also have an `unless` qualifier (restrictions only).
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct PolicyRule {
    /// A name for the rule.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// The qualifiers that must all apply.
    #[serde(default)]
    pub when: Vec<ModerationQualifier>,
    /// How the qualifiers combine.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub r#match: Option<PolicyRuleMatch>,
    /// Qualifiers that exclude an instance (restrictions only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unless: Option<Vec<ModerationQualifier>>,
    /// What happens to matching content.
    #[serde(default)]
    pub action: FlaggedContentAction,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<PolicyRule, _>")]
    pub extra: HashMap<String, Value>,
}
impl PolicyRule {
    /// A rule taking `action` when every `when` qualifier applies.
    pub fn new(when: Vec<ModerationQualifier>, action: FlaggedContentAction) -> Self {
        Self {
            when,
            action,
            ..Self::default()
        }
    }
}

/// Every policy of the project's organisation, oldest first, and the one the project uses.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct PolicyList {
    /// The organisation's policies.
    #[serde(default)]
    pub policies: Vec<Policy>,
    /// The ID of the policy the project moderates with.
    #[serde(default)]
    pub project_policy_id: String,
    /// Fields this SDK version does not know.
    #[serde(flatten, deserialize_with = "extra_fields::<PolicyList, _>")]
    pub extra: HashMap<String, Value>,
}

/// Identifies a policy.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PolicyId {
    /// The policy ID.
    pub policy_id: String,
}
impl PolicyId {
    /// Identifies policy `policy_id`.
    pub fn new(policy_id: impl Into<String>) -> Self {
        Self {
            policy_id: policy_id.into(),
        }
    }
}

/// Creates a policy from `settings` with a `name`, or a copy of the latest release of a built-in
/// preset with `preset_id` (whose name defaults to the preset's).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreatePolicy {
    /// The display name; required with `settings`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// What the policy is for.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The settings, defining every category. Send this or `preset_id`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub settings: Option<PolicySettings>,
    /// The built-in preset to copy. Send this or `settings`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preset_id: Option<PolicyPresetId>,
}
impl CreatePolicy {
    /// A copy of the latest release of `preset`.
    pub fn from_preset(preset: PolicyPresetId) -> Self {
        Self {
            preset_id: Some(preset),
            ..Self::default()
        }
    }
    /// A policy named `name` with `settings`.
    pub fn with_settings(name: impl Into<String>, settings: PolicySettings) -> Self {
        Self {
            name: Some(name.into()),
            settings: Some(settings),
            ..Self::default()
        }
    }
}

/// Changes to a policy's name, description or settings; `None` fields are unchanged.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdatePolicy {
    /// The policy ID.
    #[serde(skip_serializing)]
    pub policy_id: String,
    /// The policy's current revision.
    pub revision: u64,
    /// The new name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// The new description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The complete new settings, defining every category.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub settings: Option<PolicySettings>,
}
impl UpdatePolicy {
    /// Changes nothing yet to policy `policy_id` at `revision`.
    pub fn new(policy_id: impl Into<String>, revision: u64) -> Self {
        Self {
            policy_id: policy_id.into(),
            revision,
            ..Self::default()
        }
    }
}

/// Resets a preset copy to its pinned version (`Reset` with `preset_version` = `preset.version`)
/// or updates an unchanged copy to the latest release (`Update` with `preset.latest_version`).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplyPolicyPreset {
    /// The policy ID.
    #[serde(skip_serializing)]
    pub policy_id: String,
    /// What to do.
    pub operation: PolicyPresetOperation,
    /// The policy's current revision.
    pub revision: u64,
    /// The preset release you reviewed.
    pub preset_version: u64,
}

/// Switches automatic updates for the project's preset policy. `enabled` replaces the saved copy
/// with the latest preset, discarding its changes; `false` pins the current preset version.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SetPolicyAutomaticUpdates {
    /// The policy ID.
    #[serde(skip_serializing)]
    pub policy_id: String,
    /// Whether the policy follows its preset.
    pub enabled: bool,
    /// The policy's current revision.
    pub revision: u64,
    /// The policy's `preset.latest_version`.
    pub preset_version: u64,
}

/// Chooses the policy the project moderates with.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AssignPolicy {
    /// One of the organisation's policies.
    pub policy_id: String,
}
impl AssignPolicy {
    /// Assigns policy `policy_id`.
    pub fn new(policy_id: impl Into<String>) -> Self {
        Self {
            policy_id: policy_id.into(),
        }
    }
}