waterui-cli 0.4.3

Cross-platform tooling for WaterUI applications
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
//! Asset and font management for `WaterUI` projects.
//!
//! This module provides functionality to:
//! - Scan the project manifest (`[[assets.font]]` in `Water.toml`) and
//!   dependency crates (`[[package.metadata.waterui.assets.font]]`) for font
//!   declarations
//! - Resolve fonts from local paths, the font cache, or the built-in registry
//! - Copy assets to platform-specific locations

use std::collections::{BTreeMap, HashMap, HashSet};
use std::future::Future;
use std::path::{Component, Path, PathBuf};
use std::pin::Pin;

use cargo_metadata::PackageId;
use eyre::{Context, OptionExt};
use serde::{Deserialize, Serialize};
use smol::fs;
use tracing::{debug, info, warn};
use walkdir::WalkDir;

use waterui_assets_planner::BundleManifest;
use zenwave::{Client as _, Method};

use crate::build::BuildProgress;
use crate::project::Project;
use crate::project_model::project_types::PermissionKey;

pub mod icon;
mod unified;
mod web;

/// A font the CLI can fetch when a crate names it and nothing else.
#[derive(Debug, Clone, Deserialize)]
struct RegistryFont {
    /// Family name a crate declares.
    name: String,
    /// Where the face, or an archive containing it, is fetched from.
    url: String,
}

/// The built-in font registry.
///
/// The list is data, so it lives in `assets/fonts.toml` rather than in Rust
/// literals, and is parsed rather than compiled into a table. Fonts it offers
/// can be declared by name alone — in a crate's Cargo.toml:
///
/// ```toml
/// [[package.metadata.waterui.assets.font]]
/// name = "Inter"
/// ```
///
/// or in the project's `Water.toml`:
///
/// ```toml
/// [[assets.font]]
/// name = "Inter"
/// ```
///
/// Icon pack fonts (Font Awesome, Material Icons, Lucide, ...) do NOT belong
/// here. They declare their own faces in their own Cargo.toml with
/// `remote_path` and `required-feature`.
#[derive(Debug, Clone, Deserialize)]
struct FontRegistry {
    #[serde(rename = "font")]
    fonts: Vec<RegistryFont>,
}

impl FontRegistry {
    /// The registry shipped with this CLI.
    fn builtin() -> eyre::Result<Self> {
        toml::from_str(include_str!("assets/fonts.toml"))
            .wrap_err("built-in font registry `src/project_model/assets/fonts.toml` is malformed")
    }

    /// Where `name` is fetched from, if the registry offers it.
    fn url(&self, name: &str) -> Option<&str> {
        self.fonts
            .iter()
            .find(|font| font.name == name)
            .map(|font| font.url.as_str())
    }
}
const HYDROLYSIS_DEFAULT_FONT_FAMILY: &str = "Roboto";
const HYDROLYSIS_WEB_FONT_MANIFEST_FILE_NAME: &str = "waterui-fonts.json";

/// A font declaration — from `[[assets.font]]` in `Water.toml` or a crate's
/// `[package.metadata.waterui.assets.font]` Cargo.toml metadata.
#[derive(Debug, Clone)]
pub struct FontDeclaration {
    /// Font family name (used as `font_family` in Text).
    pub name: String,
    /// Source of the font file.
    pub source: FontSource,
    /// Crate or project that declared this font.
    pub crate_name: String,
}

/// Source of a font file.
#[derive(Debug, Clone)]
pub enum FontSource {
    /// Font bundled with the crate at a local path.
    Local {
        /// Absolute path to the crate root.
        crate_root: PathBuf,
        /// Relative path within the crate.
        relative_path: PathBuf,
    },
    /// Font that must be fetched out of band into the font cache.
    Remote {
        /// URL to fetch the font from when pre-seeding the cache.
        url: String,
    },
    /// Font from the built-in registry.
    BuiltIn,
}

/// A resolved font with its absolute path.
#[derive(Debug, Clone)]
pub struct ResolvedFont {
    /// Font family name.
    pub name: String,
    /// Absolute path to the font file.
    pub path: PathBuf,
}

#[derive(Debug, Serialize)]
struct HydrolysisWebFontManifest {
    default_family: String,
    fonts: Vec<HydrolysisWebFontManifestEntry>,
}

#[derive(Debug, Serialize)]
struct HydrolysisWebFontManifestEntry {
    name: String,
    file_name: String,
}

/// Font metadata from Cargo.toml `[package.metadata.waterui.assets]`.
#[derive(Debug, Deserialize)]
struct WaterUIMetadata {
    #[serde(default)]
    assets: AssetsMetadata,
    /// Permissions this crate cannot work without, keyed by logical permission.
    #[serde(default)]
    permissions: BTreeMap<PermissionKey, PermissionRequirement>,
}

/// One crate's declaration that it needs a permission to function.
#[derive(Debug, Deserialize)]
struct PermissionRequirement {
    /// Human-readable justification, shown to the application author.
    reason: String,
    /// Only required when this cargo feature is enabled on the declaring crate.
    #[serde(default, rename = "required-feature")]
    required_feature: Option<String>,
}

/// A permission some dependency needs, and why.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequiredPermission {
    /// Crate that declared the requirement.
    pub package: String,
    /// The logical permission.
    pub key: PermissionKey,
    /// Why that crate needs it.
    pub reason: String,
    /// How the requirement was established.
    pub evidence: PermissionEvidence,
}

/// How confident the audit is that a permission is actually needed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PermissionEvidence {
    /// The crate declared the requirement in its own manifest metadata.
    Declared,
    /// Inferred from the shape of the dependency graph; may be a false
    /// positive, so the report is phrased as a suggestion.
    Inferred,
}

#[derive(Debug, Default, Deserialize)]
struct AssetsMetadata {
    #[serde(default)]
    font: Vec<FontMetadata>,
}

#[derive(Debug, Deserialize)]
struct FontMetadata {
    name: String,
    #[serde(default)]
    local_path: Option<String>,
    #[serde(default)]
    remote_path: Option<String>,
    /// Optional feature that must be enabled for this font to be included.
    /// If specified, the font will only be bundled if this feature is enabled
    /// for the declaring package.
    #[serde(default, rename = "required-feature")]
    required_feature: Option<String>,
}

/// Fonts the project itself declares as `[[assets.font]]` tables in
/// `Water.toml`.
///
/// The fields mirror what a crate writes under
/// `[package.metadata.waterui.assets.font]`; `local_path` is resolved against
/// the project root rather than a crate root. A declaration is one source:
/// setting both paths — or an absolute `local_path` — is a manifest error.
fn manifest_font_declarations(
    manifest: &crate::project::Manifest,
    root: &Path,
) -> eyre::Result<Vec<FontDeclaration>> {
    let Some(assets) = manifest.assets.as_ref() else {
        return Ok(Vec::new());
    };
    let mut declarations = Vec::with_capacity(assets.font.len());
    for font in &assets.font {
        let source = match (&font.local_path, &font.remote_path) {
            (Some(local_path), None) => {
                let relative_path = PathBuf::from(local_path);
                // A rooted path in any flavor — `/x`, `\x`, `C:\x`, `C:x` —
                // escapes the project root on some platform, so reject it on
                // all of them.
                if matches!(
                    relative_path.components().next(),
                    Some(Component::Prefix(_) | Component::RootDir)
                ) {
                    eyre::bail!(
                        "[[assets.font]] entry '{}' in Water.toml: local_path must be \
                         relative to the project root",
                        font.name
                    );
                }
                FontSource::Local {
                    crate_root: root.to_path_buf(),
                    relative_path,
                }
            }
            (None, Some(url)) => FontSource::Remote { url: url.clone() },
            (None, None) => FontSource::BuiltIn,
            (Some(_), Some(_)) => {
                eyre::bail!(
                    "[[assets.font]] entry '{}' in Water.toml sets both local_path and \
                     remote_path; a declaration has exactly one source",
                    font.name
                );
            }
        };
        declarations.push(FontDeclaration {
            name: font.name.clone(),
            source,
            crate_name: manifest.package.name.clone(),
        });
    }
    Ok(declarations)
}

/// Scans the project manifest and the built crate's dependencies for font
/// declarations.
///
/// `[[assets.font]]` tables in `Water.toml` declare the app's own fonts and
/// rank ahead of dependency declarations between equal sources; the
/// dependency half comes from [`scan_crate_font_declarations`].
pub async fn scan_fonts(
    project: &Project,
    build_manifest: &Path,
) -> eyre::Result<Vec<FontDeclaration>> {
    let mut declarations = manifest_font_declarations(project.manifest(), project.root())?;
    declarations.extend(scan_crate_font_declarations(build_manifest).await?);
    Ok(declarations)
}

/// Scans `build_manifest`'s dependency graph for
/// `[package.metadata.waterui.assets.font]` declarations via `cargo metadata`.
///
/// `build_manifest` is the `Cargo.toml` of the crate this build compiles,
/// i.e. the generated backend or FFI crate. That crate depends on the app, so
/// the graph carries both the app's authored dependencies and the backend's
/// own (the theme crate and friends); scanning the app manifest instead
/// would miss the backend's declarations entirely.
///
/// Fonts with a `required-feature` field will only be included if that feature
/// is enabled for the declaring package (checked via cargo metadata's resolved graph).
async fn scan_crate_font_declarations(build_manifest: &Path) -> eyre::Result<Vec<FontDeclaration>> {
    debug!(
        "Scanning fonts from dependencies via cargo metadata on {}",
        build_manifest.display()
    );

    // Run cargo metadata to get all packages
    let manifest_path = build_manifest.to_path_buf();
    let metadata = smol::unblock({
        let manifest_path = manifest_path.clone();
        move || {
            cargo_metadata::MetadataCommand::new()
                .manifest_path(&manifest_path)
                .exec()
        }
    })
    .await
    .wrap_err_with(|| {
        format!(
            "Failed to run cargo metadata on {}",
            build_manifest.display()
        )
    })?;

    // Build map of package_id -> enabled features from resolved graph
    let enabled_features_map: HashMap<&PackageId, HashSet<&str>> = metadata
        .resolve
        .as_ref()
        .map(|resolve| {
            resolve
                .nodes
                .iter()
                .map(|node| (&node.id, node.features.iter().map(|f| f.as_str()).collect()))
                .collect()
        })
        .unwrap_or_default();

    let mut fonts = Vec::new();

    for package in &metadata.packages {
        // Skip if no waterui metadata
        let Some(waterui) = package.metadata.get("waterui") else {
            continue;
        };

        // Parse the metadata
        let waterui_meta: WaterUIMetadata = match serde_json::from_value(waterui.clone()) {
            Ok(m) => m,
            Err(e) => {
                warn!(
                    "Failed to parse waterui metadata for {}: {}",
                    package.name, e
                );
                continue;
            }
        };

        // Get enabled features for this package from resolve
        let enabled_features = enabled_features_map
            .get(&package.id)
            .cloned()
            .unwrap_or_default();

        // Process font declarations
        for font_meta in waterui_meta.assets.font {
            // Skip if required feature is not enabled
            if let Some(required) = &font_meta.required_feature
                && !enabled_features.contains(required.as_str())
            {
                debug!(
                    "Skipping font '{}': feature '{}' not enabled for {}",
                    font_meta.name, required, package.name
                );
                continue;
            }

            let source = if let Some(local_path) = font_meta.local_path {
                let local_path = PathBuf::from(local_path);
                if local_path.is_absolute() {
                    warn!(
                        "Skipping font '{}': local_path must be relative (crate: {})",
                        font_meta.name, package.name
                    );
                    continue;
                }

                // Local path - resolve relative to crate root
                let crate_root = package
                    .manifest_path
                    .parent()
                    .ok_or_eyre("Package has no parent directory")?
                    .as_std_path()
                    .to_path_buf();

                FontSource::Local {
                    crate_root,
                    relative_path: local_path,
                }
            } else if let Some(url) = font_meta.remote_path {
                FontSource::Remote { url }
            } else {
                // Just name - use built-in registry
                FontSource::BuiltIn
            };

            fonts.push(FontDeclaration {
                name: font_meta.name,
                source,
                crate_name: package.name.to_string(),
            });
        }
    }

    info!("Found {} font declarations from dependencies", fonts.len());
    Ok(fonts)
}

/// Resolves and satisfies font declarations for a build.
///
/// Resolution is [`resolve_declarations`]: same `name` → keep only one font,
/// local > remote > built-in, `Water.toml` ahead of dependencies on a tie.
/// Satisfaction is [`satisfy_font`]: remote and built-in declarations resolve
/// to files already in the font cache — a build performs no network access,
/// so a declaration that is not already cached is an error naming the font,
/// its URL, and `water fetch`.
pub async fn resolve_fonts(declarations: Vec<FontDeclaration>) -> eyre::Result<Vec<ResolvedFont>> {
    let cache_dir = cache_dir()?;
    let registry = FontRegistry::builtin()?;

    let mut resolved = Vec::new();
    for decl in resolve_declarations(declarations) {
        let path = satisfy_font(&decl, &cache_dir, &registry).await?;
        debug!("Resolved font '{}' -> {}", decl.name, path.display());
        resolved.push(ResolvedFont {
            name: decl.name,
            path,
        });
    }

    info!("Resolved {} fonts", resolved.len());
    Ok(resolved)
}

/// Deduplicates font declarations into the set a build or a fetch then
/// satisfies — the resolution half of [`resolve_fonts`], shared so a fetch
/// can never disagree with the build that follows it.
///
/// Rules:
/// - Same `name` → keep only one font
/// - Priority: local > remote > built-in; between equal sources the earlier
///   declaration wins, so `Water.toml` overrides a dependency on a tie
///
/// Winners come out sorted by family name so reports read deterministically.
fn resolve_declarations(declarations: Vec<FontDeclaration>) -> Vec<FontDeclaration> {
    // Group by name
    let mut by_name: HashMap<String, Vec<FontDeclaration>> = HashMap::new();
    for decl in declarations {
        by_name.entry(decl.name.clone()).or_default().push(decl);
    }

    let mut resolved: Vec<FontDeclaration> = by_name
        .into_values()
        .map(|mut decls| {
            // Sort by priority: Local > Remote > BuiltIn, take the first.
            decls.sort_by_key(|d| match &d.source {
                FontSource::Local { .. } => 0,
                FontSource::Remote { .. } => 1,
                FontSource::BuiltIn => 2,
            });
            decls.into_iter().next().unwrap()
        })
        .collect();
    resolved.sort_by(|left, right| left.name.cmp(&right.name));
    resolved
}

/// Satisfies one resolved declaration against crate-local files and the font
/// cache — the build path, which never touches the network.
///
/// A declaration that cannot be satisfied is an error, never a skip:
/// skipping renders the app in whatever face the shaper falls back to, which
/// is the silent wrong-typeface this module exists to rule out.
async fn satisfy_font(
    decl: &FontDeclaration,
    cache_dir: &Path,
    registry: &FontRegistry,
) -> eyre::Result<PathBuf> {
    let name = &decl.name;
    match &decl.source {
        FontSource::Local {
            crate_root,
            relative_path,
        } => match resolve_local_font_path(crate_root, relative_path) {
            Ok(Some(full_path)) => Ok(full_path),
            // A crate-local font missing at build time means the crate did
            // not package what it declares — say so, with the path that was
            // expected.
            Ok(None) => Err(unsatisfiable_local_font(
                decl,
                &crate_root.join(relative_path),
            )),
            Err(e) => Err(e).wrap_err_with(|| {
                format!(
                    "font '{name}' has an invalid local path '{}' (declared by {})",
                    relative_path.display(),
                    decl.crate_name
                )
            }),
        },
        FontSource::Remote { url } => cached_font(name, url, cache_dir).await,
        FontSource::BuiltIn => {
            let Some(url) = registry.url(name) else {
                // Declared by name alone and the registry has no such
                // family: nothing can satisfy it, so this fails here rather
                // than at the first glyph the shaper draws in some other
                // face.
                return Err(unsatisfiable_builtin_font(decl));
            };
            cached_font(name, url, cache_dir).await
        }
    }
}

/// The report for a crate-local declaration whose file is absent — used by
/// both the build and `water fetch`, which reports the same thing it cannot
/// fix.
fn unsatisfiable_local_font(decl: &FontDeclaration, expected: &Path) -> eyre::Report {
    eyre::eyre!(
        "font '{}' is declared by {} at '{}', which does not exist in that crate",
        decl.name,
        decl.crate_name,
        expected.display(),
    )
}

/// The report for a by-name declaration the built-in registry does not know —
/// used by both the build and `water fetch`.
fn unsatisfiable_builtin_font(decl: &FontDeclaration) -> eyre::Report {
    eyre::eyre!(
        "font '{}' is declared by {} by name alone, but no font of that name \
         is in the built-in registry — give the declaration a `local_path` or a \
         `remote_path`",
        decl.name,
        decl.crate_name
    )
}

/// Gets the cache directory holding fonts fetched out of band.
fn cache_dir() -> eyre::Result<PathBuf> {
    let cache = dirs::cache_dir()
        .map(|root| root.join("waterui").join("fonts"))
        .ok_or_eyre("Could not determine cache directory")?;
    Ok(cache)
}

fn resolve_local_font_path(
    crate_root: &Path,
    relative_path: &Path,
) -> eyre::Result<Option<PathBuf>> {
    let full_path = crate_root.join(relative_path);
    if !full_path.exists() {
        return Ok(None);
    }

    let canonical_root = crate_root
        .canonicalize()
        .wrap_err_with(|| format!("Failed to canonicalize crate root {}", crate_root.display()))?;
    let canonical_path = full_path
        .canonicalize()
        .wrap_err_with(|| format!("Failed to canonicalize font path {}", full_path.display()))?;

    if !canonical_path.starts_with(&canonical_root) {
        eyre::bail!(
            "path escapes crate root ({} -> {})",
            full_path.display(),
            canonical_path.display()
        );
    }

    Ok(Some(canonical_path))
}

/// Resolves a remotely-declared font to a file already in the font cache.
///
/// A build performs no network access: when the declaration is not already
/// cached, this fails naming the font, its URL and the cache directory, so the
/// user can run `water fetch` and retry the build.
async fn cached_font(name: &str, url: &str, cache_dir: &Path) -> eyre::Result<PathBuf> {
    cached_font_entry(name, url, cache_dir)
        .await?
        .ok_or_else(|| uncached_font_error(name, url, cache_dir))
}

/// Probes the font cache for the face `url` declares.
///
/// `Some` is exactly the path [`cached_font`] resolves to; `None` means
/// nothing usable is cached and `water fetch` can place it. A zero-length
/// entry is dropped and reported absent.
async fn cached_font_entry(
    name: &str,
    url: &str,
    cache_dir: &Path,
) -> eyre::Result<Option<PathBuf>> {
    // Use URL hash as filename to avoid conflicts
    let hash = sha256_hex(url);
    if is_zip_url(url) {
        return cached_zip_font(name, cache_dir, &hash).await;
    }

    cached_file_font(name, cache_dir, &hash).await
}

fn is_zip_url(url: &str) -> bool {
    let path = url.split(['?', '#']).next().unwrap_or(url);
    path.rsplit_once('.')
        .is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("zip"))
}

async fn cached_zip_font(
    name: &str,
    cache_dir: &Path,
    hash: &str,
) -> eyre::Result<Option<PathBuf>> {
    let extract_dir = cache_dir.join(hash);
    if extract_dir.exists() {
        debug!(
            "Font '{}' already extracted at {}",
            name,
            extract_dir.display()
        );
        return find_font_file(&extract_dir, name).await.map(Some);
    }

    let cache_file = cache_dir.join(format!("{hash}.zip"));
    if let Some(cache_len) = cached_file_len(name, &cache_file).await? {
        if cache_len == 0 {
            warn!(
                "Ignoring empty cached font '{}' at {}",
                name,
                cache_file.display()
            );
            let _ = fs::remove_file(&cache_file).await;
        } else {
            debug!("Font '{}' already cached at {}", name, cache_file.display());
            return find_font_in_extracted_zip(&cache_file, name)
                .await
                .map(Some);
        }
    }

    Ok(None)
}

async fn cached_file_font(
    name: &str,
    cache_dir: &Path,
    hash: &str,
) -> eyre::Result<Option<PathBuf>> {
    let cache_file = cache_dir.join(format!("{hash}.ttf"));

    if let Some(cache_len) = cached_file_len(name, &cache_file).await? {
        if cache_len == 0 {
            warn!(
                "Ignoring empty cached font '{}' at {}",
                name,
                cache_file.display()
            );
            let _ = fs::remove_file(&cache_file).await;
        } else {
            debug!("Font '{}' already cached at {}", name, cache_file.display());
            return Ok(Some(cache_file));
        }
    }

    Ok(None)
}

/// The error for a remote font declaration that is not already in the font
/// cache. Builds perform no network access, so the download is a separate,
/// opt-in command — the message names the font, the URL it is fetched from,
/// the cache directory, and `water fetch`.
fn uncached_font_error(name: &str, url: &str, cache_dir: &Path) -> eyre::Report {
    eyre::eyre!(
        "font '{name}' is declared remote ({url}) but is not in the font cache at {}; \
         builds never access the network — run `water fetch` to download the project's \
         fonts and retry the build",
        cache_dir.display(),
    )
}

async fn cached_file_len(name: &str, cache_file: &Path) -> eyre::Result<Option<u64>> {
    match fs::metadata(cache_file).await {
        Ok(metadata) => Ok(Some(metadata.len())),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(error).wrap_err_with(|| {
            format!(
                "Failed to read cached font metadata for '{}' at {}",
                name,
                cache_file.display()
            )
        }),
    }
}

/// What seeding the font cache did for one resolved font declaration.
///
/// `water fetch` and `water create` report these; a build never produces
/// them because it never fetches — it turns the same states into errors.
#[derive(Debug)]
pub enum FetchOutcome {
    /// Already satisfied — a crate-local file that exists, or a cache entry
    /// — so nothing was downloaded.
    Satisfied {
        /// Font family name.
        name: String,
        /// The file a build resolves this font to.
        path: PathBuf,
    },
    /// The declaration's URL was downloaded into the font cache.
    Fetched {
        /// Font family name.
        name: String,
        /// The file a build resolves this font to — the `.ttf` cache entry
        /// itself, or the one face extracted out of a downloaded archive.
        path: PathBuf,
    },
    /// No download can satisfy the declaration: a crate-local file that does
    /// not exist, or a family name the built-in registry does not know.
    /// `error` is the same report a build gives it — saying so is the point.
    Unsatisfiable {
        /// Font family name.
        name: String,
        /// What a build reports for this declaration.
        error: eyre::Report,
    },
}

/// Seeds the font cache with every font a build of `project` would demand.
///
/// `water fetch` and the tail of `water create` share this one path:
/// declarations resolve exactly as a build resolves them —
/// [`manifest_font_declarations`] plus [`scan_crate_font_declarations`] over
/// the manifest of each crate a build compiles, then [`resolve_declarations`]
/// — and whatever the cache does not already hold is downloaded into the
/// entry the build then looks for. Builds keep their no-network guarantee;
/// this is the explicit, opt-in network step.
///
/// # Errors
///
/// Returns an error when a backend crate cannot be scaffolded, a manifest
/// cannot be scanned, or a download fails — the error names the backend, or
/// the font and its URL. Declarations fetching can never satisfy arrive as
/// [`FetchOutcome::Unsatisfiable`] instead, carrying the same report the
/// build gives them.
pub async fn seed_font_cache(project: &Project) -> eyre::Result<Vec<FetchOutcome>> {
    let mut declarations = manifest_font_declarations(project.manifest(), project.root())?;
    for manifest in ensure_font_scan_manifests(project).await? {
        declarations.extend(scan_crate_font_declarations(&manifest).await?);
    }
    fetch_fonts(declarations, &cache_dir()?, download_font).await
}

/// The crate manifests a build of `project` scans for font declarations —
/// produced before they are scanned, the same way the build that compiles
/// them produces them.
///
/// The project crate is always scanned; beyond it, the manifests that matter
/// are the generated crates': the theme crate's
/// `[package.metadata.waterui.assets.font]` entries are reachable only
/// through the backend manifest that depends on it. Apple and Android builds
/// scan the FFI companion, which `Project::open` scaffolds whenever either
/// backend is managed; if it is still absent it is scaffolded here. Each of
/// the GTK4, Hydrolysis and `WinUI` crates is re-scaffolded with the
/// current templates when missing or stale, exactly as the build and preview
/// paths regenerate it. Scaffolding writes template files — nothing
/// compiles. The ESP32 harness never takes part: no build scans it for
/// fonts — `dew`'s fonts come from `[backends.esp32]` as plain files.
///
/// The scanned set follows the project: an app contributes the crates of the
/// backends it has configured, a playground the crates for the backends this
/// host can run — Hydrolysis anywhere, GTK4 on Linux, `WinUI` on Windows —
/// since the CLI manages them all. A crate that cannot be produced is an
/// error naming its backend — silently dropping it is how a build's font
/// demand and a fetch's scan disagree.
async fn ensure_font_scan_manifests(project: &Project) -> eyre::Result<Vec<PathBuf>> {
    let mut manifests = vec![project.root().join("Cargo.toml")];

    if project.is_playground()
        || project.apple_backend().is_some()
        || project.android_backend().is_some()
    {
        let manifest = project.ffi_crate_path().join("Cargo.toml");
        if !manifest.is_file() {
            project.scaffold_ffi_companion().await.map_err(|error| {
                eyre::eyre!("could not scaffold the Apple/Android FFI companion crate: {error}")
            })?;
        }
        manifests.push(manifest);
    }

    ensure_backend_manifest::<crate::gtk4::backend::Gtk4Backend>(project, &mut manifests).await?;
    ensure_backend_manifest::<crate::hydrolysis::backend::HydrolysisBackend>(
        project,
        &mut manifests,
    )
    .await?;
    ensure_backend_manifest::<crate::winui::backend::WinUiBackend>(project, &mut manifests).await?;

    Ok(manifests)
}

/// A generated backend crate — GTK4, Hydrolysis or `WinUI` — whose manifest
/// a build scans for font declarations.
trait FontScanCrate: crate::backend::Backend {
    /// The backend's name as `water backend` reports it.
    const NAME: &'static str;
    /// Whether a build of `project` can ever compile this crate: a
    /// playground can run every backend this host supports — the CLI manages
    /// all of them — while an app builds only the backends it has
    /// configured.
    fn wanted(project: &Project) -> bool;
    /// Whether the crate on disk is missing or behind the current templates
    /// — the check the build and preview paths apply before regenerating.
    fn stale(project: &Project) -> impl Future<Output = eyre::Result<bool>> + Send;
}

/// Scaffolds `B`'s crate the way the build that compiles it would —
/// [`crate::backend::reinit_backend`] when it is missing or stale — and
/// pushes its `Cargo.toml` onto `manifests`. A crate that cannot be produced
/// is an error naming the backend, never a skip.
async fn ensure_backend_manifest<B: FontScanCrate>(
    project: &Project,
    manifests: &mut Vec<PathBuf>,
) -> eyre::Result<()> {
    if !B::wanted(project) {
        return Ok(());
    }
    let stale = B::stale(project)
        .await
        .wrap_err_with(|| format!("could not inspect the {} backend crate", B::NAME))?;
    if stale {
        crate::backend::reinit_backend::<B>(project)
            .await
            .map_err(|error| {
                eyre::eyre!("could not scaffold the {} backend crate: {error}", B::NAME)
            })?;
    }
    manifests.push(project.backend_path::<B>().join("Cargo.toml"));
    Ok(())
}

impl FontScanCrate for crate::gtk4::backend::Gtk4Backend {
    const NAME: &'static str = "GTK4";
    fn wanted(project: &Project) -> bool {
        // GTK4 compiles on Linux hosts only, so a playground elsewhere never
        // builds this crate.
        project.gtk4_backend().is_some() || (project.is_playground() && cfg!(target_os = "linux"))
    }
    async fn stale(project: &Project) -> eyre::Result<bool> {
        Self::requires_regeneration(project).await
    }
}

impl FontScanCrate for crate::hydrolysis::backend::HydrolysisBackend {
    const NAME: &'static str = "hydrolysis";
    fn wanted(project: &Project) -> bool {
        project.is_playground() || project.hydrolysis_backend().is_some()
    }
    async fn stale(project: &Project) -> eyre::Result<bool> {
        Self::requires_regeneration(project).await
    }
}

impl FontScanCrate for crate::winui::backend::WinUiBackend {
    const NAME: &'static str = "WinUI";
    fn wanted(project: &Project) -> bool {
        // `WinUI` compiles on Windows hosts only, so a playground elsewhere
        // never builds this crate.
        project.winui_backend().is_some()
            || (project.is_playground() && cfg!(target_os = "windows"))
    }
    async fn stale(project: &Project) -> eyre::Result<bool> {
        Self::requires_regeneration(project).await
    }
}

/// How `fetch_fonts` downloads one URL to a path — a seam a test closes
/// with a stub so it never reaches the network.
type FontFetch =
    for<'a> fn(&'a str, &'a Path) -> Pin<Box<dyn Future<Output = eyre::Result<()>> + Send + 'a>>;

/// Fetches into `cache_dir` every font `declarations` resolves to.
///
/// Resolution is the same [`resolve_fonts`] applies —
/// [`resolve_declarations`] — so a fetch can never disagree with the build
/// that follows it, and a declaration already satisfied reports
/// [`FetchOutcome::Satisfied`] without being downloaded again.
///
/// # Errors
///
/// A failed download aborts the run with an error naming the font and its
/// URL; a quiet skip would leave the next build failing on a font this run
/// was supposed to place.
async fn fetch_fonts(
    declarations: Vec<FontDeclaration>,
    cache_dir: &Path,
    fetch: FontFetch,
) -> eyre::Result<Vec<FetchOutcome>> {
    let registry = FontRegistry::builtin()?;
    let mut outcomes = Vec::new();
    for decl in resolve_declarations(declarations) {
        let outcome = match &decl.source {
            // Whatever fetching cannot fix — a crate-local file that is not
            // there — is reported exactly as the build reports it.
            FontSource::Local { .. } => match satisfy_font(&decl, cache_dir, &registry).await {
                Ok(path) => FetchOutcome::Satisfied {
                    name: decl.name.clone(),
                    path,
                },
                Err(error) => FetchOutcome::Unsatisfiable {
                    name: decl.name.clone(),
                    error,
                },
            },
            FontSource::Remote { .. } | FontSource::BuiltIn => {
                match declaration_url(&decl, &registry) {
                    Some(url) => {
                        if let Some(path) = cached_font_entry(&decl.name, url, cache_dir).await? {
                            FetchOutcome::Satisfied {
                                name: decl.name.clone(),
                                path,
                            }
                        } else {
                            let path = fetch_remote_font(&decl.name, url, cache_dir, fetch).await?;
                            FetchOutcome::Fetched {
                                name: decl.name.clone(),
                                path,
                            }
                        }
                    }
                    // Only a `BuiltIn` declaration reaches this arm.
                    None => FetchOutcome::Unsatisfiable {
                        name: decl.name.clone(),
                        error: unsatisfiable_builtin_font(&decl),
                    },
                }
            }
        };
        outcomes.push(outcome);
    }
    Ok(outcomes)
}

/// The URL a declaration is fetched from, when it has one: `Remote`
/// declarations carry their own; `BuiltIn` ones resolve through the
/// registry; `Local` ones have none.
fn declaration_url<'a>(decl: &'a FontDeclaration, registry: &'a FontRegistry) -> Option<&'a str> {
    match &decl.source {
        FontSource::Remote { url } => Some(url.as_str()),
        FontSource::BuiltIn => registry.url(&decl.name),
        FontSource::Local { .. } => None,
    }
}

/// Downloads one remote font into the cache entry a build looks for.
///
/// `url` lands at `{sha256(url)}.ttf` — or `.zip` for an archive — the same
/// name the build probes, via a `.partial` sibling so an interrupted
/// transfer never reads as a cached font. An archive is extracted the way
/// the build's first resolution extracts it.
async fn fetch_remote_font(
    name: &str,
    url: &str,
    cache_dir: &Path,
    fetch: FontFetch,
) -> eyre::Result<PathBuf> {
    waterui_assets_core::ensure_http_allowed(url)
        .map_err(|error| eyre::eyre!("font '{name}' cannot be fetched from {url}: {error}"))?;
    fs::create_dir_all(cache_dir).await?;

    let hash = sha256_hex(url);
    let extension = if is_zip_url(url) { "zip" } else { "ttf" };
    let cache_file = cache_dir.join(format!("{hash}.{extension}"));
    let partial = cache_dir.join(format!("{hash}.{extension}.partial"));
    fetch(url, &partial)
        .await
        .wrap_err_with(|| format!("font '{name}' could not be fetched from {url}"))?;
    if fs::metadata(&partial).await?.len() == 0 {
        let _ = fs::remove_file(&partial).await;
        eyre::bail!("font '{name}' fetched from {url} is empty");
    }
    fs::rename(&partial, &cache_file).await.wrap_err_with(|| {
        format!(
            "failed to place font '{name}' fetched from {url} at {}",
            cache_file.display()
        )
    })?;

    if is_zip_url(url) {
        find_font_in_extracted_zip(&cache_file, name)
            .await
            .wrap_err_with(|| format!("font '{name}' fetched from {url}"))
    } else {
        Ok(cache_file)
    }
}

/// `GET`s `url` into `dest` — the same request shape `framework.rs` and
/// `browser_runtime.rs` send for their own downloads: a `zenwave` client, a
/// `GET` under the crate's user agent, streamed to the path.
fn download_font<'a>(
    url: &'a str,
    dest: &'a Path,
) -> Pin<Box<dyn Future<Output = eyre::Result<()>> + Send + 'a>> {
    Box::pin(async move {
        let mut client = zenwave::client();
        client
            .method(Method::GET, url)?
            .header("User-Agent", env!("CARGO_PKG_NAME"))?
            .download_to_path(dest)
            .await?;
        Ok(())
    })
}

/// Finds a font file in an extracted zip archive.
async fn find_font_in_extracted_zip(zip_path: &Path, name: &str) -> eyre::Result<PathBuf> {
    let extract_dir = zip_path.with_extension("");

    // Extract if not already done
    if !extract_dir.exists() {
        fs::create_dir_all(&extract_dir).await?;

        let zip_path = zip_path.to_path_buf();
        let extract_dir_clone = extract_dir.clone();
        let zip_path_for_extraction = zip_path.clone();

        smol::unblock(move || {
            let file = std::fs::File::open(&zip_path_for_extraction)?;
            let mut archive = zip::ZipArchive::new(file)?;
            archive.extract(&extract_dir_clone)?;
            Ok::<_, eyre::Report>(())
        })
        .await?;

        // Font Awesome's generated Rust bindings require the archive metadata.
        // Other font ZIPs do not contain icons.json and must not be treated as
        // damaged Font Awesome distributions.
        if name.to_ascii_lowercase().contains("fontawesome") {
            copy_fontawesome_icons_json(&extract_dir).await?;
        }
    }

    remove_extracted_font_archive(zip_path).await?;

    // Find a font file (.ttf or .otf)
    let font_file = find_font_file(&extract_dir, name).await?;
    Ok(font_file)
}

async fn remove_extracted_font_archive(zip_path: &Path) -> eyre::Result<()> {
    match fs::remove_file(zip_path).await {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error).wrap_err_with(|| {
            format!(
                "Failed to remove extracted font archive at {}",
                zip_path.display()
            )
        }),
    }
}

/// Copies Font Awesome icons.json to the fontawesome cache directory.
///
/// This is needed by the fontawesome7 crate's build.rs to generate icon definitions.
async fn copy_fontawesome_icons_json(extract_dir: &Path) -> eyre::Result<()> {
    // Look for metadata/icons.json in the extracted archive
    let icons_json = find_file_recursive(extract_dir, "icons.json").await?;

    // Determine version from parent directory name (e.g., "fontawesome-free-7.1.0-desktop")
    let version = extract_fontawesome_version(extract_dir);

    // Copy to fontawesome cache directory
    let fontawesome_cache = dirs::cache_dir()
        .map(|root| root.join("waterui").join("fontawesome"))
        .ok_or_eyre("Could not determine cache directory")?;

    fs::create_dir_all(&fontawesome_cache).await?;

    let dest = fontawesome_cache.join(format!("fontawesome-{version}-icons.json"));
    fs::copy(&icons_json, &dest).await?;

    debug!("Copied icons.json to {}", dest.display());
    Ok(())
}

/// Recursively finds a file by name in a directory.
async fn find_file_recursive(dir: &Path, filename: &str) -> eyre::Result<PathBuf> {
    let dir = dir.to_path_buf();
    let filename = filename.to_string();
    smol::unblock(move || {
        for entry in WalkDir::new(&dir) {
            let entry = entry?;
            if !entry.file_type().is_file() {
                continue;
            }
            if entry
                .file_name()
                .to_str()
                .is_some_and(|name| name == filename)
            {
                return Ok(entry.into_path());
            }
        }
        eyre::bail!("File '{}' not found in {}", filename, dir.display());
    })
    .await
}

/// Extracts Font Awesome version from directory structure.
fn extract_fontawesome_version(extract_dir: &Path) -> String {
    // Try to find version from directory names like "fontawesome-free-7.1.0-desktop"
    if let Ok(entries) = std::fs::read_dir(extract_dir) {
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().to_string();
            if name.starts_with("fontawesome-") {
                // Extract version: "fontawesome-free-7.1.0-desktop" -> "7.1.0"
                let parts: Vec<&str> = name.split('-').collect();
                for (i, part) in parts.iter().enumerate() {
                    if part.chars().next().is_some_and(|c| c.is_ascii_digit()) {
                        return parts[i..]
                            .join("-")
                            .split('-')
                            .next()
                            .unwrap_or("7.1.0")
                            .to_string();
                    }
                }
            }
        }
    }
    "7.1.0".to_string() // Default fallback
}

/// Recursively finds a font file in a directory.
///
/// Supports TTF and OTF formats.
async fn find_font_file(dir: &Path, name: &str) -> eyre::Result<PathBuf> {
    let dir = dir.to_path_buf();
    let name = name.to_string();
    smol::unblock(move || {
        let mut candidates = Vec::new();
        let name_lower = name.to_lowercase();

        let style_keyword =
            extract_style_keyword(&name_lower).unwrap_or_else(|| "regular".to_string());

        for entry in WalkDir::new(&dir) {
            let entry = entry?;
            if !entry.file_type().is_file() {
                continue;
            }

            let path = entry.into_path();
            let Some(ext) = path.extension() else {
                continue;
            };
            let ext = ext.to_string_lossy().to_lowercase();
            if ext != "ttf" && ext != "otf" {
                continue;
            }

            let file_name = path
                .file_stem()
                .unwrap_or_default()
                .to_string_lossy()
                .to_lowercase();

            if file_name.contains(&style_keyword) {
                let name_parts: Vec<&str> = name_lower.split_whitespace().collect();
                let matches_base = name_parts
                    .iter()
                    .take(3)
                    .all(|part| file_name.contains(part));
                if matches_base {
                    return Ok(path);
                }
            }

            candidates.push(path);
        }

        candidates
            .into_iter()
            .next()
            .ok_or_else(|| eyre::eyre!("No font file found in zip for '{}'", name))
    })
    .await
}

/// Extract style keyword from font family name for matching.
///
/// Handles patterns like:
/// - "FontAwesome7Free-Solid" -> "solid"
/// - "FontAwesome7Free-Regular" -> "regular"
/// - "FontAwesome7Free-Brands" -> "brands"
fn extract_style_keyword(name: &str) -> Option<String> {
    // Check for common style suffixes
    let styles = [
        "solid", "regular", "brands", "light", "thin", "bold", "medium",
    ];
    for style in styles {
        if name.ends_with(style) || name.contains(&format!("-{style}")) {
            return Some(style.to_string());
        }
    }
    None
}

/// Computes SHA256 hash of a string as hex.
fn sha256_hex(s: &str) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(s.as_bytes());
    let result = hasher.finalize();
    hex::encode(result)
}

/// Stage project assets for Apple packaging (Asset Catalog + raw resources).
///
/// `sccache_path` feeds the host library build whose symbol table carries the
/// `include_bundle!` mount metadata; pass `None` when no sccache binary was
/// detected. Returns the staged manifest so callers can scan it (fonts, for
/// example) without rebuilding the host artifact.
pub async fn stage_project_assets_for_apple(
    project: &Project,
    dest_dir: &Path,
    sccache_path: Option<&Path>,
    dev_server: bool,
    progress: Option<&BuildProgress>,
) -> eyre::Result<BundleManifest> {
    unified::stage_for_apple(project, dest_dir, sccache_path, dev_server, progress).await
}

/// Stage project assets for Android packaging (res + assets/raw).
pub async fn stage_project_assets_for_android(
    project: &Project,
    backend_path: &Path,
    sccache_path: Option<&Path>,
    dev_server: bool,
    progress: Option<&BuildProgress>,
) -> eyre::Result<BundleManifest> {
    unified::stage_for_android(project, backend_path, sccache_path, dev_server, progress).await
}

/// Render the project's macOS `.icns` app icon for hand-assembled bundles.
///
/// Gated to macOS along with the rest of the `.icns` chain, whose only caller is
/// the macOS packaging path.
#[cfg(target_os = "macos")]
pub fn project_macos_icns(project: &Project) -> eyre::Result<Vec<u8>> {
    unified::macos_icns(project)
}

/// Render the project's Windows `.ico` app icon for resource embedding.
pub fn project_windows_ico(project: &Project) -> eyre::Result<Vec<u8>> {
    unified::windows_ico(project)
}

/// Install the app icon into a hicolor icon-theme tree for Linux desktops.
pub async fn stage_hicolor_icons(project: &Project, icons_root: &Path) -> eyre::Result<()> {
    unified::stage_hicolor_icons(project, icons_root).await
}

/// Stage project assets for GTK4 packaging (resources + gresource bundle).
pub async fn stage_project_assets_for_gtk(
    project: &Project,
    resources_dir: &Path,
    sccache_path: Option<&Path>,
    dev_server: bool,
    progress: Option<&BuildProgress>,
) -> eyre::Result<BundleManifest> {
    unified::stage_for_gtk(project, resources_dir, sccache_path, dev_server, progress).await
}

/// Resolves the fonts declared inside an already-staged bundle manifest.
pub fn scan_project_font_assets(manifest: &BundleManifest) -> eyre::Result<Vec<ResolvedFont>> {
    unified::scan_project_fonts(manifest)
}

pub use unified::LaunchAssets;

/// Resolve the project's launch screen and load its artwork.
pub fn project_launch_assets(project: &Project) -> eyre::Result<LaunchAssets> {
    unified::launch_assets(project)
}

/// Stage project assets for web packaging.
pub async fn stage_project_assets_for_web(project: &Project, site_root: &Path) -> eyre::Result<()> {
    web::stage_for_web(project, site_root).await
}

/// Copies fonts to a destination directory.
pub async fn copy_fonts(fonts: &[ResolvedFont], dest: &Path) -> eyre::Result<()> {
    fs::create_dir_all(dest).await?;

    for font in fonts {
        let file_name = font
            .path
            .file_name()
            .ok_or_eyre("Font path has no filename")?;
        let dest_path = dest.join(file_name);

        debug!(
            "Copying font {} -> {}",
            font.path.display(),
            dest_path.display()
        );
        fs::copy(&font.path, &dest_path).await?;
    }

    Ok(())
}

/// Stage fonts for the Hydrolysis web runtime using the existing CLI font pipeline.
///
/// The web runtime discovers no system fonts — `load_web_fonts` fetches exactly
/// what `waterui-fonts.json` lists and asserts its `default_family` registered
/// — so the bundled set is whatever the project declared through
/// `[[assets.font]]` in `Water.toml` or a dependency's
/// `[package.metadata.waterui.assets.font]` entries. A project that declares no
/// fonts cannot render text on the web at all, so staging fails fast rather
/// than shipping a site that panics on startup.
pub async fn stage_hydrolysis_web_fonts(
    project: &Project,
    backend_path: &Path,
    site_root: &Path,
) -> eyre::Result<()> {
    let mut resolved_fonts =
        resolve_fonts(scan_fonts(project, &backend_path.join("Cargo.toml")).await?).await?;
    resolved_fonts.sort_by(|left, right| left.name.cmp(&right.name));

    // `default_family` must name a face the manifest actually carries. Roboto
    // stays the default when the project declares it — the same family the
    // runtime's Material baseline was written against — otherwise the first
    // declared family takes the slot.
    let Some(default_family) = resolved_fonts
        .iter()
        .find(|font| font.name == HYDROLYSIS_DEFAULT_FONT_FAMILY)
        .or_else(|| resolved_fonts.first())
    else {
        eyre::bail!(
            "the Hydrolysis web runtime has no system fonts to fall back on, so a web \
             build must bundle at least one declared font; declare one in Water.toml:\n\n\
             \x20   [[assets.font]]\n\x20   name = \"{HYDROLYSIS_DEFAULT_FONT_FAMILY}\"\n\n\
             or through `[package.metadata.waterui.assets.font]` in a dependency's \
             Cargo.toml"
        );
    };
    let default_family = default_family.name.clone();

    let fonts_dest = site_root.join("fonts");
    copy_fonts(&resolved_fonts, &fonts_dest).await?;
    write_hydrolysis_web_font_manifest(&resolved_fonts, &fonts_dest, &default_family).await?;
    Ok(())
}

async fn write_hydrolysis_web_font_manifest(
    fonts: &[ResolvedFont],
    fonts_dest: &Path,
    default_family: &str,
) -> eyre::Result<()> {
    let mut manifest_fonts = Vec::with_capacity(fonts.len());

    for font in fonts {
        let file_name = font
            .path
            .file_name()
            .ok_or_eyre("Font path has no filename")?
            .to_string_lossy()
            .into_owned();
        manifest_fonts.push(HydrolysisWebFontManifestEntry {
            name: font.name.clone(),
            file_name,
        });
    }

    let manifest = HydrolysisWebFontManifest {
        default_family: default_family.to_string(),
        fonts: manifest_fonts,
    };
    let payload = serde_json::to_vec_pretty(&manifest)?;
    fs::write(
        fonts_dest.join(HYDROLYSIS_WEB_FONT_MANIFEST_FILE_NAME),
        payload,
    )
    .await?;
    Ok(())
}

/// Returns whether `feature` is enabled on `package` in the resolved
/// dependency graph of `build_manifest`.
///
/// `build_manifest` is the `Cargo.toml` of the crate the build actually
/// compiles — the generated FFI crate for Apple and Android, the generated
/// backend crate for the self-drawn backends. That crate depends on the app,
/// so its graph carries both the app's authored dependencies and the backend's
/// own; resolving any other manifest misses declarations only the backend's
/// dependencies make.
///
/// Optional `WaterUI` capabilities are cargo features on the FFI crate, and the
/// native backends must compile the matching component only when the app turned
/// that capability on. The resolved graph is the single source of truth for
/// that, so backends never guess from the manifest text.
///
/// # Errors
///
/// Returns an error when `cargo metadata` cannot be read.
pub async fn package_feature_enabled(
    build_manifest: &Path,
    package: &str,
    feature: &str,
) -> eyre::Result<bool> {
    let manifest_path = build_manifest.to_path_buf();
    let metadata = smol::unblock({
        let manifest_path = manifest_path.clone();
        move || {
            cargo_metadata::MetadataCommand::new()
                .manifest_path(&manifest_path)
                .exec()
        }
    })
    .await
    .wrap_err_with(|| {
        format!(
            "Failed to run cargo metadata on {}",
            build_manifest.display()
        )
    })?;

    let Some(resolve) = metadata.resolve.as_ref() else {
        return Ok(false);
    };
    let enabled = metadata
        .packages
        .iter()
        .filter(|candidate| candidate.name.as_str() == package)
        .any(|candidate| {
            resolve
                .nodes
                .iter()
                .filter(|node| node.id == candidate.id)
                .any(|node| {
                    node.features
                        .iter()
                        .any(|enabled| enabled.as_str() == feature)
                })
        });
    debug!("resolved feature {package}/{feature}: {enabled}");
    Ok(enabled)
}

/// An optional `WaterUI` capability, and what in the app's resolved graph says
/// the app has it.
///
/// The name is also the feature the FFI crate exports the capability's C
/// surface under, so one entry drives both the FFI build and the native
/// backend's conditional compilation.
struct Capability {
    /// The capability's name, shared with `waterui-ffi`'s feature of the same
    /// name.
    name: &'static str,
    /// The crate that actually provides the capability.
    package: &'static str,
    /// The feature on that crate that carries it, or `None` when depending on
    /// the crate at all is the opt-in.
    feature: Option<&'static str>,
}

/// Optional `WaterUI` capabilities, each keyed on the crate that actually
/// provides it.
///
/// The source of truth is the *providing* crate, never a facade toggle. An app
/// that sets `waterui = { default-features = false }` can still pull the GPU
/// stack in through a side door — every SVG icon pack renders through
/// `waterui-svg`, which enables `waterui-graphics/gpu` on its own — and such an
/// app emits `GpuSurface` views at runtime. Keying on the facade's `gpu` there
/// pruned the FFI exports and the native backend while the authoring layer kept
/// producing GPU views, which is a guaranteed panic on first render. Reading
/// the resolved graph's `waterui-graphics/gpu` instead makes the exported
/// surface follow what the app can actually express.
///
/// `gpu` is default-on for the facade, but the generated FFI crate must set
/// `default-features = false` (the `c-api` and `android-jni` ABIs are mutually
/// exclusive), which drops it. Forwarding it here is what keeps the GPU C
/// surface present for apps whose graphs carry the GPU stack.
///
/// `map` has no feature at all: `waterui-map` is a component crate an app
/// depends on directly, exactly like an icon pack or a browser engine, so
/// linking it *is* the opt-in.
const OPTIONAL_CAPABILITIES: &[Capability] = &[
    Capability {
        name: "gpu",
        package: "waterui-graphics",
        feature: Some("gpu"),
    },
    Capability {
        name: "map",
        package: "waterui-map",
        feature: None,
    },
    // The `Video`/`Media` playback FFI surface and the `waterkit_audio`
    // keep-alive behind it. `waterui-video` is an optional dependency of the
    // facade (`media`/`video` features), so linking it *is* the opt-in — an app
    // that never plays media stops rooting the codec/streaming graph through
    // `waterui_video_*` exports.
    Capability {
        name: "media",
        package: "waterui-video",
        feature: None,
    },
    // The `WebView` FFI surface (bridge script, JS replies, cookie jar).
    // `waterui-webview` is optional on the facade and the browser-cef crate
    // reaches it through its own `webview` feature, so a plain `links` check
    // covers both entry points.
    Capability {
        name: "webview",
        package: "waterui-webview",
        feature: None,
    },
];

/// Returns whether this app's resolved graph carries the named capability.
///
/// This is the one predicate every consumer of a capability must share: the
/// FFI build forwards the capability's feature, and the native backend build
/// compiles the matching components, from this same answer. The FFI features
/// are passed on the build command line rather than written into the
/// generated manifest, so re-resolving `waterui-ffi`'s own features from the
/// manifest graph would always read them as off — the backend then prunes
/// components whose symbols the dylib does export.
///
/// `build_manifest` is the manifest of the crate being built — the resolved
/// graph the feature check reads.
///
/// # Errors
///
/// Returns an error when `cargo metadata` cannot be read.
pub async fn capability_enabled(
    project: &Project,
    build_manifest: &Path,
    capability: &str,
) -> eyre::Result<bool> {
    let capability = OPTIONAL_CAPABILITIES
        .iter()
        .find(|candidate| candidate.name == capability)
        .unwrap_or_else(|| panic!("unknown WaterUI capability: {capability}"));
    match capability.feature {
        Some(feature) => package_feature_enabled(build_manifest, capability.package, feature).await,
        None => project.links_runtime_package(capability.package).await,
    }
}

/// Returns the `waterui-ffi` features to enable for this app's capabilities.
///
/// An app opts into a capability through its dependency graph — a component
/// crate it depends on (`waterui-map`), or a crate that carries the capability
/// with it (an SVG icon pack carries `waterui-graphics/gpu`). The generated FFI
/// crate is what exports that capability's C surface, so the resolved graph's
/// choice has to reach its build; reading it back out keeps one declaration in
/// the app's manifest.
///
/// `build_manifest` is the manifest of the crate being built — the FFI
/// companion for Apple and Android builds.
///
/// # Errors
///
/// Returns an error when `cargo metadata` cannot be read.
pub async fn capability_ffi_features(
    project: &Project,
    build_manifest: &Path,
) -> eyre::Result<Vec<String>> {
    let mut features = Vec::new();
    for capability in OPTIONAL_CAPABILITIES {
        if capability_enabled(project, build_manifest, capability.name).await? {
            features.push(format!("waterui-ffi/{}", capability.name));
        }
    }
    Ok(features)
}

/// Returns the `waterui-ffi` features that select `WaterUI`'s own realizations
/// of the semantic components the facade carries, for a platform with no
/// native primitive to bridge.
///
/// Apple bridges `AVPlayer`, so an Apple build asks for none of these and links
/// no player. Every other platform draws the video itself, and the
/// application's composition root — `waterui::app::App` — is what installs it,
/// so the choice travels as a facade feature rather than as a backend
/// dependency. The realization is opt-in: linking it pulls decoders such as
/// rav1d and symphonia into the artifact, so the FFI build selects it only when
/// the application declared `waterui`'s `video-gpu` feature (or the
/// `waterui-video-gpu` crate) in its own dependency graph.
///
/// Realizations that live in their own crates — `waterui-map-gpu` — are not
/// here. The application depends on such a crate directly and installs it from
/// its own `app(env)`, the way it installs a browser engine, so no build flag
/// selects it.
///
/// `build_manifest` is the manifest of the crate being built — the FFI
/// companion whose `video` feature this list feeds.
///
/// # Errors
///
/// Returns an error when `cargo metadata` cannot be read.
pub async fn self_drawn_realization_features(
    project: &Project,
    build_manifest: &Path,
) -> eyre::Result<Vec<String>> {
    let mut features = Vec::new();
    let opted_in = package_feature_enabled(build_manifest, "waterui", "video-gpu").await?
        || project.links_runtime_package("waterui-video-gpu").await?;
    if opted_in {
        features.push("waterui-ffi/video".to_string());
    }
    Ok(features)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    /// A `FontFetch` stub for declarations that must never be downloaded.
    fn must_not_download<'a>(
        _url: &'a str,
        _dest: &'a Path,
    ) -> Pin<Box<dyn Future<Output = eyre::Result<()>> + Send + 'a>> {
        panic!("this declaration has no download to perform")
    }

    /// A `FontFetch` stub that writes a fake font file to `dest`.
    fn place_font<'a>(
        url: &'a str,
        dest: &'a Path,
    ) -> Pin<Box<dyn Future<Output = eyre::Result<()>> + Send + 'a>> {
        assert_eq!(url, "https://example.com/inter.ttf");
        let dest = dest.to_path_buf();
        Box::pin(async move {
            std::fs::write(dest, b"font-bytes")?;
            Ok(())
        })
    }

    /// A `FontFetch` stub whose download always fails.
    fn fail_download<'a>(
        _url: &'a str,
        _dest: &'a Path,
    ) -> Pin<Box<dyn Future<Output = eyre::Result<()>> + Send + 'a>> {
        Box::pin(async { Err(eyre::eyre!("connection refused")) })
    }

    fn manifest_with_fonts(toml_fonts: &str) -> crate::project::Manifest {
        toml::from_str(&format!(
            "[package]\ntype = \"app\"\nname = \"Demo\"\n\
             bundle_identifier = \"dev.example.demo\"\n\n{toml_fonts}"
        ))
        .expect("manifest parses")
    }

    #[test]
    fn water_toml_font_with_a_name_alone_uses_the_registry() {
        let manifest = manifest_with_fonts("[[assets.font]]\nname = \"Inter\"");
        let declarations =
            manifest_font_declarations(&manifest, Path::new("/project")).expect("declarations");
        assert_eq!(declarations.len(), 1);
        assert_eq!(declarations[0].name, "Inter");
        assert_eq!(declarations[0].crate_name, "Demo");
        assert!(matches!(declarations[0].source, FontSource::BuiltIn));
    }

    #[test]
    fn water_toml_font_local_path_resolves_against_the_project_root() {
        let manifest = manifest_with_fonts(
            "[[assets.font]]\nname = \"My Font\"\nlocal_path = \"fonts/my.ttf\"",
        );
        let declarations =
            manifest_font_declarations(&manifest, Path::new("/project")).expect("declarations");
        let FontSource::Local {
            crate_root,
            relative_path,
        } = &declarations[0].source
        else {
            panic!("expected a local font source");
        };
        assert_eq!(crate_root, Path::new("/project"));
        assert_eq!(relative_path, Path::new("fonts/my.ttf"));
    }

    #[test]
    fn water_toml_font_rejects_conflicting_sources() {
        let manifest = manifest_with_fonts(
            "[[assets.font]]\nname = \"X\"\nlocal_path = \"a.ttf\"\nremote_path = \"https://x\"",
        );
        assert!(manifest_font_declarations(&manifest, Path::new("/project")).is_err());
    }

    #[test]
    fn water_toml_font_rejects_an_absolute_local_path() {
        let manifest =
            manifest_with_fonts("[[assets.font]]\nname = \"X\"\nlocal_path = \"/abs/x.ttf\"");
        assert!(manifest_font_declarations(&manifest, Path::new("/project")).is_err());
    }

    #[test]
    fn a_manifest_without_assets_declares_no_fonts() {
        let manifest = manifest_with_fonts("");
        assert!(
            manifest_font_declarations(&manifest, Path::new("/project"))
                .expect("declarations")
                .is_empty()
        );
    }

    /// A remote declaration that is not already cached must fail naming the
    /// font, the URL, and the cache directory — and name `water fetch`, the
    /// command that downloads it, since builds never access the network.
    #[test]
    fn an_uncached_remote_font_names_the_font_url_and_cache_dir() {
        let cache_dir = tempdir().expect("temp cache dir");
        let error = smol::block_on(cached_font(
            "Inter",
            "https://example.com/inter.ttf",
            cache_dir.path(),
        ))
        .expect_err("an uncached remote font must surface as an error");
        let message = error.to_string();
        assert!(message.contains("Inter"), "{message}");
        assert!(
            message.contains("https://example.com/inter.ttf"),
            "{message}"
        );
        assert!(
            message.contains(&cache_dir.path().display().to_string()),
            "{message}"
        );
        assert!(message.contains("water fetch"), "{message}");
    }

    /// `water fetch` downloads a missing remote font into the cache entry
    /// the build looks for — `{sha256(url)}.ttf` — and the build's own probe
    /// then resolves it. The downloader is a stub: a test never reaches the
    /// real network.
    #[test]
    fn fetch_places_a_missing_remote_font_where_the_build_looks() {
        let cache_dir = tempdir().expect("temp cache dir");
        let url = "https://example.com/inter.ttf";
        let expected = cache_dir.path().join(format!("{}.ttf", sha256_hex(url)));

        let outcomes = smol::block_on(fetch_fonts(
            vec![FontDeclaration {
                name: "Inter".to_string(),
                source: FontSource::Remote {
                    url: url.to_string(),
                },
                crate_name: "some-theme".to_string(),
            }],
            cache_dir.path(),
            place_font,
        ))
        .expect("fetch succeeds");

        let [FetchOutcome::Fetched { name, path }] = outcomes.as_slice() else {
            panic!("expected one Fetched outcome, got {outcomes:?}");
        };
        assert_eq!(name, "Inter");
        assert_eq!(
            path, &expected,
            "the fetched font lands at the cache entry the build probes"
        );
        assert_eq!(
            fs::read(&expected).expect("read cached font"),
            b"font-bytes"
        );

        let resolved = smol::block_on(cached_font("Inter", url, cache_dir.path()))
            .expect("the build resolves the font the fetch placed");
        assert_eq!(resolved, expected);
    }

    /// `water fetch` is a no-op for a font that is already cached: the
    /// downloader is never invoked and the outcome reports it satisfied.
    #[test]
    fn fetch_is_a_no_op_for_a_font_already_in_the_cache() {
        let cache_dir = tempdir().expect("temp cache dir");
        let url = "https://example.com/inter.ttf";
        let cached = cache_dir.path().join(format!("{}.ttf", sha256_hex(url)));
        fs::write(&cached, b"cached-font").expect("seed the cache entry");

        let outcomes = smol::block_on(fetch_fonts(
            vec![FontDeclaration {
                name: "Inter".to_string(),
                source: FontSource::Remote {
                    url: url.to_string(),
                },
                crate_name: "some-theme".to_string(),
            }],
            cache_dir.path(),
            must_not_download,
        ))
        .expect("fetch succeeds");

        let [FetchOutcome::Satisfied { name, path }] = outcomes.as_slice() else {
            panic!("expected one Satisfied outcome, got {outcomes:?}");
        };
        assert_eq!(name, "Inter");
        assert_eq!(path, &cached);
    }

    /// A failed download is an error naming the font and its URL — never a
    /// quiet skip that leaves the next build failing on the same font.
    #[test]
    fn a_failed_download_is_an_error_naming_the_font_and_url() {
        let cache_dir = tempdir().expect("temp cache dir");

        let error = smol::block_on(fetch_fonts(
            vec![FontDeclaration {
                name: "Inter".to_string(),
                source: FontSource::Remote {
                    url: "https://example.com/inter.ttf".to_string(),
                },
                crate_name: "some-theme".to_string(),
            }],
            cache_dir.path(),
            fail_download,
        ))
        .expect_err("a failed download must be an error");
        let message = format!("{error:#}");
        assert!(message.contains("Inter"), "{message}");
        assert!(
            message.contains("https://example.com/inter.ttf"),
            "{message}"
        );
        assert!(message.contains("connection refused"), "{message}");
    }

    /// A font declared by a name the registry does not know is reported
    /// exactly as the build reports it — fetching cannot fix it.
    #[test]
    fn fetch_reports_an_unknown_builtin_name_the_way_the_build_does() {
        let cache_dir = tempdir().expect("temp cache dir");

        let outcomes = smol::block_on(fetch_fonts(
            vec![FontDeclaration {
                name: "No Such Family".to_string(),
                source: FontSource::BuiltIn,
                crate_name: "some-theme".to_string(),
            }],
            cache_dir.path(),
            must_not_download,
        ))
        .expect("an unsatisfiable declaration is an outcome, not a fetch error");

        let [FetchOutcome::Unsatisfiable { name, error }] = outcomes.as_slice() else {
            panic!("expected one Unsatisfiable outcome, got {outcomes:?}");
        };
        assert_eq!(name, "No Such Family");
        let message = format!("{error:#}");
        assert!(message.contains("No Such Family"), "{message}");
        assert!(message.contains("some-theme"), "{message}");
        assert!(message.contains("built-in registry"), "{message}");
    }

    /// A crate-local font that is missing is reported exactly as the build
    /// reports it — fetching cannot fix it, and saying so is the point.
    #[test]
    fn fetch_reports_a_missing_local_font_the_way_the_build_does() {
        let cache_dir = tempdir().expect("temp cache dir");
        let root = tempdir().expect("temp root");

        let outcomes = smol::block_on(fetch_fonts(
            vec![FontDeclaration {
                name: "Roboto".to_string(),
                source: FontSource::Local {
                    crate_root: root.path().to_path_buf(),
                    relative_path: PathBuf::from("assets/fonts/Roboto-Variable.ttf"),
                },
                crate_name: "some-theme".to_string(),
            }],
            cache_dir.path(),
            must_not_download,
        ))
        .expect("an unsatisfiable declaration is an outcome, not a fetch error");

        let [FetchOutcome::Unsatisfiable { name, error }] = outcomes.as_slice() else {
            panic!("expected one Unsatisfiable outcome, got {outcomes:?}");
        };
        assert_eq!(name, "Roboto");
        let message = format!("{error:#}");
        assert!(message.contains("Roboto"), "{message}");
        assert!(message.contains("Roboto-Variable.ttf"), "{message}");
    }

    #[test]
    fn test_font_registry_has_entries() {
        let registry = FontRegistry::builtin().expect("registry parses");
        assert!(!registry.fonts.is_empty());
        assert!(registry.url("Inter").is_some());
        assert!(registry.url("Roboto").is_some());
        assert!(registry.url("Noto Sans CJK SC").is_some());
        // Icon pack fonts should NOT be in the built-in registry
        assert!(
            !registry
                .fonts
                .iter()
                .any(|font| font.name.contains("Font Awesome"))
        );
        assert!(
            !registry
                .fonts
                .iter()
                .any(|font| font.name.contains("Material Design"))
        );
    }

    /// The registry must offer a face carrying an OpenType `MATH` table, and it
    /// must be reached through the archive code path.
    #[test]
    fn font_registry_offers_a_math_face() {
        let registry = FontRegistry::builtin().expect("registry parses");
        let url = registry
            .url("STIX Two Math")
            .expect("registry must offer an OpenType MATH font");
        assert!(
            is_zip_url(url),
            "the math font must resolve through the archive path so the single \
             matching face is extracted rather than the whole distribution"
        );
    }

    /// `STIX Two Math` ships in the same archive as eight `STIX Two Text` faces,
    /// none of which carry a `MATH` table. Picking a Text face would leave
    /// formula layout with no table to read, and nothing downstream would say
    /// so — the font would simply be there and be useless.
    #[test]
    fn math_face_wins_over_its_text_siblings_in_the_same_archive() {
        let extracted = tempdir().expect("temp dir");
        let root = extracted.path().join("static_otf");
        fs::create_dir_all(&root).expect("create extract dir");
        for face in [
            "STIXTwoMath-Regular.otf",
            "STIXTwoText-Bold.otf",
            "STIXTwoText-BoldItalic.otf",
            "STIXTwoText-Italic.otf",
            "STIXTwoText-Medium.otf",
            "STIXTwoText-MediumItalic.otf",
            "STIXTwoText-Regular.otf",
            "STIXTwoText-SemiBold.otf",
            "STIXTwoText-SemiBoldItalic.otf",
        ] {
            fs::write(root.join(face), []).expect("write face");
        }

        let selected = smol::block_on(find_font_file(extracted.path(), "STIX Two Math"))
            .expect("math face must be found");

        assert_eq!(
            selected.file_name().expect("selected face has a name"),
            "STIXTwoMath-Regular.otf",
            "selected {} instead of the Math face",
            selected.display()
        );
    }

    #[test]
    fn test_sha256_hex() {
        let hash = sha256_hex("hello");
        assert_eq!(hash.len(), 64); // SHA256 = 32 bytes = 64 hex chars
    }

    #[test]
    fn test_http_allowlist() {
        for url in [
            "http://localhost/font.ttf",
            "http://127.0.0.1:8080/font.ttf",
            "http://[::1]/font.ttf",
            "https://example.com/font.ttf",
        ] {
            assert!(
                waterui_assets_core::ensure_http_allowed(url).is_ok(),
                "expected to allow {url}"
            );
        }
    }

    #[test]
    fn test_http_rejects_non_loopback_and_prefix_bypass() {
        for url in [
            "http://example.com/font.ttf",
            "http://localhost.evil.com/font.ttf",
            "http://127.0.0.1.evil.com/font.ttf",
        ] {
            assert!(
                waterui_assets_core::ensure_http_allowed(url).is_err(),
                "expected to reject {url}"
            );
        }
    }

    #[test]
    fn zip_font_cache_uses_extracted_directory_without_archive() {
        let cache_dir = tempdir().expect("temp cache dir");
        let url = "https://example.com/inter.zip";
        let extracted_dir = cache_dir.path().join(sha256_hex(url));
        fs::create_dir_all(&extracted_dir).expect("create extracted dir");
        let extracted_font = extracted_dir.join("inter-regular.ttf");
        fs::write(&extracted_font, b"font").expect("write extracted font");

        let resolved = smol::block_on(cached_font("Inter", url, cache_dir.path()))
            .expect("reuse extracted cache");

        assert_eq!(resolved, extracted_font);
    }

    /// A crate that declares a font it does not ship must stop the build.
    /// Skipping it renders the app in whatever face the shaper falls back to
    /// — the silent wrong typeface, which is worse than a failed build
    /// because nothing in the output says the declaration went unmet.
    #[test]
    fn a_declared_local_font_that_is_missing_fails_the_build() {
        let root = tempdir().expect("temp root");
        let error = smol::block_on(resolve_fonts(vec![FontDeclaration {
            name: "Roboto".to_string(),
            source: FontSource::Local {
                crate_root: root.path().to_path_buf(),
                relative_path: PathBuf::from("assets/fonts/Roboto-Variable.ttf"),
            },
            crate_name: "some-theme".to_string(),
        }]))
        .expect_err("a missing crate-local font must be an error");

        let message = format!("{error:#}");
        assert!(
            message.contains("Roboto") && message.contains("some-theme"),
            "the error must name the font and the crate that declared it: {message}"
        );
        assert!(
            message.contains("Roboto-Variable.ttf"),
            "the error must name the path that was expected: {message}"
        );
    }

    #[test]
    fn test_resolve_local_font_path_rejects_escape() {
        let root = tempdir().expect("temp root");
        let outside = tempdir().expect("temp outside");
        let outside_font = outside.path().join("outside.ttf");
        fs::write(&outside_font, b"font").expect("write outside font");

        let rel_escape = Path::new("..").join(outside.path().file_name().expect("outside name"));
        let rel_escape = rel_escape.join("outside.ttf");

        let result = resolve_local_font_path(root.path(), &rel_escape);
        assert!(result.is_err(), "expected path traversal to be rejected");
    }

    #[test]
    fn test_resolve_local_font_path_accepts_inside_root() {
        let root = tempdir().expect("temp root");
        let inside_dir = root.path().join("fonts");
        fs::create_dir_all(&inside_dir).expect("create fonts dir");
        let font_path = inside_dir.join("inside.ttf");
        fs::write(&font_path, b"font").expect("write inside font");

        let resolved = resolve_local_font_path(root.path(), Path::new("fonts/inside.ttf"))
            .expect("resolve should succeed")
            .expect("font should exist");
        assert_eq!(resolved, font_path.canonicalize().expect("canonical path"));
    }
}

/// Collects the permissions this app's dependencies declare they need.
///
/// A crate states its own requirement in its manifest, so the CLI never has to
/// know what any component does:
///
/// ```toml
/// [package.metadata.waterui.permissions]
/// internet = { reason = "downloads map styles and vector tiles" }
/// ```
///
/// Declarations gated behind a cargo feature are skipped unless the resolved
/// graph actually enabled that feature for the declaring crate.
///
/// The scan runs `cargo metadata` on `build_manifest` — the `Cargo.toml` of
/// the crate this build compiles, i.e. the generated backend or FFI crate.
/// That crate depends on the app, so its graph carries both the app's authored
/// dependencies and the backend's own (a theme crate and friends); resolving
/// the app's manifest instead would miss the backend's declarations entirely.
///
/// # Errors
///
/// Returns an error when `cargo metadata` cannot be read.
pub async fn scan_required_permissions(
    build_manifest: &Path,
) -> eyre::Result<Vec<RequiredPermission>> {
    let manifest_path = build_manifest.to_path_buf();
    let metadata = smol::unblock({
        let manifest_path = manifest_path.clone();
        move || {
            cargo_metadata::MetadataCommand::new()
                .manifest_path(&manifest_path)
                .exec()
        }
    })
    .await
    .wrap_err_with(|| {
        format!(
            "Failed to run cargo metadata on {}",
            build_manifest.display()
        )
    })?;

    let enabled_features: HashMap<&PackageId, HashSet<&str>> = metadata
        .resolve
        .as_ref()
        .map(|resolve| {
            resolve
                .nodes
                .iter()
                .map(|node| (&node.id, node.features.iter().map(|f| f.as_str()).collect()))
                .collect()
        })
        .unwrap_or_default();

    let mut required = Vec::new();
    for package in &metadata.packages {
        let Some(waterui) = package.metadata.get("waterui") else {
            continue;
        };
        let parsed: WaterUIMetadata = match serde_json::from_value(waterui.clone()) {
            Ok(parsed) => parsed,
            Err(error) => {
                warn!(
                    "Failed to parse waterui metadata for {}: {error}",
                    package.name
                );
                continue;
            }
        };
        let features = enabled_features
            .get(&package.id)
            .cloned()
            .unwrap_or_default();
        for (key, requirement) in parsed.permissions {
            if let Some(gate) = &requirement.required_feature
                && !features.contains(gate.as_str())
            {
                debug!(
                    "Skipping {key:?} for {}: feature `{gate}` is not enabled",
                    package.name
                );
                continue;
            }
            required.push(RequiredPermission {
                package: package.name.to_string(),
                key,
                reason: requirement.reason.clone(),
                evidence: PermissionEvidence::Declared,
            });
        }
    }
    if let Some(inferred) = infer_internet_from_http_clients(&metadata.packages, &required) {
        required.push(inferred);
    }
    required.sort_by(|left, right| {
        (left.key, left.package.as_str()).cmp(&(right.key, right.package.as_str()))
    });
    required.dedup();
    Ok(required)
}

/// HTTP client crates whose presence almost always means the app talks to the
/// network at runtime. Presence is a hint, not proof — a client can sit behind
/// a disabled feature of some dependency — so hits are reported as
/// [`PermissionEvidence::Inferred`].
const HTTP_CLIENT_CRATES: &[&str] = &[
    "attohttpc",
    "curl",
    "hyper",
    "isahc",
    "reqwest",
    "surf",
    "ureq",
    "zenwave",
];

/// Suggests the `internet` permission when the dependency graph contains a
/// known HTTP client and nothing declared that permission outright.
///
/// A declared requirement always carries better evidence and a better message,
/// so the inference stays quiet as soon as one exists.
fn infer_internet_from_http_clients(
    packages: &[cargo_metadata::Package],
    declared: &[RequiredPermission],
) -> Option<RequiredPermission> {
    if declared
        .iter()
        .any(|requirement| requirement.key == PermissionKey::Internet)
    {
        return None;
    }
    let mut clients: Vec<&str> = packages
        .iter()
        .map(|package| package.name.as_str())
        .filter(|name| HTTP_CLIENT_CRATES.contains(name))
        .collect();
    clients.sort_unstable();
    clients.dedup();
    if clients.is_empty() {
        return None;
    }
    Some(RequiredPermission {
        package: clients.join(", "),
        key: PermissionKey::Internet,
        reason: String::from("the dependency graph contains an HTTP client"),
        evidence: PermissionEvidence::Inferred,
    })
}

/// Selects the declared requirements this app has not satisfied.
///
/// `relevant` decides whether a permission means anything on the platform being
/// built, so an iOS build stays quiet about `internet` (which iOS never
/// declares) while an Android build does not. Keeping this separate from the
/// reporting makes the selection itself testable.
fn missing_permissions<'a>(
    enabled: &HashSet<PermissionKey>,
    required: &'a [RequiredPermission],
    relevant: impl Fn(PermissionKey) -> bool,
) -> Vec<&'a RequiredPermission> {
    required
        .iter()
        .filter(|requirement| !enabled.contains(&requirement.key) && relevant(requirement.key))
        .collect()
}

/// Reports dependencies that need a permission this app has not enabled.
pub fn warn_missing_permissions(
    project: &Project,
    required: &[RequiredPermission],
    relevant: impl Fn(PermissionKey) -> bool,
) {
    let enabled: HashSet<PermissionKey> = project
        .manifest()
        .permissions
        .iter()
        .filter(|(_, entry)| entry.is_enabled())
        .map(|(key, _)| *key)
        .collect();

    for requirement in missing_permissions(&enabled, required, relevant) {
        let key = permission_toml_key(requirement.key);
        match requirement.evidence {
            PermissionEvidence::Declared => warn!(
                "{} needs the `{key}` permission ({}). Add it to Water.toml:\n\n    [permissions.{key}]\n    enable = true\n",
                requirement.package, requirement.reason
            ),
            PermissionEvidence::Inferred => warn!(
                "This app likely needs the `{key}` permission: {} ({}). If it talks to the network, add it to Water.toml:\n\n    [permissions.{key}]\n    enable = true\n",
                requirement.reason, requirement.package
            ),
        }
    }
}

/// Renders a permission key the way it is written in `Water.toml`.
fn permission_toml_key(key: PermissionKey) -> String {
    serde_json::to_value(key)
        .ok()
        .and_then(|value| value.as_str().map(str::to_owned))
        .unwrap_or_else(|| format!("{key:?}"))
}

#[cfg(test)]
mod permission_audit_tests {
    use super::*;
    use tempfile::tempdir;

    fn requirement(key: PermissionKey) -> RequiredPermission {
        RequiredPermission {
            package: String::from("waterui-map-gpu"),
            key,
            reason: String::from("downloads map styles and vector tiles"),
            evidence: PermissionEvidence::Declared,
        }
    }

    fn package(name: &str) -> cargo_metadata::Package {
        let manifest = format!(
            r#"{{
                "name": "{name}",
                "version": "1.0.0",
                "id": "registry+https://github.com/rust-lang/crates.io-index#{name}@1.0.0",
                "dependencies": [],
                "targets": [],
                "features": {{}},
                "manifest_path": "/dev/null/Cargo.toml"
            }}"#
        );
        serde_json::from_str(&manifest).expect("synthesize a cargo package")
    }

    /// Writes a minimal compilable crate — `[package]` for `name`, an empty
    /// `src/lib.rs`, and `extra` verbatim manifest TOML — and returns the
    /// manifest path a scan can be pointed at.
    fn write_crate(dir: &Path, name: &str, extra: &str) -> PathBuf {
        std::fs::create_dir_all(dir.join("src")).expect("crate src dir");
        let manifest = dir.join("Cargo.toml");
        std::fs::write(
            &manifest,
            format!(
                "[package]\nname = \"{name}\"\nversion = \"0.0.0\"\nedition = \"2021\"\n\n{extra}"
            ),
        )
        .expect("crate manifest");
        std::fs::write(dir.join("src/lib.rs"), "").expect("crate source");
        manifest
    }

    /// The scan resolves the graph of the manifest it is handed — the crate
    /// the build actually compiles. A permission declared only through the
    /// managed backend's dependency tree is reported from the backend's
    /// manifest and is invisible from the FFI companion's.
    #[test]
    fn a_permission_declared_in_the_built_crates_graph_is_scanned() {
        let project = tempdir().expect("temp project");
        // `theme` stands in for a managed backend's own dependency, such as
        // hydrolysis-m3: the backend crate links it, the FFI crate does not.
        write_crate(
            &project.path().join("theme"),
            "theme",
            "[package.metadata.waterui.permissions]\n\
             internet = { reason = \"downloads map styles and vector tiles\" }\n",
        );
        let ffi_manifest = write_crate(&project.path().join("ffi"), "app-ffi", "");
        let backend_manifest = write_crate(
            &project.path().join("hydrolysis"),
            "app-hydrolysis",
            "[dependencies]\ntheme = { path = \"../theme\" }\n",
        );

        let required = smol::block_on(scan_required_permissions(&backend_manifest))
            .expect("scan the built crate's graph");
        assert!(
            required
                .iter()
                .any(|requirement| requirement.package == "theme"
                    && requirement.key == PermissionKey::Internet
                    && requirement.evidence == PermissionEvidence::Declared),
            "the backend graph must report the permission `theme` declares"
        );

        let ffi = smol::block_on(scan_required_permissions(&ffi_manifest))
            .expect("scan the ffi crate's graph");
        assert!(
            ffi.is_empty(),
            "the ffi graph does not carry `theme` and must stay silent"
        );
    }

    /// `package_feature_enabled` reads the same graph: a feature a dependency
    /// carries only through the managed backend's manifest reports enabled
    /// there and absent from the FFI companion's.
    #[test]
    fn a_feature_enabled_in_the_built_crates_graph_is_seen() {
        let project = tempdir().expect("temp project");
        write_crate(
            &project.path().join("theme"),
            "theme",
            "[features]\nextra = []\n",
        );
        let ffi_manifest = write_crate(&project.path().join("ffi"), "app-ffi", "");
        let backend_manifest = write_crate(
            &project.path().join("hydrolysis"),
            "app-hydrolysis",
            "[dependencies]\ntheme = { path = \"../theme\", features = [\"extra\"] }\n",
        );

        assert!(
            smol::block_on(package_feature_enabled(&backend_manifest, "theme", "extra"))
                .expect("scan the built crate's graph")
        );
        assert!(
            !smol::block_on(package_feature_enabled(&ffi_manifest, "theme", "extra"))
                .expect("scan the ffi crate's graph")
        );
    }

    #[test]
    fn an_http_client_in_the_graph_suggests_internet() {
        let packages = vec![package("serde"), package("zenwave")];

        let inferred = infer_internet_from_http_clients(&packages, &[])
            .expect("zenwave should trigger the suggestion");

        assert_eq!(inferred.key, PermissionKey::Internet);
        assert_eq!(inferred.evidence, PermissionEvidence::Inferred);
        assert!(inferred.package.contains("zenwave"));
    }

    #[test]
    fn a_declared_internet_requirement_silences_the_inference() {
        let packages = vec![package("reqwest")];
        let declared = vec![requirement(PermissionKey::Internet)];

        assert!(infer_internet_from_http_clients(&packages, &declared).is_none());
    }

    #[test]
    fn a_graph_without_http_clients_suggests_nothing() {
        let packages = vec![package("serde"), package("tracing")];

        assert!(infer_internet_from_http_clients(&packages, &[]).is_none());
    }

    #[test]
    fn a_declared_permission_the_app_enabled_is_not_reported() {
        let enabled = HashSet::from([PermissionKey::Internet]);
        let required = vec![requirement(PermissionKey::Internet)];

        assert_eq!(
            missing_permissions(&enabled, &required, |_| true),
            [] as [&RequiredPermission; 0]
        );
    }

    #[test]
    fn a_missing_permission_is_reported_once() {
        let required = vec![requirement(PermissionKey::Internet)];

        let missing = missing_permissions(&HashSet::new(), &required, |_| true);

        assert_eq!(missing.len(), 1);
        assert_eq!(missing[0].key, PermissionKey::Internet);
    }

    /// iOS never declares network access, so warning about it there would be
    /// noise — and a warning that cries wolf stops being read.
    #[test]
    fn a_permission_the_platform_does_not_declare_stays_quiet() {
        let required = vec![requirement(PermissionKey::Internet)];

        let android = missing_permissions(&HashSet::new(), &required, |key| {
            key.android_permission_name().is_some()
        });
        let ios = missing_permissions(&HashSet::new(), &required, |key| {
            key.ios_plist_key().is_some()
        });

        assert_eq!(android.len(), 1, "Android must ask for INTERNET");
        assert!(ios.is_empty(), "iOS declares no network permission");
    }

    #[test]
    fn the_reported_key_matches_the_water_toml_spelling() {
        assert_eq!(permission_toml_key(PermissionKey::Internet), "internet");
        assert_eq!(
            permission_toml_key(PermissionKey::CoarseLocation),
            "coarse_location"
        );
    }
}