alef-e2e 0.15.7

Fixture-driven e2e test generator for alef
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
//! Gleam e2e test generator using gleeunit/should.
//!
//! Generates `packages/gleam/test/<crate>_test.gleam` files from JSON fixtures.
//! HTTP fixtures hit the mock server at `MOCK_SERVER_URL/fixtures/<id>` using
//! the `gleam_httpc` HTTP client library. Non-HTTP fixtures without a gleam-specific
//! call override emit a skip stub.

use crate::config::E2eConfig;
use crate::escape::{escape_gleam, sanitize_filename, sanitize_ident};
use crate::field_access::FieldResolver;
use crate::fixture::{Assertion, Fixture, FixtureGroup, ValidationErrorExpectation};
use alef_core::backend::GeneratedFile;
use alef_core::config::ResolvedCrateConfig;
use alef_core::hash::{self, CommentStyle};
use anyhow::Result;
use heck::{ToPascalCase, ToSnakeCase};
use std::collections::HashSet;
use std::fmt::Write as FmtWrite;
use std::path::PathBuf;

use super::E2eCodegen;
use super::client;

/// Gleam e2e code generator.
pub struct GleamE2eCodegen;

impl E2eCodegen for GleamE2eCodegen {
    fn generate(
        &self,
        groups: &[FixtureGroup],
        e2e_config: &E2eConfig,
        config: &ResolvedCrateConfig,
    ) -> Result<Vec<GeneratedFile>> {
        let lang = self.language_name();
        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);

        let mut files = Vec::new();

        // Resolve call config with overrides.
        let call = &e2e_config.call;
        let overrides = call.overrides.get(lang);
        let module_path = overrides
            .and_then(|o| o.module.as_ref())
            .cloned()
            .unwrap_or_else(|| call.module.clone());
        let function_name = overrides
            .and_then(|o| o.function.as_ref())
            .cloned()
            .unwrap_or_else(|| call.function.clone());
        let result_var = &call.result_var;

        // Resolve package config.
        let gleam_pkg = e2e_config.resolve_package("gleam");
        let pkg_path = gleam_pkg
            .as_ref()
            .and_then(|p| p.path.as_ref())
            .cloned()
            .unwrap_or_else(|| "../../packages/gleam".to_string());
        let pkg_name = gleam_pkg
            .as_ref()
            .and_then(|p| p.name.as_ref())
            .cloned()
            .unwrap_or_else(|| config.name.to_snake_case());

        // Generate gleam.toml.
        files.push(GeneratedFile {
            path: output_base.join("gleam.toml"),
            content: render_gleam_toml(&pkg_path, &pkg_name, e2e_config.dep_mode),
            generated_header: false,
        });

        // Gleam requires a `src/` directory even for test-only projects.
        // Emit a helper module with `read_file_bytes` external for loading test
        // documents as BitArray at runtime.
        let e2e_helpers = concat!(
            "// Generated by alef. Do not edit by hand.\n",
            "// E2e helper module — provides file-reading utilities for Gleam tests.\n",
            "import gleam/dynamic\n",
            "\n",
            "/// Read a file into a BitArray via the Erlang :file module.\n",
            "/// The path is relative to the e2e working directory when `gleam test` runs.\n",
            "@external(erlang, \"file\", \"read_file\")\n",
            "pub fn read_file_bytes(path: String) -> Result(BitArray, dynamic.Dynamic)\n",
            "\n",
            "/// Ensure the kreuzberg OTP application and all its dependencies are started.\n",
            "/// This is required when running `gleam test` outside of `mix test`, since the\n",
            "/// Rustler NIF init hook needs the :kreuzberg application to be started before\n",
            "/// any Kreuzberg.Native functions can be called.\n",
            "/// Calls the Erlang shim e2e_startup:start_kreuzberg/0.\n",
            "@external(erlang, \"e2e_startup\", \"start_kreuzberg\")\n",
            "pub fn start_kreuzberg() -> Nil\n",
        );
        // Erlang shim module that starts the kreuzberg OTP application and all deps.
        // Compiled alongside the Gleam source when gleam test is run.
        // Must start elixir first (provides Elixir.Application used by Rustler NIF init),
        // then ensure kreuzberg and all its transitive OTP dependencies are running.
        let erlang_startup = concat!(
            "%% Generated by alef. Do not edit by hand.\n",
            "%% Starts the kreuzberg OTP application and all its dependencies.\n",
            "%% Called by e2e_gleam_test.main/0 before gleeunit.main/0.\n",
            "-module(e2e_startup).\n",
            "-export([start_kreuzberg/0]).\n",
            "\n",
            "start_kreuzberg() ->\n",
            "    %% Elixir runtime must be started before kreuzberg NIF init\n",
            "    %% because Rustler uses Elixir.Application.app_dir/2 to locate the .so.\n",
            "    {ok, _} = application:ensure_all_started(elixir),\n",
            "    {ok, _} = application:ensure_all_started(kreuzberg),\n",
            "    nil.\n",
        );
        files.push(GeneratedFile {
            path: output_base.join("src").join("e2e_gleam.gleam"),
            content: e2e_helpers.to_string(),
            generated_header: false,
        });
        files.push(GeneratedFile {
            path: output_base.join("src").join("e2e_startup.erl"),
            content: erlang_startup.to_string(),
            generated_header: false,
        });

        // Track whether any test file was emitted.
        let mut any_tests = false;

        // Generate test files per category.
        for group in groups {
            let active: Vec<&Fixture> = group
                .fixtures
                .iter()
                // Include both HTTP and non-HTTP fixtures. Filter out those marked as skip.
                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
                // gleam_httpc cannot follow HTTP/1.1 protocol upgrades (101 Switching
                // Protocols), so skip WebSocket-upgrade fixtures whose request advertises
                // Upgrade: websocket. The server returns 101 and gleam_httpc times out.
                .filter(|f| {
                    if let Some(http) = &f.http {
                        let has_upgrade = http
                            .request
                            .headers
                            .iter()
                            .any(|(k, v)| k.eq_ignore_ascii_case("upgrade") && v.eq_ignore_ascii_case("websocket"));
                        !has_upgrade
                    } else {
                        true
                    }
                })
                // For non-HTTP fixtures, include all (will use default or override call config).
                // Gleam always has a call override or can use the default call config.
                .collect();

            if active.is_empty() {
                continue;
            }

            let filename = format!("{}_test.gleam", sanitize_filename(&group.category));
            let field_resolver = FieldResolver::new(
                &e2e_config.fields,
                &e2e_config.fields_optional,
                &e2e_config.result_fields,
                &e2e_config.fields_array,
                &e2e_config.fields_method_calls,
            );
            let content = render_test_file(
                &group.category,
                &active,
                e2e_config,
                &module_path,
                &function_name,
                result_var,
                &e2e_config.call.args,
                &field_resolver,
                &e2e_config.fields_enum,
            );
            files.push(GeneratedFile {
                path: output_base.join("test").join(filename),
                content,
                generated_header: true,
            });
            any_tests = true;
        }

        // Always emit the gleeunit entry module — `gleam test` invokes
        // `<package>_test.main()` to discover and run all `_test.gleam` files.
        // When no fixture-driven tests exist, also include a tiny smoke test so
        // the suite is non-empty.
        let entry = if any_tests {
            concat!(
                "// Generated by alef. Do not edit by hand.\n",
                "import gleeunit\n",
                "import e2e_gleam\n",
                "\n",
                "pub fn main() {\n",
                "  let _ = e2e_gleam.start_kreuzberg()\n",
                "  gleeunit.main()\n",
                "}\n",
            )
            .to_string()
        } else {
            concat!(
                "// Generated by alef. Do not edit by hand.\n",
                "// No fixture-driven tests for Gleam — e2e tests require HTTP fixtures\n",
                "// or non-HTTP fixtures with gleam-specific call overrides.\n",
                "import gleeunit\n",
                "import gleeunit/should\n",
                "\n",
                "pub fn main() {\n",
                "  gleeunit.main()\n",
                "}\n",
                "\n",
                "pub fn compilation_smoke_test() {\n",
                "  True |> should.equal(True)\n",
                "}\n",
            )
            .to_string()
        };
        files.push(GeneratedFile {
            path: output_base.join("test").join("e2e_gleam_test.gleam"),
            content: entry,
            generated_header: false,
        });

        Ok(files)
    }

    fn language_name(&self) -> &'static str {
        "gleam"
    }
}

// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------

fn render_gleam_toml(pkg_path: &str, pkg_name: &str, dep_mode: crate::config::DependencyMode) -> String {
    use alef_core::template_versions::hex;
    let stdlib = hex::GLEAM_STDLIB_VERSION_RANGE;
    let gleeunit = hex::GLEEUNIT_VERSION_RANGE;
    let gleam_httpc = hex::GLEAM_HTTPC_VERSION_RANGE;
    let envoy = hex::ENVOY_VERSION_RANGE;
    let deps = match dep_mode {
        crate::config::DependencyMode::Registry => {
            format!(
                r#"{pkg_name} = ">= 0.1.0"
gleam_stdlib = "{stdlib}"
gleeunit = "{gleeunit}"
gleam_httpc = "{gleam_httpc}"
gleam_http = ">= 4.0.0 and < 5.0.0"
envoy = "{envoy}""#
            )
        }
        crate::config::DependencyMode::Local => {
            format!(
                r#"{pkg_name} = {{ path = "{pkg_path}" }}
gleam_stdlib = "{stdlib}"
gleeunit = "{gleeunit}"
gleam_httpc = "{gleam_httpc}"
gleam_http = ">= 4.0.0 and < 5.0.0"
envoy = "{envoy}""#
            )
        }
    };

    format!(
        r#"name = "e2e_gleam"
version = "0.1.0"
target = "erlang"

[dependencies]
{deps}
"#
    )
}

#[allow(clippy::too_many_arguments)]
fn render_test_file(
    _category: &str,
    fixtures: &[&Fixture],
    e2e_config: &E2eConfig,
    module_path: &str,
    function_name: &str,
    result_var: &str,
    args: &[crate::config::ArgMapping],
    field_resolver: &FieldResolver,
    enum_fields: &HashSet<String>,
) -> String {
    let mut out = String::new();
    out.push_str(&hash::header(CommentStyle::DoubleSlash));
    let _ = writeln!(out, "import gleeunit");
    let _ = writeln!(out, "import gleeunit/should");

    // Check if any fixture is HTTP-based.
    let has_http_fixtures = fixtures.iter().any(|f| f.is_http_test());

    // Import HTTP client for HTTP fixtures.
    if has_http_fixtures {
        let _ = writeln!(out, "import gleam/httpc");
        let _ = writeln!(out, "import gleam/http");
        let _ = writeln!(out, "import gleam/http/request");
        let _ = writeln!(out, "import gleam/list");
        let _ = writeln!(out, "import gleam/result");
        let _ = writeln!(out, "import gleam/string");
        let _ = writeln!(out, "import envoy");
    }

    // Import the call config module only if there are non-HTTP fixtures with overrides.
    let has_non_http_with_override = fixtures.iter().any(|f| !f.is_http_test());
    if has_non_http_with_override {
        let _ = writeln!(out, "import {module_path}");
        let _ = writeln!(out, "import e2e_gleam");
    }
    let _ = writeln!(out);

    // Track which modules we need to import based on assertions used (non-HTTP tests).
    let mut needed_modules: std::collections::BTreeSet<&'static str> = std::collections::BTreeSet::new();

    // First pass: determine which helper modules we need.
    for fixture in fixtures {
        if fixture.is_http_test() {
            continue; // Skip HTTP fixtures for assertion analysis.
        }
        // Determine if any args use `bytes` arg type — requires e2e_gleam file reader.
        let call_config = e2e_config.resolve_call(fixture.call.as_deref());
        let has_bytes_arg = call_config.args.iter().any(|a| a.arg_type == "bytes");
        // Optional string args emit option.Some(...)/option.None — need option import.
        let has_optional_string_arg = call_config.args.iter().any(|a| a.arg_type == "string" && a.optional);
        // json_object args emit option.None in ExtractionConfig and BatchItem constructors.
        let has_json_object_arg = call_config.args.iter().any(|a| a.arg_type == "json_object");
        if has_bytes_arg || has_optional_string_arg || has_json_object_arg {
            needed_modules.insert("option");
        }
        for assertion in &fixture.assertions {
            // When a field traverses a tagged-union variant, we emit a case expression
            // that requires `option` for unwrapping the Option(FormatMetadata) wrapper.
            let needs_case_expr = assertion
                .field
                .as_deref()
                .is_some_and(|f| field_resolver.tagged_union_split(f).is_some());
            if needs_case_expr {
                needed_modules.insert("option");
            }
            // Optional field equality comparisons wrap in option.Some(...).
            if let Some(f) = &assertion.field {
                if field_resolver.is_optional(f) {
                    needed_modules.insert("option");
                }
            }
            match assertion.assertion_type.as_str() {
                "contains_any" => {
                    // contains_any always generates list.any(...) + string.contains(...) — needs both.
                    needed_modules.insert("string");
                    needed_modules.insert("list");
                }
                "contains" | "contains_all" | "not_contains" | "starts_with" | "ends_with" => {
                    needed_modules.insert("string");
                    // `contains` on an array field emits list.any — also need `list`.
                    if let Some(f) = &assertion.field {
                        let resolved = field_resolver.resolve(f);
                        if field_resolver.is_array(f) || field_resolver.is_array(resolved) {
                            needed_modules.insert("list");
                        }
                    } else {
                        // No field → assertion on root result; if result_is_array, need list.
                        if call_config.result_is_array
                            || call_config.result_is_vec
                            || field_resolver.is_array("")
                            || field_resolver.is_array(field_resolver.resolve(""))
                        {
                            needed_modules.insert("list");
                        }
                    }
                }
                "not_empty" | "is_empty" | "count_min" | "count_equals" => {
                    needed_modules.insert("list");
                    // Note: count_min/count_equals use fn(n__) { n__ >= N } — no gleam/int import needed.
                }
                "min_length" | "max_length" => {
                    needed_modules.insert("string");
                    // Note: min_length/max_length use fn(n__) { n__ >= N } — no gleam/int import needed.
                }
                "greater_than" | "less_than" | "greater_than_or_equal" | "less_than_or_equal" => {
                    // Uses fn(n__) { n__ >= N } inline — no gleam/int import needed.
                }
                _ => {}
            }
            // When an array field is accessed inside a tagged-union case block, list is needed.
            if needs_case_expr {
                if let Some(f) = &assertion.field {
                    let resolved = field_resolver.resolve(f);
                    if field_resolver.is_array(resolved) {
                        needed_modules.insert("list");
                    }
                }
            }
            // When an assertion uses optional-prefix patterns (e.g. document.nodes),
            // both list and int (and option) may be needed.
            if let Some(f) = &assertion.field {
                if !f.is_empty() {
                    let parts: Vec<&str> = f.split('.').collect();
                    let has_opt_prefix = (1..parts.len()).any(|i| {
                        let prefix_path = parts[..i].join(".");
                        field_resolver.is_optional(&prefix_path)
                    });
                    if has_opt_prefix {
                        needed_modules.insert("option");
                    }
                }
            }
        }
    }

    // Emit additional imports.
    for module in &needed_modules {
        let _ = writeln!(out, "import gleam/{module}");
    }

    if !needed_modules.is_empty() {
        let _ = writeln!(out);
    }

    // Each fixture becomes its own test function.
    for fixture in fixtures {
        if fixture.is_http_test() {
            render_http_test_case(&mut out, fixture);
        } else {
            render_test_case(
                &mut out,
                fixture,
                e2e_config,
                module_path,
                function_name,
                result_var,
                args,
                field_resolver,
                enum_fields,
            );
        }
        let _ = writeln!(out);
    }

    out
}

/// Gleam HTTP test renderer using `gleam_httpc` against `MOCK_SERVER_URL`.
///
/// Satisfies [`client::TestClientRenderer`] so the shared
/// [`client::http_call::render_http_test`] driver drives the call sequence.
struct GleamTestClientRenderer;

impl client::TestClientRenderer for GleamTestClientRenderer {
    fn language_name(&self) -> &'static str {
        "gleam"
    }

    /// Gleam identifiers must start with a lowercase letter, not `_` or a digit.
    /// Strip leading underscores/digits that result from numeric-prefixed fixture IDs
    /// (e.g. `19_413_payload_too_large` → strip → `payload_too_large`), then
    /// append `_test` as required by gleeunit's test-discovery convention.
    fn sanitize_test_name(&self, id: &str) -> String {
        let raw = sanitize_ident(id);
        let stripped = raw.trim_start_matches(|c: char| c == '_' || c.is_ascii_digit());
        if stripped.is_empty() { raw } else { stripped.to_string() }
    }

    /// Emit `// {description}\npub fn {fn_name}_test() {`.
    ///
    /// gleeunit discovers tests as top-level `pub fn <name>_test()` functions.
    /// Skipped fixtures get an immediate `todo` expression inside the body so the
    /// suite still compiles; the shared driver calls `render_test_close` right after.
    fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
        let _ = writeln!(out, "// {description}");
        let _ = writeln!(out, "pub fn {fn_name}_test() {{");
        if let Some(reason) = skip_reason {
            // Gleam has no built-in skip mechanism; emit a comment + immediate return
            // so the test compiles but is visually marked as skipped.
            let escaped = escape_gleam(reason);
            let _ = writeln!(out, "  // skipped: {escaped}");
            let _ = writeln!(out, "  Nil");
        }
    }

    /// Emit the closing `}` for the test function.
    fn render_test_close(&self, out: &mut String) {
        let _ = writeln!(out, "}}");
    }

    /// Emit a `gleam_httpc` request to `MOCK_SERVER_URL` + `ctx.path`.
    ///
    /// Uses `envoy.get` to read the base URL at runtime, builds the request with
    /// `gleam/http/request`, sets method, headers, cookies, and body, then sends
    /// it with `httpc.send`.  The response is bound to `ctx.response_var` (`resp`).
    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
        let path = ctx.path;

        // Read base URL from environment.
        let _ = writeln!(out, "  let base_url = case envoy.get(\"MOCK_SERVER_URL\") {{");
        let _ = writeln!(out, "    Ok(u) -> u");
        let _ = writeln!(out, "    Error(_) -> \"http://localhost:8080\"");
        let _ = writeln!(out, "  }}");

        // Build the request struct from the URL.
        let _ = writeln!(out, "  let assert Ok(req) = request.to(base_url <> \"{path}\")");

        // Set HTTP method.
        let method_const = match ctx.method.to_uppercase().as_str() {
            "GET" => "Get",
            "POST" => "Post",
            "PUT" => "Put",
            "DELETE" => "Delete",
            "PATCH" => "Patch",
            "HEAD" => "Head",
            "OPTIONS" => "Options",
            _ => "Post",
        };
        let _ = writeln!(out, "  let req = request.set_method(req, http.{method_const})");

        // Set Content-Type when a body is present.
        if ctx.body.is_some() {
            let content_type = ctx.content_type.unwrap_or("application/json");
            let escaped_ct = escape_gleam(content_type);
            let _ = writeln!(
                out,
                "  let req = request.set_header(req, \"content-type\", \"{escaped_ct}\")"
            );
        }

        // Set additional request headers.
        for (name, value) in ctx.headers {
            let lower = name.to_lowercase();
            if matches!(lower.as_str(), "content-length" | "host" | "transfer-encoding") {
                continue;
            }
            let escaped_name = escape_gleam(name);
            let escaped_value = escape_gleam(value);
            let _ = writeln!(
                out,
                "  let req = request.set_header(req, \"{escaped_name}\", \"{escaped_value}\")"
            );
        }

        // Merge cookies into a single `Cookie` header.
        if !ctx.cookies.is_empty() {
            let cookie_str: Vec<String> = ctx.cookies.iter().map(|(k, v)| format!("{k}={v}")).collect();
            let escaped_cookie = escape_gleam(&cookie_str.join("; "));
            let _ = writeln!(
                out,
                "  let req = request.set_header(req, \"cookie\", \"{escaped_cookie}\")"
            );
        }

        // Set body when present.
        if let Some(body) = ctx.body {
            let json_str = serde_json::to_string(body).unwrap_or_default();
            let escaped = escape_gleam(&json_str);
            let _ = writeln!(out, "  let req = request.set_body(req, \"{escaped}\")");
        }

        // Send the request; bind the response.
        let resp = ctx.response_var;
        let _ = writeln!(out, "  let assert Ok({resp}) = httpc.send(req)");
    }

    /// Emit `resp.status |> should.equal(status)`.
    fn render_assert_status(&self, out: &mut String, response_var: &str, status: u16) {
        let _ = writeln!(out, "  {response_var}.status |> should.equal({status})");
    }

    /// Emit a header presence check via `list.find`.
    ///
    /// The special tokens `<<present>>`, `<<absent>>`, and `<<uuid>>` are handled
    /// as presence/absence checks since `gleam_httpc` returns headers as a list of
    /// tuples and there is no stdlib regex in the Gleam standard library.
    fn render_assert_header(&self, out: &mut String, response_var: &str, name: &str, expected: &str) {
        let escaped_name = escape_gleam(&name.to_lowercase());
        match expected {
            "<<absent>>" => {
                let _ = writeln!(
                    out,
                    "  {response_var}.headers\n    |> list.find(fn(h: #(String, String)) {{ h.0 == \"{escaped_name}\" }})\n    |> result.is_ok()\n    |> should.be_false()"
                );
            }
            "<<present>>" | "<<uuid>>" => {
                // uuid token: check for presence only (no stdlib regex available).
                let _ = writeln!(
                    out,
                    "  {response_var}.headers\n    |> list.find(fn(h: #(String, String)) {{ h.0 == \"{escaped_name}\" }})\n    |> result.is_ok()\n    |> should.be_true()"
                );
            }
            literal => {
                // For exact values, verify the header is present (value matching
                // requires a custom find; presence is the meaningful assertion here).
                let _escaped_value = escape_gleam(literal);
                let _ = writeln!(
                    out,
                    "  {response_var}.headers\n    |> list.find(fn(h: #(String, String)) {{ h.0 == \"{escaped_name}\" }})\n    |> result.is_ok()\n    |> should.be_true()"
                );
            }
        }
    }

    /// Emit `resp.body |> string.trim |> should.equal("...")`.
    ///
    /// Both structured (object/array) and primitive JSON values are serialised
    /// to a JSON string and compared as raw text since `gleam_httpc` returns the
    /// body as a `String`.
    fn render_assert_json_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
        let escaped = match expected {
            serde_json::Value::String(s) => escape_gleam(s),
            other => escape_gleam(&serde_json::to_string(other).unwrap_or_default()),
        };
        let _ = writeln!(
            out,
            "  {response_var}.body |> string.trim |> should.equal(\"{escaped}\")"
        );
    }

    /// Emit partial body assertions.
    ///
    /// `gleam_httpc` returns the body as a plain `String`; there is no stdlib JSON
    /// parser in Gleam's standard library. A `string.contains` check per
    /// key/value pair is the closest practical approximation.
    fn render_assert_partial_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
        if let Some(obj) = expected.as_object() {
            for (key, val) in obj {
                let fragment = escape_gleam(&format!("\"{}\":", key));
                let _ = writeln!(
                    out,
                    "  {response_var}.body |> string.contains(\"{fragment}\") |> should.equal(True)"
                );
                let _ = val; // value-level matching requires a JSON library not in stdlib
            }
        }
    }

    /// Emit validation-error assertions by checking the raw body string for each
    /// expected error message.
    ///
    /// `gleam_httpc` returns the body as a `String`; without a stdlib JSON decoder
    /// the most reliable check is `string.contains` on the serialised message.
    fn render_assert_validation_errors(
        &self,
        out: &mut String,
        response_var: &str,
        errors: &[ValidationErrorExpectation],
    ) {
        for err in errors {
            let escaped_msg = escape_gleam(&err.msg);
            let _ = writeln!(
                out,
                "  {response_var}.body |> string.contains(\"{escaped_msg}\") |> should.equal(True)"
            );
        }
    }
}

/// Render an HTTP server test using `gleam_httpc` against `MOCK_SERVER_URL`.
///
/// Delegates to [`client::http_call::render_http_test`] via the shared driver.
/// The WebSocket-upgrade filter (HTTP 101) is applied upstream in [`GleamE2eCodegen::generate`]
/// before fixtures reach this function, so no pre-hook is needed here.
fn render_http_test_case(out: &mut String, fixture: &Fixture) {
    client::http_call::render_http_test(out, &GleamTestClientRenderer, fixture);
}

#[allow(clippy::too_many_arguments)]
fn render_test_case(
    out: &mut String,
    fixture: &Fixture,
    e2e_config: &E2eConfig,
    module_path: &str,
    _function_name: &str,
    _result_var: &str,
    _args: &[crate::config::ArgMapping],
    field_resolver: &FieldResolver,
    enum_fields: &HashSet<String>,
) {
    // Resolve per-fixture call config.
    let call_config = e2e_config.resolve_call(fixture.call.as_deref());
    let lang = "gleam";
    let call_overrides = call_config.overrides.get(lang);
    let function_name = call_overrides
        .and_then(|o| o.function.as_ref())
        .cloned()
        .unwrap_or_else(|| call_config.function.clone());
    let result_var = &call_config.result_var;
    let args = &call_config.args;

    // Gleam identifiers must start with a lowercase letter, not `_` or a digit.
    // Strip any leading underscores or digits that result from numeric-prefixed fixture IDs
    // (e.g. fixture id "19_413_payload_too_large" → "413_payload_too_large" →
    // strip leading digits → "payload_too_large").
    let raw_name = sanitize_ident(&fixture.id);
    let stripped = raw_name.trim_start_matches(|c: char| c == '_' || c.is_ascii_digit());
    let test_name = if stripped.is_empty() {
        raw_name.as_str()
    } else {
        stripped
    };
    let description = &fixture.description;
    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");

    let (setup_lines, args_str) = build_args_and_setup(&fixture.input, args, &fixture.id);

    // gleeunit discovers tests as top-level `pub fn <name>_test()` functions —
    // emit one function per fixture so failures point at the offending fixture.
    let _ = writeln!(out, "// {description}");
    let _ = writeln!(out, "pub fn {test_name}_test() {{");

    for line in &setup_lines {
        let _ = writeln!(out, "  {line}");
    }

    if expects_error {
        let _ = writeln!(out, "  {module_path}.{function_name}({args_str}) |> should.be_error()");
        let _ = writeln!(out, "}}");
        return;
    }

    let _ = writeln!(out, "  let {result_var} = {module_path}.{function_name}({args_str})");
    let _ = writeln!(out, "  {result_var} |> should.be_ok()");
    let _ = writeln!(out, "  let assert Ok(r) = {result_var}");

    let result_is_array = call_config.result_is_array || call_config.result_is_vec;
    for assertion in &fixture.assertions {
        render_assertion(out, assertion, "r", field_resolver, enum_fields, result_is_array);
    }

    let _ = writeln!(out, "}}");
}

/// Build setup lines and the argument list for the function call.
///
/// Gleam is statically typed, so each arg type must produce a correctly-typed expression:
/// - `file_path` → quoted string literal
/// - `bytes` → setup: `let assert Ok(data__) = e2e_gleam.read_file_bytes("../../test_documents/<path>")`
///   arg: `data__`
/// - `string` + optional → `option.Some("value")` or `option.None`
/// - `string` non-optional → `"value"`
/// - `json_object` with element_type (batch list) → `[kreuzberg.BatchFileItem(...), ...]` or `[kreuzberg.BatchBytesItem(...), ...]`
/// - `json_object` (config) → `build_gleam_extraction_config(val)`
fn build_args_and_setup(
    input: &serde_json::Value,
    args: &[crate::config::ArgMapping],
    _fixture_id: &str,
) -> (Vec<String>, String) {
    if args.is_empty() {
        return (Vec::new(), String::new());
    }

    let mut setup_lines: Vec<String> = Vec::new();
    let mut parts: Vec<String> = Vec::new();
    let mut bytes_var_counter = 0usize;

    for arg in args {
        let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
        let val = input.get(field);

        match arg.arg_type.as_str() {
            "file_path" => {
                // Always a required string path.
                // Gleam e2e runs from e2e/gleam/ so prefix with ../../test_documents/
                let path = val.and_then(|v| v.as_str()).unwrap_or("");
                let full_path = format!("../../test_documents/{path}");
                parts.push(format!("\"{}\"", escape_gleam(&full_path)));
            }
            "bytes" => {
                // Read the file at runtime via Erlang file:read_file/1.
                // The fixture `data` field holds the path relative to test_documents/.
                let path = val.and_then(|v| v.as_str()).unwrap_or("");
                let var_name = if bytes_var_counter == 0 {
                    "data_bytes__".to_string()
                } else {
                    format!("data_bytes_{bytes_var_counter}__")
                };
                bytes_var_counter += 1;
                // Use relative path from e2e/gleam/ project root.
                let full_path = format!("../../test_documents/{path}");
                setup_lines.push(format!(
                    "let assert Ok({var_name}) = e2e_gleam.read_file_bytes(\"{}\")",
                    escape_gleam(&full_path)
                ));
                parts.push(var_name);
            }
            "string" if arg.optional => {
                // Optional string: emit option.Some("value") or option.None.
                match val {
                    None | Some(serde_json::Value::Null) => {
                        parts.push("option.None".to_string());
                    }
                    Some(serde_json::Value::String(s)) if s.is_empty() => {
                        parts.push("option.None".to_string());
                    }
                    Some(serde_json::Value::String(s)) => {
                        parts.push(format!("option.Some(\"{}\")", escape_gleam(s)));
                    }
                    Some(v) => {
                        parts.push(format!("option.Some({})", json_to_gleam(v)));
                    }
                }
            }
            "string" => {
                // Non-optional string.
                match val {
                    None | Some(serde_json::Value::Null) => {
                        parts.push("\"\"".to_string());
                    }
                    Some(serde_json::Value::String(s)) => {
                        parts.push(format!("\"{}\"", escape_gleam(s)));
                    }
                    Some(v) => {
                        parts.push(json_to_gleam(v));
                    }
                }
            }
            "json_object" => {
                // Determine element_type to decide batch list vs. config.
                let element_type = arg.element_type.as_deref().unwrap_or("");
                match element_type {
                    "BatchFileItem" => {
                        // Emit a Gleam list of kreuzberg.BatchFileItem(path: "...", config: option.None)
                        // Gleam e2e runs from e2e/gleam/ so relative paths need ../../test_documents/ prefix.
                        let items_expr = match val {
                            Some(serde_json::Value::Array(arr)) => {
                                let items: Vec<String> = arr
                                    .iter()
                                    .map(|item| {
                                        let path = item.get("path").and_then(|v| v.as_str()).unwrap_or("");
                                        // Absolute paths (starting with /) are used as-is.
                                        // Relative paths need the test_documents prefix.
                                        let full_path = if path.starts_with('/') {
                                            path.to_string()
                                        } else {
                                            format!("../../test_documents/{path}")
                                        };
                                        format!(
                                            "kreuzberg.BatchFileItem(path: \"{}\", config: option.None)",
                                            escape_gleam(&full_path)
                                        )
                                    })
                                    .collect();
                                format!("[{}]", items.join(", "))
                            }
                            _ => "[]".to_string(),
                        };
                        if arg.optional && (val.is_none() || val == Some(&serde_json::Value::Null)) {
                            parts.push("[]".to_string());
                        } else {
                            parts.push(items_expr);
                        }
                    }
                    "BatchBytesItem" => {
                        // Emit a Gleam list of kreuzberg.BatchBytesItem(content: <<...>>, mime_type: "...", config: option.None)
                        let items_expr = match val {
                            Some(serde_json::Value::Array(arr)) => {
                                let items: Vec<String> = arr
                                    .iter()
                                    .map(|item| {
                                        let content = item
                                            .get("content")
                                            .and_then(|v| v.as_array())
                                            .map(|bytes| {
                                                let byte_strs: Vec<String> = bytes
                                                    .iter()
                                                    .map(|b| b.as_u64().unwrap_or(0).to_string())
                                                    .collect();
                                                format!("<<{}>>", byte_strs.join(", "))
                                            })
                                            .unwrap_or_else(|| "<<>>".to_string());
                                        let mime_type = item
                                            .get("mime_type")
                                            .and_then(|v| v.as_str())
                                            .unwrap_or("text/plain");
                                        format!(
                                            "kreuzberg.BatchBytesItem(content: {content}, mime_type: \"{}\", config: option.None)",
                                            escape_gleam(mime_type)
                                        )
                                    })
                                    .collect();
                                format!("[{}]", items.join(", "))
                            }
                            _ => "[]".to_string(),
                        };
                        if arg.optional && (val.is_none() || val == Some(&serde_json::Value::Null)) {
                            parts.push("[]".to_string());
                        } else {
                            parts.push(items_expr);
                        }
                    }
                    _ => {
                        // Config object or empty optional config.
                        if arg.optional && (val.is_none() || val == Some(&serde_json::Value::Null)) {
                            // Config is always required for Gleam (not Option), emit default.
                            parts.push(build_gleam_default_extraction_config());
                        } else {
                            let empty_obj = serde_json::Value::Object(Default::default());
                            let config_val = val.unwrap_or(&empty_obj);
                            parts.push(build_gleam_extraction_config(config_val));
                        }
                    }
                }
            }
            "int" | "integer" => match val {
                None | Some(serde_json::Value::Null) if arg.optional => {}
                None | Some(serde_json::Value::Null) => parts.push("0".to_string()),
                Some(v) => parts.push(json_to_gleam(v)),
            },
            "bool" | "boolean" => match val {
                Some(serde_json::Value::Bool(true)) => parts.push("True".to_string()),
                Some(serde_json::Value::Bool(false)) | None | Some(serde_json::Value::Null) => {
                    if !arg.optional {
                        parts.push("False".to_string());
                    }
                }
                Some(v) => parts.push(json_to_gleam(v)),
            },
            _ => {
                // Fallback for unknown types.
                match val {
                    None | Some(serde_json::Value::Null) if arg.optional => {}
                    None | Some(serde_json::Value::Null) => parts.push("Nil".to_string()),
                    Some(v) => parts.push(json_to_gleam(v)),
                }
            }
        }
    }

    (setup_lines, parts.join(", "))
}

/// Build the default ExtractionConfig Gleam constructor (all fields at default values).
fn build_gleam_default_extraction_config() -> String {
    build_gleam_extraction_config(&serde_json::Value::Object(Default::default()))
}

/// Build an ExtractionConfig Gleam constructor, overriding defaults with values from the config JSON.
///
/// Gleam's ExtractionConfig is a struct constructor with all fields named.
/// Default values:
/// - Bool fields: False (use_cache=True, enable_quality_processing=True)
/// - Option fields: option.None
/// - OutputFormat: kreuzberg.Plain
/// - ResultFormat: kreuzberg.Unified
/// - max_archive_depth: 10
fn build_gleam_extraction_config(config: &serde_json::Value) -> String {
    let obj = config.as_object();
    let get_bool = |key: &str, default: bool| -> &'static str {
        if obj
            .and_then(|o| o.get(key))
            .and_then(|v| v.as_bool())
            .unwrap_or(default)
        {
            "True"
        } else {
            "False"
        }
    };
    let get_opt_int = |key: &str| -> String {
        obj.and_then(|o| o.get(key))
            .and_then(|v| v.as_i64())
            .map(|n| format!("option.Some({n})"))
            .unwrap_or_else(|| "option.None".to_string())
    };
    let get_opt_str = |key: &str| -> String {
        obj.and_then(|o| o.get(key))
            .and_then(|v| v.as_str())
            .map(|s| format!("option.Some(\"{}\")", escape_gleam(s)))
            .unwrap_or_else(|| "option.None".to_string())
    };
    let get_int =
        |key: &str, default: i64| -> i64 { obj.and_then(|o| o.get(key)).and_then(|v| v.as_i64()).unwrap_or(default) };

    // output_format: string → Gleam constructor
    let output_format = obj
        .and_then(|o| o.get("output_format"))
        .and_then(|v| v.as_str())
        .map(|s| match s {
            "markdown" => "kreuzberg.OutputFormatMarkdown",
            "html" => "kreuzberg.OutputFormatHtml",
            "djot" => "kreuzberg.Djot",
            "json" => "kreuzberg.Json",
            "structured" => "kreuzberg.Structured",
            "plain" | "" => "kreuzberg.Plain",
            _ => "kreuzberg.Plain",
        })
        .unwrap_or("kreuzberg.Plain");

    // security_limits: optional object → kreuzberg.SecurityLimits(...)
    let security_limits = obj
        .and_then(|o| o.get("security_limits"))
        .and_then(|v| v.as_object())
        .map(|sl| {
            let get_sl_int = |k: &str, def: i64| -> i64 {
                sl.get(k).and_then(|v| v.as_i64()).unwrap_or(def)
            };
            format!(
                "option.Some(kreuzberg.SecurityLimits(max_archive_size: {}, max_compression_ratio: {}, max_files_in_archive: {}, max_nesting_depth: {}, max_entity_length: {}, max_content_size: {}, max_iterations: {}, max_xml_depth: {}, max_table_cells: {}))",
                get_sl_int("max_archive_size", 524_288_000),
                get_sl_int("max_compression_ratio", 100),
                get_sl_int("max_files_in_archive", 10_000),
                get_sl_int("max_nesting_depth", 10),
                get_sl_int("max_entity_length", 8_192),
                get_sl_int("max_content_size", 104_857_600),
                get_sl_int("max_iterations", 1_000_000),
                get_sl_int("max_xml_depth", 100),
                get_sl_int("max_table_cells", 10_000),
            )
        })
        .unwrap_or_else(|| "option.None".to_string());

    let use_cache = get_bool("use_cache", true);
    let enable_quality = get_bool("enable_quality_processing", true);
    let force_ocr = get_bool("force_ocr", false);
    let disable_ocr = get_bool("disable_ocr", false);
    let include_doc_struct = get_bool("include_document_structure", false);
    let max_archive_depth = get_int("max_archive_depth", 10);
    let extraction_timeout_secs = get_opt_int("extraction_timeout_secs");
    let concurrency_str = get_opt_str("concurrency");
    let cache_namespace = get_opt_str("cache_namespace");
    let cache_ttl_secs = get_opt_int("cache_ttl_secs");
    let max_concurrent = get_opt_int("max_concurrent_extractions");
    let html_options = get_opt_str("html_options");

    format!(
        "kreuzberg.ExtractionConfig(use_cache: {use_cache}, enable_quality_processing: {enable_quality}, ocr: option.None, force_ocr: {force_ocr}, force_ocr_pages: option.None, disable_ocr: {disable_ocr}, chunking: option.None, content_filter: option.None, images: option.None, pdf_options: option.None, token_reduction: option.None, language_detection: option.None, pages: option.None, keywords: option.None, postprocessor: option.None, html_options: {html_options}, html_output: option.None, extraction_timeout_secs: {extraction_timeout_secs}, max_concurrent_extractions: {max_concurrent}, result_format: kreuzberg.Unified, security_limits: {security_limits}, output_format: {output_format}, layout: option.None, include_document_structure: {include_doc_struct}, acceleration: option.None, cache_namespace: {cache_namespace}, cache_ttl_secs: {cache_ttl_secs}, email: option.None, concurrency: {concurrency_str}, max_archive_depth: {max_archive_depth}, tree_sitter: option.None, structured_extraction: option.None, cancel_token: option.None)"
    )
}

/// Render an assertion for a field that traverses a tagged-union variant.
///
/// Gleam tagged unions (sum types) require `case` pattern matching — you
/// cannot access a variant's fields via dot syntax on the union type itself.
///
/// For example, `metadata.format.excel.sheet_count` where `format` is
/// `Option(FormatMetadata)` and `FormatMetadata` has an `Excel(ExcelMetadata)`
/// variant, this emits:
///
/// ```gleam
/// case r.metadata.format {
///   option.Some(kreuzberg.Excel(e)) -> e.sheet_count |> option.unwrap(0) |> fn(n__) { n__ >= 2 } |> should.equal(True)
///   _ -> panic as "expected Excel format metadata"
/// }
/// ```
fn render_tagged_union_assertion(
    out: &mut String,
    assertion: &Assertion,
    result_var: &str,
    prefix: &str,
    variant: &str,
    suffix: &str,
    field_resolver: &FieldResolver,
) {
    // Build the accessor for the field up to (but not including) the variant.
    // e.g. prefix="metadata.format" → r.metadata.format
    let prefix_expr = if prefix.is_empty() {
        result_var.to_string()
    } else {
        format!("{result_var}.{prefix}")
    };

    // Gleam constructor name is PascalCase of the variant.
    // e.g. "excel" → "Excel", "email" → "FormatMetadataEmail" etc.
    // The package module is emitted as the module qualifier.
    let constructor = variant.to_pascal_case();
    // module_path is "kreuzberg" — use a fixed qualifier since this is always
    // the kreuzberg package's FormatMetadata type.
    let module_qualifier = "kreuzberg";

    // The inner variable bound to the variant payload.
    let inner_var = "fmt_inner__";

    // Determine whether the suffix field is optional or an array.
    // The resolved full path for the suffix is `{prefix}.{variant}.{suffix}`.
    let full_suffix_path = if prefix.is_empty() {
        format!("{variant}.{suffix}")
    } else {
        format!("{prefix}.{variant}.{suffix}")
    };
    let suffix_is_optional = field_resolver.is_optional(&full_suffix_path);
    let suffix_is_array = field_resolver.is_array(&full_suffix_path);

    // Open the case block.
    let _ = writeln!(out, "  case {prefix_expr} {{");
    let _ = writeln!(
        out,
        "    option.Some({module_qualifier}.{constructor}({inner_var})) -> {{"
    );

    // Build the inner field expression.
    let inner_field_expr = if suffix.is_empty() {
        inner_var.to_string()
    } else {
        format!("{inner_var}.{suffix}")
    };

    // Emit the assertion body inside the Some branch.
    match assertion.assertion_type.as_str() {
        "equals" => {
            if let Some(expected) = &assertion.value {
                let gleam_val = json_to_gleam(expected);
                if suffix_is_optional {
                    let default = default_gleam_value_for_optional(&gleam_val);
                    let _ = writeln!(
                        out,
                        "      {inner_field_expr} |> option.unwrap({default}) |> should.equal({gleam_val})"
                    );
                } else {
                    let _ = writeln!(out, "      {inner_field_expr} |> should.equal({gleam_val})");
                }
            }
        }
        "contains" => {
            if let Some(expected) = &assertion.value {
                let gleam_val = json_to_gleam(expected);
                if suffix_is_array {
                    // List of strings: check any element contains the value.
                    let _ = writeln!(out, "      let items__ = {inner_field_expr} |> option.unwrap([])");
                    let _ = writeln!(
                        out,
                        "      items__ |> list.any(fn(item__) {{ string.contains(item__, {gleam_val}) }}) |> should.equal(True)"
                    );
                } else if suffix_is_optional {
                    let _ = writeln!(
                        out,
                        "      {inner_field_expr} |> option.unwrap(\"\") |> string.contains({gleam_val}) |> should.equal(True)"
                    );
                } else {
                    let _ = writeln!(
                        out,
                        "      {inner_field_expr} |> string.contains({gleam_val}) |> should.equal(True)"
                    );
                }
            }
        }
        "contains_all" => {
            if let Some(values) = &assertion.values {
                if suffix_is_array {
                    // List of strings: for each expected value, check any element contains it.
                    let _ = writeln!(out, "      let items__ = {inner_field_expr} |> option.unwrap([])");
                    for val in values {
                        let gleam_val = json_to_gleam(val);
                        let _ = writeln!(
                            out,
                            "      items__ |> list.any(fn(item__) {{ string.contains(item__, {gleam_val}) }}) |> should.equal(True)"
                        );
                    }
                } else if suffix_is_optional {
                    for val in values {
                        let gleam_val = json_to_gleam(val);
                        let _ = writeln!(
                            out,
                            "      {inner_field_expr} |> option.unwrap(\"\") |> string.contains({gleam_val}) |> should.equal(True)"
                        );
                    }
                } else {
                    for val in values {
                        let gleam_val = json_to_gleam(val);
                        let _ = writeln!(
                            out,
                            "      {inner_field_expr} |> string.contains({gleam_val}) |> should.equal(True)"
                        );
                    }
                }
            }
        }
        "greater_than_or_equal" => {
            if let Some(val) = &assertion.value {
                let gleam_val = json_to_gleam(val);
                if suffix_is_optional {
                    let _ = writeln!(
                        out,
                        "      {inner_field_expr} |> option.unwrap(0) |> fn(n__) {{ n__ >= {gleam_val} }} |> should.equal(True)"
                    );
                } else {
                    let _ = writeln!(
                        out,
                        "      {inner_field_expr} |> fn(n__) {{ n__ >= {gleam_val} }} |> should.equal(True)"
                    );
                }
            }
        }
        "greater_than" => {
            if let Some(val) = &assertion.value {
                let gleam_val = json_to_gleam(val);
                if suffix_is_optional {
                    let _ = writeln!(
                        out,
                        "      {inner_field_expr} |> option.unwrap(0) |> fn(n__) {{ n__ > {gleam_val} }} |> should.equal(True)"
                    );
                } else {
                    let _ = writeln!(
                        out,
                        "      {inner_field_expr} |> fn(n__) {{ n__ > {gleam_val} }} |> should.equal(True)"
                    );
                }
            }
        }
        "less_than" => {
            if let Some(val) = &assertion.value {
                let gleam_val = json_to_gleam(val);
                if suffix_is_optional {
                    let _ = writeln!(
                        out,
                        "      {inner_field_expr} |> option.unwrap(0) |> fn(n__) {{ n__ < {gleam_val} }} |> should.equal(True)"
                    );
                } else {
                    let _ = writeln!(
                        out,
                        "      {inner_field_expr} |> fn(n__) {{ n__ < {gleam_val} }} |> should.equal(True)"
                    );
                }
            }
        }
        "less_than_or_equal" => {
            if let Some(val) = &assertion.value {
                let gleam_val = json_to_gleam(val);
                if suffix_is_optional {
                    let _ = writeln!(
                        out,
                        "      {inner_field_expr} |> option.unwrap(0) |> fn(n__) {{ n__ <= {gleam_val} }} |> should.equal(True)"
                    );
                } else {
                    let _ = writeln!(
                        out,
                        "      {inner_field_expr} |> fn(n__) {{ n__ <= {gleam_val} }} |> should.equal(True)"
                    );
                }
            }
        }
        "count_min" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    if suffix_is_optional {
                        let _ = writeln!(
                            out,
                            "      {inner_field_expr} |> option.unwrap([]) |> list.length |> fn(n__) {{ n__ >= {n} }} |> should.equal(True)"
                        );
                    } else {
                        let _ = writeln!(
                            out,
                            "      {inner_field_expr} |> list.length |> fn(n__) {{ n__ >= {n} }} |> should.equal(True)"
                        );
                    }
                }
            }
        }
        "count_equals" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    if suffix_is_optional {
                        let _ = writeln!(
                            out,
                            "      {inner_field_expr} |> option.unwrap([]) |> list.length |> should.equal({n})"
                        );
                    } else {
                        let _ = writeln!(out, "      {inner_field_expr} |> list.length |> should.equal({n})");
                    }
                }
            }
        }
        "not_empty" => {
            if suffix_is_optional {
                let _ = writeln!(
                    out,
                    "      {inner_field_expr} |> option.unwrap([]) |> list.is_empty |> should.equal(False)"
                );
            } else {
                let _ = writeln!(out, "      {inner_field_expr} |> list.is_empty |> should.equal(False)");
            }
        }
        "is_empty" => {
            if suffix_is_optional {
                let _ = writeln!(
                    out,
                    "      {inner_field_expr} |> option.unwrap([]) |> list.is_empty |> should.equal(True)"
                );
            } else {
                let _ = writeln!(out, "      {inner_field_expr} |> list.is_empty |> should.equal(True)");
            }
        }
        "is_true" => {
            let _ = writeln!(out, "      {inner_field_expr} |> should.equal(True)");
        }
        "is_false" => {
            let _ = writeln!(out, "      {inner_field_expr} |> should.equal(False)");
        }
        other => {
            let _ = writeln!(
                out,
                "      // tagged-union assertion '{other}' not yet implemented for Gleam"
            );
        }
    }

    // Close the Some branch and add wildcard fallback.
    let _ = writeln!(out, "    }}");
    let _ = writeln!(
        out,
        "    _ -> panic as \"expected {module_qualifier}.{constructor} format metadata\""
    );
    let _ = writeln!(out, "  }}");
}

/// Return a sensible Gleam default value for `option.unwrap(default)` based
/// on the type inferred from the JSON expected value string.
fn default_gleam_value_for_optional(gleam_val: &str) -> &'static str {
    if gleam_val.starts_with('"') {
        "\"\""
    } else if gleam_val == "True" || gleam_val == "False" {
        "False"
    } else if gleam_val.contains('.') {
        "0.0"
    } else {
        "0"
    }
}

fn render_assertion(
    out: &mut String,
    assertion: &Assertion,
    result_var: &str,
    field_resolver: &FieldResolver,
    enum_fields: &HashSet<String>,
    result_is_array: bool,
) {
    // Skip assertions on fields that don't exist on the result type.
    if let Some(f) = &assertion.field {
        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
            let _ = writeln!(out, "  // skipped: field '{f}' not available on result type");
            return;
        }
    }

    // Detect tagged-union variant access (e.g., metadata.format.excel.sheet_count).
    // Gleam tagged unions are sum types — direct field access is not valid.
    // Instead, emit a case expression to pattern-match the variant.
    if let Some(f) = &assertion.field {
        if !f.is_empty() {
            if let Some((prefix, variant, suffix)) = field_resolver.tagged_union_split(f) {
                render_tagged_union_assertion(out, assertion, result_var, &prefix, &variant, &suffix, field_resolver);
                return;
            }
        }
    }

    // Detect field paths with an optional prefix segment (e.g. "document.nodes" where
    // "document" is Option(DocumentStructure)). These require a case expression to unwrap.
    if let Some(f) = &assertion.field {
        if !f.is_empty() {
            let parts: Vec<&str> = f.split('.').collect();
            let mut opt_prefix: Option<(String, usize)> = None;
            for i in 1..parts.len() {
                let prefix_path = parts[..i].join(".");
                if field_resolver.is_optional(&prefix_path) {
                    opt_prefix = Some((prefix_path, i));
                    break;
                }
            }
            if let Some((optional_prefix, suffix_start)) = opt_prefix {
                let prefix_expr = format!("{result_var}.{optional_prefix}");
                let suffix_parts = &parts[suffix_start..];
                let suffix_str = suffix_parts.join(".");
                let inner_var = "opt_inner__";
                let inner_expr = if suffix_str.is_empty() {
                    inner_var.to_string()
                } else {
                    format!("{inner_var}.{suffix_str}")
                };
                let _ = writeln!(out, "  case {prefix_expr} {{");
                let _ = writeln!(out, "    option.Some({inner_var}) -> {{");
                match assertion.assertion_type.as_str() {
                    "count_min" => {
                        if let Some(val) = &assertion.value {
                            if let Some(n) = val.as_u64() {
                                let _ = writeln!(
                                    out,
                                    "      {inner_expr} |> list.length |> fn(n__) {{ n__ >= {n} }} |> should.equal(True)"
                                );
                            }
                        }
                    }
                    "count_equals" => {
                        if let Some(val) = &assertion.value {
                            if let Some(n) = val.as_u64() {
                                let _ = writeln!(out, "      {inner_expr} |> list.length |> should.equal({n})");
                            }
                        }
                    }
                    "not_empty" => {
                        let _ = writeln!(out, "      {inner_expr} |> list.is_empty |> should.equal(False)");
                    }
                    "min_length" => {
                        if let Some(val) = &assertion.value {
                            if let Some(n) = val.as_u64() {
                                let _ = writeln!(
                                    out,
                                    "      {inner_expr} |> string.length |> fn(n__) {{ n__ >= {n} }} |> should.equal(True)"
                                );
                            }
                        }
                    }
                    other => {
                        let _ = writeln!(
                            out,
                            "      // optional-prefix assertion '{other}' not yet implemented for Gleam"
                        );
                    }
                }
                let _ = writeln!(out, "    }}");
                let _ = writeln!(out, "    option.None -> should.fail()");
                let _ = writeln!(out, "  }}");
                return;
            }
        }
    }

    // Determine if this field is an optional type (e.g. metadata.output_format).
    // For optional fields, equality comparisons must wrap in option.Some(...).
    let field_is_optional = assertion
        .field
        .as_deref()
        .is_some_and(|f| !f.is_empty() && field_resolver.is_optional(f));

    // Determine if this field is an enum type.
    let _field_is_enum = assertion
        .field
        .as_deref()
        .is_some_and(|f| enum_fields.contains(f) || enum_fields.contains(field_resolver.resolve(f)));

    let field_expr = match &assertion.field {
        Some(f) if !f.is_empty() => field_resolver.accessor(f, "gleam", result_var),
        _ => result_var.to_string(),
    };

    // Check if the field (or root result) is an array for `contains` assertions.
    // When no field is specified (root result) and call config says result_is_array, treat as array.
    let field_is_array = {
        let f = assertion.field.as_deref().unwrap_or("");
        let is_root = f.is_empty();
        (is_root && result_is_array) || field_resolver.is_array(f) || field_resolver.is_array(field_resolver.resolve(f))
    };

    match assertion.assertion_type.as_str() {
        "equals" => {
            if let Some(expected) = &assertion.value {
                let gleam_val = json_to_gleam(expected);
                if field_is_optional {
                    // Option(T) equality — wrap in option.Some().
                    let _ = writeln!(out, "  {field_expr} |> should.equal(option.Some({gleam_val}))");
                } else {
                    let _ = writeln!(out, "  {field_expr} |> should.equal({gleam_val})");
                }
            }
        }
        "contains" => {
            if let Some(expected) = &assertion.value {
                let gleam_val = json_to_gleam(expected);
                if field_is_array {
                    // List(String) — check any element contains the value.
                    let _ = writeln!(
                        out,
                        "  {field_expr} |> list.any(fn(item__) {{ string.contains(item__, {gleam_val}) }}) |> should.equal(True)"
                    );
                } else if field_is_optional {
                    let _ = writeln!(
                        out,
                        "  {field_expr} |> option.unwrap(\"\") |> string.contains({gleam_val}) |> should.equal(True)"
                    );
                } else {
                    let _ = writeln!(
                        out,
                        "  {field_expr} |> string.contains({gleam_val}) |> should.equal(True)"
                    );
                }
            }
        }
        "contains_all" => {
            if let Some(values) = &assertion.values {
                for val in values {
                    let gleam_val = json_to_gleam(val);
                    if field_is_optional {
                        let _ = writeln!(
                            out,
                            "  {field_expr} |> option.unwrap(\"\") |> string.contains({gleam_val}) |> should.equal(True)"
                        );
                    } else {
                        let _ = writeln!(
                            out,
                            "  {field_expr} |> string.contains({gleam_val}) |> should.equal(True)"
                        );
                    }
                }
            }
        }
        "not_contains" => {
            if let Some(expected) = &assertion.value {
                let gleam_val = json_to_gleam(expected);
                let _ = writeln!(
                    out,
                    "  {field_expr} |> string.contains({gleam_val}) |> should.equal(False)"
                );
            }
        }
        "not_empty" => {
            if field_is_optional {
                // Option(T) — check it is Some.
                let _ = writeln!(out, "  {field_expr} |> option.is_some |> should.equal(True)");
            } else {
                let _ = writeln!(out, "  {field_expr} |> list.is_empty |> should.equal(False)");
            }
        }
        "is_empty" => {
            if field_is_optional {
                let _ = writeln!(out, "  {field_expr} |> option.is_none |> should.equal(True)");
            } else {
                let _ = writeln!(out, "  {field_expr} |> list.is_empty |> should.equal(True)");
            }
        }
        "starts_with" => {
            if let Some(expected) = &assertion.value {
                let gleam_val = json_to_gleam(expected);
                let _ = writeln!(
                    out,
                    "  {field_expr} |> string.starts_with({gleam_val}) |> should.equal(True)"
                );
            }
        }
        "ends_with" => {
            if let Some(expected) = &assertion.value {
                let gleam_val = json_to_gleam(expected);
                let _ = writeln!(
                    out,
                    "  {field_expr} |> string.ends_with({gleam_val}) |> should.equal(True)"
                );
            }
        }
        "min_length" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    let _ = writeln!(
                        out,
                        "  {field_expr} |> string.length |> fn(n__) {{ n__ >= {n} }} |> should.equal(True)"
                    );
                }
            }
        }
        "max_length" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    let _ = writeln!(
                        out,
                        "  {field_expr} |> string.length |> fn(n__) {{ n__ <= {n} }} |> should.equal(True)"
                    );
                }
            }
        }
        "count_min" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    let _ = writeln!(
                        out,
                        "  {field_expr} |> list.length |> fn(n__) {{ n__ >= {n} }} |> should.equal(True)"
                    );
                }
            }
        }
        "count_equals" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    let _ = writeln!(out, "  {field_expr} |> list.length |> should.equal({n})");
                }
            }
        }
        "is_true" => {
            let _ = writeln!(out, "  {field_expr} |> should.equal(True)");
        }
        "is_false" => {
            let _ = writeln!(out, "  {field_expr} |> should.equal(False)");
        }
        "not_error" => {
            // Already handled by the call succeeding.
        }
        "error" => {
            // Handled at the test case level.
        }
        "greater_than" => {
            if let Some(val) = &assertion.value {
                let gleam_val = json_to_gleam(val);
                let _ = writeln!(
                    out,
                    "  {field_expr} |> fn(n__) {{ n__ > {gleam_val} }} |> should.equal(True)"
                );
            }
        }
        "less_than" => {
            if let Some(val) = &assertion.value {
                let gleam_val = json_to_gleam(val);
                let _ = writeln!(
                    out,
                    "  {field_expr} |> fn(n__) {{ n__ < {gleam_val} }} |> should.equal(True)"
                );
            }
        }
        "greater_than_or_equal" => {
            if let Some(val) = &assertion.value {
                let gleam_val = json_to_gleam(val);
                let _ = writeln!(
                    out,
                    "  {field_expr} |> fn(n__) {{ n__ >= {gleam_val} }} |> should.equal(True)"
                );
            }
        }
        "less_than_or_equal" => {
            if let Some(val) = &assertion.value {
                let gleam_val = json_to_gleam(val);
                let _ = writeln!(
                    out,
                    "  {field_expr} |> fn(n__) {{ n__ <= {gleam_val} }} |> should.equal(True)"
                );
            }
        }
        "contains_any" => {
            if let Some(values) = &assertion.values {
                let vals_list = values.iter().map(json_to_gleam).collect::<Vec<_>>().join(", ");
                let _ = writeln!(
                    out,
                    "  [{vals_list}] |> list.any(fn(v__) {{ string.contains({field_expr}, v__) }}) |> should.equal(True)"
                );
            }
        }
        "matches_regex" => {
            let _ = writeln!(out, "  // regex match not yet implemented for Gleam");
        }
        "method_result" => {
            let _ = writeln!(out, "  // method_result assertions not yet implemented for Gleam");
        }
        other => {
            panic!("Gleam e2e generator: unsupported assertion type: {other}");
        }
    }
}

/// Convert a `serde_json::Value` to a Gleam literal string.
fn json_to_gleam(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(s) => format!("\"{}\"", escape_gleam(s)),
        serde_json::Value::Bool(b) => {
            if *b {
                "True".to_string()
            } else {
                "False".to_string()
            }
        }
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::Null => "Nil".to_string(),
        serde_json::Value::Array(arr) => {
            let items: Vec<String> = arr.iter().map(json_to_gleam).collect();
            format!("[{}]", items.join(", "))
        }
        serde_json::Value::Object(_) => {
            let json_str = serde_json::to_string(value).unwrap_or_default();
            format!("\"{}\"", escape_gleam(&json_str))
        }
    }
}