paperboy 0.1.7

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
//! Static validation of a [`ReportFlow`] — run on open/edit and before a run.
//!
//! The parser already guarantees a structurally well-formed flow (balanced
//! `FOR`/`END`, valid syntax, reserved `JOIN`/`ON` rejected). This pass adds the
//! *semantic* checks that need the whole flow (and, when available, the bound
//! collection + loaded environments):
//!
//! - a `collection:` directive is present and (with context) every
//!   `REQUEST`/`REPORT REQUEST` name resolves to exactly one entry;
//! - destructuring arity matches the producer, where statically known;
//! - `LIST` names are unique and referenced only after declaration;
//! - `ENVS` role clauses obey the ≤1 `BASELINE` / ≥1 `COMPARISON` rule and
//!   (with context) name only loaded environments;
//! - `output:` is a supported format.
//!
//! Diagnostics never abort; the caller decides whether any `Error` blocks a run.

use std::collections::{HashMap, HashSet};

use super::flow::{EnvClause, FlowNode, Pattern, Producer, ReportFlow, ReportStmt};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    Error,
    Warning,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
    pub severity: Severity,
    pub message: String,
}

impl Diagnostic {
    fn error(msg: impl Into<String>) -> Self {
        Diagnostic {
            severity: Severity::Error,
            message: msg.into(),
        }
    }
    fn warning(msg: impl Into<String>) -> Self {
        Diagnostic {
            severity: Severity::Warning,
            message: msg.into(),
        }
    }
}

/// What's known about the environment a flow will run in. Both fields are
/// optional: `None` means "not bound yet", so name-resolution checks are
/// skipped (with a single reminder diagnostic) rather than producing noise.
#[derive(Default)]
pub struct Context<'a> {
    /// Full entry titles (incl. virtual-folder paths) of the bound collection.
    pub request_titles: Option<&'a [String]>,
    /// Names of environments currently loaded (for `ENVS` resolution).
    pub env_names: Option<&'a [String]>,
    /// Each bound-collection entry's full title paired with its `[Reports]`
    /// field names — used to validate a `SHOW(...)` selector's field list
    /// against the fields the request can actually produce. `None` when no
    /// collection is bound (the check is then skipped).
    pub request_fields: Option<&'a [(String, Vec<String>)]>,
    /// The directory relative paths resolve against (the report's folder or a
    /// `# root:` override). When present, a `# baseline:` snapshot that doesn't
    /// exist on disk is flagged so the user finds out before running rather
    /// than after. `None` skips the filesystem check (e.g. an unsaved report).
    pub root: Option<&'a std::path::Path>,
    /// Variable names that the report's effective base environment provides
    /// (global + pinned, or the `# environment:` override). `None` means the
    /// environment isn't known at validation time — the variable-availability
    /// check is skipped entirely to avoid false positives.
    pub base_var_names: Option<&'a [String]>,
    /// Union of every variable name defined across ALL loaded environments —
    /// used conservatively inside `FOR … IN ENVS` loop bodies, where any of
    /// the named environments may be active so any of their variables is
    /// potentially in scope. `None` skips the check inside ENVS bodies.
    pub all_env_var_names: Option<&'a [String]>,
    /// The bound collection's entries, used to scan each request's `{{VAR}}`
    /// references and to know which names its `[Captures]` block defines after
    /// it runs. `None` (unbound collection) skips the variable-availability
    /// check entirely.
    pub request_entries: Option<&'a [crate::hurl::HurlEntry]>,
}

/// Validate `flow` against `ctx`, returning all diagnostics (errors + warnings).
pub fn validate(flow: &ReportFlow, ctx: &Context) -> Vec<Diagnostic> {
    let mut diags = Vec::new();

    // Header: collection binding + output format.
    match flow.header.collection() {
        None => diags.push(Diagnostic::error(
            "missing '# collection:' header — the report isn't bound to a collection",
        )),
        Some(c) if c.trim().is_empty() => diags.push(Diagnostic::error("'# collection:' is empty")),
        Some(_) => {}
    }
    if let Some(out) = flow.header.output() {
        let out = out.trim();
        if !out.is_empty()
            && !super::writer::OUTPUT_EXTENSIONS
                .iter()
                .any(|e| out.eq_ignore_ascii_case(e))
        {
            diags.push(Diagnostic::error(format!(
                "unsupported output format '{out}' (supported: {})",
                super::writer::OUTPUT_EXTENSIONS.join(", ")
            )));
        }
    }
    // Two resolved columns that share the same header collide when the report is
    // written as JSON (row objects are keyed by header, so the later column
    // silently overwrites the earlier one) — a data loss the other formats don't
    // have. Reject a duplicate header up front so every format stays faithful;
    // the fix is to give each column a distinct `AS <name>`.
    if let Some(spec) = flow.header.columns() {
        let cols = super::model::parse_columns(spec);
        let mut seen: Vec<&str> = Vec::new();
        let mut reported: Vec<&str> = Vec::new();
        for header in cols.iter().map(|c| c.header.as_str()) {
            if seen.contains(&header) {
                if !reported.contains(&header) {
                    diags.push(Diagnostic::error(format!(
                        "duplicate column header '{header}' in '# columns:' — give each \
                         column a distinct name with AS"
                    )));
                    reported.push(header);
                }
            } else {
                seen.push(header);
            }
        }
    }
    // An optional `# environment:` names a single already-loaded environment to
    // use as the report's base variable layer (the plain, no-comparison run).
    // Like an `ENVS` loop, the environment must be loaded — flag it when it
    // isn't (only once the loaded set is known).
    if let Some(env) = flow.header.environment() {
        let env = env.trim();
        if env.is_empty() {
            diags.push(Diagnostic::error("'# environment:' is empty"));
        } else if let Some(loaded) = ctx.env_names
            && !loaded.iter().any(|e| e == env)
        {
            diags.push(Diagnostic::error(format!(
                "environment '{env}' is not loaded"
            )));
        }
    }

    // A `# baseline:` snapshot diff and a live `ENVS BASELINE/COMPARISON`
    // clause both fill the `Result` column; the live comparison takes
    // precedence (see `run::run_flow`), so flag the directive as ignored rather
    // than let it silently do nothing.
    if flow.header.baseline().is_some_and(|b| !b.trim().is_empty())
        && super::compare::comparison_roles(flow).is_some()
    {
        diags.push(Diagnostic::warning(
            "'# baseline:' is ignored because the flow already has an ENVS BASELINE/COMPARISON comparison",
        ));
    } else if let Some(rel) = flow
        .header
        .baseline()
        .map(str::trim)
        .filter(|b| !b.is_empty())
        && let Some(root) = ctx.root
    {
        // The snapshot will be diffed against at finalize time; a missing file
        // there is only a non-fatal run error, so warn up front (once the
        // report is anchored) that the referenced snapshot can't be found.
        let path = super::producers::resolve_path(Some(root), rel);
        if !path.exists() {
            diags.push(Diagnostic::warning(format!(
                "baseline snapshot '{rel}' was not found ({})",
                path.display()
            )));
        }
    }

    if ctx.request_titles.is_none() {
        diags.push(Diagnostic::warning(
            "collection not loaded — request names can't be validated until it's bound",
        ));
    }

    // Walk the tree with a scope stack of declared LIST producers.
    let mut scopes: Vec<HashMap<String, Producer>> = vec![HashMap::new()];
    walk(&flow.nodes, ctx, &mut scopes, &mut diags);

    // Variable-availability analysis: walk the flow in execution order and
    // warn when a request references a `{{VAR}}` that is provably not defined
    // at that point. Only runs when both the base-env variable names AND the
    // bound collection's entries are known; if either is absent we can't
    // distinguish "definitely undefined" from "defined by an unknown source"
    // and must stay silent to avoid false positives.
    if ctx.request_entries.is_some() && ctx.base_var_names.is_some() {
        let mut defined = initial_defined_vars(ctx);
        check_var_availability(&flow.nodes, ctx, &mut defined, &mut diags);
    }

    diags
}

fn walk(
    nodes: &[FlowNode],
    ctx: &Context,
    scopes: &mut Vec<HashMap<String, Producer>>,
    diags: &mut Vec<Diagnostic>,
) {
    for node in nodes {
        match node {
            FlowNode::Assign { .. } => {}
            FlowNode::ListDecl { name, producer } => {
                check_producer(producer, ctx, scopes, diags);
                if scopes.iter().any(|s| s.contains_key(name)) {
                    diags.push(Diagnostic::warning(format!(
                        "LIST '{name}' shadows an earlier declaration of the same name"
                    )));
                }
                scopes
                    .last_mut()
                    .unwrap()
                    .insert(name.clone(), producer.clone());
            }
            FlowNode::Request { name } => check_request_name(name, ctx, diags),
            FlowNode::Report(stmt) => check_report(stmt, ctx, diags),
            FlowNode::ForEach {
                pattern,
                producer,
                body,
                ..
            } => {
                check_producer(producer, ctx, scopes, diags);
                check_arity(pattern, producer, scopes, diags);
                scopes.push(HashMap::new());
                walk(body, ctx, scopes, diags);
                scopes.pop();
            }
            FlowNode::ForEnvs { clause, body, .. } => {
                check_env_clause(clause, ctx, diags);
                scopes.push(HashMap::new());
                walk(body, ctx, scopes, diags);
                scopes.pop();
            }
        }
    }
}

fn check_report(stmt: &ReportStmt, ctx: &Context, diags: &mut Vec<Diagnostic>) {
    if let ReportStmt::Request {
        name,
        show,
        hide,
        with,
        ..
    } = stmt
    {
        check_request_name(name, ctx, diags);
        check_show_hide_overlap(show, hide, diags);
        check_show_fields(name, show, with, ctx, diags);
        check_hide_fields(name, hide, with, ctx, diags);
    }
}

/// Warn when a `SHOW(...)` field can't be produced by the request: it is
/// neither an intrinsic (`HttpStatus`/`Time`/`Asserts`/`Error`/`Response`), a
/// `WITH` field on this statement, nor a `[Reports]` field of the resolved
/// request.  Under the additive model such a field is silently ignored at
/// runtime (it will not appear in the output), so this is a warning rather than
/// an error — consistent with how `check_hide_fields` handles unknown fields.
/// Skipped when the collection isn't bound (the field set is unknown), so it
/// never false-warns on a real `[Reports]` field we can't see.
fn check_show_fields(
    name: &str,
    show: &[String],
    with: &[super::flow::WithItem],
    ctx: &Context,
    diags: &mut Vec<Diagnostic>,
) {
    if show.is_empty() {
        return;
    }
    let Some(entries) = ctx.request_fields else {
        return;
    };
    // Resolve the request's `[Reports]` field names: exact full-title, then a
    // unique leaf match (mirroring `check_request_name`). An unresolved name is
    // already reported by `check_request_name`, so bail quietly here.
    let by_exact = entries.iter().find(|(t, _)| t == name);
    let resolved = by_exact.or_else(|| {
        let mut leaves = entries
            .iter()
            .filter(|(t, _)| t.rsplit('/').next() == Some(name));
        match (leaves.next(), leaves.next()) {
            (Some(hit), None) => Some(hit),
            _ => None,
        }
    });
    let Some((_, report_fields)) = resolved else {
        return;
    };
    let with_fields: Vec<&str> = with
        .iter()
        .filter_map(|w| match w {
            super::flow::WithItem::Field { name, .. } => Some(name.as_str()),
            _ => None,
        })
        .collect();
    for field in show {
        let known = super::run::INTRINSIC_FIELDS.contains(&field.as_str())
            || with_fields.contains(&field.as_str())
            || report_fields.iter().any(|f| f == field);
        if !known {
            diags.push(Diagnostic::warning(format!(
                "SHOW field '{field}' on request '{name}' isn't an intrinsic, a WITH field, or one of its [Reports] fields — it will be ignored"
            )));
        }
    }
}

/// Error when the same field suffix appears in both SHOW and HIDE — the two
/// clauses are contradictory (SHOW keeps, HIDE removes) and no ordering of
/// evaluation resolves the conflict sensibly.
fn check_show_hide_overlap(show: &[String], hide: &[String], diags: &mut Vec<Diagnostic>) {
    for field in show {
        if hide.iter().any(|h| h == field) {
            diags.push(Diagnostic::error(format!(
                "field '{field}' appears in both SHOW and HIDE — these clauses conflict"
            )));
        }
    }
}

/// Warn when a `HIDE(...)` field can't be produced by the request (mirrors
/// `check_show_fields`): it is neither an intrinsic, a WITH field, nor a
/// `[Reports]` field of the resolved request. Skipped when the collection isn't
/// bound (the field set is unknown).
fn check_hide_fields(
    name: &str,
    hide: &[String],
    with: &[super::flow::WithItem],
    ctx: &Context,
    diags: &mut Vec<Diagnostic>,
) {
    if hide.is_empty() {
        return;
    }
    let Some(entries) = ctx.request_fields else {
        return;
    };
    let by_exact = entries.iter().find(|(t, _)| t == name);
    let resolved = by_exact.or_else(|| {
        let mut leaves = entries
            .iter()
            .filter(|(t, _)| t.rsplit('/').next() == Some(name));
        match (leaves.next(), leaves.next()) {
            (Some(hit), None) => Some(hit),
            _ => None,
        }
    });
    let Some((_, report_fields)) = resolved else {
        return;
    };
    let with_fields: Vec<&str> = with
        .iter()
        .filter_map(|w| match w {
            super::flow::WithItem::Field { name, .. } => Some(name.as_str()),
            _ => None,
        })
        .collect();
    for field in hide {
        let known = super::run::INTRINSIC_FIELDS.contains(&field.as_str())
            || with_fields.contains(&field.as_str())
            || report_fields.iter().any(|f| f == field);
        if !known {
            diags.push(Diagnostic::warning(format!(
                "HIDE field '{field}' on request '{name}' isn't an intrinsic, a WITH field, or one of its [Reports] fields — that field isn't produced by this request"
            )));
        }
    }
}

/// Resolve a request name against the bound collection's titles: exact
/// full-title → unique leaf name → error. Skipped when no collection is bound.
fn check_request_name(name: &str, ctx: &Context, diags: &mut Vec<Diagnostic>) {
    let Some(titles) = ctx.request_titles else {
        return;
    };
    let exact = titles.iter().filter(|t| t.as_str() == name).count();
    if exact == 1 {
        return;
    }
    if exact > 1 {
        diags.push(Diagnostic::error(format!(
            "request '{name}' is ambiguous ({exact} entries share that title)"
        )));
        return;
    }
    // No exact full-title match: try a unique leaf (last '/'-segment) match.
    let leaves: Vec<&String> = titles
        .iter()
        .filter(|t| t.rsplit('/').next() == Some(name))
        .collect();
    match leaves.len() {
        1 => {}
        0 => diags.push(Diagnostic::error(format!(
            "request '{name}' not found in the bound collection"
        ))),
        n => diags.push(Diagnostic::error(format!(
            "request '{name}' is ambiguous ({n} entries end with that name — qualify it with its folder path)"
        ))),
    }
}

fn check_env_clause(clause: &EnvClause, ctx: &Context, diags: &mut Vec<Diagnostic>) {
    let names: Vec<&String> = match clause {
        EnvClause::Plain(names) => {
            if names.is_empty() {
                diags.push(Diagnostic::error("ENVS loop has no environments"));
            }
            names.iter().collect()
        }
        EnvClause::Roles {
            baseline,
            comparisons,
            ..
        } => {
            if baseline.len() > 1 {
                diags.push(Diagnostic::error(
                    "at most one BASELINE environment is allowed",
                ));
            }
            if comparisons.is_empty() {
                diags.push(Diagnostic::error(
                    "a role clause needs at least one COMPARISON environment",
                ));
            }
            baseline.iter().chain(comparisons.iter()).collect()
        }
    };
    if let Some(loaded) = ctx.env_names {
        for n in names {
            if !loaded.iter().any(|e| e == n) {
                diags.push(Diagnostic::error(format!(
                    "environment '{n}' is not loaded"
                )));
            }
        }
    }
}

/// The static element arity of a producer, if knowable without touching the
/// filesystem. `None` = runtime-determined (e.g. `TUPLES FROM` a CSV).
fn producer_arity(p: &Producer, scopes: &[HashMap<String, Producer>]) -> Option<usize> {
    match p {
        // A folder path (roles are accessed by name, not destructured).
        Producer::Files { .. } | Producer::Folders { .. } => Some(1),
        Producer::Zip(ps) => Some(ps.len()),
        Producer::Concat(ps) => {
            // CONCAT preserves arity: it appends items, it doesn't widen them.
            // The whole is knowable only when every input's arity is known and
            // they all agree (a disagreement is reported by check_producer).
            let arities: Vec<usize> = ps
                .iter()
                .filter_map(|p| producer_arity(p, scopes))
                .collect();
            if arities.len() != ps.len() {
                return None;
            }
            match arities.first() {
                Some(&first) if arities.iter().all(|&a| a == first) => Some(first),
                _ => None,
            }
        }
        Producer::Tuples { .. } => None,
        Producer::List(elems) => {
            let arities: Vec<usize> = elems
                .iter()
                .map(|e| match e {
                    super::flow::Element::Scalar(_) => 1,
                    super::flow::Element::Tuple(items) => items.len(),
                })
                .collect();
            match arities.first() {
                None => Some(1),
                Some(&first) if arities.iter().all(|&a| a == first) => Some(first),
                // Inconsistent — reported by check_arity via the mismatch below.
                _ => None,
            }
        }
        Producer::Named(name) => scopes
            .iter()
            .rev()
            .find_map(|s| s.get(name))
            .and_then(|inner| producer_arity(inner, scopes)),
    }
}

fn check_arity(
    pattern: &Pattern,
    producer: &Producer,
    scopes: &[HashMap<String, Producer>],
    diags: &mut Vec<Diagnostic>,
) {
    let Some(arity) = producer_arity(producer, scopes) else {
        return; // Runtime-determined (or inconsistent — flagged by check_producer).
    };
    let binders = pattern.binders.len();
    if pattern.rest {
        if binders > arity {
            diags.push(Diagnostic::error(format!(
                "pattern binds {binders} names before '...' but the producer yields only {arity}"
            )));
        }
    } else if binders != arity {
        diags.push(Diagnostic::error(format!(
            "pattern binds {binders} name(s) but the producer yields {arity} per item \
             (use '_' to discard or '...' to absorb extras)"
        )));
    }
}

fn check_producer(
    producer: &Producer,
    _ctx: &Context,
    scopes: &[HashMap<String, Producer>],
    diags: &mut Vec<Diagnostic>,
) {
    if let Producer::Named(name) = producer
        && !scopes.iter().rev().any(|s| s.contains_key(name))
    {
        diags.push(Diagnostic::error(format!(
            "unknown list '{name}' (declare it with 'LIST {name} = …' before use)"
        )));
    }
    // Inconsistent list-literal arity (a mix of scalars/tuples of different
    // sizes) is caught wherever the literal appears — a `LIST` declaration or an
    // inline `FOR … IN [ … ]` — so it surfaces at its definition site.
    if let Producer::List(elems) = producer {
        let arities: Vec<usize> = elems
            .iter()
            .map(|e| match e {
                super::flow::Element::Scalar(_) => 1,
                super::flow::Element::Tuple(items) => items.len(),
            })
            .collect();
        if let Some(&first) = arities.first()
            && !arities.iter().all(|&a| a == first)
        {
            diags.push(Diagnostic::error(
                "list elements have inconsistent arity (mix of scalars/tuples of different sizes)",
            ));
        }
    }
    if let Producer::Zip(ps) = producer {
        for p in ps {
            check_producer(p, _ctx, scopes, diags);
        }
    }
    if let Producer::Concat(ps) = producer {
        for p in ps {
            check_producer(p, _ctx, scopes, diags);
        }
        // All inputs must yield items of the same arity, else the loop pattern
        // can't destructure them uniformly. Only flag when statically knowable.
        let arities: Vec<usize> = ps
            .iter()
            .filter_map(|p| producer_arity(p, scopes))
            .collect();
        if let Some(&first) = arities.first()
            && arities.len() == ps.len()
            && !arities.iter().all(|&a| a == first)
        {
            diags.push(Diagnostic::error(
                "CONCAT inputs have inconsistent arity (every input must yield the \
                 same number of values per item)",
            ));
        }
    }
}

// ---------------------------------------------------------------------------
// Variable-availability analysis
// ---------------------------------------------------------------------------

/// Build the initial set of variable names available before the first
/// statement executes: the base environment's keys plus the engine's
/// built-in `PRELUDE_*` names (which always have defaults, so a request
/// that references one is never provably undefined).
fn initial_defined_vars(ctx: &Context) -> HashSet<String> {
    let mut defined = HashSet::new();
    if let Some(names) = ctx.base_var_names {
        defined.extend(names.iter().cloned());
    }
    // Engine defaults — any flow can reference these without an explicit
    // assignment and they will always resolve.
    for name in [
        "PRELUDE_NO_MATCH_MARKER",
        "PRELUDE_RESPONSE_FORMAT",
        "PRELUDE_MAX_PARALLEL",
    ] {
        defined.insert(name.to_string());
    }
    defined
}

/// Resolve a request name against the bound entries — same leaf/exact logic
/// as [`check_request_name`] — returning the first matching entry, or `None`
/// for an ambiguous/missing name (those cases are already reported by the
/// structural walk; here we silently skip to avoid double-reporting).
fn resolve_entry_by_name<'a>(
    entries: &'a [crate::hurl::HurlEntry],
    name: &str,
) -> Option<&'a crate::hurl::HurlEntry> {
    let exact: Vec<_> = entries.iter().filter(|e| e.title == name).collect();
    if exact.len() == 1 {
        return Some(exact[0]);
    }
    if exact.len() > 1 {
        return None; // ambiguous
    }
    let leaves: Vec<_> = entries
        .iter()
        .filter(|e| e.title.rsplit('/').next() == Some(name))
        .collect();
    if leaves.len() == 1 {
        Some(leaves[0])
    } else {
        None
    }
}

/// The named fields a producer binds by name (not position) — specifically
/// the role names in a `FOLDERS … WITH role="glob", …` producer. These bind
/// directly into the loop scope like `FOR (A, B) IN …` would bind `A` and `B`,
/// so they must be treated as defined inside the loop body.
fn producer_static_named_fields(producer: &Producer) -> Vec<String> {
    match producer {
        Producer::Folders { roles, .. } => roles.iter().map(|(r, _)| r.clone()).collect(),
        // ZIP/CONCAT: union the named fields from all sub-producers.
        Producer::Zip(ps) | Producer::Concat(ps) => {
            ps.iter().flat_map(producer_static_named_fields).collect()
        }
        _ => Vec::new(),
    }
}

/// Emit a warning for each `{{VAR}}` that `name`'s request references but
/// that isn't in `defined` at the call site. Silently skips unresolvable
/// request names (already reported by the structural walk).
fn warn_if_vars_undefined(
    name: &str,
    ctx: &Context,
    defined: &HashSet<String>,
    diags: &mut Vec<Diagnostic>,
) {
    let Some(entries) = ctx.request_entries else {
        return;
    };
    let Some(entry) = resolve_entry_by_name(entries, name) else {
        return; // unresolvable — structural check already warned
    };
    let refs = crate::request::entry_referenced_keys(entry);
    for var in &refs {
        if !defined.contains(var.as_str()) {
            diags.push(Diagnostic::warning(format!(
                "request '{name}' references {{{{{}}}}} which may not be defined at this point \
                 in the flow — add it to the environment or assign it before this request",
                var
            )));
        }
    }
}

/// Thread the capture names of a successfully-resolved request into `defined`
/// so that subsequent requests in the same block can use them.
fn add_entry_captures(name: &str, ctx: &Context, defined: &mut HashSet<String>) {
    let Some(entries) = ctx.request_entries else {
        return;
    };
    let Some(entry) = resolve_entry_by_name(entries, name) else {
        return;
    };
    for (cap_name, _) in &entry.captures {
        defined.insert(cap_name.clone());
    }
}

/// Walk `nodes` in execution order, maintaining `defined` (the set of
/// variable names provably in scope), and emit a warning for every `{{VAR}}`
/// in a request that isn't covered by any in-scope source.
///
/// Conservative design: when a scope source can't be statically enumerated
/// (e.g. `TUPLES FROM` column names, or a `FOR … IN ENVS` body when the
/// loaded env variable names aren't known), we skip that scope entirely and
/// produce no warnings — under-warning is far better than a false positive.
fn check_var_availability(
    nodes: &[FlowNode],
    ctx: &Context,
    defined: &mut HashSet<String>,
    diags: &mut Vec<Diagnostic>,
) {
    for node in nodes {
        match node {
            // An assignment defines the key for all subsequent nodes.
            FlowNode::Assign { key, .. } => {
                defined.insert(key.clone());
            }
            FlowNode::ListDecl { .. } => {}
            // A bare REQUEST (no report output) — check its vars, then thread
            // its captures forward.
            FlowNode::Request { name } => {
                warn_if_vars_undefined(name, ctx, defined, diags);
                add_entry_captures(name, ctx, defined);
            }
            // A REPORT statement — only the REQUEST form sends HTTP.
            FlowNode::Report(stmt) => {
                if let ReportStmt::Request { name, .. } = stmt {
                    warn_if_vars_undefined(name, ctx, defined, diags);
                    add_entry_captures(name, ctx, defined);
                }
            }
            // A FOR loop over a producer: pattern binders and any named fields
            // (FOLDERS roles, TUPLES headers when statically unknown are left
            // out — they're runtime-determined, so we err on the side of not
            // warning). The loop body runs with a snapshot of `defined` plus
            // those new names; changes inside the body don't leak outward.
            FlowNode::ForEach {
                pattern,
                producer,
                body,
                ..
            } => {
                let mut inner = defined.clone();
                for binder_name in pattern.named() {
                    inner.insert(binder_name.to_string());
                }
                // FOLDERS roles are known statically and bind by name.
                for fname in producer_static_named_fields(producer) {
                    inner.insert(fname);
                }
                // TUPLES FROM / ZIP / CONCAT may also yield named fields at
                // runtime (CSV headers, etc.) — we can't enumerate them here,
                // so we don't add them. This means we may miss some true
                // negatives inside TUPLES loops, but we'll never false-positive.
                check_var_availability(body, ctx, &mut inner, diags);
            }
            // A FOR … IN ENVS loop: the loop variable is in scope, and each
            // iteration's environment also makes its variables available.
            // We add the union of ALL loaded env vars so we don't false-warn
            // inside the body regardless of which env is active. If the loaded
            // env variable names are unknown (`all_env_var_names` is None) we
            // skip the body entirely to stay conservative.
            FlowNode::ForEnvs { var, body, .. } => {
                let mut inner = defined.clone();
                inner.insert(var.clone());
                if let Some(env_vars) = ctx.all_env_var_names {
                    inner.extend(env_vars.iter().cloned());
                    check_var_availability(body, ctx, &mut inner, diags);
                }
                // If all_env_var_names is None, skip the body — we can't know
                // what the environment will provide, so no warnings here.
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::report::parser::parse_flow;

    /// Validate a flow parsed from source under an optional collection/env
    /// context. Returns all diagnostics.
    fn diags_for(src: &str, titles: Option<&[String]>, envs: Option<&[String]>) -> Vec<Diagnostic> {
        let flow = parse_flow(src).expect("test source should parse");
        let ctx = Context {
            request_titles: titles,
            env_names: envs,
            ..Default::default()
        };
        validate(&flow, &ctx)
    }

    fn errors(src: &str, titles: Option<&[String]>, envs: Option<&[String]>) -> Vec<String> {
        diags_for(src, titles, envs)
            .into_iter()
            .filter(|d| d.severity == Severity::Error)
            .map(|d| d.message)
            .collect()
    }

    fn has_err(
        src: &str,
        titles: Option<&[String]>,
        envs: Option<&[String]>,
        needle: &str,
    ) -> bool {
        errors(src, titles, envs)
            .iter()
            .any(|m| m.to_lowercase().contains(&needle.to_lowercase()))
    }

    fn titles() -> Vec<String> {
        vec![
            "Oauth".into(),
            "CreateSession".into(),
            "upload/process_file".into(),
            "finalise_session".into(),
        ]
    }

    /// Warnings from validating `src` with a bound collection whose entries
    /// expose the given `[Reports]` field names (title → fields).
    fn warnings_with_fields(src: &str, fields: &[(&str, &[&str])]) -> Vec<String> {
        let flow = parse_flow(src).expect("test source should parse");
        let titles: Vec<String> = fields.iter().map(|(t, _)| t.to_string()).collect();
        let field_map: Vec<(String, Vec<String>)> = fields
            .iter()
            .map(|(t, fs)| (t.to_string(), fs.iter().map(|s| s.to_string()).collect()))
            .collect();
        let ctx = Context {
            request_titles: Some(&titles),
            request_fields: Some(&field_map),
            ..Default::default()
        };
        validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Warning)
            .map(|d| d.message)
            .collect()
    }

    #[test]
    fn duplicate_column_headers_are_rejected() {
        let titles = titles();
        // `FILE AS X` and `Oauth.status AS X` both resolve to header `X`, which
        // would collide in JSON output — one error, reported once.
        let errs = errors(
            "# collection: c\n# columns: FILE AS X, Oauth.status AS X, Oauth AS X\nREPORT REQUEST Oauth\n",
            Some(&titles),
            None,
        );
        let dup: Vec<_> = errs
            .iter()
            .filter(|m| m.contains("duplicate column"))
            .collect();
        assert_eq!(dup.len(), 1, "one duplicate-header error: {errs:?}");
        assert!(dup[0].contains('X'));

        // Distinct headers are fine.
        assert!(!has_err(
            "# collection: c\n# columns: FILE AS Name, Oauth.status AS Status\nREPORT REQUEST Oauth\n",
            Some(&titles),
            None,
            "duplicate column",
        ));
    }

    #[test]
    fn show_unknown_field_warns_but_known_fields_do_not() {
        // `Response`/`Time` are intrinsics; `status` is a [Reports] field —
        // all fine. `bogus` is none of those → one warning.
        let warns = warnings_with_fields(
            "REPORT REQUEST process SHOW(Response, Time, status, bogus)\n",
            &[("process", &["status", "overall"])],
        );
        assert_eq!(warns.len(), 1, "only 'bogus' should warn: {warns:?}");
        assert!(warns[0].contains("bogus"));
    }

    #[test]
    fn show_with_field_counts_as_known() {
        // A field provided only by this statement's WITH block is known.
        let warns = warnings_with_fields(
            "REPORT REQUEST process SHOW(extra) WITH\n    extra: jsonpath \"$.x\"\nEND\n",
            &[("process", &[])],
        );
        assert!(
            warns.iter().all(|w| !w.contains("extra")),
            "WITH field should not warn: {warns:?}"
        );
    }

    #[test]
    fn show_is_not_validated_without_a_bound_collection() {
        // No request_fields context → the field set is unknown, so no warning
        // (never false-warn on a real [Reports] field we can't see).
        let flow = parse_flow("REPORT REQUEST process SHOW(bogus)\n").unwrap();
        let ctx = Context::default();
        let warns: Vec<_> = validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Warning)
            .filter(|d| d.message.contains("SHOW"))
            .collect();
        assert!(warns.is_empty(), "unbound flow shouldn't warn: {warns:?}");
    }

    #[test]
    fn missing_collection_is_an_error() {
        assert!(has_err(
            "REQUEST Oauth\n",
            None,
            None,
            "missing '# collection:'"
        ));
    }

    #[test]
    fn empty_collection_directive_is_an_error() {
        assert!(has_err(
            "# collection:\nREQUEST Oauth\n",
            None,
            None,
            "empty"
        ));
    }

    #[test]
    fn valid_header_with_bound_collection_has_no_errors() {
        let t = titles();
        let errs = errors("# collection: ./c.hurl\nREQUEST Oauth\n", Some(&t), None);
        assert!(errs.is_empty(), "unexpected errors: {errs:?}");
    }

    #[test]
    fn unsupported_output_format_is_an_error() {
        let t = titles();
        assert!(has_err(
            "# collection: ./c.hurl\n# output: pdf\nREQUEST Oauth\n",
            Some(&t),
            None,
            "unsupported output format"
        ));
    }

    #[test]
    fn csv_output_is_accepted() {
        let t = titles();
        assert!(!has_err(
            "# collection: ./c.hurl\n# output: csv\nREQUEST Oauth\n",
            Some(&t),
            None,
            "unsupported"
        ));
    }

    #[test]
    fn xlsx_json_html_outputs_are_accepted() {
        let t = titles();
        for fmt in ["xlsx", "json", "html"] {
            assert!(
                !has_err(
                    &format!("# collection: ./c.hurl\n# output: {fmt}\nREQUEST Oauth\n"),
                    Some(&t),
                    None,
                    "unsupported"
                ),
                "format {fmt} should be accepted"
            );
        }
    }

    #[test]
    fn environment_header_naming_an_unloaded_env_is_an_error() {
        let t = titles();
        let envs = ["au".to_string()];
        assert!(has_err(
            "# collection: ./c.hurl\n# environment: staging\nREQUEST Oauth\n",
            Some(&t),
            Some(&envs),
            "environment 'staging' is not loaded"
        ));
    }

    #[test]
    fn environment_header_naming_a_loaded_env_is_accepted() {
        let t = titles();
        let envs = ["au".to_string(), "staging".to_string()];
        assert!(!has_err(
            "# collection: ./c.hurl\n# environment: staging\nREQUEST Oauth\n",
            Some(&t),
            Some(&envs),
            "is not loaded"
        ));
    }

    #[test]
    fn empty_environment_header_is_an_error() {
        let t = titles();
        assert!(has_err(
            "# collection: ./c.hurl\n# environment:\nREQUEST Oauth\n",
            Some(&t),
            None,
            "'# environment:' is empty"
        ));
    }

    #[test]
    fn environment_header_is_not_checked_until_envs_are_known() {
        // With no loaded-env context, a named environment can't be verified —
        // it must not spuriously error (mirrors how ENVS names are skipped).
        let t = titles();
        assert!(!has_err(
            "# collection: ./c.hurl\n# environment: staging\nREQUEST Oauth\n",
            Some(&t),
            None,
            "is not loaded"
        ));
    }

    #[test]
    fn unbound_collection_warns_but_does_not_error_on_names() {
        let diags = diags_for("# collection: ./c.hurl\nREQUEST Whatever\n", None, None);
        assert!(diags.iter().any(
            |d| d.severity == Severity::Warning && d.message.contains("collection not loaded")
        ));
        // No name-resolution error while unbound.
        assert!(!diags.iter().any(|d| d.message.contains("not found")));
    }

    #[test]
    fn request_name_resolves_by_exact_full_title() {
        let t = titles();
        assert!(!has_err(
            "# collection: ./c.hurl\nREQUEST upload/process_file\n",
            Some(&t),
            None,
            "not found"
        ));
    }

    #[test]
    fn request_name_resolves_by_unique_leaf() {
        let t = titles();
        // "process_file" is the leaf of "upload/process_file".
        assert!(!has_err(
            "# collection: ./c.hurl\nREPORT REQUEST process_file\n",
            Some(&t),
            None,
            "not found"
        ));
    }

    #[test]
    fn unknown_request_name_is_an_error() {
        let t = titles();
        assert!(has_err(
            "# collection: ./c.hurl\nREQUEST nope\n",
            Some(&t),
            None,
            "not found"
        ));
    }

    #[test]
    fn ambiguous_leaf_is_an_error() {
        let t = vec!["a/dup".to_string(), "b/dup".to_string()];
        assert!(has_err(
            "# collection: ./c.hurl\nREQUEST dup\n",
            Some(&t),
            None,
            "ambiguous"
        ));
    }

    #[test]
    fn envs_plain_empty_is_an_error() {
        // An ENVS clause with no names can't be produced by the parser directly,
        // so drive check_env_clause via a role clause missing comparisons.
        let t = titles();
        assert!(has_err(
            "# collection: ./c.hurl\nFOR T IN ENVS BASELINE(\"prod\")\n  REQUEST Oauth\nEND\n",
            Some(&t),
            None,
            "at least one COMPARISON"
        ));
    }

    #[test]
    fn envs_multiple_baseline_is_an_error() {
        let t = titles();
        assert!(has_err(
            "# collection: ./c.hurl\nFOR T IN ENVS BASELINE(\"a\", \"b\"), COMPARISON(\"c\")\n  REQUEST Oauth\nEND\n",
            Some(&t),
            None,
            "at most one BASELINE"
        ));
    }

    #[test]
    fn baseline_directive_with_envs_comparison_warns_it_is_ignored() {
        // Both a `# baseline:` snapshot diff and a live ENVS comparison target
        // the `Result` column; the live comparison wins, so the directive is
        // flagged as ignored rather than silently doing nothing.
        let t = titles();
        let warns: Vec<String> = diags_for(
            "# collection: ./c.hurl\n# baseline: prev.baseline\nFOR T IN ENVS BASELINE(\"a\"), COMPARISON(\"b\")\n  REQUEST Oauth\nEND\n",
            Some(&t),
            None,
        )
        .into_iter()
        .filter(|d| d.severity == Severity::Warning)
        .map(|d| d.message)
        .collect();
        assert!(
            warns.iter().any(|m| m.contains("'# baseline:' is ignored")),
            "expected the ignored-baseline warning: {warns:?}"
        );
    }

    #[test]
    fn baseline_directive_without_envs_comparison_does_not_warn() {
        // A plain snapshot diff (no ENVS roles) is the normal Source-B path — no
        // warning.
        let t = titles();
        let warns: Vec<String> = diags_for(
            "# collection: ./c.hurl\n# baseline: prev.baseline\nREPORT REQUEST Oauth\n",
            Some(&t),
            None,
        )
        .into_iter()
        .filter(|d| d.severity == Severity::Warning)
        .map(|d| d.message)
        .collect();
        assert!(
            !warns.iter().any(|m| m.contains("'# baseline:'")),
            "a plain baseline diff should not warn: {warns:?}"
        );
    }

    #[test]
    fn missing_baseline_snapshot_warns_when_anchored() {
        // With a known base directory, a `# baseline:` naming a file that isn't
        // there is surfaced as a warning up front (not silently at run time).
        let dir = std::env::temp_dir().join(format!("pb-vbl-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let flow = parse_flow(
            "# collection: ./c.hurl\n# baseline: missing.baseline\nREPORT REQUEST Oauth\n",
        )
        .unwrap();
        let t = titles();
        let ctx = Context {
            request_titles: Some(&t),
            root: Some(dir.as_path()),
            ..Default::default()
        };
        let warns: Vec<String> = validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Warning)
            .map(|d| d.message)
            .collect();
        assert!(
            warns.iter().any(|m| m.contains("was not found")),
            "expected a missing-snapshot warning: {warns:?}"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn present_baseline_snapshot_does_not_warn() {
        let dir = std::env::temp_dir().join(format!("pb-vbl-ok-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("prev.baseline"), "{}").unwrap();
        let flow =
            parse_flow("# collection: ./c.hurl\n# baseline: prev.baseline\nREPORT REQUEST Oauth\n")
                .unwrap();
        let t = titles();
        let ctx = Context {
            request_titles: Some(&t),
            root: Some(dir.as_path()),
            ..Default::default()
        };
        let warns: Vec<String> = validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Warning)
            .map(|d| d.message)
            .collect();
        assert!(
            !warns.iter().any(|m| m.contains("was not found")),
            "an existing snapshot should not warn: {warns:?}"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn envs_unloaded_environment_is_an_error() {
        let t = titles();
        let envs = vec!["prod-au".to_string()];
        assert!(has_err(
            "# collection: ./c.hurl\nFOR T IN ENVS \"prod-au\", \"staging-au\"\n  REQUEST Oauth\nEND\n",
            Some(&t),
            Some(&envs),
            "'staging-au' is not loaded"
        ));
    }

    #[test]
    fn envs_all_loaded_has_no_env_error() {
        let t = titles();
        let envs = vec!["prod-au".to_string(), "staging-au".to_string()];
        assert!(!has_err(
            "# collection: ./c.hurl\nFOR T IN ENVS \"prod-au\", \"staging-au\"\n  REQUEST Oauth\nEND\n",
            Some(&t),
            Some(&envs),
            "not loaded"
        ));
    }

    #[test]
    fn arity_mismatch_is_an_error() {
        let t = titles();
        assert!(has_err(
            "# collection: ./c.hurl\nFOR (A, B) IN FILES \"d\"\n  REQUEST Oauth\nEND\n",
            Some(&t),
            None,
            "binds 2 name"
        ));
    }

    #[test]
    fn arity_match_on_zip_is_ok() {
        let t = titles();
        assert!(!has_err(
            "# collection: ./c.hurl\nFOR (A, B) IN ZIP(FILES \"x\", FILES \"y\")\n  REQUEST Oauth\nEND\n",
            Some(&t),
            None,
            "binds"
        ));
    }

    #[test]
    fn concat_of_same_arity_sources_is_ok() {
        let t = titles();
        assert!(!has_err(
            "# collection: ./c.hurl\nFOR F IN CONCAT(FILES \"x\", FILES \"y\", FOLDERS \"z\")\n  REQUEST Oauth\nEND\n",
            Some(&t),
            None,
            "arity"
        ));
    }

    #[test]
    fn concat_of_mismatched_arity_is_an_error() {
        let t = titles();
        assert!(has_err(
            "# collection: ./c.hurl\nFOR F IN CONCAT(FILES \"x\", ZIP(FILES \"a\", FILES \"b\"))\n  REQUEST Oauth\nEND\n",
            Some(&t),
            None,
            "inconsistent arity"
        ));
    }

    #[test]
    fn inconsistent_list_literal_arity_is_an_error() {
        let t = titles();
        assert!(has_err(
            "# collection: ./c.hurl\nLIST L = [(\"a\", \"b\"), \"c\"]\nFOR (X, Y) IN L\n  REQUEST Oauth\nEND\n",
            Some(&t),
            None,
            "inconsistent arity"
        ));
    }

    #[test]
    fn rest_pattern_absorbs_extra_positions() {
        let t = titles();
        assert!(!has_err(
            "# collection: ./c.hurl\nLIST L = [(\"a\", \"b\", \"c\")]\nFOR (X, ...) IN L\n  REQUEST Oauth\nEND\n",
            Some(&t),
            None,
            "binds",
        ));
    }

    #[test]
    fn unknown_list_reference_is_an_error() {
        let t = titles();
        assert!(has_err(
            "# collection: ./c.hurl\nFOR X IN MISSING\n  REQUEST Oauth\nEND\n",
            Some(&t),
            None,
            "unknown list"
        ));
    }

    #[test]
    fn declared_list_reference_is_ok() {
        let t = titles();
        assert!(!has_err(
            "# collection: ./c.hurl\nLIST DOCS = FILES \"d\"\nFOR X IN DOCS\n  REQUEST Oauth\nEND\n",
            Some(&t),
            None,
            "unknown list"
        ));
    }

    #[test]
    fn show_and_hide_overlap_is_an_error() {
        // A field in both SHOW and HIDE is contradictory → validation error.
        let t = titles();
        let errs = errors(
            "# collection: c\nREPORT REQUEST Oauth SHOW(HttpStatus, Time) HIDE(Time)\n",
            Some(&t),
            None,
        );
        let overlap: Vec<_> = errs.iter().filter(|m| m.contains("Time")).collect();
        assert_eq!(overlap.len(), 1, "one overlap error for Time: {errs:?}");
        assert!(
            overlap[0].contains("conflict")
                || overlap[0].contains("SHOW")
                || overlap[0].contains("HIDE")
        );
    }

    #[test]
    fn hide_unknown_field_warns_but_known_fields_do_not() {
        // Same semantics as the SHOW unknown-field warning, but for HIDE.
        let warns = warnings_with_fields(
            "REPORT REQUEST process HIDE(Response, Time, status, ghost)\n",
            &[("process", &["status", "overall"])],
        );
        assert_eq!(warns.len(), 1, "only 'ghost' should warn: {warns:?}");
        assert!(warns[0].contains("ghost"));
    }

    #[test]
    fn hide_is_not_validated_without_a_bound_collection() {
        let flow = parse_flow("REPORT REQUEST process HIDE(bogus)\n").unwrap();
        let ctx = Context::default();
        let warns: Vec<_> = validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Warning)
            .filter(|d| d.message.contains("HIDE"))
            .collect();
        assert!(
            warns.is_empty(),
            "unbound flow shouldn't warn on HIDE: {warns:?}"
        );
    }

    // -----------------------------------------------------------------------
    // Variable-availability analysis tests
    // -----------------------------------------------------------------------

    /// Make a minimal `HurlEntry` for testing: `title` as the name,
    /// `{{VAR}}` references baked into the URL, and named captures.
    fn test_entry(title: &str, url_vars: &[&str], captures: &[&str]) -> crate::hurl::HurlEntry {
        use crate::hurl::HurlEntry;
        let url: String = url_vars
            .iter()
            .map(|v| format!("{{{{{}}}}} ", v))
            .collect::<String>();
        HurlEntry {
            title: title.to_string(),
            method: "GET".to_string(),
            url: format!("http://example/{}x", url),
            captures: captures
                .iter()
                .map(|c| ((*c).to_string(), "jsonpath \"$.v\"".to_string()))
                .collect(),
            ..Default::default()
        }
    }

    /// Validate `src` with a given context and return only the variable-
    /// availability warning messages.
    fn var_warns(
        src: &str,
        base_vars: &[&str],
        all_env_vars: &[&str],
        entries: &[crate::hurl::HurlEntry],
    ) -> Vec<String> {
        let flow = parse_flow(src).expect("test source should parse");
        let base: Vec<String> = base_vars.iter().map(|s| s.to_string()).collect();
        let all_env: Vec<String> = all_env_vars.iter().map(|s| s.to_string()).collect();
        let titles: Vec<String> = entries.iter().map(|e| e.title.clone()).collect();
        let ctx = Context {
            request_titles: Some(&titles),
            base_var_names: Some(&base),
            all_env_var_names: Some(&all_env),
            request_entries: Some(entries),
            ..Default::default()
        };
        validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Warning && d.message.contains("may not be defined"))
            .map(|d| d.message)
            .collect()
    }

    #[test]
    fn missing_var_in_request_url_produces_a_warning() {
        // Oauth's URL references {{TOKEN}} which isn't in the env or in scope.
        let entries = vec![test_entry("Oauth", &["TOKEN"], &[])];
        let warns = var_warns(
            "# collection: c\nREPORT REQUEST Oauth\n",
            &[], // no env vars
            &[],
            &entries,
        );
        assert!(
            warns.iter().any(|w| w.contains("TOKEN")),
            "{{TOKEN}} should warn as undefined: {warns:?}"
        );
    }

    #[test]
    fn var_defined_by_base_env_does_not_warn() {
        // When BASE_URL is in the base environment, no warning.
        let entries = vec![test_entry("Oauth", &["BASE_URL"], &[])];
        let warns = var_warns(
            "# collection: c\nREPORT REQUEST Oauth\n",
            &["BASE_URL"], // provided by env
            &[],
            &entries,
        );
        assert!(
            warns.is_empty(),
            "BASE_URL is in the base env — no warning expected: {warns:?}"
        );
    }

    #[test]
    fn var_defined_by_explicit_assignment_does_not_warn() {
        // An explicit `KEY=value` assignment before the request defines it.
        let entries = vec![test_entry("Oauth", &["TOKEN"], &[])];
        let warns = var_warns(
            "# collection: c\nTOKEN=abc\nREPORT REQUEST Oauth\n",
            &[], // not in env
            &[],
            &entries,
        );
        assert!(
            warns.is_empty(),
            "TOKEN is assigned before the request — no warning: {warns:?}"
        );
    }

    #[test]
    fn var_defined_by_for_loop_binder_does_not_warn() {
        // TOKEN is the loop binder inside a FOR loop.
        let entries = vec![test_entry("Oauth", &["TOKEN"], &[])];
        let warns = var_warns(
            "# collection: c\nFOR TOKEN IN [\"x\", \"y\"]\n    REPORT REQUEST Oauth\nEND\n",
            &[],
            &[],
            &entries,
        );
        assert!(
            warns.is_empty(),
            "TOKEN is a FOR loop binder — no warning: {warns:?}"
        );
    }

    #[test]
    fn var_defined_by_prior_capture_does_not_warn() {
        // Auth request captures TOKEN; then Api uses it.
        let auth = test_entry("Auth", &[], &["TOKEN"]);
        let api = test_entry("Api", &["TOKEN"], &[]);
        let entries = vec![auth, api];
        let warns = var_warns(
            "# collection: c\nREQUEST Auth\nREPORT REQUEST Api\n",
            &[],
            &[],
            &entries,
        );
        assert!(
            warns.is_empty(),
            "TOKEN is captured by Auth before Api runs — no warning: {warns:?}"
        );
    }

    #[test]
    fn var_defined_by_envs_loop_does_not_warn() {
        // Inside a FOR … IN ENVS loop, any env variable is potentially in scope.
        let entries = vec![test_entry("Api", &["REGION"], &[])];
        // REGION is in one of the loaded envs (all_env_vars).
        let warns = var_warns(
            "# collection: c\nFOR ENV IN ENVS \"prod\", \"staging\"\n    REPORT REQUEST Api\nEND\n",
            &[],         // not in base env
            &["REGION"], // but one of the envs provides it
            &entries,
        );
        assert!(
            warns.is_empty(),
            "REGION comes from the ENVS loop env — no warning: {warns:?}"
        );
    }

    #[test]
    fn no_warning_without_base_var_names_context() {
        // When base_var_names is None the check is skipped entirely
        // (conservative: we can't know what the env provides).
        let entries = vec![test_entry("Oauth", &["MISSING"], &[])];
        let titles: Vec<String> = entries.iter().map(|e| e.title.clone()).collect();
        let flow = parse_flow("# collection: c\nREPORT REQUEST Oauth\n").unwrap();
        let ctx = Context {
            request_titles: Some(&titles),
            base_var_names: None, // unknown
            request_entries: Some(&entries),
            ..Default::default()
        };
        let warns: Vec<_> = validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Warning && d.message.contains("may not be defined"))
            .collect();
        assert!(
            warns.is_empty(),
            "without base_var_names the check must be skipped: {warns:?}"
        );
    }

    #[test]
    fn capture_is_only_available_after_the_capturing_request() {
        // TOKEN is captured by Auth, but if a request runs before Auth and uses
        // TOKEN, it should warn. After Auth the warning is gone.
        let auth = test_entry("Auth", &[], &["TOKEN"]);
        let before = test_entry("Before", &["TOKEN"], &[]);
        let after = test_entry("After", &["TOKEN"], &[]);
        let entries = vec![auth.clone(), before.clone(), after.clone()];
        // Flow: Before (uses TOKEN — not yet captured), then Auth (captures TOKEN),
        // then After (uses TOKEN — OK, captured by Auth).
        let warns_before = var_warns(
            "# collection: c\nREPORT REQUEST Before\nREQUEST Auth\nREPORT REQUEST After\n",
            &[],
            &[],
            &entries,
        );
        assert!(
            warns_before
                .iter()
                .any(|w| w.contains("TOKEN") && w.contains("Before")),
            "TOKEN is not yet captured when Before runs: {warns_before:?}"
        );
        assert!(
            !warns_before
                .iter()
                .any(|w| w.contains("TOKEN") && w.contains("After")),
            "TOKEN IS captured by the time After runs: {warns_before:?}"
        );
    }
}