ezu-cli 0.7.0

Command-line renderer for the Ezu Style Spec
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
//! Command-line renderer for the Ezu Style Spec.
//!
//! ```text
//! ezu tile --style STYLE.json --pmtiles URL_OR_PATH --tile Z/X/Y [--out FILE]
//! ezu bbox --style STYLE.json --mvt-url 'https://.../{z}/{x}/{y}.pbf' \
//!          --bbox MIN_LNG,MIN_LAT,MAX_LNG,MAX_LAT --zoom Z [--out FILE]
//! ```

mod serve;
pub(crate) mod source;

use std::path::{Path, PathBuf};
use std::sync::Arc;

use clap::{Args, Parser, Subcommand, ValueEnum};
use ezu::core::TileId as CoreTileId;
use ezu::features::mvt;
use ezu::graph::{
    build_graph, Cache, CanvasInfo, Evaluator, Graph, ParamValues, PortValue, RasterBuf, TileId,
};
use ezu::paint::host::{
    bind_dem_sources, bind_raster_sources, build_dem_sources, build_raster_sources, pixmap_to_webp,
    raster_to_png, raster_to_webp, requested_neighbor_offsets, BrushBankLoader, DemSourceRegistry,
    RasterSourceRegistry, TileLoader,
};
use ezu::paint::nodes::default_registry;
use ezu::style::{Document, SourceDecl};
use futures::future::try_join_all;
use futures::stream::{StreamExt, TryStreamExt};
use tiny_skia::{Pixmap, PixmapPaint, Transform};
use tracing_subscriber::EnvFilter;

use crate::source::{SourceSpec, TileSource};

#[derive(Parser, Debug)]
#[command(name = "ezu", about = "Render Ezu Style documents to PNG")]
struct Cli {
    /// Emit per-node debug logs from the graph evaluator (op name,
    /// cache hit/miss, output shape, eval duration). Overrides
    /// `RUST_LOG` for this run.
    #[arg(long, short = 'v', global = true)]
    verbose: bool,
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand, Debug)]
enum Cmd {
    /// Render a single z/x/y tile to PNG.
    Tile(TileCmd),
    /// Render the tile mosaic covering a lon/lat bounding box at a fixed zoom.
    Bbox(BboxCmd),
    /// Bulk-render an XYZ tile pyramid into `<out>/<z>/<x>/<y>.png`.
    Tiles(TilesCmd),
    /// Validate an Ezu Style document without rendering — exits non-zero
    /// on parse / graph / asset errors. Suitable for CI + pre-commit hooks.
    Check(CheckCmd),
    /// Emit a Mermaid `graph LR` diagram of the style's node dependencies.
    Graph(GraphCmd),
    /// Emit the style's declared legend as JSON, for a host to lay out
    /// beside the map.
    Legend(LegendCmd),
    /// Translate a map-engine style (MapLibre GL) into an ezu recipe.
    Translate(TranslateCmd),
    /// Start the live editor + tile server at `http://127.0.0.1:8080`.
    Serve(serve::ServeCmd),
    /// Print the Ezu Style JSON Schema, gathered from the registered ops.
    Schema(SchemaCmd),
}

#[derive(Args, Debug)]
struct SchemaCmd {
    /// Write to this path instead of stdout.
    #[arg(long)]
    out: Option<PathBuf>,
}

#[derive(Args, Debug)]
struct CommonArgs {
    /// Ezu Style JSON document — local path or http(s):// URL.
    #[arg(long)]
    style: String,
    /// Base directory for resolving asset `src` paths. Defaults to the
    /// style file's parent directory (or the current directory when
    /// `--style` is a URL).
    #[arg(long)]
    assets_dir: Option<PathBuf>,
    /// PMTiles archive — local path or http(s):// URL.
    #[arg(long, conflicts_with = "mvt")]
    pmtiles: Option<String>,
    /// Templated MVT tile source containing `{z}`, `{x}`, `{y}`
    /// placeholders. Accepts an http(s):// URL or a local path
    /// template (e.g. `/tiles/{z}/{x}/{y}.pbf`).
    #[arg(long, conflicts_with = "pmtiles")]
    mvt: Option<String>,
    /// When a requested tile is missing, fall back to a parent tile
    /// up to this many zoom levels up and re-project its geometry
    /// onto the requested tile (MVT "overzoom"). `0` disables.
    #[arg(long, default_value_t = 4)]
    overzoom_levels: u8,
    /// Override a document parameter, as `name=value` (repeatable).
    /// Values are validated against the style's `params` declarations:
    /// numbers respect `min`/`max`, colors are `#rrggbb[aa]`, bools
    /// are `true`/`false`.
    #[arg(long = "param", value_name = "NAME=VALUE")]
    params: Vec<String>,
}

/// Output raster format. Pure-Rust pipelines on both sides — WebP is
/// lossless via the `image-webp` codec, typically 20–40 % smaller than
/// PNG for painterly content.
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum OutputFormat {
    Png,
    Webp,
}

impl OutputFormat {
    fn extension(self) -> &'static str {
        match self {
            OutputFormat::Png => "png",
            OutputFormat::Webp => "webp",
        }
    }

    /// Pick a format from a filename extension, falling back to PNG.
    fn from_path(path: &Path) -> Self {
        match path.extension().and_then(|s| s.to_str()) {
            Some(s) if s.eq_ignore_ascii_case("webp") => OutputFormat::Webp,
            _ => OutputFormat::Png,
        }
    }
}

#[derive(Args, Debug)]
struct CheckCmd {
    /// Ezu Style JSON document — local path or http(s):// URL.
    style: String,
    /// Base directory for resolving relative asset `src` paths.
    /// Defaults to the style file's parent directory (or the current
    /// directory when `--style` is a URL).
    #[arg(long)]
    assets_dir: Option<PathBuf>,
    /// Skip fetching URL assets and reading local asset files — only
    /// run parse + `build_graph`. Faster and works offline; misses
    /// errors like an unreachable brush URL or a missing image file.
    #[arg(long)]
    no_fetch: bool,
    /// Write the report to stdout as JSON instead of log lines: name,
    /// version, counts, padding, attribution, and the style's params
    /// schema. Logs move to stderr so the stream stays parseable.
    #[arg(long)]
    json: bool,
}

#[derive(Args, Debug)]
struct GraphCmd {
    /// Ezu Style JSON document — local path or http(s):// URL.
    style: String,
    /// Output file. Writes to stdout when omitted.
    #[arg(long)]
    out: Option<PathBuf>,
}

#[derive(Args, Debug)]
struct LegendCmd {
    /// Ezu Style JSON document — local path or http(s):// URL.
    style: String,
    /// Keep only the entries that apply at this zoom. Also the zoom the
    /// swatches are drawn at, since a symbol may change with scale.
    #[arg(long)]
    zoom: Option<u8>,
    /// Output file. Writes to stdout when omitted.
    #[arg(long)]
    out: Option<PathBuf>,
    /// Pretty-print the emitted JSON.
    #[arg(long)]
    pretty: bool,
    /// Draw each entry's symbol into this directory as a PNG, and add
    /// its path to that entry in the emitted JSON.
    #[arg(long)]
    swatch_dir: Option<PathBuf>,
    /// Swatch size as `WIDTHxHEIGHT` (or one number for a square).
    #[arg(long, default_value = "48x32", value_parser = parse_wxh)]
    swatch_size: (u32, u32),
    /// Base directory for resolving relative asset `src` paths, for
    /// swatches whose symbol needs a brush, font or sprite.
    #[arg(long)]
    assets_dir: Option<PathBuf>,
}

/// Parse `WIDTHxHEIGHT`, or a single number as a square.
fn parse_wxh(s: &str) -> Result<(u32, u32), String> {
    let parse = |v: &str| {
        v.trim()
            .parse::<u32>()
            .map_err(|_| format!("`{s}`: expected WIDTHxHEIGHT in whole pixels"))
            .and_then(|n| (n > 0).then_some(n).ok_or_else(|| format!("`{s}`: zero")))
    };
    match s.split_once(['x', 'X']) {
        Some((w, h)) => Ok((parse(w)?, parse(h)?)),
        None => {
            let n = parse(s)?;
            Ok((n, n))
        }
    }
}

#[derive(Args, Debug)]
struct TranslateCmd {
    /// Source map-engine style (MapLibre GL JSON) — local path or
    /// http(s):// URL.
    style: String,
    /// Output file for the ezu recipe. Writes to stdout when omitted.
    #[arg(long)]
    out: Option<PathBuf>,
    /// Emitted `tile-size` (MapLibre uses 512).
    #[arg(long, default_value_t = 512)]
    tile_size: u32,
    /// Emitted `pad` — the margin for geometry painted wider than its own
    /// extent (a thick stroke) before the crop. Filter reach (blur, warp,
    /// mosaic, label extent) is sized by the renderer from the graph, so
    /// this is only about paint width, which an expression can decide per
    /// feature. The default covers a typical basemap's line widths.
    #[arg(long, default_value_t = 16)]
    pad: u32,
    /// Keep `visibility: none` layers in the recipe, gated off behind a
    /// `switch` (instead of dropping them).
    #[arg(long)]
    keep_hidden: bool,
    /// Map a MapLibre fontstack entry to a font source, as `NAME=SOURCE`
    /// (repeatable). SOURCE is an installed-font reference
    /// (`system:Helvetica`, optionally `?weight=700&style=italic`) or a
    /// font-file URL (`http(s)://…`, `file:…`, `data:…`) — e.g.
    /// `--font "Noto Sans Regular=system:Noto Sans"` or
    /// `--font "Noto Sans Regular=https://example.com/NotoSans-Regular.ttf"`.
    /// Optional: unmapped `text-font` stacks fall back to the style's
    /// `glyphs` endpoint (SDF glyph ranges); a mapping wins where
    /// present and renders from the real font.
    #[arg(long = "font", value_name = "NAME=SOURCE")]
    fonts: Vec<String>,
    /// Pretty-print the emitted JSON.
    #[arg(long)]
    pretty: bool,
}

#[derive(Args, Debug)]
struct TileCmd {
    #[command(flatten)]
    common: CommonArgs,
    /// Tile coordinate as `Z/X/Y`.
    #[arg(long, value_parser = parse_zxy)]
    tile: CoreTileId,
    /// Output path. Format is sniffed from the extension (`.png` /
    /// `.webp`); use `--format` to override.
    #[arg(long, default_value = "out.png")]
    out: PathBuf,
    /// Output format. Defaults to whatever `--out`'s extension implies.
    #[arg(long, value_enum)]
    format: Option<OutputFormat>,
}

#[derive(Args, Debug)]
struct BboxCmd {
    #[command(flatten)]
    common: CommonArgs,
    /// Bounding box `min_lng,min_lat,max_lng,max_lat` (WGS84).
    #[arg(long, value_parser = parse_bbox)]
    bbox: BBox,
    /// Zoom level.
    #[arg(long)]
    zoom: u8,
    /// Output path. Format is sniffed from the extension (`.png` /
    /// `.webp`); use `--format` to override.
    #[arg(long, default_value = "out.png")]
    out: PathBuf,
    /// Output format. Defaults to whatever `--out`'s extension implies.
    #[arg(long, value_enum)]
    format: Option<OutputFormat>,
}

#[derive(Args, Debug)]
struct TilesCmd {
    #[command(flatten)]
    common: CommonArgs,
    /// Bounding box `min_lng,min_lat,max_lng,max_lat` (WGS84). When
    /// omitted, every tile at each zoom is generated — at z=14 that
    /// is 268M tiles, so a bbox is strongly recommended.
    #[arg(long, value_parser = parse_bbox)]
    bbox: Option<BBox>,
    /// Minimum zoom level (inclusive).
    #[arg(long)]
    min_zoom: u8,
    /// Maximum zoom level (inclusive).
    #[arg(long)]
    max_zoom: u8,
    /// Output directory; tiles are written as
    /// `<out>/<z>/<x>/<y>.<ext>` (extension picked by `--format`).
    #[arg(long, default_value = "tiles")]
    out: PathBuf,
    /// Output format. Defaults to PNG.
    #[arg(long, value_enum, default_value_t = OutputFormat::Png)]
    format: OutputFormat,
    /// Number of tiles rendered in parallel. Defaults to the number
    /// of logical CPU cores.
    // Resolved at run time rather than through `default_value_t`, so
    // `--help` does not print the core count of whichever machine ran it.
    #[arg(long)]
    concurrency: Option<usize>,
}

fn default_concurrency() -> usize {
    std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(4)
}

#[derive(Clone, Copy, Debug)]
struct BBox {
    min_lng: f64,
    min_lat: f64,
    max_lng: f64,
    max_lat: f64,
}

/// Heap profiler, wired in only under `--features heap-profile`. Writes
/// `dhat-heap.json` (viewable at <https://nnethercote.github.io/dh_view/>)
/// on exit, attributing peak heap to allocation sites — the tool to reach
/// for when a render's memory is not explained by its pixel buffers.
#[cfg(feature = "heap-profile")]
#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;

#[tokio::main]
async fn main() {
    #[cfg(feature = "heap-profile")]
    let _dhat = dhat::Profiler::new_heap();
    // Returning the error from `main` would print it with `Debug`, which
    // for a `thiserror` type means the struct dump rather than the
    // `#[error(...)]` sentence written for exactly this moment. Print
    // `Display` instead, then the chain of `source()`s, so a nested
    // parse failure reads as the story it is.
    if let Err(e) = run().await {
        let top = e.to_string();
        eprintln!("error: {top}");
        let mut shown = top;
        let mut src = e.source();
        while let Some(cause) = src {
            let text = cause.to_string();
            // Several of these errors interpolate their source into their
            // own message, so printing the chain verbatim repeats it.
            if !shown.contains(&text) {
                eprintln!("  caused by: {text}");
            }
            shown = text;
            src = cause.source();
        }
        std::process::exit(1);
    }
}

async fn run() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();
    let filter = if cli.verbose {
        // Bump just the per-node evaluator target — info elsewhere keeps
        // the noise focused on the graph trace the user asked for.
        EnvFilter::new("info,ezu_graph::eval=debug")
    } else {
        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"))
    };
    // `check --json` owns stdout for its report, so its log lines go to
    // stderr — a pipe into `jq` has to see JSON and nothing else.
    let fmt = tracing_subscriber::fmt().with_env_filter(filter);
    match &cli.cmd {
        Cmd::Check(a) if a.json => fmt.with_writer(std::io::stderr).init(),
        _ => fmt.init(),
    }
    match cli.cmd {
        Cmd::Tile(args) => run_tile(args).await,
        Cmd::Bbox(args) => run_bbox(args).await,
        Cmd::Tiles(args) => run_tiles(args).await,
        Cmd::Check(args) => run_check(args).await,
        Cmd::Graph(args) => run_graph(args).await,
        Cmd::Legend(args) => run_legend(args).await,
        Cmd::Translate(args) => run_translate(args).await,
        Cmd::Serve(args) => serve::run(args).await,
        Cmd::Schema(args) => run_schema(args),
    }
}

/// Shared one-time setup: parse the style, build the graph, load
/// declared assets, and open the tile source. Returned components are
/// `Arc`-wrapped so callers can hand them to concurrent render tasks.
struct Prepared {
    graph: Arc<Graph>,
    cache: Arc<Cache>,
    loader: Arc<BrushBankLoader>,
    source: Option<Arc<TileSource>>,
    /// Name of the document's mvt/pmtiles source that `source`
    /// resolves to; passed to `bind_mvt` so that bindings land under
    /// the same name the style's `features` nodes reference.
    source_name: Option<Arc<str>>,
    dem_sources: Arc<DemSourceRegistry>,
    raster_sources: Arc<RasterSourceRegistry>,
    canvas: CanvasInfo,
    overzoom_levels: u8,
    params: Arc<ParamValues>,
}

async fn prepare(common: &CommonArgs) -> Result<Prepared, Box<dyn std::error::Error>> {
    let style_text = fetch_text(&common.style).await?;
    let doc = Document::from_json(&style_text)?;
    tracing::info!(
        "style: {} v{} ({} nodes, tile={})",
        doc.name,
        doc.version,
        doc.nodes.len(),
        doc.tile_size,
    );

    let assets_dir = common.assets_dir.clone().unwrap_or_else(|| {
        if is_url(&common.style) {
            PathBuf::from(".")
        } else {
            Path::new(&common.style)
                .parent()
                .map(|p| p.to_path_buf())
                .unwrap_or_else(|| PathBuf::from("."))
        }
    });
    let loader = Arc::new(build_asset_loader(&doc, &assets_dir).await?);

    let registry = default_registry();
    let graph = Arc::new(build_graph(&doc, &registry)?);
    report_pad(&graph, &doc);
    let cache = Arc::new(Cache::with_limits(
        ezu::graph::cache::DEFAULT_CAPACITY,
        cache_budget_bytes(),
    ));
    let canvas = CanvasInfo::square(doc.tile_size, canvas_pad(&graph, &doc));

    // CLI flags override the URL but keep the doc's source NAME, since
    // the style's `features` nodes reference sources by name.
    let cli_override = match (&common.pmtiles, &common.mvt) {
        (Some(p), None) => Some((SourceSpec::PmTiles(p.clone()), "--pmtiles flag")),
        (None, Some(u)) => Some((SourceSpec::Mvt(u.clone()), "--mvt flag")),
        (None, None) => None,
        _ => return Err("--pmtiles and --mvt are mutually exclusive".into()),
    };
    let pick = feature_source_from_doc(&doc);
    let (source, source_name): (Option<Arc<TileSource>>, Option<Arc<str>>) = match (
        pick,
        cli_override,
    ) {
        (Some(p), Some((spec, origin))) => {
            tracing::info!("opening source ({origin}, bound as `{}`): {spec:?}", p.name);
            (
                Some(Arc::new(TileSource::open(&spec).await?)),
                Some(Arc::from(p.name)),
            )
        }
        (Some(p), None) => {
            tracing::info!("opening source ({}): {:?}", p.origin, p.spec);
            (
                Some(Arc::new(TileSource::open(&p.spec).await?)),
                Some(Arc::from(p.name)),
            )
        }
        (None, Some((spec, origin))) => {
            return Err(format!(
                    "{origin} ({spec:?}) requires the style to declare a matching `mvt`/`pmtiles` source, but the document has none — `features` nodes have no source to reference"
                )
                .into());
        }
        (None, None) => {
            tracing::info!("no MVT source — `features` bindings will be empty");
            (None, None)
        }
    };

    let dem_sources = Arc::new(build_dem_sources(&doc));
    if !dem_sources.is_empty() {
        let names: Vec<&str> = dem_sources.names().collect();
        tracing::info!("dem sources: {}", names.join(", "));
    }
    let raster_sources = Arc::new(build_raster_sources(&doc, Some(assets_dir.clone())));
    if !raster_sources.is_empty() {
        let names: Vec<&str> = raster_sources.names().collect();
        tracing::info!("raster sources: {}", names.join(", "));
    }

    Ok(Prepared {
        graph,
        cache,
        loader,
        source,
        source_name,
        dem_sources,
        raster_sources,
        canvas,
        overzoom_levels: common.overzoom_levels,
        params: Arc::new(parse_cli_params(&common.params, &doc)?),
    })
}

/// Parse repeated `--param name=value` flags against the document's
/// `params` declarations. Unknown names, type mismatches, and
/// out-of-range numbers are hard errors.
fn parse_cli_params(
    flags: &[String],
    doc: &Document,
) -> Result<ParamValues, Box<dyn std::error::Error>> {
    let mut values = ParamValues::new();
    for flag in flags {
        let (name, raw) = flag
            .split_once('=')
            .ok_or_else(|| format!("--param `{flag}`: expected `name=value`"))?;
        let v = ezu::graph::parse_param_value(&doc.params, name, raw)?;
        values.set(name.to_string(), v);
    }
    Ok(values)
}

/// Dump the document JSON Schema assembled from every registered op —
/// the same document served at `/schemas/ezu-style.json` by `ezu serve`.
/// Feed it to editor tooling, an `ajv` CI check, or a docs generator.
fn run_schema(args: SchemaCmd) -> Result<(), Box<dyn std::error::Error>> {
    let schema = default_registry().document_schema();
    let mut text = serde_json::to_string_pretty(&schema)?;
    text.push('\n');
    match args.out {
        Some(path) => std::fs::write(&path, text)?,
        None => print!("{text}"),
    }
    Ok(())
}

/// The canvas margin to render with: whichever is larger of what the
/// style asks for and what its filters actually read.
///
/// A style's `pad` is a floor, not the answer. Rendering happens on one
/// canvas of `tile-size + 2 * pad` and nothing grows it mid-render, so a
/// margin narrower than the furthest a node reaches leaves the tile's own
/// edge pixels computed from clamped data — a seam between tiles rather
/// than an error. The graph knows the distance, so use it, and let a
/// style that wants a deliberately wider margin keep it.
pub(crate) fn canvas_pad(graph: &Graph, doc: &Document) -> u32 {
    match graph.required_pad() {
        Ok(needed) => doc.pad.max(needed),
        // Only a graph over `MAX_PAD` gets here; `report_pad` has already
        // said so, and rendering with what the style asked for is a more
        // useful answer than refusing.
        Err(_) => doc.pad,
    }
}

/// Say what the canvas margin will be and where it came from.
fn report_pad(graph: &Graph, doc: &Document) {
    let needed = match graph.required_pad() {
        Ok(needed) => needed,
        Err(e) => {
            tracing::warn!("pad: {e}");
            return;
        }
    };
    if needed > doc.pad {
        tracing::info!(
            "pad: {} declared, {needed} needed — rendering with {needed}",
            doc.pad,
        );
    } else {
        tracing::info!("pad: {} declared, {needed} needed", doc.pad);
    }
}

/// Machine-readable `ezu check` report — `--json`.
///
/// `params` is the same JSON Schema the tile server serves at
/// `/style/params` and the wasm renderer returns from `paramsSchema`.
/// A host that generates its own params panel can diff this in CI and
/// be told when a style grows a knob the UI has no control for, instead
/// of finding out from a widget that quietly went missing.
#[derive(serde::Serialize)]
struct CheckReport<'a> {
    name: &'a str,
    version: &'a str,
    nodes: usize,
    sources: usize,
    pad: PadReport,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    attribution: Vec<&'a str>,
    params: serde_json::Value,
    /// True when asset `src` entries were resolved too — the inverse of
    /// `--no-fetch`, stated so a consumer knows how much this pass
    /// actually covered.
    assets_resolved: bool,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    warnings: Vec<String>,
}

#[derive(serde::Serialize)]
struct PadReport {
    declared: u32,
    /// What the graph needs. Absent when it could not be computed — the
    /// reason is then in `warnings`.
    #[serde(skip_serializing_if = "Option::is_none")]
    needed: Option<u32>,
}

async fn run_check(args: CheckCmd) -> Result<(), Box<dyn std::error::Error>> {
    let text = fetch_text(&args.style).await?;
    let doc = Document::from_json(&text)?;
    let registry = default_registry();
    let graph = build_graph(&doc, &registry)?;
    let mut warnings = Vec::new();
    let needed = match graph.required_pad() {
        Ok(needed) => Some(needed),
        Err(e) => {
            warnings.push(format!("pad: {e}"));
            None
        }
    };
    let attributions = doc.attributions();
    if !args.json {
        match needed {
            Some(needed) if needed > doc.pad => tracing::info!(
                "pad: {} declared, {needed} needed — rendering with {needed}",
                doc.pad,
            ),
            Some(needed) => tracing::info!("pad: {} declared, {needed} needed", doc.pad),
            None => tracing::warn!("{}", warnings[0]),
        }
        if !attributions.is_empty() {
            tracing::info!("attribution: {}", attributions.join(" | "));
        }
    }

    let doc_scoped_count = count_doc_scoped_sources(&doc);
    if !args.no_fetch && doc_scoped_count > 0 {
        let base_dir = args.assets_dir.clone().unwrap_or_else(|| {
            if is_url(&args.style) {
                PathBuf::from(".")
            } else {
                Path::new(&args.style)
                    .parent()
                    .map(|p| p.to_path_buf())
                    .unwrap_or_else(|| PathBuf::from("."))
            }
        });
        let mut loader = BrushBankLoader::new()
            .with_dir(base_dir.clone())
            .with_images_dir(base_dir.clone());
        ezu::paint::host::prefetch_doc_assets(&doc, &base_dir, &mut loader).await?;
    }

    if args.json {
        let report = CheckReport {
            name: &doc.name,
            version: &doc.version,
            nodes: graph.len(),
            sources: doc.sources.len(),
            pad: PadReport {
                declared: doc.pad,
                needed,
            },
            attribution: attributions,
            params: doc.params_schema(),
            assets_resolved: !args.no_fetch,
            warnings,
        };
        println!("{}", serde_json::to_string_pretty(&report)?);
        return Ok(());
    }

    tracing::info!(
        "ok: {} v{} ({} nodes, {} sources){}",
        doc.name,
        doc.version,
        graph.len(),
        doc.sources.len(),
        if args.no_fetch {
            " [parse + graph only]"
        } else {
            ""
        },
    );
    Ok(())
}

/// Number of document-scoped sources (brush / image / font / glyphs) —
/// the ones `prefetch_doc_assets` stages on style load.
fn count_doc_scoped_sources(doc: &Document) -> usize {
    doc.sources
        .values()
        .filter(|d| {
            matches!(
                d,
                SourceDecl::Brush(_)
                    | SourceDecl::Image(_)
                    | SourceDecl::Font(_)
                    | SourceDecl::Glyphs(_)
            )
        })
        .count()
}

async fn run_graph(args: GraphCmd) -> Result<(), Box<dyn std::error::Error>> {
    let text = fetch_text(&args.style).await?;
    let doc = Document::from_json(&text)?;
    let mermaid = render_mermaid(&doc);
    match &args.out {
        Some(p) => {
            std::fs::write(p, &mermaid)?;
            tracing::info!("wrote {} ({} bytes)", p.display(), mermaid.len());
        }
        None => print!("{mermaid}"),
    }
    Ok(())
}

async fn run_legend(args: LegendCmd) -> Result<(), Box<dyn std::error::Error>> {
    let text = fetch_text(&args.style).await?;
    let doc = Document::from_json(&text)?;
    // Build the graph too: it is what verifies that every entry names a
    // node that exists and draws something, so a legend emitted here has
    // already been checked against the map it describes.
    build_graph(&doc, &default_registry())?;

    let Some(legend) = &doc.legend else {
        return Err(format!("{} declares no `legend` block", args.style).into());
    };
    // Serialized straight from the declaration, never through
    // `serde_json::Value`, so the emitted keys keep the order the type
    // declares them in rather than coming out alphabetized.
    let filtered = args.zoom.map(|z| ezu::style::LegendDecl {
        title: legend.title.clone(),
        note: legend.note.clone(),
        entries: legend.entries_at(z).cloned().collect(),
    });
    let legend = filtered.as_ref().unwrap_or(legend);

    let swatches = match &args.swatch_dir {
        Some(dir) => draw_swatches(&doc, legend, dir, &args).await?,
        None => vec![None; legend.entries.len()],
    };
    let out = LegendOut {
        title: legend.title.as_deref(),
        note: legend.note.as_deref(),
        entries: legend
            .entries
            .iter()
            .zip(&swatches)
            .map(|(e, swatch)| EntryOut {
                label: &e.label,
                from: &e.from,
                properties: &e.properties,
                note: e.note.as_deref(),
                min_zoom: e.min_zoom,
                max_zoom: e.max_zoom,
                geometry: e.geometry,
                swatch: swatch.as_deref(),
            })
            .collect(),
    };
    let json = if args.pretty {
        serde_json::to_string_pretty(&out)?
    } else {
        serde_json::to_string(&out)?
    };
    match &args.out {
        Some(p) => {
            std::fs::write(p, &json)?;
            tracing::info!("wrote {} ({} bytes)", p.display(), json.len());
        }
        None => println!("{json}"),
    }
    Ok(())
}

/// The emitted legend: the declaration as written, plus where each
/// entry's swatch was drawn.
///
/// Spelled out rather than `#[serde(flatten)]`-ed onto `LegendEntry`,
/// because flattening routes serialization through a `serde_json::Map`,
/// which sorts its keys — and a legend read by a human wants its title
/// before its entries.
#[derive(serde::Serialize)]
#[serde(rename_all = "kebab-case")]
struct LegendOut<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    title: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    note: Option<&'a str>,
    entries: Vec<EntryOut<'a>>,
}

#[derive(serde::Serialize)]
#[serde(rename_all = "kebab-case")]
struct EntryOut<'a> {
    label: &'a str,
    from: &'a ezu::style::NodeRef,
    #[serde(skip_serializing_if = "serde_json::Map::is_empty")]
    properties: &'a serde_json::Map<String, serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    note: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    min_zoom: Option<u8>,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_zoom: Option<u8>,
    #[serde(skip_serializing_if = "Option::is_none")]
    geometry: Option<ezu::style::LegendGeometry>,
    /// Path of the PNG this entry's symbol was drawn to, when
    /// `--swatch-dir` asked for one.
    #[serde(skip_serializing_if = "Option::is_none")]
    swatch: Option<&'a str>,
}

/// Draw every entry's symbol into `dir`, returning each one's path.
///
/// One cache serves the whole legend: entries that share upstream nodes
/// share the work, and the entry's own identity is in the cache key so
/// they cannot be confused for one another.
async fn draw_swatches(
    doc: &Document,
    legend: &ezu::style::LegendDecl,
    dir: &Path,
    args: &LegendCmd,
) -> Result<Vec<Option<String>>, Box<dyn std::error::Error>> {
    use ezu::paint::host::{crop_to_png, PngCompression};
    use ezu::paint::legend::{render_swatch, SwatchOptions};

    std::fs::create_dir_all(dir)?;
    let base_dir = args.assets_dir.clone().unwrap_or_else(|| {
        if is_url(&args.style) {
            PathBuf::from(".")
        } else {
            Path::new(&args.style)
                .parent()
                .map(|p| p.to_path_buf())
                .unwrap_or_else(|| PathBuf::from("."))
        }
    });
    let assets = build_asset_loader(doc, &base_dir).await?;
    let registry = default_registry();
    let cache = Cache::new();
    let params = ParamValues::new();
    let (width, height) = args.swatch_size;
    let opts = SwatchOptions {
        width,
        height,
        // A symbol may change with scale, so a swatch is only true for
        // one zoom. `--zoom` picks it; without one, mid-scale.
        zoom: args.zoom.unwrap_or(12),
        pad: 0,
        geometry: Default::default(),
    };

    let mut out = Vec::with_capacity(legend.entries.len());
    for (i, entry) in legend.entries.iter().enumerate() {
        let (raster, canvas) =
            render_swatch(doc, entry, &registry, &assets, &params, &cache, &opts)?;
        let png = crop_to_png(
            &raster,
            canvas.tile_w,
            canvas.tile_h,
            canvas.pad,
            PngCompression::Default,
        )?;
        let path = dir.join(format!("{i}.png"));
        std::fs::write(&path, &png)?;
        tracing::info!("wrote {} ({} bytes)", path.display(), png.len());
        out.push(Some(path.to_string_lossy().into_owned()));
    }
    Ok(out)
}

async fn run_translate(args: TranslateCmd) -> Result<(), Box<dyn std::error::Error>> {
    let text = fetch_text(&args.style).await?;
    let style: serde_json::Value = serde_json::from_str(&text)?;
    let mut fonts = std::collections::HashMap::new();
    for entry in &args.fonts {
        let Some((name, url)) = entry.split_once('=') else {
            return Err(format!("--font `{entry}`: expected NAME=URL").into());
        };
        fonts.insert(name.trim().to_string(), url.trim().to_string());
    }
    let opts = ezu::translate::maplibre::ConvertOptions {
        tile_size: args.tile_size,
        pad: args.pad,
        keep_hidden: args.keep_hidden,
        fonts,
    };
    let (recipe, report) = ezu::translate::maplibre::convert(&style, &opts)?;

    // Surface everything the converter skipped or approximated on stderr, so
    // it doesn't pollute the recipe written to stdout.
    for w in &report.warnings {
        tracing::warn!("{w}");
    }

    let json = if args.pretty {
        serde_json::to_string_pretty(&recipe)?
    } else {
        serde_json::to_string(&recipe)?
    };
    match &args.out {
        Some(p) => {
            std::fs::write(p, &json)?;
            tracing::info!(
                "wrote {} ({} bytes, {} warnings)",
                p.display(),
                json.len(),
                report.warnings.len()
            );
        }
        None => println!("{json}"),
    }
    Ok(())
}

/// Render the document's node DAG as a Mermaid `graph LR` block.
/// Edges follow data flow: each `@ref` becomes `ref --> consumer`.
/// `sources` entries are emitted as styled nodes so brush/image and
/// tile-pyramid sources stay visible.
fn render_mermaid(doc: &ezu::style::Document) -> String {
    use std::collections::HashSet;

    let mut s = String::new();
    s.push_str("graph LR\n");

    let mut doc_scoped_ids: Vec<&str> = Vec::new();
    for (id, decl) in &doc.sources {
        let kind = match decl {
            SourceDecl::Brush(_) => "brush",
            SourceDecl::Image(_) => "image",
            SourceDecl::Mvt(_) => "mvt",
            SourceDecl::Pmtiles(_) => "pmtiles",
            SourceDecl::Dem(_) => "dem",
            SourceDecl::Raster(_) => "raster",
            SourceDecl::GeoJson(_) => "geojson",
            SourceDecl::Sprite(_) => "sprite",
            SourceDecl::Font(_) => "font",
            SourceDecl::Glyphs(_) => "glyphs",
        };
        s.push_str(&format!("  {id}[/\"{id} (source:{kind})\"/]\n"));
        if matches!(decl, SourceDecl::Brush(_) | SourceDecl::Image(_)) {
            doc_scoped_ids.push(id);
        }
    }

    let output_id = doc.output.as_str();
    let mut source_ids: Vec<&str> = Vec::new();
    for (id, spec) in &doc.nodes {
        let is_source = spec.op == "features";
        let suffix = if id == output_id { ":::output" } else { "" };
        // Function calls label as `func:<name>` so the diagram reads at
        // the source level (calls stay single nodes, not expansions).
        let op = if spec.op == "func" {
            match spec.fields.get("fn").and_then(serde_json::Value::as_str) {
                Some(f) => format!("func:{f}"),
                None => spec.op.clone(),
            }
        } else {
            spec.op.clone()
        };
        // Cylinder shape for data-source nodes (MVT-backed `features`);
        // rectangle for everything else.
        if is_source {
            s.push_str(&format!("  {id}[(\"{id} ({op})\")]{suffix}\n"));
            source_ids.push(id);
        } else {
            s.push_str(&format!("  {id}[\"{id} ({op})\"]{suffix}\n"));
        }
    }
    s.push_str("  __output__([\"OUTPUT\"]):::sink\n");
    s.push_str(&format!("  {output_id} ==> __output__\n"));

    s.push('\n');
    for (id, spec) in &doc.nodes {
        let mut seen = HashSet::new();
        for r in spec.refs() {
            if !seen.insert(r.clone()) {
                continue;
            }
            if doc.nodes.contains_key(&r) || doc.sources.contains_key(&r) {
                s.push_str(&format!("  {r} --> {id}\n"));
            }
        }
    }

    // Each class fixes its own text colour as well as its fill. Mermaid's dark
    // theme otherwise draws light label text, which is unreadable on these
    // deliberately light fills — and a diagram rendered dark is the common case
    // when it is embedded in a dark page.
    s.push_str("\n  classDef asset fill:#fff4d6,color:#3a2e00,stroke:#a88500;\n");
    s.push_str("  classDef output fill:#ffe0e0,color:#4a1010,stroke:#cc3333,stroke-width:2px;\n");
    s.push_str("  classDef sink fill:#cc3333,color:#ffffff,stroke:#7a1f1f,stroke-width:2px;\n");
    s.push_str("  classDef source fill:#d9ecff,color:#0d2b45,stroke:#2a6fb0;\n");
    if !doc_scoped_ids.is_empty() {
        s.push_str(&format!("  class {} asset;\n", doc_scoped_ids.join(",")));
    }
    if !source_ids.is_empty() {
        s.push_str(&format!("  class {} source;\n", source_ids.join(",")));
    }
    s
}

async fn run_tile(args: TileCmd) -> Result<(), Box<dyn std::error::Error>> {
    let prep = prepare(&args.common).await?;
    let format = args
        .format
        .unwrap_or_else(|| OutputFormat::from_path(&args.out));
    let raster = render_one(
        Arc::clone(&prep.graph),
        Arc::clone(&prep.cache),
        Arc::clone(&prep.loader),
        prep.source.as_ref().map(Arc::clone),
        prep.source_name.as_ref().map(Arc::clone),
        Arc::clone(&prep.dem_sources),
        Arc::clone(&prep.raster_sources),
        prep.canvas,
        args.tile,
        prep.overzoom_levels,
        Arc::clone(&prep.params),
    )
    .await
    .map_err(|e| e.to_string())?;
    let bytes = match format {
        OutputFormat::Png => raster_to_png(&raster, prep.canvas.tile_w, prep.canvas.pad)?,
        OutputFormat::Webp => raster_to_webp(&raster, prep.canvas.tile_w, prep.canvas.pad)?,
    };
    std::fs::write(&args.out, &bytes)?;
    tracing::info!("wrote {} ({} bytes)", args.out.display(), bytes.len());
    Ok(())
}

async fn run_bbox(args: BboxCmd) -> Result<(), Box<dyn std::error::Error>> {
    let prep = prepare(&args.common).await?;
    let format = args
        .format
        .unwrap_or_else(|| OutputFormat::from_path(&args.out));
    let (x_range, y_range) = bbox_to_tiles(args.bbox, args.zoom);
    let nx = x_range.end - x_range.start;
    let ny = y_range.end - y_range.start;
    tracing::info!(
        "bbox covers {nx}×{ny} tiles at z={} ({}..{}, {}..{})",
        args.zoom,
        x_range.start,
        x_range.end,
        y_range.start,
        y_range.end,
    );

    let mut tasks = Vec::with_capacity((nx * ny) as usize);
    for ty in y_range.clone() {
        for tx in x_range.clone() {
            let tile = CoreTileId::new(args.zoom, tx, ty);
            let graph = Arc::clone(&prep.graph);
            let cache = Arc::clone(&prep.cache);
            let loader = Arc::clone(&prep.loader);
            let source = prep.source.as_ref().map(Arc::clone);
            let source_name = prep.source_name.as_ref().map(Arc::clone);
            let dem_sources = Arc::clone(&prep.dem_sources);
            let raster_sources = Arc::clone(&prep.raster_sources);
            let canvas = prep.canvas;
            let overzoom_levels = prep.overzoom_levels;
            let params = Arc::clone(&prep.params);
            tasks.push(tokio::spawn(async move {
                let raster = render_one(
                    graph,
                    cache,
                    loader,
                    source,
                    source_name,
                    dem_sources,
                    raster_sources,
                    canvas,
                    tile,
                    overzoom_levels,
                    params,
                )
                .await?;
                Ok::<(CoreTileId, Arc<RasterBuf>), Box<dyn std::error::Error + Send + Sync>>((
                    tile, raster,
                ))
            }));
        }
    }

    let mut mosaic =
        Pixmap::new(nx * prep.canvas.tile_w, ny * prep.canvas.tile_w).ok_or("mosaic alloc")?;
    for handle in try_join_all(tasks).await? {
        let (tile, raster) = handle.map_err(|e| e.to_string())?;
        let dx = ((tile.x - x_range.start) * prep.canvas.tile_w) as i32;
        let dy = ((tile.y - y_range.start) * prep.canvas.tile_w) as i32;
        blit_padded_into(
            &mut mosaic,
            &raster,
            dx,
            dy,
            prep.canvas.tile_w,
            prep.canvas.pad,
        )?;
    }
    let bytes = match format {
        OutputFormat::Png => mosaic.encode_png().map_err(|e| e.to_string())?,
        OutputFormat::Webp => pixmap_to_webp(&mosaic).map_err(|e| e.to_string())?,
    };
    std::fs::write(&args.out, &bytes)?;
    tracing::info!("wrote {} ({} bytes)", args.out.display(), bytes.len());
    Ok(())
}

async fn run_tiles(args: TilesCmd) -> Result<(), Box<dyn std::error::Error>> {
    if args.min_zoom > args.max_zoom {
        return Err("--min-zoom must be ≤ --max-zoom".into());
    }
    let concurrency = args.concurrency.unwrap_or_else(default_concurrency);
    if concurrency == 0 {
        return Err("--concurrency must be ≥ 1".into());
    }
    let prep = prepare(&args.common).await?;

    let mut total: u64 = 0;
    for z in args.min_zoom..=args.max_zoom {
        let (x_range, y_range) = match args.bbox {
            Some(b) => bbox_to_tiles(b, z),
            None => {
                let n = 1u32 << z;
                (0..n, 0..n)
            }
        };
        let nx = x_range.end - x_range.start;
        let ny = y_range.end - y_range.start;
        let count = nx as u64 * ny as u64;
        total += count;
        tracing::info!(
            "z={z}: {nx}×{ny} = {count} tiles ({}..{}, {}..{})",
            x_range.start,
            x_range.end,
            y_range.start,
            y_range.end,
        );

        // Lazily enumerate every (x, y) so memory stays bounded even
        // when a whole-world zoom is requested.
        let xr = x_range.clone();
        let coords = y_range
            .clone()
            .flat_map(move |ty| xr.clone().map(move |tx| (tx, ty)));
        let prep = &prep;
        let out = &args.out;
        let format = args.format;
        let t0 = std::time::Instant::now();
        futures::stream::iter(coords)
            .map(|(tx, ty)| async move {
                let tile = CoreTileId::new(z, tx, ty);
                let raster = render_one(
                    Arc::clone(&prep.graph),
                    Arc::clone(&prep.cache),
                    Arc::clone(&prep.loader),
                    prep.source.as_ref().map(Arc::clone),
                    prep.source_name.as_ref().map(Arc::clone),
                    Arc::clone(&prep.dem_sources),
                    Arc::clone(&prep.raster_sources),
                    prep.canvas,
                    tile,
                    prep.overzoom_levels,
                    Arc::clone(&prep.params),
                )
                .await?;
                let bytes = tokio::task::spawn_blocking({
                    let canvas = prep.canvas;
                    move || match format {
                        OutputFormat::Png => raster_to_png(&raster, canvas.tile_w, canvas.pad),
                        OutputFormat::Webp => raster_to_webp(&raster, canvas.tile_w, canvas.pad),
                    }
                })
                .await
                .map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { e.to_string().into() })?
                .map_err(|e| -> Box<dyn std::error::Error + Send + Sync> {
                    e.to_string().into()
                })?;
                let dir = out.join(z.to_string()).join(tx.to_string());
                tokio::fs::create_dir_all(&dir).await?;
                let path = dir.join(format!("{ty}.{}", format.extension()));
                tokio::fs::write(&path, bytes).await?;
                Ok::<(), Box<dyn std::error::Error + Send + Sync>>(())
            })
            .buffer_unordered(concurrency)
            .try_collect::<Vec<_>>()
            .await
            .map_err(|e| e.to_string())?;
        tracing::info!("z={z}: done in {:.1}s", t0.elapsed().as_secs_f64());
    }
    tracing::info!("wrote {total} tiles → {}", args.out.display());
    Ok(())
}

#[allow(clippy::too_many_arguments)]
async fn render_one(
    graph: Arc<Graph>,
    cache: Arc<Cache>,
    loader: Arc<BrushBankLoader>,
    source: Option<Arc<TileSource>>,
    source_name: Option<Arc<str>>,
    dem_sources: Arc<DemSourceRegistry>,
    raster_sources: Arc<RasterSourceRegistry>,
    canvas: CanvasInfo,
    tile: CoreTileId,
    overzoom_levels: u8,
    params: Arc<ParamValues>,
) -> Result<Arc<RasterBuf>, Box<dyn std::error::Error + Send + Sync>> {
    let fetched = match &source {
        Some(s) => s.fetch_with_fallback(tile, overzoom_levels).await?,
        None => None,
    };
    // Cross-tile placement (label collision): fetch only the neighbour
    // tiles the graph actually asks for (via `@dx,dy` binding names),
    // never the whole 3×3 window unconditionally.
    let neighbor_mvt: Vec<((i32, i32), (bytes::Bytes, CoreTileId))> = match (&source, &source_name)
    {
        (Some(s), Some(name)) => {
            let offsets = requested_neighbor_offsets(&graph.asset_inputs(), name);
            if offsets.is_empty() {
                Vec::new()
            } else {
                s.fetch_neighbors(tile, &offsets, overzoom_levels).await?
            }
        }
        _ => Vec::new(),
    };
    let tile_id = TileId {
        z: tile.z,
        x: tile.x,
        y: tile.y,
    };
    // Pre-fetch DEM mosaics for the tile before entering spawn_blocking
    // so the blocking path doesn't have to juggle async fetches.
    let mut dem_bindings: Vec<(String, ezu::graph::ScalarField)> = Vec::new();
    if !dem_sources.is_empty() {
        let base_loader = BrushBankLoader::new();
        let mut tmp = TileLoader::new(&base_loader, tile_id);
        bind_dem_sources(&mut tmp, &dem_sources, tile_id, canvas).await?;
        for name in dem_sources.names() {
            if let Ok(ezu::graph::Asset::ScalarField(field)) =
                ezu::graph::AssetLoader::load(&tmp, name)
            {
                dem_bindings.push((name.to_string(), (*field).clone()));
            }
        }
    }
    // Same dance for RGBA raster pyramids: fetch + stitch up front so
    // the blocking render path receives ready-to-bind buffers.
    let mut raster_bindings: Vec<(String, RasterBuf)> = Vec::new();
    if !raster_sources.is_empty() {
        let base_loader = BrushBankLoader::new();
        let mut tmp = TileLoader::new(&base_loader, tile_id);
        bind_raster_sources(&mut tmp, &raster_sources, tile_id, canvas).await?;
        for name in raster_sources.names() {
            if let Ok(ezu::graph::Asset::Image(buf)) = ezu::graph::AssetLoader::load(&tmp, name) {
                raster_bindings.push((name.to_string(), (*buf).clone()));
            }
        }
    }
    let raster = tokio::task::spawn_blocking(
        move || -> Result<Arc<RasterBuf>, Box<dyn std::error::Error + Send + Sync>> {
            let mut tile_loader = TileLoader::new(loader.as_ref(), tile_id);
            if let (Some((bytes, src_tile)), Some(src_name)) = (fetched, &source_name) {
                let mut decoded = mvt::decode(&bytes)?;
                if src_tile != tile {
                    decoded = mvt::clip_to_descendant(&decoded, src_tile, tile)?;
                }
                tile_loader.bind_mvt(src_name, decoded);
            }
            if let Some(src_name) = &source_name {
                for ((dx, dy), (bytes, src_tile)) in neighbor_mvt {
                    let ntile = CoreTileId::new(
                        tile.z,
                        (tile.x as i64 + dx as i64).rem_euclid(1i64 << tile.z) as u32,
                        (tile.y as i64 + dy as i64) as u32,
                    );
                    let mut decoded = mvt::decode(&bytes)?;
                    if src_tile != ntile {
                        decoded = mvt::clip_to_descendant(&decoded, src_tile, ntile)?;
                    }
                    tile_loader.bind_mvt_neighbor(src_name, dx, dy, decoded);
                }
            }
            for (name, field) in dem_bindings {
                tile_loader.bind_scalar_field(name, field);
            }
            for (name, buf) in raster_bindings {
                tile_loader.bind_raster(name, buf);
            }
            let ev = Evaluator::new(&graph, &cache, &tile_loader);
            let out = if serial_eval() {
                ev.render(tile_id, canvas, &params, tile_seed(tile))?
            } else {
                ev.render_parallel(tile_id, canvas, &params, tile_seed(tile))?
            };
            if ezu::graph::mem::enabled() {
                report_glyph_memory(loader.as_ref());
            }
            match out {
                PortValue::Raster(r) => Ok(r),
                other => Err(format!("expected Raster output, got {:?}", other.kind()).into()),
            }
        },
    )
    .await??;
    Ok(raster)
}

/// Print how much each glyph fontstack is holding, alongside the
/// evaluator's own `EZU_MEM_REPORT` breakdown. Glyph ranges are fetched
/// lazily and then kept for the process's life, so on a label-heavy tile
/// they can outweigh every pixel buffer in the render.
fn report_glyph_memory(loader: &BrushBankLoader) {
    let stacks = loader.glyphs.read().expect("glyphs bank poisoned");
    if stacks.is_empty() {
        return;
    }
    let mut total = 0usize;
    let mut lines = String::new();
    for (key, stack) in stacks.iter() {
        let (ranges, bytes) = stack.loaded_size();
        total += bytes;
        let name = key.rsplit('/').nth(1).unwrap_or(key);
        lines.push_str(&format!(
            "  {name:<32} {:>8.1} MB over {ranges} range(s)\n",
            bytes as f64 / (1024.0 * 1024.0)
        ));
    }
    eprintln!(
        "glyph ranges: {:.1} MB\n{lines}",
        total as f64 / (1024.0 * 1024.0)
    );
}

/// Ceiling on the pixel bytes the intermediate cache retains, from
/// `EZU_CACHE_MB` (default: the library's own).
///
/// The default is sized for rendering a tile at a time. Bulk runs
/// (`ezu tiles`, `ezu bbox`) re-use world-anchored intermediates across
/// neighbouring tiles, so on a machine with memory to spare, raising it
/// trades RAM for a shorter run.
fn cache_budget_bytes() -> usize {
    std::env::var("EZU_CACHE_MB")
        .ok()
        .and_then(|v| v.parse::<usize>().ok())
        .map(|mb| mb * 1024 * 1024)
        .unwrap_or(ezu::graph::cache::DEFAULT_BYTE_BUDGET)
}

/// Whether to evaluate the graph on one thread, as `EZU_SERIAL=1`
/// requests. Single-threaded evaluation is what a WebAssembly host gets,
/// and it holds far fewer intermediates alive at once than the Rayon
/// scheduler does, so it is the mode to reach for when reproducing a
/// browser or Workers memory profile from the CLI.
fn serial_eval() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| {
        std::env::var("EZU_SERIAL")
            .map(|v| v != "0" && !v.is_empty())
            .unwrap_or(false)
    })
}

/// Pre-resolve every entry in the style's `assets` block: each `src`
/// may be a local file path (looked up against `base_dir`) or an
/// `http(s)://` URL (fetched via `ezu::paint::host::prefetch_doc_assets`).
/// Decoded payloads are staged in the returned [`BrushBankLoader`].
async fn build_asset_loader(
    doc: &Document,
    base_dir: &Path,
) -> Result<BrushBankLoader, Box<dyn std::error::Error>> {
    let mut loader = BrushBankLoader::new()
        .with_dir(base_dir.to_path_buf())
        .with_images_dir(base_dir.to_path_buf());
    ezu::paint::host::prefetch_doc_assets(doc, base_dir, &mut loader).await?;
    tracing::info!(
        "loaded {} brushes + {} images (base={})",
        loader.bank.len(),
        loader.images.len(),
        base_dir.display(),
    );
    Ok(loader)
}

/// Resolve `<base>/<src>` first as-is, then with `.<ext>` appended.
/// Mirrors `BrushBankLoader`'s lazy lookup so `assets.src` can omit
/// the extension as a shorthand (e.g. `"watercolor_glazing"` →
/// `"watercolor_glazing.myb"`).
/// Fetch a text resource by URL (http/https) or local path. Used for
/// the style document so callers can pass either form to `--style`.
pub(crate) async fn fetch_text(arg: &str) -> Result<String, Box<dyn std::error::Error>> {
    if is_url(arg) {
        let body = reqwest::get(arg).await?.error_for_status()?.text().await?;
        Ok(body)
    } else {
        Ok(std::fs::read_to_string(arg)?)
    }
}

/// Return the first MVT/Pmtiles entry in the style's `sources` block as
/// a [`SourceSpec`] the CLI can open. DEM sources are handled
/// separately. Returns `None` if no compatible source is declared;
/// when several are present the document order wins (later entries are
/// ignored with a warning).
pub(crate) struct FeatureSourcePick {
    pub name: String,
    pub spec: SourceSpec,
    pub origin: &'static str,
}

pub(crate) fn feature_source_from_doc(doc: &Document) -> Option<FeatureSourcePick> {
    let mut chosen: Option<FeatureSourcePick> = None;
    for (name, decl) in &doc.sources {
        let (spec, origin) = match decl {
            SourceDecl::Mvt(s) => (SourceSpec::Mvt(s.url.clone()), "style sources (mvt)"),
            SourceDecl::Pmtiles(s) => (
                SourceSpec::PmTiles(s.url.clone()),
                "style sources (pmtiles)",
            ),
            // Document-scoped and tile-scoped raster — not feature
            // sources, skip.
            SourceDecl::Brush(_)
            | SourceDecl::Image(_)
            | SourceDecl::Dem(_)
            | SourceDecl::GeoJson(_)
            | SourceDecl::Sprite(_)
            | SourceDecl::Font(_)
            | SourceDecl::Glyphs(_)
            | SourceDecl::Raster(_) => continue,
        };
        if chosen.is_some() {
            tracing::warn!("multiple feature sources in style; ignoring `{name}`");
            continue;
        }
        chosen = Some(FeatureSourcePick {
            name: name.clone(),
            spec,
            origin,
        });
    }
    chosen
}

fn is_url(s: &str) -> bool {
    s.starts_with("http://") || s.starts_with("https://")
}

/// Copy the central `tile_size × tile_size` region of `raster` (which
/// is `pad`-padded on every side) into `mosaic` at `(dx, dy)`.
fn blit_padded_into(
    mosaic: &mut Pixmap,
    raster: &RasterBuf,
    dx: i32,
    dy: i32,
    tile_size: u32,
    pad: u32,
) -> Result<(), Box<dyn std::error::Error>> {
    // Hand-crop the central tile region out of the padded raster so we
    // can paste with no clip-mask gymnastics. The mosaic gets exactly
    // the visible tile pixels and nothing of the neighbour-bleed pad.
    let mut tile = Pixmap::new(tile_size, tile_size).ok_or("tile pixmap alloc")?;
    let stride = (raster.width * 4) as usize;
    let row_bytes = (tile_size * 4) as usize;
    let dst = tile.data_mut();
    for row in 0..tile_size {
        let src_y = pad + row;
        let src_off = src_y as usize * stride + (pad as usize) * 4;
        let dst_off = row as usize * row_bytes;
        dst[dst_off..dst_off + row_bytes]
            .copy_from_slice(&raster.pixels[src_off..src_off + row_bytes]);
    }
    mosaic.draw_pixmap(
        dx,
        dy,
        tile.as_ref(),
        &PixmapPaint::default(),
        Transform::identity(),
        None,
    );
    Ok(())
}

/// Convert a lon/lat bounding box to an inclusive-min, exclusive-max
/// tile range at the given zoom. Latitudes north of ~85.05° are
/// clamped to the Web Mercator domain.
fn bbox_to_tiles(b: BBox, z: u8) -> (std::ops::Range<u32>, std::ops::Range<u32>) {
    let n = 2f64.powi(z as i32);
    let xt = |lng: f64| {
        (ezu::core::coord::lon_to_world_x(lng) * n)
            .floor()
            .clamp(0.0, n - 1.0) as u32
    };
    let yt = |lat: f64| {
        (ezu::core::coord::lat_to_world_y(lat) * n)
            .floor()
            .clamp(0.0, n - 1.0) as u32
    };
    let x0 = xt(b.min_lng);
    let x1 = xt(b.max_lng);
    // min_lat is south → larger y_tile; max_lat is north → smaller y_tile.
    let y0 = yt(b.max_lat);
    let y1 = yt(b.min_lat);
    (x0..(x1 + 1), y0..(y1 + 1))
}

fn parse_zxy(s: &str) -> Result<CoreTileId, String> {
    let parts: Vec<&str> = s.split('/').collect();
    if parts.len() != 3 {
        return Err(format!("expected `Z/X/Y`, got `{s}`"));
    }
    let z: u8 = parts[0].parse().map_err(|e| format!("bad z: {e}"))?;
    let x: u32 = parts[1].parse().map_err(|e| format!("bad x: {e}"))?;
    let y: u32 = parts[2].parse().map_err(|e| format!("bad y: {e}"))?;
    Ok(CoreTileId::new(z, x, y))
}

fn parse_bbox(s: &str) -> Result<BBox, String> {
    let parts: Vec<&str> = s.split(',').collect();
    if parts.len() != 4 {
        return Err(format!(
            "expected `min_lng,min_lat,max_lng,max_lat`, got `{s}`"
        ));
    }
    let v: Vec<f64> = parts
        .iter()
        .map(|p| {
            p.trim()
                .parse::<f64>()
                .map_err(|e| format!("bad number `{p}`: {e}"))
        })
        .collect::<Result<_, _>>()?;
    let (min_lng, min_lat, max_lng, max_lat) = (v[0], v[1], v[2], v[3]);
    if min_lng >= max_lng || min_lat >= max_lat {
        return Err(format!(
            "bbox min must be strictly less than max: {min_lng},{min_lat},{max_lng},{max_lat}"
        ));
    }
    Ok(BBox {
        min_lng,
        min_lat,
        max_lng,
        max_lat,
    })
}

fn tile_seed(tile: CoreTileId) -> u64 {
    let mut s = 0u64;
    s = s
        .wrapping_mul(0x9E37_79B9_7F4A_7C15)
        .wrapping_add(tile.z as u64);
    s = s
        .wrapping_mul(0x9E37_79B9_7F4A_7C15)
        .wrapping_add(tile.x as u64);
    s = s
        .wrapping_mul(0x9E37_79B9_7F4A_7C15)
        .wrapping_add(tile.y as u64);
    s
}