paperboy 0.4.0

A Rust TUI API tester
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
//! The PaperTrail AST ([`ReportFlow`]) and its canonical text serializer.
//!
//! The serializer round-trips with [`super::parser::parse_flow`]: parsing then
//! serializing (or vice-versa) is stable. Keywords are emitted uppercase and
//! block bodies are indented four spaces per level — indentation is purely
//! cosmetic (the parser ignores it); `FOR … END` delimits blocks.
//!
//! See `docs/reports/02-grammar.md` for the grammar these types model.

use std::fmt::Write as _;

use super::model::StatKind;

/// A whole report flow: a comment/directive header plus the ordered statements
/// the interpreter executes.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ReportFlow {
    pub header: Header,
    pub nodes: Vec<FlowNode>,
}

/// The header block: the `# key: value` directives (and any free `#` comments)
/// that precede the first statement. Stored as an ordered list so it
/// round-trips verbatim; typed access to known directives is via the helper
/// methods.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Header {
    pub lines: Vec<HeaderLine>,
}

/// One declared collection: a reference plus, for a helper, the alias its
/// requests are addressed through (`alias/request`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CollectionRef<'a> {
    pub reference: &'a str,
    pub alias: Option<&'a str>,
}

/// Split `<ref> [AS <alias>]`.
///
/// The keyword is matched case-insensitively and only when it stands alone as
/// the second-to-last whitespace-separated word, so a path that merely contains
/// "as" (`./as-built/api.hurl`, `git:origin/as.hurl`) is not mangled. The alias
/// is returned unvalidated — checking it is an identifier, is present on every
/// helper and absent on the primary is validation's job, which can report a
/// useful message rather than silently treating the line as a plain path.
pub fn split_collection_ref(value: &str) -> (&str, Option<&str>) {
    let value = value.trim();
    let mut it = value.rsplitn(2, char::is_whitespace);
    let (Some(last), Some(head)) = (it.next(), it.next()) else {
        return (value, None);
    };
    let head = head.trim_end();
    if head
        .rsplit(char::is_whitespace)
        .next()
        .is_some_and(|w| w.eq_ignore_ascii_case("AS"))
        && !last.is_empty()
    {
        let reference = head[..head.len() - 2].trim_end();
        if !reference.is_empty() {
            return (reference, Some(last));
        }
    }
    (value, None)
}

/// Split a `# labels:` value into its canonical label and its synonym list.
///
/// `Pass = ok, low risk` becomes `("Pass", "ok, low risk")`. A line with no `=`
/// yet is all label and no synonyms, so a half-typed directive still splits --
/// the structured editors need to show one as it is being written, not refuse
/// it. Both halves are trimmed; neither is validated here (that is
/// [`crate::report::labels::LabelMap`]'s job), so what the user typed always
/// survives a round-trip through a form.
/// Only the GUI's settings panel splits a class today -- the TUI edits the
/// directive as one line -- so a non-GUI build has no caller outside the tests.
#[cfg_attr(not(feature = "gui"), allow(dead_code))]
pub fn split_label_class(value: &str) -> (&str, &str) {
    match value.split_once('=') {
        Some((name, synonyms)) => (name.trim(), synonyms.trim()),
        None => (value.trim(), ""),
    }
}

/// One line of the header: either a recognised `# key: value` directive or a
/// free-form `#` comment (preserved as-is).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HeaderLine {
    Directive { key: String, value: String },
    Comment(String),
}

impl Header {
    /// The value of the first directive named `key` (case-insensitive), if any.
    pub fn get(&self, key: &str) -> Option<&str> {
        self.lines.iter().find_map(|l| match l {
            HeaderLine::Directive { key: k, value } if k.eq_ignore_ascii_case(key) => {
                Some(value.as_str())
            }
            _ => None,
        })
    }

    /// Every value of the directives named `key`, in the order they were
    /// written. Repeatable directives (`collection:`) need all of them; `get`
    /// only ever sees the first.
    pub fn get_all(&self, key: &str) -> Vec<&str> {
        self.lines
            .iter()
            .filter_map(|l| match l {
                HeaderLine::Directive { key: k, value } if k.eq_ignore_ascii_case(key) => {
                    Some(value.as_str())
                }
                _ => None,
            })
            .collect()
    }

    /// The bound collection reference (`collection:` directive), required for a
    /// runnable flow. This is the *primary* collection: the first one declared,
    /// with any `AS alias` suffix stripped. Helper collections are `collections()`.
    pub fn collection(&self) -> Option<&str> {
        self.get("collection").map(|v| split_collection_ref(v).0)
    }

    /// Every declared collection, in directive order, primary first.
    ///
    /// The primary carries no alias; each helper must (that is enforced by
    /// validation, not here, so the editors can still show a half-typed line).
    pub fn collections(&self) -> Vec<CollectionRef<'_>> {
        self.get_all("collection")
            .into_iter()
            .map(|v| {
                let (reference, alias) = split_collection_ref(v);
                CollectionRef { reference, alias }
            })
            .collect()
    }
    pub fn output(&self) -> Option<&str> {
        self.get("output")
    }
    /// The declared label classes (`labels:` directives), one per line, in the
    /// order written — which is also the order a confusion matrix's axes take.
    ///
    /// Repeatable, like `collection:`: each line declares one canonical label
    /// and its synonyms (`Pass = pass, ok, low risk`). Parsing them into a
    /// lookup is [`crate::report::labels::LabelMap`]'s job; the header only
    /// hands back the raw text, so a half-typed line in an editor is still
    /// round-tripped rather than dropped.
    pub fn labels(&self) -> Vec<&str> {
        self.get_all("labels")
    }
    pub fn columns(&self) -> Option<&str> {
        self.get("columns")
    }
    pub fn root(&self) -> Option<&str> {
        self.get("root")
    }
    /// The saved-run snapshot (`baseline:` directive) to diff this run against —
    /// PaperTrail's "Source B" comparison. Names a `.baseline` JSON file (a
    /// previous run saved via the results grid) whose reported fields are diffed
    /// against the current run to produce the `Result` column, exactly like an
    /// `ENVS BASELINE/COMPARISON` clause but against stored values rather than a
    /// live baseline environment. The path resolves like producer paths
    /// (relative to `# root:` / the report's directory). Ignored when the flow
    /// already configures an `ENVS` role comparison (that takes precedence).
    pub fn baseline(&self) -> Option<&str> {
        self.get("baseline")
    }
    /// The single environment (`environment:` directive) to use as the report's
    /// base variable layer for a plain, no-comparison run. Names an
    /// *already-loaded* global environment (validation errors if it isn't
    /// loaded); when absent the run falls back to the app's active + the bound
    /// collection's pinned environment. Multi-environment comparison still uses
    /// a `FOR … IN ENVS` loop, not this directive.
    pub fn environment(&self) -> Option<&str> {
        self.get("environment")
    }
}

/// One statement in a flow body (or loop body).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FlowNode {
    /// `KEY=value` — set `{{KEY}}` in the current scope (includes `PRELUDE_*`).
    Assign { key: String, value: String },
    /// `PARAM <kind> NAME = "default" [LABEL "…"]` — declare a run parameter.
    ///
    /// A parameter behaves exactly like an [`Assign`](FlowNode::Assign) of its
    /// effective value, so `{{NAME}}` interpolation needs no new concept; what
    /// it adds is that the value is *offered to the user before the run*, with
    /// a type the front-ends can put a sensible control behind. It is a
    /// statement rather than a header directive because it binds a variable
    /// (and so belongs in the same precedence ladder as everything else), and
    /// because unknown header lines are silently treated as comments — an
    /// older PaperBoy would run a parameterised report with nothing bound
    /// instead of saying it can't.
    ///
    /// Validation confines it to the prelude (before the first statement that
    /// does anything), so the whole parameter set can be read off a flow
    /// without executing it.
    Param(ParamDecl),
    /// `LIST NAME = <producer>` — declare a named, iteration-only list.
    ListDecl { name: String, producer: Producer },
    /// A whole-line `# …` comment in the body.
    ///
    /// Comments are kept in the AST, not skipped as trivia, because every
    /// structural edit re-serializes the flow — so anything the AST can't hold
    /// is deleted the moment you touch the report in the node editor. Commenting
    /// a block out and losing it is the case that made this non-negotiable.
    ///
    /// Holds the text *after* the `#`, verbatim (leading space included), so a
    /// comment round-trips byte for byte.
    Comment(String),
    /// `REQUEST <name>` — send a request, emit no column.
    Request { name: String },
    /// `REPORT …` — send/compute and emit column(s) into the current row.
    Report(ReportStmt),
    /// `[PARALLEL[(n)]] FOR <pattern> IN <producer> … END`.
    ForEach {
        pattern: Pattern,
        producer: Producer,
        body: Vec<FlowNode>,
        /// `Some(..)` when the loop is marked `PARALLEL`: its iterations run
        /// concurrently, each on an independent snapshot of the enclosing
        /// scope, with rows still emitted in iteration order. `None` = the
        /// default sequential loop.
        parallel: Option<ParallelSpec>,
    },
    /// `[PARALLEL[(n)]] FOR <var> IN ENVS <clause> … END`.
    ForEnvs {
        var: String,
        clause: EnvClause,
        body: Vec<FlowNode>,
        parallel: Option<ParallelSpec>,
    },
}

/// The `PARALLEL` marker on a loop: run its iterations concurrently.
///
/// Iterations are independent — each gets its own snapshot of the enclosing
/// scope and its own forward capture chain, so a body like
/// `create → upload → process` still runs sequentially *within* one iteration.
/// Results are buffered by iteration index and emitted in order, so the report
/// is deterministic no matter which iteration finishes first.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ParallelSpec {
    /// An explicit worker cap from `PARALLEL(n)`. `None` means "use the engine
    /// default" (`PRELUDE_MAX_PARALLEL`, itself defaulting to a built-in cap).
    pub degree: Option<u32>,
}

/// A declared run parameter: what a `PARAM` statement binds.
///
/// The `default` is what the checked-in `.trail` file says; a front-end may
/// offer a different value for a particular run, but never writes the chosen
/// value back into the file — a report under version control keeps meaning the
/// same thing to everyone who opens it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParamDecl {
    /// The control to put behind it, and the values it accepts.
    pub kind: ParamKind,
    /// The variable it binds; `{{NAME}}` reads it like any other variable.
    pub name: String,
    /// The value used when nothing is supplied. `None` = the parameter is
    /// required and the run settings open with it empty and flagged.
    pub default: Option<String>,
    /// A human-friendly prompt for the run settings. `None` → one is derived
    /// from the name (see [`ParamDecl::prompt`]).
    pub label: Option<String>,
}

impl ParamDecl {
    /// What to put beside the field in the run settings.
    ///
    /// The `LABEL` when one was written, and otherwise a readable rendering of
    /// the identifier itself. Deriving one matters more than it sounds: most
    /// parameters will never carry a label, and a form shouting `TICKET_REF`
    /// at someone who only ever runs the report — never edits it — is the
    /// difference between a tool and a script someone else wrote. `LABEL` is
    /// then an override for the cases the derivation can't get right
    /// (acronyms, wording), not a chore on every declaration.
    ///
    /// The raw name stays the identity everywhere it matters — `{{NAME}}`, the
    /// CLI's `--param`, the remembered values — so renaming a label never
    /// loses anything.
    pub fn prompt(&self) -> String {
        match &self.label {
            Some(l) if !l.trim().is_empty() => l.trim().to_string(),
            _ => derive_prompt(&self.name),
        }
    }
}

/// Turn an identifier into something readable: `TICKET_REF` → "Ticket ref",
/// `api_version` → "Api version", `imageWidth` → "imageWidth".
///
/// Underscores become spaces, and a word that is all one case is
/// sentence-cased. Anything already mixed-case is left exactly as written —
/// it was deliberate, and second-guessing `iOSBuild` produces worse names than
/// leaving it alone.
fn derive_prompt(name: &str) -> String {
    let words: Vec<String> = name
        .split('_')
        .filter(|w| !w.is_empty())
        .map(|w| {
            let mixed = w.chars().any(|c| c.is_ascii_uppercase())
                && w.chars().any(|c| c.is_ascii_lowercase());
            if mixed {
                w.to_string()
            } else {
                w.to_ascii_lowercase()
            }
        })
        .collect();
    let mut out = words.join(" ");
    // Only the first letter is raised: "Ticket ref", not "Ticket Ref". Title
    // Case reads like a heading; these are field labels in a form.
    if let Some(first) = out.chars().next()
        && first.is_ascii_lowercase()
        && !out
            .split_whitespace()
            .next()
            .is_some_and(|w| w.chars().any(|c| c.is_ascii_uppercase()))
    {
        out.replace_range(0..first.len_utf8(), &first.to_ascii_uppercase().to_string());
    }
    out
}

/// The type of a `PARAM` — what the run settings offer and what validation
/// will accept.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum ParamKind {
    /// Free text (the default when no type is written).
    #[default]
    Text,
    /// A number, offered as a number field and checked as one.
    Number,
    /// The name of a loaded environment.
    Env,
    /// A directory path, offered with a folder picker.
    Folder,
    /// A file path, offered with a file picker.
    File,
    /// One of a fixed set, offered as a drop-down. The list is never empty
    /// (validation rejects `CHOICE()`), and a default must be one of it.
    Choice(Vec<String>),
}

impl ParamKind {
    /// The keyword this kind is written as, without any `CHOICE` options.
    pub fn keyword(&self) -> &'static str {
        match self {
            ParamKind::Text => "TEXT",
            ParamKind::Number => "NUMBER",
            ParamKind::Env => "ENV",
            ParamKind::Folder => "FOLDER",
            ParamKind::File => "FILE",
            ParamKind::Choice(_) => "CHOICE",
        }
    }
}

/// The column-emitting `REPORT` statement in its three forms.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReportStmt {
    /// `REPORT REQUEST <name> [AS <alias>] [RESPONSE …] [SHOW(…)] [HIDE(…)] [WITH … END]`.
    Request {
        name: String,
        alias: Option<String>,
        response_fmt: Option<ResponseFmt>,
        /// The per-statement field selector `SHOW(a, b, …)`: when non-empty,
        /// only these field suffixes (intrinsics like `Time` and/or
        /// `[Reports]`/`WITH` field names) are emitted, in listed order — so a
        /// noisy `Response` (e.g. a base64 blob) can be dropped. Empty = no
        /// `SHOW` clause, i.e. emit every field (the default).
        show: Vec<ShowField>,
        /// `HIDE(a, b, …)`: remove these field suffixes from the final output
        /// after all other selection rules have been applied. Takes effect in
        /// every branch (SHOW, WITH-restricted, and default). Cannot overlap
        /// with `SHOW` (validation rejects the conflict).
        hide: Vec<String>,
        with: Vec<WithItem>,
    },
    /// `REPORT <var>` / `REPORT (<v1>, <v2>, …)` — one column per variable.
    Vars(Vec<String>),
    /// `REPORT <var> AS <name> [STATISTICS(…)]` — a single variable's value
    /// under a renamed column, with optional summary statistics. The bareword
    /// source is what distinguishes this from the quoted-template `Computed`
    /// form.
    VarAs {
        var: String,
        name: String,
        stats: Vec<StatKind>,
        image: Option<ImageSpec>,
        truth: Option<String>,
        detail: bool,
    },
    /// `REPORT "<template>" AS <name> [STATISTICS(…)] [IMAGE(…)]` — a computed
    /// column.
    Computed {
        template: String,
        name: String,
        stats: Vec<StatKind>,
        image: Option<ImageSpec>,
        truth: Option<String>,
        detail: bool,
    },
}

/// An `IMAGE[(HEIGHT n | WIDTH n | FIT, …)]` clause on a column.
///
/// This is a **render hint, never a value**: the cell's text stays exactly what
/// it was (a path, a URL, a base64 blob), and `IMAGE` only tells a writer that
/// can show pictures to draw that value as one. That is what keeps CSV and JSON
/// exports lossless, keeps baseline comparison textual, and lets a format with
/// no picture support degrade to the text automatically rather than needing a
/// fallback rule of its own.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ImageSpec {
    /// Target height in pixels. With no `width`, the picture scales
    /// proportionally to this height.
    pub height: Option<u32>,
    /// Target width in pixels. With no `height`, the picture scales
    /// proportionally to this width.
    pub width: Option<u32>,
    /// `FIT`: size the picture to the cell rather than to a fixed box.
    pub fit: bool,
}

/// The height, in pixels, an `IMAGE` column's pictures are drawn at when the
/// clause names no size. Chosen to match the row height the reports this
/// feature was built for use, so a bare `IMAGE` produces a usable report.
pub const DEFAULT_IMAGE_HEIGHT: u32 = 110;

impl ImageSpec {
    /// The `(width, height)` box to scale a picture of `(w, h)` natural pixels
    /// into, preserving aspect ratio unless both dimensions were given.
    /// `None` for a `FIT` spec, whose sizing is the writer's business.
    pub fn scaled_size(&self, natural: (u32, u32)) -> Option<(f64, f64)> {
        if self.fit {
            return None;
        }
        let (nw, nh) = (natural.0.max(1) as f64, natural.1.max(1) as f64);
        Some(match (self.width, self.height) {
            (Some(w), Some(h)) => (w as f64, h as f64),
            (Some(w), None) => (w as f64, w as f64 * nh / nw),
            (None, Some(h)) => (h as f64 * nw / nh, h as f64),
            (None, None) => {
                let h = DEFAULT_IMAGE_HEIGHT as f64;
                (h * nw / nh, h)
            }
        })
    }
}

/// An item inside a `REPORT REQUEST … WITH … END` block.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WithItem {
    ResponseFmt(ResponseFmt),
    /// `name: <hurl query> [STATISTICS(…)]` — an ad-hoc report field. The query
    /// is the same syntax as `[Reports]`, and may also be an intrinsic name
    /// (`HttpStatus`/`Time`/`Asserts`/`Error`/`Response`) to alias an intrinsic
    /// under a friendlier column name. An optional trailing `STATISTICS(…)`
    /// clause attaches summary statistics to the field's column.
    Field {
        name: String,
        query: String,
        stats: Vec<StatKind>,
        image: Option<ImageSpec>,
        truth: Option<String>,
        detail: bool,
    },
    /// A whole-line `#` comment written inside the block, kept so that
    /// commenting a field out doesn't destroy it the next time an editor
    /// re-serializes the flow. The text is stored exactly as written after the
    /// `#`, like [`FlowNode::Comment`].
    Comment(String),
}

/// How a reported response body is rendered.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResponseFmt {
    Raw,
    Pretty,
}

/// Anything a `FOR` can iterate (the `ENVS` special form aside).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Producer {
    /// `[ … ]` literal list of scalars/tuples.
    List(Vec<Element>),
    /// `FILES "dir" [MATCH "glob"]`.
    Files { dir: String, glob: Option<String> },
    /// `FOLDERS "dir" [MATCH "glob"] [WITH role="glob"[?], …]`.
    ///
    /// `glob` filters subfolder *names* the way `FILES … MATCH` filters file
    /// names, and likewise recurses when it contains `**`.
    Folders {
        dir: String,
        glob: Option<String>,
        roles: Vec<RoleBinding>,
    },
    /// `TUPLES FROM "file"`.
    Tuples { path: String },
    /// `ZIP(a, b, …)`.
    Zip(Vec<Producer>),
    /// `CONCAT(a, b, …)` — the items of each input appended end-to-end into one
    /// longer stream (all inputs must share the same arity).
    Concat(Vec<Producer>),
    /// A previously declared `LIST` referenced by name.
    Named(String),
}

/// One `FOLDERS … WITH role="glob"` binding: the role name, the glob that picks
/// its file inside each folder, and whether the role is **optional**.
///
/// A required role must match exactly one file. An optional role (written with a
/// trailing `?`) may match none — it then binds the empty string, so a group
/// missing a genuinely optional input (a document with no back side, a folder
/// with no expected-result file) still produces a row instead of failing the
/// run. Matching *more* than one file is an error either way: ambiguity is never
/// silently resolved.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RoleBinding {
    pub name: String,
    pub glob: String,
    pub optional: bool,
}

#[cfg(test)]
impl RoleBinding {
    /// A required role (the default form) -- a test convenience, since the
    /// parser and the editors always build the struct literally.
    pub fn required(name: impl Into<String>, glob: impl Into<String>) -> Self {
        RoleBinding {
            name: name.into(),
            glob: glob.into(),
            optional: false,
        }
    }
}

/// One element of a list literal: a scalar or a tuple.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Element {
    Scalar(String),
    Tuple(Vec<String>),
}

/// A destructuring pattern on the left of `FOR … IN`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pattern {
    pub binders: Vec<Binder>,
    /// `true` when the pattern ends with `...` (absorb trailing positions).
    pub rest: bool,
}

/// One position in a [`Pattern`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Binder {
    Named(String),
    /// `_` — discard this position.
    Discard,
}

impl Pattern {
    /// A single-binder pattern (`FOR X IN …`).
    pub fn single(name: impl Into<String>) -> Self {
        Pattern {
            binders: vec![Binder::Named(name.into())],
            rest: false,
        }
    }
    /// Whether this is exactly one binder (arity-1 producer form).
    pub fn is_single(&self) -> bool {
        self.binders.len() == 1 && !self.rest
    }
    /// The named binders (skipping `_`), in order — the variables this pattern
    /// introduces into scope.
    pub fn named(&self) -> impl Iterator<Item = &str> {
        self.binders.iter().filter_map(|b| match b {
            Binder::Named(n) => Some(n.as_str()),
            Binder::Discard => None,
        })
    }
}

/// One environment role argument: either a named environment run live each
/// time, or a previously-exported snapshot loaded once and reused in place of a
/// live run. `FILE(…)` only appears in argument position inside a role clause
/// (`BASELINE(…)`/`COMPARISON(…)`), where a bare string would otherwise mean an
/// environment *name* — so it disambiguates "load this saved snapshot" from
/// "run this named environment". Every other path in the grammar (`FILES`,
/// `FOLDERS`, `TUPLES FROM`, header directives) is already unambiguously a path
/// by keyword/position and stays a bare string.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RoleRef {
    /// A named environment, run live for this role.
    Env(String),
    /// A saved baseline snapshot file (resolved like producer paths, relative to
    /// `# root:`/the report dir). Its rows stand in for a live run of this role,
    /// so no environment is executed for it.
    File(String),
}

impl RoleRef {
    /// The comparison *target* identity this ref contributes: a named env is
    /// keyed by its name, a snapshot by its (relative) path. Used to align the
    /// injected/produced rows against the role sets in [`super::compare`].
    pub fn target(&self) -> &str {
        match self {
            RoleRef::Env(n) => n,
            RoleRef::File(p) => p,
        }
    }
}

/// One field of a `SHOW(…)` clause: the field suffix, plus the optional
/// `STATISTICS(…)` to summarise the column it produces.
///
/// The statistics live on the field rather than in the `# columns:` header
/// because that header is an *exhaustive* whitelist — asking for a mean there
/// means restating every other column you still wanted. A clause written where
/// the column is declared also survives the column set changing around it.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ShowField {
    pub field: String,
    pub stats: Vec<StatKind>,
}

impl ShowField {
    /// The field name, for the selection logic (which cares only about which
    /// suffixes were named).
    pub fn name(&self) -> &str {
        &self.field
    }

    /// The clause as written, e.g. `Time STATISTICS(MEAN)`.
    pub fn to_text(&self) -> String {
        format!("{}{}", self.field, stats_text(&self.stats))
    }
}

impl From<&str> for ShowField {
    fn from(field: &str) -> Self {
        ShowField {
            field: field.to_string(),
            stats: Vec::new(),
        }
    }
}

impl From<String> for ShowField {
    fn from(field: String) -> Self {
        ShowField {
            field,
            stats: Vec::new(),
        }
    }
}

impl PartialEq<str> for ShowField {
    fn eq(&self, other: &str) -> bool {
        self.field == other
    }
}

/// A field with no statistics is just its name, so a caller (and a test) can
/// compare against a plain string list without unpacking the struct.
impl PartialEq<String> for ShowField {
    fn eq(&self, other: &String) -> bool {
        self.stats.is_empty() && &self.field == other
    }
}

/// Render a `SHOW(…)` field list back to source.
pub(crate) fn show_text(fields: &[ShowField]) -> String {
    fields
        .iter()
        .map(ShowField::to_text)
        .collect::<Vec<_>>()
        .join(", ")
}

/// The environment clause of `FOR … IN ENVS …`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EnvClause {
    /// `"a", "b"` — iterate the named environments, no comparison.
    Plain(Vec<String>),
    /// `BASELINE("prod") SHOW(Time), COMPARISON("staging", …)`.
    ///
    /// Each role argument is a [`RoleRef`]: a live environment name or a
    /// `FILE("…")` snapshot to reuse in place of running it.
    ///
    /// `baseline_show` names the baseline fields to copy into each candidate row
    /// under `baseline.<alias>.<field>` (only for aliases the candidate already
    /// emits that field).  Empty when no `SHOW(…)` clause is present.
    Roles {
        baseline: Vec<RoleRef>,
        comparisons: Vec<RoleRef>,
        baseline_show: Vec<ShowField>,
    },
}

// ---------------------------------------------------------------------------
// Serialization
// ---------------------------------------------------------------------------

const INDENT: &str = "    ";

impl ReportFlow {
    /// The parameters this report declares, in the order they are written —
    /// which is the order the run settings present them in.
    ///
    /// Only top-level nodes are looked at: a `PARAM` inside a loop is a
    /// validation error, and reading a nested one here would let it reach the
    /// run settings anyway.
    pub fn params(&self) -> Vec<&ParamDecl> {
        self.nodes
            .iter()
            .filter_map(|n| match n {
                FlowNode::Param(p) => Some(p),
                _ => None,
            })
            .collect()
    }

    /// Serialize to canonical PaperTrail text (round-trips with `parse_flow`).
    pub fn to_text(&self) -> String {
        let mut out = String::new();
        for line in &self.header.lines {
            match line {
                HeaderLine::Directive { key, value } => {
                    let _ = writeln!(out, "# {key}: {value}");
                }
                // Verbatim: the text already holds whatever spacing followed
                // the `#` (see the parser), so it must not be re-padded here.
                HeaderLine::Comment(c) => {
                    let _ = writeln!(out, "#{c}");
                }
            }
        }
        // Blank line between a non-empty header and the body.
        if !self.header.lines.is_empty() && !self.nodes.is_empty() {
            out.push('\n');
        }
        for node in &self.nodes {
            write_node(&mut out, node, 0);
        }
        out
    }

    /// Collect the per-column summary statistics requested by
    /// `REPORT … AS <header> STATISTICS(…)` statements anywhere in the flow
    /// (including inside loops), keyed by output-column header. Later statements
    /// for the same header win. Used to attach statistics to the resolved
    /// columns at render time.
    pub fn column_stats(&self) -> std::collections::HashMap<String, Vec<StatKind>> {
        let mut out = std::collections::HashMap::new();
        collect_column_stats(&self.nodes, &mut out);
        out
    }

    /// Collect the per-column `IMAGE[(…)]` render hints requested anywhere in
    /// the flow, keyed by output-column header, exactly as
    /// [`column_stats`](Self::column_stats) does for statistics — the two
    /// clauses attach at the same three places and are resolved the same way.
    pub fn column_images(&self) -> std::collections::HashMap<String, ImageSpec> {
        let mut out = std::collections::HashMap::new();
        collect_column_images(&self.nodes, &mut out);
        out
    }

    /// Collect the per-column `TRUTH "<template>"` clauses declared anywhere in
    /// the flow, keyed by output-column header, exactly as
    /// [`column_images`](Self::column_images) does — the three clauses attach at
    /// the same three places and are resolved the same way.
    ///
    /// The value is the **unevaluated template**. It is interpolated per row,
    /// after the run, against that row's variable snapshot: a ground truth is by
    /// definition something known before the request was sent, so it is read
    /// from the loop that chose the input (a labels manifest, a folder name),
    /// never from the response it is judging.
    pub fn column_truths(&self) -> std::collections::HashMap<String, String> {
        let mut out = std::collections::HashMap::new();
        collect_column_truths(&self.nodes, &mut out);
        out
    }

    /// The columns flagged `DETAIL` — shown in a row's drill-down rather than
    /// in the table itself.
    ///
    /// Like `IMAGE`, this is *placement*, not content: a `DETAIL` column is
    /// still a full column of the model, so it is exported to CSV and JSON,
    /// compared, and stored in a baseline snapshot. Only the renderers that
    /// have somewhere else to put it treat it differently, which is what lets
    /// every other format ignore the flag without losing data.
    pub fn column_details(&self) -> std::collections::HashSet<String> {
        let mut out = std::collections::HashSet::new();
        collect_column_details(&self.nodes, &mut out);
        out
    }
}

fn collect_column_images(
    nodes: &[FlowNode],
    out: &mut std::collections::HashMap<String, ImageSpec>,
) {
    for node in nodes {
        match node {
            FlowNode::Report(ReportStmt::VarAs { name, image, .. })
            | FlowNode::Report(ReportStmt::Computed { name, image, .. }) => {
                if let Some(img) = image {
                    out.insert(name.clone(), *img);
                }
            }
            FlowNode::Report(ReportStmt::Request {
                name, alias, with, ..
            }) => {
                let a = alias
                    .clone()
                    .unwrap_or_else(|| name.rsplit('/').next().unwrap_or(name).to_string());
                for item in with {
                    if let WithItem::Field {
                        name: fname,
                        image: Some(img),
                        ..
                    } = item
                    {
                        out.insert(format!("{a}.{fname}"), *img);
                    }
                }
            }
            FlowNode::ForEach { body, .. } | FlowNode::ForEnvs { body, .. } => {
                collect_column_images(body, out);
            }
            _ => {}
        }
    }
}

fn collect_column_details(nodes: &[FlowNode], out: &mut std::collections::HashSet<String>) {
    for node in nodes {
        match node {
            FlowNode::Report(ReportStmt::VarAs { name, detail, .. })
            | FlowNode::Report(ReportStmt::Computed { name, detail, .. }) => {
                if *detail {
                    out.insert(name.clone());
                }
            }
            FlowNode::Report(ReportStmt::Request {
                name, alias, with, ..
            }) => {
                let a = alias
                    .clone()
                    .unwrap_or_else(|| name.rsplit('/').next().unwrap_or(name).to_string());
                for item in with {
                    if let WithItem::Field {
                        name: fname,
                        detail: true,
                        ..
                    } = item
                    {
                        out.insert(format!("{a}.{fname}"));
                    }
                }
            }
            FlowNode::ForEach { body, .. } | FlowNode::ForEnvs { body, .. } => {
                collect_column_details(body, out);
            }
            _ => {}
        }
    }
}

fn collect_column_truths(nodes: &[FlowNode], out: &mut std::collections::HashMap<String, String>) {
    for node in nodes {
        match node {
            FlowNode::Report(ReportStmt::VarAs { name, truth, .. })
            | FlowNode::Report(ReportStmt::Computed { name, truth, .. }) => {
                if let Some(t) = truth {
                    out.insert(name.clone(), t.clone());
                }
            }
            FlowNode::Report(ReportStmt::Request {
                name, alias, with, ..
            }) => {
                let a = alias
                    .clone()
                    .unwrap_or_else(|| name.rsplit('/').next().unwrap_or(name).to_string());
                for item in with {
                    if let WithItem::Field {
                        name: fname,
                        truth: Some(t),
                        ..
                    } = item
                    {
                        out.insert(format!("{a}.{fname}"), t.clone());
                    }
                }
            }
            FlowNode::ForEach { body, .. } | FlowNode::ForEnvs { body, .. } => {
                collect_column_truths(body, out);
            }
            _ => {}
        }
    }
}

fn collect_column_stats(
    nodes: &[FlowNode],
    out: &mut std::collections::HashMap<String, Vec<StatKind>>,
) {
    for node in nodes {
        match node {
            FlowNode::Report(ReportStmt::VarAs { name, stats, .. })
            | FlowNode::Report(ReportStmt::Computed { name, stats, .. })
                if !stats.is_empty() =>
            {
                out.insert(name.clone(), stats.clone());
            }
            // `WITH` fields carry their own optional `STATISTICS(…)`; their
            // output column is `alias.field`, where `alias` defaults to the
            // request's leaf name. Compute that key statically so the stats
            // attach at render time just like a `REPORT … STATISTICS(…)`.
            FlowNode::Report(ReportStmt::Request {
                name,
                alias,
                with,
                show,
                ..
            }) => {
                let a = alias
                    .clone()
                    .unwrap_or_else(|| name.rsplit('/').next().unwrap_or(name).to_string());
                // A `SHOW(field STATISTICS(…))` names the same `alias.field`
                // column a `WITH` field would.
                for f in show {
                    if !f.stats.is_empty() {
                        out.insert(format!("{a}.{}", f.field), f.stats.clone());
                    }
                }
                for item in with {
                    if let WithItem::Field {
                        name: fname, stats, ..
                    } = item
                        && !stats.is_empty()
                    {
                        out.insert(format!("{a}.{fname}"), stats.clone());
                    }
                }
            }
            // `BASELINE(…) SHOW(field STATISTICS(…))` summarises the copied
            // baseline column, which the comparison names
            // `baseline.<alias>.<field>` — one per alias that emits the field,
            // and those aliases aren't known until the run produces them. The
            // key is therefore matched by suffix at render time (see
            // `ReportResult::resolved_columns`), recorded here under the bare
            // field with a `baseline.` marker prefix.
            FlowNode::ForEnvs { body, clause, .. } => {
                if let EnvClause::Roles { baseline_show, .. } = clause {
                    for f in baseline_show {
                        if !f.stats.is_empty() {
                            out.insert(format!("baseline.*.{}", f.field), f.stats.clone());
                        }
                    }
                }
                collect_column_stats(body, out);
            }
            FlowNode::ForEach { body, .. } => {
                collect_column_stats(body, out);
            }
            _ => {}
        }
    }
}

fn indent(out: &mut String, depth: usize) {
    for _ in 0..depth {
        out.push_str(INDENT);
    }
}

fn write_node(out: &mut String, node: &FlowNode, depth: usize) {
    indent(out, depth);
    match node {
        FlowNode::Assign { key, value } => {
            let _ = writeln!(out, "{key}={value}");
        }
        FlowNode::ListDecl { name, producer } => {
            let _ = writeln!(out, "LIST {name} = {}", producer_text(producer));
        }
        FlowNode::Param(p) => {
            let _ = writeln!(out, "{}", param_text(p));
        }
        FlowNode::Comment(text) => {
            let _ = writeln!(out, "#{text}");
        }
        FlowNode::Request { name } => {
            let _ = writeln!(out, "REQUEST {}", name_text(name));
        }
        FlowNode::Report(stmt) => write_report(out, stmt, depth),
        FlowNode::ForEach {
            pattern,
            producer,
            body,
            parallel,
        } => {
            let _ = writeln!(
                out,
                "{}FOR {} IN {}",
                parallel_prefix(parallel),
                pattern_text(pattern),
                producer_text(producer)
            );
            for n in body {
                write_node(out, n, depth + 1);
            }
            indent(out, depth);
            out.push_str("END\n");
        }
        FlowNode::ForEnvs {
            var,
            clause,
            body,
            parallel,
        } => {
            let _ = writeln!(
                out,
                "{}FOR {var} IN ENVS {}",
                parallel_prefix(parallel),
                env_clause_text(clause)
            );
            for n in body {
                write_node(out, n, depth + 1);
            }
            indent(out, depth);
            out.push_str("END\n");
        }
    }
}

/// The `PARALLEL[(n)] ` prefix a loop serializes with (empty when sequential).
fn parallel_prefix(p: &Option<ParallelSpec>) -> String {
    match p {
        None => String::new(),
        Some(ParallelSpec { degree: None }) => "PARALLEL ".to_string(),
        Some(ParallelSpec { degree: Some(n) }) => format!("PARALLEL({n}) "),
    }
}

fn write_report(out: &mut String, stmt: &ReportStmt, depth: usize) {
    match stmt {
        ReportStmt::Request {
            name,
            alias,
            response_fmt,
            show,
            hide,
            with,
        } => {
            let _ = write!(out, "REPORT REQUEST {}", name_text(name));
            if let Some(a) = alias {
                let _ = write!(out, " AS {}", name_text(a));
            }
            if let Some(fmt) = response_fmt {
                let _ = write!(out, " RESPONSE {}", fmt_text(*fmt));
            }
            if !show.is_empty() {
                let _ = write!(out, " SHOW({})", show_text(show));
            }
            if !hide.is_empty() {
                let _ = write!(out, " HIDE({})", hide.join(", "));
            }
            if with.is_empty() {
                out.push('\n');
            } else {
                out.push_str(" WITH\n");
                for item in with {
                    indent(out, depth + 1);
                    out.push_str(&with_item_text(item));
                    out.push('\n');
                }
                indent(out, depth);
                out.push_str("END\n");
            }
        }
        ReportStmt::Vars(vars) => {
            if vars.len() == 1 {
                let _ = writeln!(out, "REPORT {}", vars[0]);
            } else {
                let _ = writeln!(out, "REPORT ({})", vars.join(", "));
            }
        }
        ReportStmt::VarAs {
            var,
            name,
            stats,
            image,
            truth,
            detail,
        } => {
            let _ = writeln!(
                out,
                "REPORT {var} AS {}{}{}{}{}",
                name_text(name),
                stats_text(stats),
                image_text(image.as_ref()),
                truth_text(truth.as_deref()),
                detail_text(*detail)
            );
        }
        ReportStmt::Computed {
            template,
            name,
            stats,
            image,
            truth,
            detail,
        } => {
            let _ = writeln!(
                out,
                "REPORT {} AS {}{}{}{}{}",
                quote(template),
                name_text(name),
                stats_text(stats),
                image_text(image.as_ref()),
                truth_text(truth.as_deref()),
                detail_text(*detail)
            );
        }
    }
}

/// Render a `STATISTICS(…)` clause (with a leading space) for a report
/// statement, or the empty string when no statistics are requested.
/// One `WITH` item as it is written inside the block (no indentation, no
/// newline). Shared with the node editor so an outline row and the source line
/// it stands for can't drift apart.
pub(crate) fn with_item_text(item: &WithItem) -> String {
    match item {
        WithItem::ResponseFmt(fmt) => format!("RESPONSE {}", fmt_text(*fmt)),
        WithItem::Comment(text) => format!("#{text}"),
        WithItem::Field {
            name,
            query,
            stats,
            image,
            truth,
            detail,
        } => format!(
            "{}: {query}{}{}{}{}",
            name_text(name),
            stats_text(stats),
            image_text(image.as_ref()),
            truth_text(truth.as_deref()),
            detail_text(*detail)
        ),
    }
}

/// Render the `DETAIL` flag (with a leading space), or the empty string. A bare
/// keyword with no argument, because it says *where* a column goes and there is
/// only one other place for it to be.
pub(crate) fn detail_text(detail: bool) -> String {
    if detail {
        " DETAIL".to_string()
    } else {
        String::new()
    }
}

fn stats_text(stats: &[StatKind]) -> String {
    if stats.is_empty() {
        return String::new();
    }
    let list: Vec<&str> = stats.iter().map(|s| s.keyword()).collect();
    format!(" STATISTICS({})", list.join(", "))
}

/// Render an `IMAGE[(…)]` clause (with a leading space), or the empty string
/// when the column carries none. A spec with no options round-trips as the bare
/// keyword rather than `IMAGE()`, which is how it is written.
pub(crate) fn image_text(image: Option<&ImageSpec>) -> String {
    let Some(img) = image else {
        return String::new();
    };
    let mut opts: Vec<String> = Vec::new();
    if img.fit {
        opts.push("FIT".to_string());
    }
    if let Some(w) = img.width {
        opts.push(format!("WIDTH {w}"));
    }
    if let Some(h) = img.height {
        opts.push(format!("HEIGHT {h}"));
    }
    if opts.is_empty() {
        " IMAGE".to_string()
    } else {
        format!(" IMAGE({})", opts.join(", "))
    }
}

/// Render a `TRUTH "<template>"` clause (with a leading space), or the empty
/// string when the column declares no ground truth.
///
/// The template is re-quoted rather than written verbatim because it is a
/// string literal in the grammar: a truth of `{{ expected }}` and one of
/// `pass` are both perfectly ordinary values, and only the quotes tell them
/// apart from the keywords around them.
pub(crate) fn truth_text(truth: Option<&str>) -> String {
    match truth {
        Some(t) => format!(" TRUTH {}", quote(t)),
        None => String::new(),
    }
}

fn fmt_text(fmt: ResponseFmt) -> &'static str {
    match fmt {
        ResponseFmt::Raw => "RAW",
        ResponseFmt::Pretty => "PRETTY",
    }
}

fn pattern_text(p: &Pattern) -> String {
    if p.is_single() {
        return binder_text(&p.binders[0]);
    }
    let mut parts: Vec<String> = p.binders.iter().map(binder_text).collect();
    if p.rest {
        parts.push("...".to_string());
    }
    format!("({})", parts.join(", "))
}

fn binder_text(b: &Binder) -> String {
    match b {
        Binder::Named(n) => n.clone(),
        Binder::Discard => "_".to_string(),
    }
}

fn producer_text(p: &Producer) -> String {
    match p {
        Producer::List(elems) => {
            let items: Vec<String> = elems.iter().map(element_text).collect();
            format!("[{}]", items.join(", "))
        }
        Producer::Files { dir, glob } => match glob {
            Some(g) => format!("FILES {} MATCH {}", quote(dir), quote(g)),
            None => format!("FILES {}", quote(dir)),
        },
        Producer::Folders { dir, glob, roles } => {
            let mut out = format!("FOLDERS {}", quote(dir));
            if let Some(g) = glob {
                out.push_str(&format!(" MATCH {}", quote(g)));
            }
            if !roles.is_empty() {
                let rs: Vec<String> = roles
                    .iter()
                    .map(|r| {
                        let opt = if r.optional { "?" } else { "" };
                        format!("{}={}{opt}", r.name, quote(&r.glob))
                    })
                    .collect();
                out.push_str(&format!(" WITH {}", rs.join(", ")));
            }
            out
        }
        Producer::Tuples { path } => format!("TUPLES FROM {}", quote(path)),
        Producer::Zip(ps) => {
            let items: Vec<String> = ps.iter().map(producer_text).collect();
            format!("ZIP({})", items.join(", "))
        }
        Producer::Concat(ps) => {
            let items: Vec<String> = ps.iter().map(producer_text).collect();
            format!("CONCAT({})", items.join(", "))
        }
        Producer::Named(n) => n.clone(),
    }
}

fn element_text(e: &Element) -> String {
    match e {
        Element::Scalar(s) => quote(s),
        Element::Tuple(items) => {
            let parts: Vec<String> = items.iter().map(|s| quote(s)).collect();
            format!("({})", parts.join(", "))
        }
    }
}

fn env_clause_text(c: &EnvClause) -> String {
    match c {
        EnvClause::Plain(names) => names
            .iter()
            .map(|s| quote(s))
            .collect::<Vec<_>>()
            .join(", "),
        EnvClause::Roles {
            baseline,
            comparisons,
            baseline_show,
        } => {
            let mut parts = Vec::new();
            if !baseline.is_empty() {
                let names: Vec<String> = baseline.iter().map(role_ref_text).collect();
                let mut token = format!("BASELINE({})", names.join(", "));
                if !baseline_show.is_empty() {
                    token.push_str(&format!(" SHOW({})", show_text(baseline_show)));
                }
                parts.push(token);
            }
            if !comparisons.is_empty() {
                let names: Vec<String> = comparisons.iter().map(role_ref_text).collect();
                parts.push(format!("COMPARISON({})", names.join(", ")));
            }
            parts.join(", ")
        }
    }
}

/// Render a single role argument: a bare quoted env name, or `FILE("…")` for a
/// snapshot reference.
fn role_ref_text(r: &RoleRef) -> String {
    match r {
        RoleRef::Env(n) => quote(n),
        RoleRef::File(p) => format!("FILE({})", quote(p)),
    }
}

/// Render a request/column name: bare when it is a valid bareword, quoted when
/// it is empty or contains any character the parser's `word` production would
/// stop at (whitespace or one of `()[],="`), so it always re-parses as one
/// name.
fn name_text(name: &str) -> String {
    if name.is_empty()
        || name
            .chars()
            .any(|c| c.is_whitespace() || "()[],=\"".contains(c))
    {
        quote(name)
    } else {
        name.to_string()
    }
}

// ---------------------------------------------------------------------------
// Single-node views (for the structured node editor)
// ---------------------------------------------------------------------------

impl FlowNode {
    /// A concise, human-readable one-line label for this node — what the
    /// structured ("node") editor shows for it in the outline. For a loop this
    /// is only the `FOR … IN …` opener (its body and `END` are separate rows);
    /// a `REPORT REQUEST … WITH …` is summarised with a trailing `WITH …`.
    pub fn label(&self) -> String {
        match self {
            FlowNode::Assign { key, value } => format!("{key} = {value}"),
            FlowNode::ListDecl { name, producer } => {
                format!("LIST {name} = {}", producer_text(producer))
            }
            FlowNode::Param(p) => param_text(p),
            FlowNode::Comment(text) => format!("#{text}"),
            FlowNode::Request { name } => format!("REQUEST {name}"),
            FlowNode::Report(stmt) => report_label(stmt),
            FlowNode::ForEach {
                pattern,
                producer,
                parallel,
                ..
            } => format!(
                "{}FOR {} IN {}",
                parallel_prefix(parallel),
                pattern_text(pattern),
                producer_text(producer)
            ),
            FlowNode::ForEnvs {
                var,
                clause,
                parallel,
                ..
            } => format!(
                "{}FOR {var} IN ENVS {}",
                parallel_prefix(parallel),
                env_clause_text(clause)
            ),
        }
    }

    /// The re-parseable single-line source form of this node's *header* — the
    /// node itself for leaf statements, or the `FOR … IN …` opener for a loop
    /// (its body and `END` excluded). Used by the node editor's "edit as line"
    /// prompt: the returned text, followed by `END` for a loop, round-trips
    /// through [`super::parser::parse_flow`]. A `REPORT REQUEST … WITH …` block
    /// is *not* representable on one line, so its `WITH` items are dropped here
    /// (request nodes are edited via the request picker, not this line form).
    pub fn header_line(&self) -> String {
        match self {
            FlowNode::Report(ReportStmt::Request {
                name,
                alias,
                response_fmt,
                show,
                hide,
                ..
            }) => {
                let mut out = format!("REPORT REQUEST {}", name_text(name));
                if let Some(a) = alias {
                    let _ = write!(out, " AS {}", name_text(a));
                }
                if let Some(fmt) = response_fmt {
                    let _ = write!(out, " RESPONSE {}", fmt_text(*fmt));
                }
                if !show.is_empty() {
                    let _ = write!(out, " SHOW({})", show_text(show));
                }
                if !hide.is_empty() {
                    let _ = write!(out, " HIDE({})", hide.join(", "));
                }
                out
            }
            _ => self.label(),
        }
    }

    /// The request title this node references, if it is a `REQUEST` or
    /// `REPORT REQUEST` node — used by the node editor to colour the row by
    /// whether the name resolves in the bound collection.
    pub fn request_name(&self) -> Option<&str> {
        match self {
            FlowNode::Request { name } => Some(name),
            FlowNode::Report(ReportStmt::Request { name, .. }) => Some(name),
            _ => None,
        }
    }

    /// Whether this node opens a loop block (`FOR …`), i.e. it carries a body
    /// and closes with an `END`. The node editor renders these with a matching
    /// `END` row and nests their body one level deeper.
    pub fn is_loop(&self) -> bool {
        matches!(self, FlowNode::ForEach { .. } | FlowNode::ForEnvs { .. })
    }

    /// The loop body of a `FOR …` node (mutable), or `None` for a leaf node.
    pub fn body_mut(&mut self) -> Option<&mut Vec<FlowNode>> {
        match self {
            FlowNode::ForEach { body, .. } | FlowNode::ForEnvs { body, .. } => Some(body),
            _ => None,
        }
    }
}

/// The label for a [`ReportStmt`] (see [`FlowNode::label`]).
fn report_label(stmt: &ReportStmt) -> String {
    match stmt {
        ReportStmt::Request {
            name,
            alias,
            response_fmt,
            show,
            hide,
            with,
        } => {
            let mut out = format!("REPORT REQUEST {name}");
            if let Some(a) = alias {
                let _ = write!(out, " AS {a}");
            }
            if let Some(fmt) = response_fmt {
                let _ = write!(out, " RESPONSE {}", fmt_text(*fmt));
            }
            if !show.is_empty() {
                let _ = write!(out, " SHOW({})", show_text(show));
            }
            if !hide.is_empty() {
                let _ = write!(out, " HIDE({})", hide.join(", "));
            }
            if !with.is_empty() {
                out.push_str(" WITH …");
            }
            out
        }
        ReportStmt::Vars(vars) => {
            if vars.len() == 1 {
                format!("REPORT {}", vars[0])
            } else {
                format!("REPORT ({})", vars.join(", "))
            }
        }
        ReportStmt::VarAs {
            var,
            name,
            stats,
            image,
            truth,
            detail,
        } => {
            format!(
                "REPORT {var} AS {name}{}{}{}{}",
                stats_text(stats),
                image_text(image.as_ref()),
                truth_text(truth.as_deref()),
                detail_text(*detail)
            )
        }
        ReportStmt::Computed {
            template,
            name,
            stats,
            image,
            truth,
            detail,
        } => {
            format!(
                "REPORT {} AS {name}{}{}{}{}",
                quote(template),
                stats_text(stats),
                image_text(image.as_ref()),
                truth_text(truth.as_deref()),
                detail_text(*detail)
            )
        }
    }
}

/// Double-quote a string, escaping `\` and `"`.
/// One `PARAM` statement as canonical text.
///
/// The kind is always written out, even when it is the `TEXT` default that may
/// have been omitted in the source: the canonical form says what a parameter
/// is, so nobody has to know which type you get by saying nothing. Values are
/// always quoted so a default or label containing spaces survives.
fn param_text(p: &ParamDecl) -> String {
    let mut out = String::from("PARAM ");
    out.push_str(p.kind.keyword());
    if let ParamKind::Choice(options) = &p.kind {
        out.push('(');
        for (i, o) in options.iter().enumerate() {
            if i > 0 {
                out.push_str(", ");
            }
            out.push_str(&quote(o));
        }
        out.push(')');
    }
    out.push(' ');
    out.push_str(&p.name);
    if let Some(default) = &p.default {
        out.push_str(" = ");
        out.push_str(&quote(default));
    }
    if let Some(label) = &p.label {
        out.push_str(" LABEL ");
        out.push_str(&quote(label));
    }
    out
}

pub(crate) fn quote(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for c in s.chars() {
        match c {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            _ => out.push(c),
        }
    }
    out.push('"');
    out
}