atpmcp 0.15.0

AT Protocol MCP server (Model Context Protocol 2026-07-28)
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
//! The `generate_bsky_post` tool: an `app.bsky.feed.post` record, built and
//! validated, but not published.
//!
//! # What it builds
//!
//! The record carries the text exactly as given, its facets, an optional
//! `app.bsky.embed.external` link card, `langs` (`["en"]` unless the caller
//! says otherwise, and left out for `[]`), and `createdAt`. Publishing is a
//! separate step, `invoke_xrpc` with `com.atproto.repo.createRecord`, so this
//! tool never writes a record and a host can show the post before it goes
//! anywhere.
//!
//! # Facets
//!
//! Through `atproto_extras::parse_facets_allowed`, the same parser
//! `parse_facets` uses, with one allow-list per kind: an absent or empty list
//! keeps every facet of its kind, and a non-empty one keeps only the facets it
//! names. The lists are applied before the facet limits and before any
//! mention is resolved, so a mention left out costs no lookup.
//!
//! # The link card
//!
//! `embed_external` names a page. The page is fetched, and its Open Graph
//! metadata becomes the card's `title` and `description`, falling back to the
//! Twitter card metadata and then the page's own `<title>` and
//! `<meta name="description">`; `atproto_extras::link_card` has the rules.
//! The card's `uri` is the URL as the caller gave it.
//!
//! The page and its image are both a third party's choice of URL, and the
//! caller is a model, so both fetches are held to what the other caller-named
//! hosts are: the endpoint policy on the first URL (with its query and
//! fragment set aside, as the redirect check does), a check on every redirect
//! that is never waived, the address guard, a timeout, and a size cap. A page
//! is read to [`MAX_PAGE_BYTES`] and parsed as far as that goes, since the
//! metadata is in its head. An image is read to the download ceiling, and one
//! over [`MAX_THUMB_BYTES`], the lexicon's `maxSize`, is shrunk to a JPEG that
//! fits ([`crate::thumbnail`]).
//!
//! # The thumbnail
//!
//! A blob reference resolves only once the blob is on the PDS that will hold
//! the record, so a thumbnail needs an account: with `auth_handle`, the page's
//! image is uploaded to that account's own PDS through the same path as
//! `upload_blob`, and the blob reference the PDS answers with goes into the
//! card as is. An uploaded blob that no record references is temporary on a
//! PDS, so the record should be created soon after, as the same account.
//!
//! The image is a third party's, and uploading it republishes whatever it
//! carries, so its metadata is removed first: EXIF, XMP, IPTC and comments,
//! without touching the pixels ([`crate::image_metadata`]). An image that
//! only its EXIF says is stored turned is re-encoded with the turn applied
//! instead, since without the EXIF it would show on its side. An operator
//! who wants the metadata kept sets `ATPMCP_PRESERVE_EXIF=1`: then an image
//! is uploaded as served, and a shrunk one gets its source's EXIF copied in.
//!
//! A thumbnail that cannot be had is not an error: without `auth_handle`, or
//! when the page names no image, or the image is over the download ceiling,
//! cannot be shrunk, is not an image, or is unreachable, the card is written
//! without one and the result says why. A
//! card without a thumbnail is still a valid card. A page that cannot be read
//! at all is an error, because a card without the page's title is not what
//! was asked for. So is a failed upload, because that is the account's
//! problem, not the page's.
//!
//! # Images
//!
//! `gallery` makes an `app.bsky.embed.gallery` of up to [`MAX_GALLERY_ITEMS`]
//! images, and `images` the older `app.bsky.embed.images` of up to
//! [`MAX_IMAGES_ITEMS`], which more clients show. Each item is a local `path`
//! or a `url`, with an optional `alt` that defaults to empty. A post has one
//! embed, so `gallery`, `images` and `embed_external` exclude each other.
//!
//! Each image goes through the thumbnail's pipeline ([`prepare_image`]) with
//! the lexicons' [`MAX_MEDIA_IMAGE_BYTES`] as its limit: judged by its bytes,
//! stripped of metadata unless `ATPMCP_PRESERVE_EXIF`, and re-encoded when it
//! is stored turned or is over the limit. Its aspect ratio is read from the
//! result, as shown. Unlike a thumbnail, these are images the caller named,
//! so one that cannot be used fails the call, and every image is prepared
//! before any is uploaded, so that failure uploads nothing.
//!
//! # Shortened links
//!
//! `shorten_links` does what the Bluesky app does when it posts: a link
//! facet's text becomes the URL without its scheme, cut after 13 characters
//! of path ([`to_short_url`]), and the facet keeps the full URL
//! ([`shorten_links`]).
//!
//! # Validation
//!
//! The record is checked against `app.bsky.feed.post` and the embed and
//! facet lexicons, bundled under `lexicons/` (copies of the ones
//! `atproto-pds` bundles): once before any page is fetched or image uploaded,
//! and again with its embed. That is what makes "valid" a property of the
//! result rather than a hope: a text over 300 graphemes, a malformed `langs`
//! entry, a gallery item without its aspect ratio or an unusable
//! `embed_external` is refused here rather than by the PDS.

use std::collections::HashSet;
use std::sync::{Arc, LazyLock};

use atproto_extras::link_card::extract_link_card;
use atproto_extras::{
    FacetAllowList, FacetLimits, parse_facets_allowed, parse_mention_spans, parse_tags, parse_urls,
};
use atproto_identity::traits::IdentityResolver;
use atproto_lexicon::validation::{BaseCatalog, ValidateFlags, validate_record};
use atproto_record::lexicon::app::bsky::richtext::facet::{Facet, FacetFeature};
use atpxrpc::accounts;
use futures::StreamExt;
use reqwest::Url;
use reqwest::header::{ACCEPT, CONTENT_TYPE};
use serde_json::{Map, Value};

use crate::context::ServerContext;
use crate::errors::ToolError;
use crate::host_policy;
use crate::mime;
use crate::proto::serve::RequestCtx;
use crate::tools::blob::{Uploaded, put_blob};
use crate::tools::{tool_error, tool_structured};

/// The record type this tool builds.
pub const POST_NSID: &str = "app.bsky.feed.post";

/// The embed type a link card is.
pub const EXTERNAL_NSID: &str = "app.bsky.embed.external";

/// How much of a page is read for its link card, in bytes.
///
/// The metadata is in the head, so a page over this is parsed as far as it
/// goes rather than refused.
pub const MAX_PAGE_BYTES: u64 = 1_048_576;

/// The largest thumbnail used, in bytes: `app.bsky.embed.external#external`'s
/// `thumb.maxSize`. An image over it is shrunk to fit.
pub const MAX_THUMB_BYTES: u64 = 1_000_000;

/// The most `langs` entries the lexicon allows.
pub const MAX_LANGS: usize = 3;

/// `langs` when the caller gives none.
pub const DEFAULT_LANGS: &[&str] = &["en"];

/// The embed a `gallery` argument makes.
pub const GALLERY_NSID: &str = "app.bsky.embed.gallery";

/// The embed an `images` argument makes.
pub const IMAGES_NSID: &str = "app.bsky.embed.images";

/// The most images a `gallery` takes. The lexicon allows 20 and asks
/// authoring clients to stop at 10 for now, and this is one.
pub const MAX_GALLERY_ITEMS: usize = 10;

/// The most images an `images` embed takes: its lexicon's `maxLength`.
pub const MAX_IMAGES_ITEMS: usize = 4;

/// The largest image either embed takes, in bytes: both lexicons' `maxSize`.
/// One over it is shrunk to fit, as a card's thumbnail is.
pub const MAX_MEDIA_IMAGE_BYTES: u64 = 2_000_000;

/// The lexicons a post is validated against, bundled with the binary.
///
/// `post.json` names more than these: the other embed types, `selfLabels`,
/// and the reply refs. The validator resolves only the refs a value uses, so
/// a post this tool builds -- which has no reply, labels or other embed --
/// needs just these, and the tests hold that.
const LEXICONS: &[(&str, &str)] = &[
    (
        "app.bsky.feed.post",
        include_str!("../../lexicons/app/bsky/feed/post.json"),
    ),
    (
        "app.bsky.embed.external",
        include_str!("../../lexicons/app/bsky/embed/external.json"),
    ),
    (
        "app.bsky.embed.gallery",
        include_str!("../../lexicons/app/bsky/embed/gallery.json"),
    ),
    (
        "app.bsky.embed.images",
        include_str!("../../lexicons/app/bsky/embed/images.json"),
    ),
    (
        "app.bsky.embed.defs",
        include_str!("../../lexicons/app/bsky/embed/defs.json"),
    ),
    (
        "app.bsky.richtext.facet",
        include_str!("../../lexicons/app/bsky/richtext/facet.json"),
    ),
    (
        "com.atproto.repo.strongRef",
        include_str!("../../lexicons/com/atproto/repo/strongRef.json"),
    ),
    (
        "com.atproto.label.defs",
        include_str!("../../lexicons/com/atproto/label/defs.json"),
    ),
];

/// [`LEXICONS`], parsed once.
static CATALOG: LazyLock<BaseCatalog> = LazyLock::new(|| {
    let mut catalog = BaseCatalog::new();
    for (nsid, json) in LEXICONS {
        // A bundled lexicon that does not parse is a build defect, which
        // `every_bundled_lexicon_parses` catches; a post then fails
        // validation with `SchemaNotFound` rather than passing unchecked.
        if let Err(error) = catalog.add_schema_json(json) {
            tracing::error!(nsid = %nsid, error = %error, "A bundled lexicon does not parse.");
        }
    }
    catalog
});

/// Execute the `generate_bsky_post` tool.
pub async fn generate_bsky_post(
    ctx: &Arc<ServerContext>,
    rctx: &mut RequestCtx,
    arguments: Value,
) -> Value {
    let cancel = rctx.cancel.clone();
    let result = tokio::select! {
        biased;
        () = cancel.cancelled() => Err(ToolError::PostGenerationFailed {
            reason: "cancelled".to_string(),
        }),
        result = generate(ctx, rctx, arguments) => result,
    };
    match result {
        Ok(value) => value,
        Err(error) => {
            tracing::error!(error = %error, "Post generation failed.");
            tool_error(&error.to_string())
        }
    }
}

/// The arguments, read and checked.
struct PostRequest {
    text: String,
    allow: FacetAllowList,
    /// The page for a link card: as given (trimmed), and parsed.
    embed_external: Option<(String, Url)>,
    /// The images for a `gallery` or `images` embed.
    media: Option<Media>,
    langs: Vec<String>,
    auth_handle: Option<String>,
    shorten_links: bool,
}

/// Which embed a list of images makes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MediaKind {
    /// `gallery`: `app.bsky.embed.gallery`.
    Gallery,
    /// `images`: `app.bsky.embed.images`.
    Images,
}

impl MediaKind {
    /// The argument that names it.
    fn argument(self) -> &'static str {
        match self {
            Self::Gallery => "gallery",
            Self::Images => "images",
        }
    }

    fn max_items(self) -> usize {
        match self {
            Self::Gallery => MAX_GALLERY_ITEMS,
            Self::Images => MAX_IMAGES_ITEMS,
        }
    }

    fn nsid(self) -> &'static str {
        match self {
            Self::Gallery => GALLERY_NSID,
            Self::Images => IMAGES_NSID,
        }
    }
}

/// Where an image comes from.
enum ImageSource {
    /// An absolute path on this machine.
    Path(String),
    /// A URL, fetched like a link card's image.
    Url(Url),
}

/// One image of a `gallery` or `images` argument.
struct ImageItem {
    source: ImageSource,
    alt: String,
    /// How notes and errors name it: `gallery item 2 (/path/to/file.png)`.
    label: String,
}

/// A `gallery` or `images` argument, read and checked.
struct Media {
    kind: MediaKind,
    items: Vec<ImageItem>,
}

fn invalid(reason: impl Into<String>) -> ToolError {
    ToolError::PostGenerationFailed {
        reason: reason.into(),
    }
}

/// An optional string argument: `None` when absent or `null`.
fn optional_string(arguments: &Value, name: &str) -> Result<Option<String>, ToolError> {
    match arguments.get(name) {
        None | Some(Value::Null) => Ok(None),
        Some(Value::String(value)) => Ok(Some(value.clone())),
        Some(_) => Err(invalid(format!("the '{name}' argument must be a string"))),
    }
}

/// An optional array-of-strings argument: `None` when absent or `null`.
fn optional_strings(arguments: &Value, name: &str) -> Result<Option<Vec<String>>, ToolError> {
    let refused = || invalid(format!("the '{name}' argument must be an array of strings"));
    match arguments.get(name) {
        None | Some(Value::Null) => Ok(None),
        Some(Value::Array(items)) => items
            .iter()
            .map(|item| item.as_str().map(str::to_string).ok_or_else(refused))
            .collect::<Result<Vec<_>, _>>()
            .map(Some),
        Some(_) => Err(refused()),
    }
}

/// The `gallery` or `images` argument, if there is one.
fn read_media(arguments: &Value) -> Result<Option<Media>, ToolError> {
    let present = |name: &str| !matches!(arguments.get(name), None | Some(Value::Null));
    let kind = match (present("gallery"), present("images")) {
        (true, true) => {
            return Err(invalid(
                "give 'gallery' or 'images', not both: a post has one embed",
            ));
        }
        (true, false) => MediaKind::Gallery,
        (false, true) => MediaKind::Images,
        (false, false) => return Ok(None),
    };
    let name = kind.argument();
    let Some(Value::Array(list)) = arguments.get(name) else {
        return Err(invalid(format!(
            "the '{name}' argument must be an array of images"
        )));
    };
    if list.is_empty() || list.len() > kind.max_items() {
        return Err(invalid(format!(
            "'{name}' takes 1 to {} images, not {}",
            kind.max_items(),
            list.len()
        )));
    }

    let items = list
        .iter()
        .enumerate()
        .map(|(index, item)| {
            let number = index + 1;
            let Value::Object(fields) = item else {
                return Err(invalid(format!(
                    "{name} item {number} must be an object with 'path' or 'url'"
                )));
            };
            if let Some(unknown) = fields
                .keys()
                .find(|key| !matches!(key.as_str(), "path" | "url" | "alt"))
            {
                return Err(invalid(format!(
                    "{name} item {number} has an unknown field '{unknown}'; an image is \
                     {{\"path\"}} or {{\"url\"}}, with an optional \"alt\""
                )));
            }
            let text = |field: &str| match fields.get(field) {
                None | Some(Value::Null) => Ok(None),
                Some(Value::String(value)) => Ok(Some(value.clone())),
                Some(_) => Err(invalid(format!(
                    "{name} item {number}'s '{field}' must be a string"
                ))),
            };
            let source = match (text("path")?, text("url")?) {
                (Some(path), None) => ImageSource::Path(path),
                (None, Some(raw)) => {
                    let url = Url::parse(raw.trim()).map_err(|error| {
                        invalid(format!(
                            "{name} item {number}'s 'url' must be an absolute URL ({raw}): {error}"
                        ))
                    })?;
                    if !matches!(url.scheme(), "http" | "https") {
                        return Err(invalid(format!(
                            "{name} item {number}'s 'url' must be http or https, not {}",
                            url.scheme()
                        )));
                    }
                    ImageSource::Url(url)
                }
                (Some(_), Some(_)) => {
                    return Err(invalid(format!(
                        "{name} item {number} gives both 'path' and 'url'; give one"
                    )));
                }
                (None, None) => {
                    return Err(invalid(format!(
                        "{name} item {number} needs a 'path' or a 'url'"
                    )));
                }
            };
            let label = match &source {
                ImageSource::Path(path) => format!("{name} item {number} ({path})"),
                ImageSource::Url(url) => format!("{name} item {number} ({url})"),
            };
            Ok(ImageItem {
                source,
                alt: text("alt")?.unwrap_or_default(),
                label,
            })
        })
        .collect::<Result<Vec<_>, _>>()?;
    Ok(Some(Media { kind, items }))
}

fn read_arguments(arguments: &Value) -> Result<PostRequest, ToolError> {
    let text = match arguments.get("text") {
        Some(Value::String(text)) => text.clone(),
        _ => return Err(invalid("the 'text' argument must be a string")),
    };

    let allow = FacetAllowList {
        mentions: optional_strings(arguments, "mention_facet_allow")?.unwrap_or_default(),
        tags: optional_strings(arguments, "tag_facet_allow")?.unwrap_or_default(),
        links: optional_strings(arguments, "link_facet_allow")?.unwrap_or_default(),
    };

    let embed_external = match optional_string(arguments, "embed_external")? {
        None => None,
        Some(raw) => {
            let raw = raw.trim().to_string();
            let url = Url::parse(&raw).map_err(|error| {
                invalid(format!(
                    "'embed_external' must be an absolute URL ({raw}): {error}"
                ))
            })?;
            if !matches!(url.scheme(), "http" | "https") {
                return Err(invalid(format!(
                    "'embed_external' must be an http or https URL, not {}",
                    url.scheme()
                )));
            }
            Some((raw, url))
        }
    };

    let media = read_media(arguments)?;
    if let (Some(media), Some(_)) = (&media, &embed_external) {
        return Err(invalid(format!(
            "give one of '{}' or 'embed_external', not both: a post has one embed",
            media.kind.argument()
        )));
    }

    let shorten_links = match arguments.get("shorten_links") {
        None | Some(Value::Null) => false,
        Some(Value::Bool(value)) => *value,
        Some(_) => return Err(invalid("the 'shorten_links' argument must be a boolean")),
    };

    let langs = match optional_strings(arguments, "langs")? {
        None => DEFAULT_LANGS
            .iter()
            .map(|lang| (*lang).to_string())
            .collect(),
        Some(langs) if langs.len() > MAX_LANGS => {
            return Err(invalid(format!(
                "'langs' has {} entries; a post has at most {MAX_LANGS}",
                langs.len()
            )));
        }
        Some(langs) => langs,
    };

    Ok(PostRequest {
        text,
        allow,
        embed_external,
        media,
        langs,
        auth_handle: optional_string(arguments, "auth_handle")?,
        shorten_links,
    })
}

async fn generate(
    ctx: &Arc<ServerContext>,
    rctx: &mut RequestCtx,
    arguments: Value,
) -> Result<Value, ToolError> {
    let request = read_arguments(&arguments)?;

    if let (Some(media), None) = (&request.media, &request.auth_handle) {
        return Err(invalid(format!(
            "'{}' needs auth_handle: its images are uploaded to that account's PDS",
            media.kind.argument()
        )));
    }

    // Loaded before anything is fetched, so a mistyped handle is reported as
    // that and not after a page fetch. Only an embed uses the account.
    let embeds = request.embed_external.is_some() || request.media.is_some();
    let mut account =
        match (embeds, &request.auth_handle) {
            (true, Some(handle)) => Some(accounts::load_account(handle).map_err(|error| {
                invalid(format!("the account '{handle}' cannot be used: {error}"))
            })?),
            _ => None,
        };

    let (facets, mut notes) =
        facets_for(&request.text, &request.allow, ctx.resolver.as_ref()).await;
    let (text, facets) = if request.shorten_links {
        shorten_links(&request.text, &facets)
    } else {
        (request.text.clone(), facets)
    };

    let mut record = Map::new();
    record.insert("$type".to_string(), Value::from(POST_NSID));
    record.insert("text".to_string(), Value::from(text));
    if !facets.is_empty() {
        let facets = serde_json::to_value(&facets)
            .map_err(|error| invalid(format!("the facets could not be serialized: {error}")))?;
        record.insert("facets".to_string(), facets);
    }
    if !request.langs.is_empty() {
        record.insert("langs".to_string(), Value::from(request.langs.clone()));
    }
    record.insert(
        "createdAt".to_string(),
        Value::from(atproto_record::datetime::Datetime::now().into_string()),
    );

    // Checked before the embed too, so a text over the lexicon's limits is
    // refused before a page is fetched or an image uploaded.
    let validate = |record: &Value| {
        validate_record(POST_NSID, record, &*CATALOG, ValidateFlags::empty()).map_err(|error| {
            invalid(format!(
                "the record does not validate against {POST_NSID}: {error}"
            ))
        })
    };
    validate(&Value::Object(record.clone()))?;

    let mut card_summary = None;
    let mut thumbnail = None;
    let mut uploaded = Vec::new();
    if let Some((raw, url)) = &request.embed_external {
        let card = link_card(ctx, rctx, raw, url, account.as_mut(), &mut notes).await?;
        card_summary = Some(format!(
            ", and a link card for {raw} titled \"{}\"",
            card.embed["external"]["title"].as_str().unwrap_or_default()
        ));
        thumbnail = card.thumbnail;
        record.insert("embed".to_string(), card.embed);
    } else if let Some(media) = &request.media {
        let Some(account) = account.as_mut() else {
            return Err(invalid("images need a stored account to upload them to"));
        };
        let embed = media_embed(ctx, rctx, media, account, &mut notes).await?;
        card_summary = Some(format!(
            ", and an {} of {} image{} uploaded to {}'s PDS",
            media.kind.nsid(),
            embed.uploaded.len(),
            if embed.uploaded.len() == 1 { "" } else { "s" },
            account.handle
        ));
        uploaded = embed.uploaded;
        record.insert("embed".to_string(), embed.value);
    }

    let record = Value::Object(record);
    validate(&record)?;

    let count = record["facets"].as_array().map_or(0, Vec::len);
    let mut summary = format!(
        "Generated an {POST_NSID} record with {count} facet{}",
        if count == 1 { "" } else { "s" }
    );
    if let Some(card) = card_summary {
        summary.push_str(&card);
    }
    let publisher = match (&thumbnail, &account) {
        (Some(uploaded), Some(account)) => {
            summary.push_str(&format!(
                ", with a thumbnail uploaded to {}'s PDS (blob {})",
                account.handle, uploaded.cid
            ));
            format!(
                "{}, the account its thumbnail was uploaded to",
                account.handle
            )
        }
        (None, Some(account)) if !uploaded.is_empty() => {
            format!(
                "{}, the account its images were uploaded to",
                account.handle
            )
        }
        _ => "the account that should post it".to_string(),
    };
    summary.push_str(&format!(
        ". It is not published: create it with invoke_xrpc com.atproto.repo.createRecord \
         (collection {POST_NSID}) as {publisher}."
    ));
    for note in &notes {
        summary.push_str(&format!(" Note: {note}."));
    }

    let mut structured = serde_json::json!({ "record": record, "notes": notes });
    let described = |uploaded: &Uploaded| {
        serde_json::json!({
            "cid": uploaded.cid,
            "uri": uploaded.uri,
            "verified": uploaded.verified,
        })
    };
    if let Some(uploaded) = &thumbnail {
        structured["thumbnail"] = described(uploaded);
    }
    if !uploaded.is_empty() {
        structured["uploaded"] = Value::from(uploaded.iter().map(described).collect::<Vec<_>>());
    }
    Ok(tool_structured(&summary, structured, Vec::new()))
}

/// The facets for `text` under `allow`, and a note for each mention, link or
/// tag in it that has none.
async fn facets_for(
    text: &str,
    allow: &FacetAllowList,
    resolver: &dyn IdentityResolver,
) -> (Vec<Facet>, Vec<String>) {
    let limits = FacetLimits::default();
    let facets = parse_facets_allowed(text, resolver, &limits, allow)
        .await
        .unwrap_or_default();
    let mut notes = Vec::new();

    let mentioned: HashSet<usize> = facets
        .iter()
        .filter(|facet| matches!(facet.features.first(), Some(FacetFeature::Mention(_))))
        .map(|facet| facet.index.byte_start)
        .collect();
    let spans = parse_mention_spans(text);
    let admitted = spans
        .iter()
        .filter(|span| allow.admits_mention(&span.handle))
        .count();
    for span in &spans {
        if !allow.admits_mention(&span.handle) {
            notes.push(format!(
                "@{} has no facet: mention_facet_allow leaves it out",
                span.handle
            ));
        } else if !mentioned.contains(&span.index.byte_start) {
            notes.push(if admitted > limits.mentions_max {
                format!(
                    "@{} has no facet: it did not resolve to a DID, or the post has more than {} mentions",
                    span.handle, limits.mentions_max
                )
            } else {
                format!("@{} has no facet: it did not resolve to a DID", span.handle)
            });
        }
    }

    let links = parse_urls(text);
    for facet in &links {
        if let Some(FacetFeature::Link(link)) = facet.features.first()
            && !allow.admits_link(&link.uri)
        {
            notes.push(format!(
                "{} has no facet: link_facet_allow leaves it out",
                link.uri
            ));
        }
    }
    let tags = parse_tags(text);
    for facet in &tags {
        if let Some(FacetFeature::Tag(tag)) = facet.features.first()
            && !allow.admits_tag(&tag.tag)
        {
            notes.push(format!(
                "#{} has no facet: tag_facet_allow leaves it out",
                tag.tag
            ));
        }
    }

    // Past the limits: what was admitted and still has no facet.
    let kept = |kind: fn(&FacetFeature) -> bool| {
        facets
            .iter()
            .filter(|facet| facet.features.first().is_some_and(kind))
            .count()
    };
    let admitted_links = links
        .iter()
        .filter(|facet| match facet.features.first() {
            Some(FacetFeature::Link(link)) => allow.admits_link(&link.uri),
            _ => false,
        })
        .count();
    let admitted_tags = tags
        .iter()
        .filter(|facet| match facet.features.first() {
            Some(FacetFeature::Tag(tag)) => allow.admits_tag(&tag.tag),
            _ => false,
        })
        .count();
    for (noun, admitted, kept) in [
        (
            "links",
            admitted_links,
            kept(|f| matches!(f, FacetFeature::Link(_))),
        ),
        (
            "tags",
            admitted_tags,
            kept(|f| matches!(f, FacetFeature::Tag(_))),
        ),
    ] {
        if kept < admitted {
            notes.push(format!(
                "{} of the post's {noun} have no facet: a post gets at most {} links, {} tags and {} facets in all",
                admitted - kept,
                limits.links_max,
                limits.tags_max,
                limits.max
            ));
        }
    }

    (facets, notes)
}

/// A link card, and the thumbnail uploaded for it if there is one.
struct Card {
    /// The `app.bsky.embed.external` value.
    embed: Value,
    thumbnail: Option<Uploaded>,
}

/// Build the link card for the page at `url`, given as `raw`.
async fn link_card(
    ctx: &Arc<ServerContext>,
    rctx: &mut RequestCtx,
    raw: &str,
    url: &Url,
    account: Option<&mut accounts::Account>,
    notes: &mut Vec<String>,
) -> Result<Card, ToolError> {
    let failed = |reason: String| ToolError::LinkCardFailed {
        url: raw.to_string(),
        reason,
    };

    check_url(ctx, url)?;
    let page = fetch(
        &ctx.web_client,
        url,
        "text/html, application/xhtml+xml",
        MAX_PAGE_BYTES,
        Overflow::Truncate,
    )
    .await
    .map_err(|error| failed(error.to_string()))?;
    if !is_html(page.content_type.as_deref(), &page.body) {
        return Err(failed(format!(
            "the page is served as {}, not HTML",
            page.content_type.as_deref().unwrap_or("an unnamed type")
        )));
    }
    let html = decode(&page.body, page.content_type.as_deref());
    let found = extract_link_card(&html, &page.url);

    let mut external = serde_json::json!({
        "uri": raw,
        "title": found.title,
        "description": found.description,
    });

    let thumbnail = match (found.image, account) {
        (None, _) => {
            notes.push("the card has no thumbnail: the page names no image".to_string());
            None
        }
        (Some(image), None) => {
            notes.push(format!(
                "the card has no thumbnail: pass auth_handle to upload the page's image ({image}) to that account"
            ));
            None
        }
        (Some(image), Some(account)) => match thumbnail_bytes(ctx, &image).await {
            Err(reason) => {
                notes.push(format!("the card has no thumbnail: {reason}"));
                None
            }
            Ok(thumb) => {
                if let Some(note) = thumb.note {
                    notes.push(note);
                }
                let uploaded = put_blob(ctx, rctx, account, thumb.data, &thumb.mime_type).await?;
                external["thumb"] = uploaded.blob.clone();
                Some(uploaded)
            }
        },
    };

    Ok(Card {
        embed: serde_json::json!({ "$type": EXTERNAL_NSID, "external": external }),
        thumbnail,
    })
}

/// An image ready to upload.
struct Thumb {
    data: Vec<u8>,
    mime_type: String,
    /// Set when the image was changed beyond having its metadata removed, or
    /// had metadata removed, saying what was done.
    note: Option<String>,
}

/// The thumbnail for the image at `image`, or why there is none.
async fn thumbnail_bytes(ctx: &ServerContext, image: &Url) -> Result<Thumb, String> {
    let label = format!("the page's image ({image})");
    let fetched = fetch_image(ctx, image, &label).await?;
    prepare_image(
        ctx.limits.preserve_exif,
        fetched.body,
        fetched.content_type.as_deref(),
        MAX_THUMB_BYTES,
        &label,
    )
    .await
}

/// Fetch the image at `url` up to the download ceiling, under the endpoint
/// policy. `label` names it in the reason it could not be had.
async fn fetch_image(ctx: &ServerContext, url: &Url, label: &str) -> Result<Fetched, String> {
    check_url(ctx, url).map_err(|error| format!("{label} is refused: {error}"))?;
    let ceiling = ctx.limits.blob_max_download_bytes;
    fetch(&ctx.web_client, url, "image/*", ceiling, Overflow::Refuse)
        .await
        .map_err(|error| match error {
            FetchError::TooLarge => format!(
                "{label} is over {ceiling} bytes, atpmcp's download ceiling \
                 (ATPMCP_BLOB_MAX_DOWNLOAD_BYTES)"
            ),
            FetchError::Failed(reason) => format!("{label} could not be fetched: {reason}"),
        })
}

/// Make `body` an image fit to upload under `limit_bytes`, or say why it is
/// not one. `label` names it in notes and reasons.
///
/// The bytes decide what it is, not `served`, the type it came labelled as.
/// One at or under the limit has its metadata removed without re-encoding
/// ([`crate::image_metadata::strip`]), or is used as it is when `preserve`
/// (`ATPMCP_PRESERVE_EXIF`) is on. One over the limit, or one whose EXIF says
/// it is stored turned, is re-encoded as a JPEG that fits by
/// [`crate::thumbnail::shrink`], on a blocking thread, since decoding is CPU
/// work on bytes that may be a third party's.
async fn prepare_image(
    preserve: bool,
    body: Vec<u8>,
    served: Option<&str>,
    limit_bytes: u64,
    label: &str,
) -> Result<Thumb, String> {
    // A host can label anything an image, and a type recorded on a blob is
    // permanent. SVG has no magic bytes and can carry script, so it is never
    // recognised here, which is the intent.
    let sniffed = match mime::sniff(&body) {
        Some(sniffed) if mime::is_image(sniffed) => sniffed,
        _ => {
            return Err(format!(
                "{label} is not a recognised image{}",
                served
                    .map(|served| format!(" (served as {served})"))
                    .unwrap_or_default()
            ));
        }
    };

    let size = body.len();
    let limit = usize::try_from(limit_bytes).unwrap_or(usize::MAX);

    // At or under the limit, the image is used as it is when the operator
    // preserves EXIF, and otherwise with its metadata removed -- unless that
    // metadata is what says it is stored turned, when it is re-encoded with
    // the turn applied.
    let mut turned = false;
    if size <= limit {
        if preserve {
            return Ok(Thumb {
                data: body,
                mime_type: sniffed.to_string(),
                note: None,
            });
        }
        let stripped = crate::image_metadata::strip(&body).map_err(|reason| {
            format!("{label}: {reason}; with ATPMCP_PRESERVE_EXIF=1 it would be used as it is")
        })?;
        if !stripped.needs_turning() {
            return Ok(Thumb {
                data: stripped.bytes,
                mime_type: sniffed.to_string(),
                note: stripped
                    .removed
                    .then(|| format!("{label} had its metadata (EXIF and the like) removed")),
            });
        }
        turned = true;
    }

    let shrunk =
        tokio::task::spawn_blocking(move || crate::thumbnail::shrink(&body, limit, preserve))
            .await
            .map_err(|error| format!("re-encoding {label} failed: {error}"))?
            .map_err(|reason| {
                if turned {
                    format!("{label} is stored turned, and re-encoding it failed: {reason}")
                } else {
                    format!(
                        "{label} is {size} bytes, over the lexicon's {limit_bytes}-byte limit, \
                         and {reason}"
                    )
                }
            })?;
    let note = if turned {
        format!(
            "{label} is stored turned, which only its EXIF says, so it was re-encoded as a \
             {}x{} JPEG of {} bytes with the turn applied and no metadata",
            shrunk.width,
            shrunk.height,
            shrunk.bytes.len()
        )
    } else {
        format!(
            "{label} was {size} bytes, {}x{}, so it was shrunk to a {}x{} JPEG of {} bytes, {}",
            shrunk.source_width,
            shrunk.source_height,
            shrunk.width,
            shrunk.height,
            shrunk.bytes.len(),
            if preserve {
                "with its EXIF copied in"
            } else {
                "without its metadata"
            }
        )
    };
    Ok(Thumb {
        data: shrunk.bytes,
        mime_type: "image/jpeg".to_string(),
        note: Some(note),
    })
}

/// A `gallery` or `images` embed, and the blobs uploaded for it.
struct MediaEmbed {
    value: Value,
    uploaded: Vec<Uploaded>,
}

/// Build the `gallery` or `images` embed, uploading its images as `account`.
///
/// Every image is read, checked and prepared before any is uploaded, so an
/// image that cannot be used fails the call with nothing uploaded. An upload
/// that fails part-way through leaves the earlier blobs on the PDS, where a
/// blob no record references is temporary.
async fn media_embed(
    ctx: &Arc<ServerContext>,
    rctx: &mut RequestCtx,
    media: &Media,
    account: &mut accounts::Account,
    notes: &mut Vec<String>,
) -> Result<MediaEmbed, ToolError> {
    let failed = |reason: String| ToolError::ImageFailed { reason };
    let mut prepared = Vec::with_capacity(media.items.len());
    for item in &media.items {
        let (body, served) = match &item.source {
            ImageSource::Path(path) => (
                crate::tools::blob::read_local_file(path, ctx.limits.blob_max_upload_bytes).await?,
                None,
            ),
            ImageSource::Url(url) => {
                let fetched = fetch_image(ctx, url, &item.label).await.map_err(failed)?;
                (fetched.body, fetched.content_type)
            }
        };
        let image = prepare_image(
            ctx.limits.preserve_exif,
            body,
            served.as_deref(),
            MAX_MEDIA_IMAGE_BYTES,
            &item.label,
        )
        .await
        .map_err(failed)?;
        // A gallery item must say its aspect ratio; an `images` item may.
        let dimensions = match (
            crate::thumbnail::display_dimensions(&image.data),
            media.kind,
        ) {
            (Ok(dimensions), _) => Some(dimensions),
            (Err(_), MediaKind::Images) => None,
            (Err(reason), MediaKind::Gallery) => {
                return Err(failed(format!(
                    "{}: {reason}, and a gallery item needs its aspect ratio",
                    item.label
                )));
            }
        };
        prepared.push((item, image, dimensions));
    }

    let mut entries = Vec::with_capacity(prepared.len());
    let mut uploaded = Vec::with_capacity(prepared.len());
    for (item, image, dimensions) in prepared {
        if let Some(note) = image.note {
            notes.push(note);
        }
        let blob = put_blob(ctx, rctx, account, image.data, &image.mime_type).await?;
        let mut entry = serde_json::json!({ "alt": item.alt, "image": blob.blob });
        if let Some((width, height)) = dimensions {
            entry["aspectRatio"] = serde_json::json!({ "width": width, "height": height });
        }
        if media.kind == MediaKind::Gallery {
            entry["$type"] = Value::from(format!("{GALLERY_NSID}#image"));
        }
        entries.push(entry);
        uploaded.push(blob);
    }

    let unlabelled: Vec<String> = media
        .items
        .iter()
        .enumerate()
        .filter(|(_, item)| item.alt.is_empty())
        .map(|(index, _)| (index + 1).to_string())
        .collect();
    if !unlabelled.is_empty() {
        notes.push(format!(
            "{} item{} {} {} no alt text",
            media.kind.argument(),
            if unlabelled.len() == 1 { "" } else { "s" },
            unlabelled.join(", "),
            if unlabelled.len() == 1 { "has" } else { "have" }
        ));
    }

    let value = match media.kind {
        MediaKind::Gallery => serde_json::json!({ "$type": GALLERY_NSID, "items": entries }),
        MediaKind::Images => serde_json::json!({ "$type": IMAGES_NSID, "images": entries }),
    };
    Ok(MediaEmbed { value, uploaded })
}

/// A URL's text as the Bluesky app shows it in a post: social-app's
/// `toShortUrl` (`src/lib/strings/url-helpers.ts`).
///
/// The scheme goes; the host (with a port, if any) and the path, query and
/// fragment stay, and a path-and-after over 15 characters is cut to its first
/// 13 and `...`. A root path counts as none. Text that is not an `http` or
/// `https` URL is left as it is.
fn to_short_url(text: &str) -> String {
    let Ok(url) = Url::parse(text) else {
        return text.to_string();
    };
    if !matches!(url.scheme(), "http" | "https") {
        return text.to_string();
    }
    let Some(host) = url.host_str() else {
        return text.to_string();
    };
    let host = match url.port() {
        Some(port) => format!("{host}:{port}"),
        None => host.to_string(),
    };
    let mut path = if url.path() == "/" {
        String::new()
    } else {
        url.path().to_string()
    };
    // As the WHATWG URL `search` and `hash` are: empty when there is nothing
    // after the `?` or the `#`.
    if let Some(query) = url.query().filter(|query| !query.is_empty()) {
        path.push('?');
        path.push_str(query);
    }
    if let Some(fragment) = url.fragment().filter(|fragment| !fragment.is_empty()) {
        path.push('#');
        path.push_str(fragment);
    }
    // JavaScript counts UTF-16 units; a URL's path is percent-encoded ASCII,
    // where the two agree.
    if path.encode_utf16().count() > 15 {
        format!("{host}{}...", path.chars().take(13).collect::<String>())
    } else {
        format!("{host}{path}")
    }
}

/// `text` with each link facet's text shortened by [`to_short_url`], and
/// every facet moved to the bytes it covers afterwards: social-app's
/// `shortenLinks` (`src/lib/strings/rich-text-manip.ts`). A link facet keeps
/// its full URL; only the text it covers changes.
///
/// Facets that overlap, or that do not fall on character boundaries, leave
/// everything as it was. The parser never produces either.
fn shorten_links(text: &str, facets: &[Facet]) -> (String, Vec<Facet>) {
    let unchanged = || (text.to_string(), facets.to_vec());
    let mut order: Vec<usize> = (0..facets.len()).collect();
    order.sort_by_key(|&index| facets[index].index.byte_start);

    let mut shortened = String::with_capacity(text.len());
    let mut moved = facets.to_vec();
    let mut cursor = 0;
    for index in order {
        let (start, end) = (facets[index].index.byte_start, facets[index].index.byte_end);
        if start < cursor
            || end < start
            || end > text.len()
            || !text.is_char_boundary(start)
            || !text.is_char_boundary(end)
        {
            return unchanged();
        }
        shortened.push_str(&text[cursor..start]);
        let new_start = shortened.len();
        let covered = &text[start..end];
        match facets[index].features.first() {
            Some(FacetFeature::Link(_)) => shortened.push_str(&to_short_url(covered)),
            _ => shortened.push_str(covered),
        }
        moved[index].index.byte_start = new_start;
        moved[index].index.byte_end = shortened.len();
        cursor = end;
    }
    shortened.push_str(&text[cursor..]);
    (shortened, moved)
}

/// Hold a URL a page or a caller named to the endpoint policy.
///
/// The policy refuses a query and a fragment, because a service endpoint has
/// neither; a web page may have both. They are set aside for the check, as
/// `validated_policy` does for each redirect: what the policy is about is the
/// scheme, the host and the port.
fn check_url(ctx: &ServerContext, url: &Url) -> Result<(), ToolError> {
    let mut bare = url.clone();
    bare.set_query(None);
    bare.set_fragment(None);
    host_policy::check_endpoint(&ctx.limits, bare.as_str())
}

/// What [`fetch`] brought back.
struct Fetched {
    /// Where the body came from, after redirects.
    url: Url,
    /// The `Content-Type` header, if there was one.
    content_type: Option<String>,
    /// The body, at most the cap.
    body: Vec<u8>,
}

/// What [`fetch`] does with a body longer than its cap.
#[derive(Clone, Copy)]
enum Overflow {
    /// Keep the first `cap` bytes.
    Truncate,
    /// Fail with [`FetchError::TooLarge`].
    Refuse,
}

/// Why [`fetch`] failed.
enum FetchError {
    /// The body is over the cap, under [`Overflow::Refuse`].
    TooLarge,
    /// Anything else, described.
    Failed(String),
}

impl std::fmt::Display for FetchError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::TooLarge => f.write_str("the response is too large"),
            Self::Failed(reason) => f.write_str(reason),
        }
    }
}

/// `GET` `url`, reading at most `cap` bytes of the body.
///
/// `Content-Length` is the host's claim, so it only refuses early; the running
/// total is what bounds the read.
async fn fetch(
    client: &reqwest::Client,
    url: &Url,
    accept: &str,
    cap: u64,
    overflow: Overflow,
) -> Result<Fetched, FetchError> {
    let response = client
        .get(url.clone())
        .header(ACCEPT, accept)
        .send()
        .await
        .map_err(|error| {
            // `Debug` names a refused redirect's target; `Display` stops at
            // "error following redirect".
            tracing::debug!(error = ?error, url = %url, "A link card fetch failed.");
            FetchError::Failed(describe(&error))
        })?;

    let status = response.status();
    if !status.is_success() {
        return Err(FetchError::Failed(format!(
            "{} answered HTTP {}",
            response.url(),
            status.as_u16()
        )));
    }
    if matches!(overflow, Overflow::Refuse)
        && response
            .content_length()
            .is_some_and(|declared| declared > cap)
    {
        return Err(FetchError::TooLarge);
    }

    let final_url = response.url().clone();
    let content_type = response
        .headers()
        .get(CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .map(str::to_string);

    let cap = usize::try_from(cap).unwrap_or(usize::MAX);
    let mut body = Vec::new();
    let mut stream = response.bytes_stream();
    while let Some(chunk) = stream.next().await {
        let chunk = chunk.map_err(|error| {
            FetchError::Failed(format!("reading {final_url} failed: {}", describe(&error)))
        })?;
        let room = cap - body.len();
        if chunk.len() > room {
            match overflow {
                Overflow::Truncate => {
                    body.extend_from_slice(&chunk[..room]);
                    break;
                }
                Overflow::Refuse => return Err(FetchError::TooLarge),
            }
        }
        body.extend_from_slice(&chunk);
    }

    Ok(Fetched {
        url: final_url,
        content_type,
        body,
    })
}

/// An error and its sources, as one line.
fn describe(error: &dyn std::error::Error) -> String {
    let mut text = error.to_string();
    let mut source = error.source();
    while let Some(next) = source {
        text.push_str(": ");
        text.push_str(&next.to_string());
        source = next.source();
    }
    text
}

/// A `Content-Type`'s type and subtype, lowercased, without parameters.
fn base_type(content_type: &str) -> String {
    content_type
        .split(';')
        .next()
        .unwrap_or_default()
        .trim()
        .to_ascii_lowercase()
}

/// Whether a response is a page: served as HTML or XHTML, or served with no
/// type and starting like an HTML document.
fn is_html(content_type: Option<&str>, body: &[u8]) -> bool {
    match content_type.map(base_type).as_deref() {
        Some("text/html" | "application/xhtml+xml") => true,
        Some(_) => false,
        None => {
            let start = String::from_utf8_lossy(&body[..body.len().min(64)]).to_ascii_lowercase();
            let start = start.trim_start_matches('\u{feff}').trim_start();
            start.starts_with("<!doctype html") || start.starts_with("<html")
        }
    }
}

/// A page's text, in the charset its `Content-Type` names, else UTF-8.
///
/// A byte-order mark overrides either, and a sequence that does not decode
/// becomes U+FFFD, so a page cut off at the cap mid-character still parses.
/// A charset named only in a `<meta>` tag is not read: nearly every page that
/// declares one there declares UTF-8.
fn decode(body: &[u8], content_type: Option<&str>) -> String {
    let encoding = content_type
        .and_then(|value| {
            value.split(';').skip(1).find_map(|parameter| {
                let (name, label) = parameter.split_once('=')?;
                name.trim()
                    .eq_ignore_ascii_case("charset")
                    .then(|| label.trim().trim_matches('"').to_string())
            })
        })
        .and_then(|label| encoding_rs::Encoding::for_label(label.as_bytes()))
        .unwrap_or(encoding_rs::UTF_8);
    encoding.decode(body).0.into_owned()
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use async_trait::async_trait;
    use atproto_identity::model::Document;

    use super::*;
    use crate::tools::test_support::{Route, route_server, test_context, test_request};

    async fn call(arguments: Value) -> Value {
        let ctx = test_context();
        let mut rctx = test_request();
        generate_bsky_post(&ctx, &mut rctx, arguments).await
    }

    fn record_of(result: &Value) -> &Value {
        assert_eq!(result["isError"], false, "{result}");
        &result["structuredContent"]["record"]
    }

    fn notes_of(result: &Value) -> Vec<String> {
        result["structuredContent"]["notes"]
            .as_array()
            .expect("notes")
            .iter()
            .map(|note| note.as_str().unwrap().to_string())
            .collect()
    }

    fn error_of(result: &Value) -> String {
        assert_eq!(result["isError"], true, "{result}");
        result["content"][0]["text"].as_str().unwrap().to_string()
    }

    /// A resolver that knows a fixed set of handles.
    struct FixedResolver(HashMap<&'static str, &'static str>);

    #[async_trait]
    impl IdentityResolver for FixedResolver {
        async fn resolve(&self, subject: &str) -> anyhow::Result<Document> {
            let did = self
                .0
                .get(subject)
                .ok_or_else(|| anyhow::anyhow!("unknown handle {subject}"))?;
            Ok(Document {
                context: vec![],
                id: (*did).to_string(),
                also_known_as: vec![format!("at://{subject}")],
                verification_method: vec![],
                service: vec![],
                extra: HashMap::new(),
            })
        }
    }

    fn resolver() -> FixedResolver {
        FixedResolver(HashMap::from([(
            "ngerakines.me",
            "did:plc:cbkjy5n7bk3ax2wplmtjofq2",
        )]))
    }

    fn allow_mentions(mentions: &[&str]) -> FacetAllowList {
        FacetAllowList {
            mentions: mentions.iter().map(|m| (*m).to_string()).collect(),
            ..FacetAllowList::default()
        }
    }

    #[test]
    fn every_bundled_lexicon_parses() {
        for (nsid, _) in LEXICONS {
            assert!(CATALOG.get_schema(nsid).is_some(), "{nsid} did not parse");
        }
    }

    /// The bundled copies are `atproto-pds`'s, byte for byte, so the two
    /// cannot drift apart.
    #[test]
    fn the_bundled_lexicons_are_atproto_pds_copies() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        for (nsid, json) in LEXICONS {
            let path = format!("{}.json", nsid.replace('.', "/"));
            let theirs = std::fs::read_to_string(root.join("../atproto-pds/lexicons").join(&path))
                .unwrap_or_else(|error| panic!("{path}: {error}"));
            assert_eq!(*json, theirs, "{path} differs from atproto-pds's copy");
        }
    }

    /// The catalog checks the card itself, not only the post around it: a
    /// card missing a required field, or with a thumbnail over the lexicon's
    /// size, is refused. Were the embed union's refs skipped when unresolved,
    /// "the record validates" would say nothing about the card.
    #[test]
    fn the_catalog_checks_the_link_card() {
        let post = |external: Value| {
            serde_json::json!({
                "$type": POST_NSID,
                "text": "x",
                "createdAt": "2026-11-18T00:00:00.000Z",
                "embed": { "$type": EXTERNAL_NSID, "external": external },
            })
        };
        let valid = |record: &Value| {
            validate_record(POST_NSID, record, &*CATALOG, ValidateFlags::empty()).is_ok()
        };
        let thumb = |size: u64| {
            serde_json::json!({
                "$type": "blob",
                "ref": { "$link": "bafkreidyl3nf2xm3iyswuw5mj42dwz5mogk45kxwcdzufj6oc27e4cpzqy" },
                "mimeType": "image/jpeg",
                "size": size,
            })
        };

        assert!(valid(&post(serde_json::json!({
            "uri": "https://example.com/", "title": "t", "description": "",
            "thumb": thumb(166_721),
        }))));
        assert!(!valid(&post(
            serde_json::json!({ "uri": "https://example.com/", "description": "" })
        )));
        assert!(!valid(&post(serde_json::json!({
            "uri": "https://example.com/", "title": "t", "description": "",
            "thumb": thumb(MAX_THUMB_BYTES + 1),
        }))));
        assert!(!valid(&post(serde_json::json!({
            "uri": "not a uri", "title": "t", "description": "",
        }))));
    }

    // Example 1.
    #[tokio::test]
    async fn a_plain_text_is_a_plain_post() {
        let result = call(serde_json::json!({ "text": "hello world" })).await;
        let record = record_of(&result);
        assert_eq!(record["$type"], POST_NSID);
        assert_eq!(record["text"], "hello world");
        assert_eq!(record["langs"], serde_json::json!(["en"]));
        assert!(record.get("facets").is_none());
        assert!(record.get("embed").is_none());
        let created = record["createdAt"].as_str().unwrap();
        assert!(
            atproto_record::datetime::Datetime::new(created).is_ok(),
            "{created}"
        );
        assert!(created.ends_with('Z') && created.len() == 24, "{created}");
        assert!(notes_of(&result).is_empty());
    }

    #[tokio::test]
    async fn the_text_is_kept_exactly() {
        let text = "Hello  World\n\nwith a ✨ and trailing space ";
        let result = call(serde_json::json!({ "text": text })).await;
        assert_eq!(record_of(&result)["text"], text);
    }

    // Examples 2 and 3: no list, or an empty one, keeps the mention.
    #[tokio::test]
    async fn an_absent_or_empty_mention_list_keeps_every_mention() {
        for allow in [FacetAllowList::default(), allow_mentions(&[])] {
            let (facets, notes) = facets_for("Hello @ngerakines.me", &allow, &resolver()).await;
            assert_eq!(facets.len(), 1);
            assert_eq!(facets[0].index.byte_start, 6);
            assert_eq!(facets[0].index.byte_end, 20);
            assert!(matches!(
                &facets[0].features[0],
                FacetFeature::Mention(mention) if mention.did == "did:plc:cbkjy5n7bk3ax2wplmtjofq2"
            ));
            assert!(notes.is_empty(), "{notes:?}");
        }
    }

    // Example 4: a list that does not name the mention leaves it out.
    #[tokio::test]
    async fn a_mention_list_leaves_out_what_it_does_not_name() {
        let (facets, notes) = facets_for(
            "Hello @ngerakines.me",
            &allow_mentions(&["@mattie.thegem.city"]),
            &resolver(),
        )
        .await;
        assert!(facets.is_empty());
        assert_eq!(
            notes,
            vec!["@ngerakines.me has no facet: mention_facet_allow leaves it out"]
        );
    }

    /// The same through the tool, which needs no resolver for it: a mention
    /// the list leaves out is never looked up.
    #[tokio::test]
    async fn example_four_through_the_tool() {
        let result = call(serde_json::json!({
            "text": "Hello @ngerakines.me",
            "mention_facet_allow": ["@mattie.thegem.city"],
        }))
        .await;
        let record = record_of(&result);
        assert_eq!(record["text"], "Hello @ngerakines.me");
        assert!(record.get("facets").is_none());
        assert_eq!(notes_of(&result).len(), 1);
    }

    #[tokio::test]
    async fn an_unresolved_mention_is_noted() {
        let (facets, notes) = facets_for(
            "Hi @nobody.example",
            &FacetAllowList::default(),
            &resolver(),
        )
        .await;
        assert!(facets.is_empty());
        assert_eq!(
            notes,
            vec!["@nobody.example has no facet: it did not resolve to a DID"]
        );
    }

    #[tokio::test]
    async fn link_and_tag_lists_filter_their_own_kind() {
        let result = call(serde_json::json!({
            "text": "see https://a.example and https://b.example #rust #go",
            "link_facet_allow": ["https://b.example"],
            "tag_facet_allow": ["#Rust"],
        }))
        .await;
        let facets = record_of(&result)["facets"].as_array().unwrap().clone();
        assert_eq!(facets.len(), 2);
        assert_eq!(facets[0]["features"][0]["uri"], "https://b.example");
        assert_eq!(facets[1]["features"][0]["tag"], "rust");
        let notes = notes_of(&result);
        assert!(
            notes
                .iter()
                .any(|n| n.starts_with("https://a.example has no facet"))
        );
        assert!(notes.iter().any(|n| n.starts_with("#go has no facet")));
    }

    #[tokio::test]
    async fn links_past_the_limit_are_noted() {
        let text = (1..=6)
            .map(|n| format!("https://site{n}.example"))
            .collect::<Vec<_>>()
            .join(" ");
        let result = call(serde_json::json!({ "text": text })).await;
        assert_eq!(record_of(&result)["facets"].as_array().unwrap().len(), 5);
        assert!(
            notes_of(&result)
                .iter()
                .any(|n| n.starts_with("1 of the post's links have no facet"))
        );
    }

    #[tokio::test]
    async fn langs_default_to_english_and_can_be_given_or_left_out() {
        let given = call(serde_json::json!({ "text": "salut", "langs": ["fr", "en-CA"] })).await;
        assert_eq!(
            record_of(&given)["langs"],
            serde_json::json!(["fr", "en-CA"])
        );

        let none = call(serde_json::json!({ "text": "salut", "langs": [] })).await;
        assert!(record_of(&none).get("langs").is_none());

        let null = call(serde_json::json!({ "text": "hi", "langs": null })).await;
        assert_eq!(record_of(&null)["langs"], serde_json::json!(["en"]));
    }

    #[tokio::test]
    async fn bad_arguments_are_refused() {
        for (arguments, expect) in [
            (serde_json::json!({}), "'text'"),
            (serde_json::json!({ "text": 5 }), "'text'"),
            (
                serde_json::json!({ "text": "x", "langs": ["en", "fr", "de", "es"] }),
                "at most 3",
            ),
            (serde_json::json!({ "text": "x", "langs": "en" }), "'langs'"),
            (
                serde_json::json!({ "text": "x", "mention_facet_allow": "@a.example" }),
                "'mention_facet_allow'",
            ),
            (
                serde_json::json!({ "text": "x", "tag_facet_allow": [1] }),
                "'tag_facet_allow'",
            ),
            (
                serde_json::json!({ "text": "x", "embed_external": "not a url" }),
                "absolute URL",
            ),
            (
                serde_json::json!({ "text": "x", "embed_external": "ftp://example.com/" }),
                "http or https",
            ),
        ] {
            let error = error_of(&call(arguments.clone()).await);
            assert!(error.starts_with("error-atpmcp-tool-23 "), "{error}");
            assert!(error.contains(expect), "{arguments}: {error}");
        }
    }

    /// The lexicon's limits are enforced here, not left to the PDS.
    #[tokio::test]
    async fn a_record_the_lexicon_refuses_is_not_returned() {
        let too_long = call(serde_json::json!({ "text": "x".repeat(301) })).await;
        assert!(error_of(&too_long).contains("does not validate"));

        let bad_lang = call(serde_json::json!({ "text": "x", "langs": ["not a language!"] })).await;
        assert!(error_of(&bad_lang).contains("does not validate"));
    }

    const PAGE: &str = r#"<!doctype html><html><head>
        <title>Fallback title</title>
        <meta property="og:title" content="A bit about email">
        <meta property="og:description" content="Notes &amp; history">
        <meta property="og:image" content="/card.png">
        </head><body><p>Hello</p></body></html>"#;

    // Example 5, without an account: the card, and no thumbnail.
    #[tokio::test]
    async fn a_link_card_comes_from_the_pages_open_graph_metadata() {
        let base = route_server(vec![Route::ok("/misc/email/", "text/html", PAGE)]).await;
        let page = format!("{base}/misc/email/");
        let result = call(serde_json::json!({
            "text": format!("Check out {page}"),
            "embed_external": page,
        }))
        .await;

        let record = record_of(&result);
        assert_eq!(record["embed"]["$type"], EXTERNAL_NSID);
        let external = &record["embed"]["external"];
        assert_eq!(external["uri"], page);
        assert_eq!(external["title"], "A bit about email");
        assert_eq!(external["description"], "Notes & history");
        assert!(external.get("thumb").is_none());
        assert_eq!(record["facets"][0]["features"][0]["uri"], page);
        let notes = notes_of(&result);
        assert!(
            notes[0].contains("pass auth_handle") && notes[0].contains(&format!("{base}/card.png")),
            "{notes:?}"
        );
    }

    #[tokio::test]
    async fn a_page_with_no_metadata_still_makes_a_valid_card() {
        let base = route_server(vec![Route::ok(
            "/",
            "text/html; charset=utf-8",
            "<p>bare</p>",
        )])
        .await;
        let result =
            call(serde_json::json!({ "text": "x", "embed_external": format!("{base}/") })).await;
        let external = &record_of(&result)["embed"]["external"];
        assert_eq!(external["title"], "");
        assert_eq!(external["description"], "");
        assert!(notes_of(&result)[0].contains("names no image"));
    }

    #[tokio::test]
    async fn a_page_in_another_charset_is_decoded() {
        let mut body = b"<head><meta property=\"og:title\" content=\"caf".to_vec();
        body.push(0xE9); // "é" in windows-1252
        body.extend_from_slice(b"\"></head>");
        let base = route_server(vec![Route::ok(
            "/",
            "text/html; charset=windows-1252",
            body,
        )])
        .await;
        let result =
            call(serde_json::json!({ "text": "x", "embed_external": format!("{base}/") })).await;
        assert_eq!(record_of(&result)["embed"]["external"]["title"], "café");
    }

    #[tokio::test]
    async fn a_page_past_the_cap_is_read_as_far_as_the_cap() {
        let mut body = PAGE.replace("<p>Hello</p>", "").into_bytes();
        body.extend(std::iter::repeat_n(b'x', MAX_PAGE_BYTES as usize + 10));
        let base = route_server(vec![Route::ok("/", "text/html", body)]).await;
        let result =
            call(serde_json::json!({ "text": "x", "embed_external": format!("{base}/") })).await;
        assert_eq!(
            record_of(&result)["embed"]["external"]["title"],
            "A bit about email"
        );
    }

    #[tokio::test]
    async fn a_page_that_cannot_be_read_is_an_error() {
        let base = route_server(vec![
            Route::ok("/json", "application/json", "{}"),
            Route {
                path: "/gone",
                status: 410,
                headers: vec![],
                body: Vec::new(),
            },
        ])
        .await;
        for (path, expect) in [
            ("/json", "not HTML"),
            ("/gone", "HTTP 410"),
            ("/missing", "HTTP 404"),
        ] {
            let error = error_of(
                &call(
                    serde_json::json!({ "text": "x", "embed_external": format!("{base}{path}") }),
                )
                .await,
            );
            assert!(error.starts_with("error-atpmcp-tool-24 "), "{error}");
            assert!(error.contains(expect), "{path}: {error}");
        }
    }

    /// A redirect is checked against the policy, and the waiver these tests
    /// run under does not cover it: the first URL may be a local server, but
    /// a hop to one is refused.
    #[tokio::test]
    async fn a_redirect_to_a_local_address_is_refused() {
        let base = route_server(vec![Route {
            path: "/hop",
            status: 302,
            headers: vec![("Location", "http://127.0.0.1:9/admin".to_string())],
            body: Vec::new(),
        }])
        .await;
        let error = error_of(
            &call(serde_json::json!({ "text": "x", "embed_external": format!("{base}/hop") }))
                .await,
        );
        assert!(error.starts_with("error-atpmcp-tool-24 "), "{error}");
        assert!(error.contains("redirect"), "{error}");
    }

    #[tokio::test]
    async fn a_page_url_with_a_query_is_checked_without_it() {
        let base = route_server(vec![Route::ok("/p?id=3", "text/html", PAGE)]).await;
        let result =
            call(serde_json::json!({ "text": "x", "embed_external": format!("{base}/p?id=3") }))
                .await;
        assert_eq!(
            record_of(&result)["embed"]["external"]["uri"],
            format!("{base}/p?id=3")
        );
    }

    /// The limits this tool enforces are the lexicons' own, read from the
    /// bundled copies, so a lexicon change that moves one fails here.
    #[test]
    fn the_media_limits_are_the_lexicons() {
        let def = |nsid: &str, name: &str| {
            let (_, json) = LEXICONS.iter().find(|(id, _)| *id == nsid).unwrap();
            serde_json::from_str::<Value>(json).unwrap()["defs"][name].clone()
        };
        let images = def(IMAGES_NSID, "main");
        assert_eq!(
            images["properties"]["images"]["maxLength"],
            MAX_IMAGES_ITEMS as u64
        );
        for nsid in [IMAGES_NSID, GALLERY_NSID] {
            assert_eq!(
                def(nsid, "image")["properties"]["image"]["maxSize"],
                MAX_MEDIA_IMAGE_BYTES,
                "{nsid}"
            );
        }
        let gallery_max = def(GALLERY_NSID, "main")["properties"]["items"]["maxLength"]
            .as_u64()
            .unwrap();
        assert!(MAX_GALLERY_ITEMS as u64 <= gallery_max);
        assert_eq!(
            def(EXTERNAL_NSID, "external")["properties"]["thumb"]["maxSize"],
            MAX_THUMB_BYTES
        );
    }

    /// The catalog checks a gallery's and an images embed's items, not only
    /// the post around them.
    #[test]
    fn the_catalog_checks_gallery_and_images_items() {
        let blob = |size: u64| {
            serde_json::json!({
                "$type": "blob",
                "ref": { "$link": "bafkreidyl3nf2xm3iyswuw5mj42dwz5mogk45kxwcdzufj6oc27e4cpzqy" },
                "mimeType": "image/jpeg",
                "size": size,
            })
        };
        let post = |embed: Value| {
            serde_json::json!({
                "$type": POST_NSID, "text": "x", "createdAt": "2026-11-18T00:00:00.000Z",
                "embed": embed,
            })
        };
        let valid = |record: &Value| {
            validate_record(POST_NSID, record, &*CATALOG, ValidateFlags::empty()).is_ok()
        };
        let gallery_item = |size: u64| {
            serde_json::json!({
                "$type": "app.bsky.embed.gallery#image", "alt": "",
                "aspectRatio": { "width": 446, "height": 248 }, "image": blob(size),
            })
        };
        let gallery =
            |items: Vec<Value>| post(serde_json::json!({ "$type": GALLERY_NSID, "items": items }));
        let images =
            |items: Vec<Value>| post(serde_json::json!({ "$type": IMAGES_NSID, "images": items }));

        assert!(valid(&gallery(vec![gallery_item(86_967); 7])));
        assert!(!valid(&gallery(vec![gallery_item(86_967); 21])));
        assert!(!valid(&gallery(vec![gallery_item(
            MAX_MEDIA_IMAGE_BYTES + 1
        )])));
        let mut no_ratio = gallery_item(1);
        no_ratio.as_object_mut().unwrap().remove("aspectRatio");
        assert!(
            !valid(&gallery(vec![no_ratio])),
            "a gallery item needs its ratio"
        );

        let image = serde_json::json!({ "alt": "", "image": blob(1) });
        assert!(
            valid(&images(vec![image.clone(); 4])),
            "an images item's ratio is optional"
        );
        assert!(!valid(&images(vec![image.clone(); 5])));
        let mut no_alt = image;
        no_alt.as_object_mut().unwrap().remove("alt");
        assert!(!valid(&images(vec![no_alt])));
    }

    #[tokio::test]
    async fn media_arguments_are_checked_before_anything_is_read() {
        let png = serde_json::json!({ "path": "/tmp/a.png" });
        let many = |n: usize| Value::from(vec![png.clone(); n]);
        for (arguments, expect) in [
            (
                serde_json::json!({ "text": "x", "gallery": [png], "images": [png] }),
                "not both",
            ),
            (
                serde_json::json!({ "text": "x", "gallery": [png], "embed_external": "https://example.com/" }),
                "'gallery' or 'embed_external'",
            ),
            (serde_json::json!({ "text": "x", "gallery": [] }), "1 to 10"),
            (
                serde_json::json!({ "text": "x", "gallery": many(11) }),
                "1 to 10",
            ),
            (
                serde_json::json!({ "text": "x", "images": many(5) }),
                "1 to 4",
            ),
            (
                serde_json::json!({ "text": "x", "gallery": "a.png" }),
                "array of images",
            ),
            (
                serde_json::json!({ "text": "x", "gallery": ["/tmp/a.png"] }),
                "an object",
            ),
            (
                serde_json::json!({ "text": "x", "gallery": [{ "path": "/a", "url": "https://e.com/a" }] }),
                "both 'path' and 'url'",
            ),
            (
                serde_json::json!({ "text": "x", "gallery": [{ "alt": "a" }] }),
                "needs a 'path' or a 'url'",
            ),
            (
                serde_json::json!({ "text": "x", "gallery": [{ "data_base64": "AAAA" }] }),
                "unknown field 'data_base64'",
            ),
            (
                serde_json::json!({ "text": "x", "gallery": [{ "url": "ftp://e.com/a.png" }] }),
                "http or https",
            ),
            (
                serde_json::json!({ "text": "x", "gallery": [{ "path": "/a", "alt": 3 }] }),
                "'alt'",
            ),
            (
                serde_json::json!({ "text": "x", "shorten_links": "yes" }),
                "'shorten_links'",
            ),
            (
                serde_json::json!({ "text": "x", "gallery": [png] }),
                "needs auth_handle",
            ),
        ] {
            let error = error_of(&call(arguments.clone()).await);
            assert!(error.starts_with("error-atpmcp-tool-23 "), "{error}");
            assert!(error.contains(expect), "{arguments}: {error}");
        }
    }

    #[test]
    fn urls_are_shortened_as_the_bluesky_app_shortens_them() {
        for (url, short) in [
            (
                "https://tangled.org/ngerakines.me/wow-break-timer",
                "tangled.org/ngerakines.m...",
            ),
            ("https://example.com/", "example.com"),
            ("https://example.com", "example.com"),
            ("http://example.com/abc", "example.com/abc"),
            // Exactly 15 is kept; 16 is cut to 13 and "...".
            (
                "https://example.com/abcdefghijklmn",
                "example.com/abcdefghijklmn",
            ),
            (
                "https://example.com/abcdefghijklmno",
                "example.com/abcdefghijkl...",
            ),
            ("https://example.com/?q=1#top", "example.com?q=1#top"),
            ("https://example.com:8443/a", "example.com:8443/a"),
            ("https://EXAMPLE.com/A", "example.com/A"),
            ("mailto:alice@example.com", "mailto:alice@example.com"),
            ("not a url", "not a url"),
        ] {
            assert_eq!(to_short_url(url), short, "{url}");
        }
    }

    /// The example post, shortened: the link's text is cut and its facet
    /// keeps the full URL, at exactly the bytes the Bluesky app wrote.
    #[tokio::test]
    async fn shorten_links_reproduces_the_bluesky_apps_post() {
        let text = "Started playing WoW Forever and wrote a small add-on to remind myself to take \
                    breaks and stand up.\n\nhttps://tangled.org/ngerakines.me/wow-break-timer";
        let result = call(serde_json::json!({ "text": text, "shorten_links": true })).await;
        let record = record_of(&result);
        assert_eq!(
            record["text"],
            "Started playing WoW Forever and wrote a small add-on to remind myself to take breaks \
             and stand up.\n\ntangled.org/ngerakines.m..."
        );
        assert_eq!(
            record["facets"],
            serde_json::json!([{
                "features": [{
                    "$type": "app.bsky.richtext.facet#link",
                    "uri": "https://tangled.org/ngerakines.me/wow-break-timer"
                }],
                "index": { "byteStart": 100, "byteEnd": 127 }
            }])
        );
    }

    #[tokio::test]
    async fn shortening_moves_the_facets_after_a_link() {
        let result = call(serde_json::json!({
            "text": "see https://example.com/a/very/long/path #rust and https://b.example/x",
            "shorten_links": true,
            "link_facet_allow": ["https://example.com/a/very/long/path"],
        }))
        .await;
        let record = record_of(&result);
        let text = record["text"].as_str().unwrap();
        // The link without a facet is not shortened: it would not be a link.
        assert_eq!(
            text,
            "see example.com/a/very/long/... #rust and https://b.example/x"
        );
        for facet in record["facets"].as_array().unwrap() {
            let (start, end) = (
                facet["index"]["byteStart"].as_u64().unwrap() as usize,
                facet["index"]["byteEnd"].as_u64().unwrap() as usize,
            );
            let covered = &text[start..end];
            match facet["features"][0]["$type"].as_str().unwrap() {
                "app.bsky.richtext.facet#tag" => assert_eq!(covered, "#rust"),
                _ => {
                    assert_eq!(covered, "example.com/a/very/long/...");
                    assert_eq!(
                        facet["features"][0]["uri"],
                        "https://example.com/a/very/long/path"
                    );
                }
            }
        }
    }

    #[tokio::test]
    async fn links_are_left_alone_without_shorten_links() {
        let text = "https://tangled.org/ngerakines.me/wow-break-timer";
        let result = call(serde_json::json!({ "text": text })).await;
        assert_eq!(record_of(&result)["text"], text);
    }

    /// A text the lexicon refuses is refused before an image is read.
    #[tokio::test]
    async fn a_text_over_the_limit_is_refused_before_any_image_is_read() {
        // No stored account is needed: the record fails before one is used.
        let result = call(serde_json::json!({
            "text": "x".repeat(301),
            "embed_external": "https://127.0.0.1:1/never-fetched",
        }))
        .await;
        assert!(error_of(&result).contains("does not validate"));
    }

    // The `auth_handle` cases are in `tests/bsky_post.rs`, which runs the
    // binary over a sandboxed account store: a unit test here would read the
    // real one. `thumbnail_bytes` uploads nothing, so its cases are here.

    async fn thumbnail_from(
        ctx: &ServerContext,
        content_type: &str,
        body: Vec<u8>,
    ) -> Result<Thumb, String> {
        let base = route_server(vec![Route::ok("/image", content_type, body)]).await;
        let url = Url::parse(&format!("{base}/image")).unwrap();
        thumbnail_bytes(ctx, &url).await
    }

    fn preserving_context() -> Arc<ServerContext> {
        crate::tools::test_support::test_context_with_cache_and_limits(crate::context::Limits {
            preserve_exif: true,
            ..crate::tools::test_support::test_limits()
        })
    }

    /// An image under the limit that only its EXIF says is turned is
    /// re-encoded with the turn applied, since removing the EXIF would show it
    /// on its side.
    #[tokio::test]
    async fn an_image_stored_turned_is_re_encoded_turned() {
        use crate::image_metadata::tests::{SECRET, jpeg_with_metadata};
        let thumb = thumbnail_from(&test_context(), "image/jpeg", jpeg_with_metadata(6))
            .await
            .expect("a thumbnail");
        assert_eq!(thumb.mime_type, "image/jpeg");
        assert!(thumb.note.as_deref().unwrap().contains("stored turned"));
        assert!(!thumb.data.windows(SECRET.len()).any(|w| w == SECRET));
        let decoded = image::load_from_memory(&thumb.data).unwrap();
        assert_eq!((decoded.width(), decoded.height()), (16, 24));
    }

    /// A format whose metadata cannot be removed is not used, and the note
    /// names the variable that would allow it; with the variable set, it is
    /// used as served.
    #[tokio::test]
    async fn a_format_that_cannot_be_stripped_needs_the_preserve_setting() {
        let mut bmp = Vec::new();
        image::DynamicImage::ImageRgb8(image::RgbImage::new(4, 4))
            .write_to(&mut std::io::Cursor::new(&mut bmp), image::ImageFormat::Bmp)
            .unwrap_or_else(|_| {
                bmp.clear();
                bmp.extend_from_slice(b"BM\x46\0\0\0\0\0\0\0\x36\0\0\0\x28\0\0\0");
                bmp.resize(70, 0);
            });
        let refused = thumbnail_from(&test_context(), "image/bmp", bmp.clone()).await;
        let reason = refused.err().expect("refused while stripping");
        assert!(reason.contains("ATPMCP_PRESERVE_EXIF=1"), "{reason}");

        let served = thumbnail_from(&preserving_context(), "image/bmp", bmp.clone())
            .await
            .expect("used as served");
        assert_eq!(served.data, bmp);
        assert!(served.note.is_none());
    }

    /// A shrunk image gets its source's EXIF only when preserving.
    #[tokio::test]
    async fn a_shrunk_image_keeps_its_exif_only_when_preserving() {
        use crate::image_metadata::tests::SECRET;
        let mut exif = vec![
            b'I', b'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 0x01, 3, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
            0,
        ];
        exif.extend_from_slice(SECRET);
        let png = {
            use image::ImageEncoder;
            let pixels = crate::thumbnail::tests::noise(800 * 600 * 3, 7);
            let mut png = Vec::new();
            let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
            encoder.set_exif_metadata(exif).unwrap();
            encoder
                .write_image(&pixels, 800, 600, image::ExtendedColorType::Rgb8)
                .unwrap();
            png
        };
        assert!(png.len() as u64 > MAX_THUMB_BYTES);
        let has_secret = |data: &[u8]| data.windows(SECRET.len()).any(|w| w == SECRET);

        let stripped = thumbnail_from(&test_context(), "image/png", png.clone())
            .await
            .unwrap();
        assert!(!has_secret(&stripped.data));
        assert!(stripped.note.unwrap().contains("without its metadata"));

        let kept = thumbnail_from(&preserving_context(), "image/png", png)
            .await
            .unwrap();
        assert!(has_secret(&kept.data));
        assert!(kept.note.unwrap().contains("with its EXIF copied in"));
    }

    #[test]
    fn html_is_recognised_by_type_or_by_its_start() {
        assert!(is_html(Some("text/html; charset=utf-8"), b""));
        assert!(is_html(Some("Application/XHTML+XML"), b""));
        assert!(!is_html(Some("text/plain"), b"<html>"));
        assert!(is_html(None, b"\xEF\xBB\xBF  <!DOCTYPE html><html>"));
        assert!(!is_html(None, b"{\"json\": true}"));
    }
}