muntjac 0.1.0

Translate uv.lock into Buck2 build rules
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
//! Hand-rolled string-writer implementation of `BuckEmitter`.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write;

use super::emit::{BuckEmitter, ConfigName, EmitDeps, EmitInput, EmitOutput, EmitPackage};

pub struct StringTemplateEmitter;

impl BuckEmitter for StringTemplateEmitter {
    fn emit(&self, input: &EmitInput) -> EmitOutput {
        EmitOutput {
            buck: emit_buck(input),
            muntjac_bzl: emit_muntjac_bzl(input),
            config_buck: emit_config_buck(input),
            wiring_bzl: emit_wiring_bzl(input),
        }
    }
}

fn emit_buck(input: &EmitInput) -> String {
    let mut s = String::new();
    writeln!(s, "##").unwrap();
    writeln!(s, "## @generated by muntjac").unwrap();
    writeln!(s, "## Do not edit by hand.").unwrap();
    writeln!(s, "##").unwrap();
    writeln!(s).unwrap();
    writeln!(
        s,
        "load(\"//{}:muntjac.bzl\", \"pypi_package\")",
        input.third_party_dir
    )
    .unwrap();

    // Packages are pre-sorted by (name, version) in EmitInput; defensive sort anyway.
    let mut sorted_pkgs: Vec<&EmitPackage> = input.packages.iter().collect();
    sorted_pkgs.sort_by(|a, b| a.name.cmp(&b.name).then(a.version.cmp(&b.version)));

    for pkg in sorted_pkgs {
        writeln!(s).unwrap();
        write_pypi_package(&mut s, pkg, &input.third_party_dir);
    }
    s
}

fn emit_muntjac_bzl(input: &EmitInput) -> String {
    let mut s = String::new();
    let tpd = &input.third_party_dir;

    // Header: @generated tag + wiring contract for consumers.
    writeln!(s, "##").unwrap();
    writeln!(s, "## @generated by muntjac").unwrap();
    writeln!(s, "##").unwrap();
    writeln!(s, "## Wiring contract for consumers:").unwrap();
    writeln!(s, "##").unwrap();
    writeln!(
        s,
        "##   One-time project setup — add to your root PACKAGE (see"
    )
    .unwrap();
    writeln!(s, "##   {}/wiring.bzl for the full snippet):", tpd).unwrap();
    writeln!(s, "##").unwrap();
    writeln!(
        s,
        "##     load(\"@prelude//cfg/modifier:set_cfg_modifiers.bzl\", \"set_cfg_modifiers\")"
    )
    .unwrap();
    writeln!(
        s,
        "##     load(\"//{}:wiring.bzl\", \"MUNTJAC_HOST_MODIFIERS\")",
        tpd
    )
    .unwrap();
    writeln!(s, "##     # ...plus cfg_constructor loads...").unwrap();
    writeln!(s, "##     set_cfg_constructor(...)").unwrap();
    writeln!(
        s,
        "##     set_cfg_modifiers(cfg_modifiers = MUNTJAC_HOST_MODIFIERS)"
    )
    .unwrap();
    writeln!(s, "##").unwrap();
    writeln!(
        s,
        "##   This registers buck2's cfg_constructor and auto-routes the host"
    )
    .unwrap();
    writeln!(
        s,
        "##   OS+CPU to the matching muntjac platform constraint."
    )
    .unwrap();
    writeln!(s, "##").unwrap();
    writeln!(
        s,
        "##   To pick a python version, set a per-binary modifier or a"
    )
    .unwrap();
    writeln!(s, "##   root-PACKAGE default:").unwrap();
    writeln!(s, "##").unwrap();
    writeln!(s, "##     # per-binary").unwrap();
    writeln!(s, "##     python_binary(").unwrap();
    writeln!(s, "##         name = \"service\",").unwrap();
    writeln!(s, "##         modifiers = [\"//{}/config:py312\"],", tpd).unwrap();
    writeln!(s, "##         deps = [\"//{}:numpy\"],", tpd).unwrap();
    writeln!(s, "##         main = \"main.py\",").unwrap();
    writeln!(s, "##     )").unwrap();
    writeln!(s, "##").unwrap();
    writeln!(s, "##     # root PACKAGE default").unwrap();
    writeln!(s, "##     set_cfg_modifiers([\"//{}/config:py312\"])", tpd).unwrap();
    writeln!(s, "##").unwrap();

    // Available python constraints derived from configs (sorted set).
    let py_constraints: BTreeSet<String> = input
        .configs
        .iter()
        .filter_map(|c| c.as_str().split('-').next().map(|p| p.to_string()))
        .filter(|p| p.starts_with("py"))
        .collect();
    let py_list: Vec<&str> = py_constraints.iter().map(|p| p.as_str()).collect();
    writeln!(
        s,
        "## Available muntjac python constraints: {}",
        py_list.join(", ")
    )
    .unwrap();
    writeln!(s, "##").unwrap();
    writeln!(s).unwrap();

    // _CONFIGS list, sorted lex.
    let mut sorted_configs: Vec<&ConfigName> = input.configs.iter().collect();
    sorted_configs.sort();
    writeln!(s, "_CONFIGS = [").unwrap();
    for cfg in &sorted_configs {
        writeln!(s, "    \"{}\",", cfg).unwrap();
    }
    writeln!(s, "]").unwrap();
    writeln!(s).unwrap();

    // pypi_package macro — uses native.<rule> for http_file, prebuilt_python_library,
    // alias. Replaces expect(...) with explicit if/fail. sha256 stripping handled
    // inside the macro to match uv.lock's "sha256:" prefix convention.
    writeln!(
        s,
        "def pypi_package(name, version, wheels, deps = [], visibility = None, labels = [], overlay_files = [], entry_points = [], runtime_env = {{}}, **kwargs):"
    )
    .unwrap();
    writeln!(
        s,
        "    unknown = [cfg for cfg in wheels.keys() if cfg not in _CONFIGS]"
    )
    .unwrap();
    writeln!(s, "    if unknown:").unwrap();
    writeln!(
        s,
        "        fail(\"unknown config(s) in {{}}: {{}}\".format(name, unknown))"
    )
    .unwrap();
    writeln!(s).unwrap();
    writeln!(
        s,
        "    # Dedup source-target rules by (src, sha): pure-python wheels often span"
    )
    .unwrap();
    writeln!(
        s,
        "    # all cfgs with the same content. Emit one rule per unique tuple, then"
    )
    .unwrap();
    writeln!(
        s,
        "    # N library variants referencing it. Source-target index assignment is"
    )
    .unwrap();
    writeln!(s, "    # deterministic (sorted cfg iteration).").unwrap();
    writeln!(s, "    seen_sources = {{}}").unwrap();
    writeln!(s, "    src_targets = {{}}").unwrap();
    writeln!(s, "    for cfg in sorted(wheels.keys()):").unwrap();
    writeln!(s, "        src, sha256 = wheels[cfg]").unwrap();
    writeln!(s, "        sha = sha256.removeprefix(\"sha256:\")").unwrap();
    writeln!(s, "        key = (src, sha)").unwrap();
    writeln!(s, "        if key in seen_sources:").unwrap();
    writeln!(s, "            src_targets[cfg] = seen_sources[key]").unwrap();
    writeln!(s, "            continue").unwrap();
    writeln!(
        s,
        "        target = \"{{}}-{{}}-src-{{}}\".format(name, version, len(seen_sources))"
    )
    .unwrap();
    writeln!(s, "        seen_sources[key] = target").unwrap();
    writeln!(s, "        src_targets[cfg] = target").unwrap();
    writeln!(s).unwrap();
    writeln!(s, "        if src.startswith(\"prebake:\"):").unwrap();
    writeln!(s, "            rel = src[len(\"prebake:\"):]").unwrap();
    writeln!(s, "            native.export_file(").unwrap();
    writeln!(s, "                name = target,").unwrap();
    writeln!(s, "                src = \"prebake/{{}}\".format(rel),").unwrap();
    writeln!(s, "                visibility = [],").unwrap();
    writeln!(s, "            )").unwrap();
    writeln!(s, "        else:").unwrap();
    writeln!(s, "            native.http_file(").unwrap();
    writeln!(s, "                name = target,").unwrap();
    writeln!(s, "                sha256 = sha,").unwrap();
    writeln!(s, "                urls = [src],").unwrap();
    writeln!(s, "                visibility = [],").unwrap();
    writeln!(s, "            )").unwrap();
    writeln!(s).unwrap();
    writeln!(
        s,
        "    # Overlay (S6): if overlay_files non-empty, build an `__overlaid` rule"
    )
    .unwrap();
    writeln!(
        s,
        "    # that unzips the wheel, copies overlay sources in, and re-zips."
    )
    .unwrap();
    writeln!(
        s,
        "    # The result is a single .whl that replaces every per-cell source."
    )
    .unwrap();
    writeln!(s, "    overlay_label = None").unwrap();
    writeln!(s, "    if overlay_files:").unwrap();
    writeln!(s, "        first_src = sorted(src_targets.values())[0]").unwrap();
    writeln!(
        s,
        "        # Wrap each overlay file in an export_file so genrule's $(location ...)"
    )
    .unwrap();
    writeln!(
        s,
        "        # can resolve to it (buck2 rejects raw file paths inside $(location))."
    )
    .unwrap();
    writeln!(s, "        overlay_targets = []").unwrap();
    writeln!(
        s,
        "        for (i, (path_in_wheel, src_label)) in enumerate(overlay_files):"
    )
    .unwrap();
    writeln!(
        s,
        "            t = \"{{}}-{{}}__overlay-src-{{}}\".format(name, version, i)"
    )
    .unwrap();
    writeln!(s, "            native.export_file(").unwrap();
    writeln!(s, "                name = t,").unwrap();
    writeln!(s, "                src = src_label,").unwrap();
    writeln!(s, "                visibility = [],").unwrap();
    writeln!(s, "            )").unwrap();
    writeln!(s, "            overlay_targets.append((path_in_wheel, t))").unwrap();
    writeln!(s, "        cp_lines = []").unwrap();
    writeln!(s, "        for (path_in_wheel, t) in overlay_targets:").unwrap();
    writeln!(s, "            parent = path_in_wheel.rsplit(\"/\", 1)[0] if \"/\" in path_in_wheel else \".\"").unwrap();
    writeln!(s, "            cp_lines.append(\"mkdir -p _u/\" + parent + \" && cp $(location :\" + t + \") _u/\" + path_in_wheel)").unwrap();
    writeln!(s, "        cp_cmds = \" && \".join(cp_lines)").unwrap();
    writeln!(
        s,
        "        # Genrule cmd runs at the project root. Buck's $(location :X)"
    )
    .unwrap();
    writeln!(
        s,
        "        # expands to a project-root-relative path, so unzip must NOT cd"
    )
    .unwrap();
    writeln!(
        s,
        "        # into _u before invoking it — instead, use `unzip -d _u`. The"
    )
    .unwrap();
    writeln!(
        s,
        "        # final zip is run from inside _u so the archive's entries don't"
    )
    .unwrap();
    writeln!(s, "        # carry the `_u/` prefix.").unwrap();
    writeln!(s, "        cmd_template = (").unwrap();
    writeln!(s, "            \"set -e && mkdir _u && unzip -q -d _u $(location :\" + first_src + \") && \" +").unwrap();
    writeln!(
        s,
        "            cp_cmds + \" && cd _u && zip -qrX ../$OUT . -x '*/RECORD'\""
    )
    .unwrap();
    writeln!(s, "        )").unwrap();
    writeln!(s, "        native.genrule(").unwrap();
    writeln!(
        s,
        "            name = \"{{}}-{{}}__overlaid\".format(name, version),"
    )
    .unwrap();
    writeln!(
        s,
        "            srcs = [\":\" + first_src] + [\":\" + t for (_, t) in overlay_targets],"
    )
    .unwrap();
    writeln!(
        s,
        "            out = \"{{}}-{{}}-overlaid.whl\".format(name, version),"
    )
    .unwrap();
    writeln!(s, "            cmd = cmd_template,").unwrap();
    writeln!(s, "            visibility = [],").unwrap();
    writeln!(s, "        )").unwrap();
    writeln!(
        s,
        "        overlay_label = \":{{}}-{{}}__overlaid\".format(name, version)"
    )
    .unwrap();
    writeln!(s).unwrap();
    writeln!(s, "    for cfg in sorted(wheels.keys()):").unwrap();
    writeln!(s, "        native.prebuilt_python_library(").unwrap();
    writeln!(
        s,
        "            name = \"{{}}-{{}}__{{}}\".format(name, version, cfg),"
    )
    .unwrap();
    writeln!(
        s,
        "            binary_src = overlay_label or \":{{}}\".format(src_targets[cfg]),"
    )
    .unwrap();
    writeln!(s, "            deps = deps,").unwrap();
    writeln!(s, "            visibility = [],").unwrap();
    writeln!(s, "        )").unwrap();
    writeln!(s).unwrap();
    writeln!(s, "    native.alias(").unwrap();
    writeln!(s, "        name = \"{{}}-{{}}\".format(name, version),").unwrap();
    writeln!(s, "        actual = select({{").unwrap();
    writeln!(
        s,
        "            \"//{}/config:{{}}\".format(cfg): \":{{}}-{{}}__{{}}\".format(name, version, cfg)",
        tpd
    )
    .unwrap();
    writeln!(s, "            for cfg in wheels.keys()").unwrap();
    writeln!(s, "        }}),").unwrap();
    writeln!(s, "        visibility = [],").unwrap();
    writeln!(s, "    )").unwrap();
    writeln!(s, "    native.alias(").unwrap();
    writeln!(s, "        name = name,").unwrap();
    writeln!(s, "        actual = \":{{}}-{{}}\".format(name, version),").unwrap();
    writeln!(s, "        visibility = visibility or [\"PUBLIC\"],").unwrap();
    writeln!(s, "    )").unwrap();
    writeln!(s).unwrap();
    writeln!(
        s,
        "    # Entry points (S6): one python_binary + convenience alias per name."
    )
    .unwrap();
    writeln!(
        s,
        "    # main_module uses the standard `<importable>.__main__` convention;"
    )
    .unwrap();
    writeln!(
        s,
        "    # entry points that need a different module require a wheel-meta shim"
    )
    .unwrap();
    writeln!(s, "    # (deferred — see TECH_DEBT TD-S6-03).").unwrap();
    writeln!(s, "    for ep_name in entry_points:").unwrap();
    writeln!(s, "        importable = name.replace(\"-\", \"_\")").unwrap();
    writeln!(s, "        native.python_binary(").unwrap();
    writeln!(
        s,
        "            name = \"{{}}-{{}}__bin-{{}}\".format(name, version, ep_name),"
    )
    .unwrap();
    writeln!(s, "            main_module = importable + \".__main__\",").unwrap();
    writeln!(s, "            deps = [\":\" + name],").unwrap();
    writeln!(s, "            env = runtime_env,").unwrap();
    writeln!(s, "            visibility = visibility or [\"PUBLIC\"],").unwrap();
    writeln!(s, "            labels = labels,").unwrap();
    writeln!(s, "        )").unwrap();
    writeln!(s, "        native.alias(").unwrap();
    writeln!(s, "            name = ep_name,").unwrap();
    writeln!(
        s,
        "            actual = \":{{}}-{{}}__bin-{{}}\".format(name, version, ep_name),"
    )
    .unwrap();
    writeln!(s, "            visibility = visibility or [\"PUBLIC\"],").unwrap();
    writeln!(s, "        )").unwrap();
    s
}

fn emit_config_buck(input: &EmitInput) -> String {
    let mut s = String::new();
    writeln!(s, "##").unwrap();
    writeln!(s, "## @generated by muntjac").unwrap();
    writeln!(s, "## Do not edit by hand.").unwrap();
    writeln!(s, "##").unwrap();
    writeln!(s).unwrap();

    // Derive axes from configs.
    let mut pythons: BTreeSet<&str> = BTreeSet::new();
    let mut platforms: BTreeSet<&str> = BTreeSet::new();
    for cfg in &input.configs {
        // Tokenize "py3XX-<platform>". The "py3XX" prefix is the first '-'-delimited segment.
        let s_cfg = cfg.as_str();
        if let Some(dash) = s_cfg.find('-') {
            pythons.insert(&s_cfg[..dash]);
            platforms.insert(&s_cfg[dash + 1..]);
        }
    }

    // python_version axis — constraint_values get visibility = ["PUBLIC"] because they
    // are referenced from the root PACKAGE via a different cell-relative path.
    writeln!(s, "constraint_setting(name = \"python_version\")").unwrap();
    for py in &pythons {
        writeln!(s, "constraint_value(name = \"{}\", constraint_setting = \":python_version\", visibility = [\"PUBLIC\"])", py).unwrap();
    }
    writeln!(s).unwrap();

    // platform axis — same visibility note.
    writeln!(s, "constraint_setting(name = \"platform\")").unwrap();
    for plat in &platforms {
        writeln!(s, "constraint_value(name = \"{}\", constraint_setting = \":platform\", visibility = [\"PUBLIC\"])", plat).unwrap();
    }
    writeln!(s).unwrap();

    // config_settings — one per cell (= one per ConfigName in input.configs).
    // Also PUBLIC since wiring.bzl's MUNTJAC_HOST_MODIFIERS targets + per-binary
    // modifiers reference these.
    let mut sorted_configs: Vec<&ConfigName> = input.configs.iter().collect();
    sorted_configs.sort();

    for cell in &sorted_configs {
        let s_cell = cell.as_str();
        let dash = s_cell
            .find('-')
            .expect("ConfigName format py<X>-<platform>");
        let py = &s_cell[..dash];
        let plat = &s_cell[dash + 1..];

        // sort constraint_values lex (platform before python alphabetically)
        let mut cvs = vec![plat, py];
        cvs.sort();

        writeln!(s, "config_setting(").unwrap();
        writeln!(s, "    name = \"{}\",", cell).unwrap();
        writeln!(s, "    constraint_values = [").unwrap();
        for cv in &cvs {
            writeln!(s, "        \":{}\",", cv).unwrap();
        }
        writeln!(s, "    ],").unwrap();
        writeln!(s, "    visibility = [\"PUBLIC\"],").unwrap();
        writeln!(s, ")").unwrap();
    }

    s
}

fn emit_wiring_bzl(input: &EmitInput) -> String {
    let mut s = String::new();
    writeln!(s, "##").unwrap();
    writeln!(s, "## @generated by muntjac").unwrap();
    writeln!(s, "## Do not edit by hand.").unwrap();
    writeln!(s, "##").unwrap();
    writeln!(
        s,
        "## Host-axis modifiers for muntjac's per-cell platform constraints."
    )
    .unwrap();
    writeln!(s, "##").unwrap();
    writeln!(
        s,
        "## The user's root PACKAGE loads MUNTJAC_HOST_MODIFIERS and passes it"
    )
    .unwrap();
    writeln!(
        s,
        "## to set_cfg_modifiers() directly. set_cfg_modifiers() cannot be wrapped"
    )
    .unwrap();
    writeln!(
        s,
        "## in a helper function — the prelude enforces that it be called from"
    )
    .unwrap();
    writeln!(s, "## a PACKAGE/BUCK_TREE file, not a .bzl file.").unwrap();
    writeln!(s, "##").unwrap();
    writeln!(
        s,
        "## Wiring contract for consumers — add to your root PACKAGE:"
    )
    .unwrap();
    writeln!(s, "##").unwrap();
    writeln!(s, "##   load(").unwrap();
    writeln!(
        s,
        "##       \"@prelude//cfg/modifier:cfg_constructor.bzl\","
    )
    .unwrap();
    writeln!(s, "##       \"cfg_constructor_post_constraint_analysis\",").unwrap();
    writeln!(s, "##       \"cfg_constructor_pre_constraint_analysis\",").unwrap();
    writeln!(s, "##   )").unwrap();
    writeln!(
        s,
        "##   load(\"@prelude//cfg/modifier:common.bzl\", \"MODIFIER_METADATA_KEY\")"
    )
    .unwrap();
    writeln!(
        s,
        "##   load(\"@prelude//cfg/modifier:set_cfg_modifiers.bzl\", \"set_cfg_modifiers\")"
    )
    .unwrap();
    writeln!(
        s,
        "##   load(\"//{}:wiring.bzl\", \"MUNTJAC_HOST_MODIFIERS\")",
        input.third_party_dir
    )
    .unwrap();
    writeln!(s, "##").unwrap();
    writeln!(s, "##   set_cfg_constructor(").unwrap();
    writeln!(
        s,
        "##       stage0 = cfg_constructor_pre_constraint_analysis,"
    )
    .unwrap();
    writeln!(
        s,
        "##       stage1 = cfg_constructor_post_constraint_analysis,"
    )
    .unwrap();
    writeln!(s, "##       key = MODIFIER_METADATA_KEY,").unwrap();
    writeln!(s, "##       aliases = struct(),").unwrap();
    writeln!(s, "##       extra_data = struct(),").unwrap();
    writeln!(s, "##   )").unwrap();
    writeln!(
        s,
        "##   set_cfg_modifiers(cfg_modifiers = MUNTJAC_HOST_MODIFIERS)"
    )
    .unwrap();
    writeln!(s, "##").unwrap();
    writeln!(s).unwrap();

    // Derive platforms from configs (strip "py3XX-" prefix).
    let mut platforms: BTreeSet<&str> = BTreeSet::new();
    for cfg in &input.configs {
        if let Some((_, plat)) = cfg.as_str().split_once('-') {
            platforms.insert(plat);
        }
    }

    // Group platforms by OS family for nested ModifiersMatch.
    // Keys: "linux"/"macos"; values: Vec<(cpu_constraint, full_platform_name)>.
    // The "linux-x86_64-gnu" platform name parses as os="linux", cpu="x86_64";
    // "macos-arm64" parses as os="macos", cpu="arm64". Platform-name CPU
    // tokens are mapped to the open-source prelude's CPU constraint names —
    // notably "aarch64" (the platform-token used by Rust/PEP 425 tags) maps to
    // the prelude's "arm64" constraint (see prelude/cpu/constraints/BUCK).
    //
    // The "linux-x86_64-musl" (musllinux) case has no corresponding prelude OS
    // constraint, so the emitter SKIPS such platforms — they require user-side
    // --modifier selection rather than auto-routing.
    let mut by_os: BTreeMap<&str, Vec<(&str, &str)>> = BTreeMap::new();
    for p in &platforms {
        let parts: Vec<&str> = p.split('-').collect();
        if parts.len() < 2 {
            continue;
        }
        let os = parts[0];
        // Skip musllinux platforms — the open-source prelude has no
        // `musl` OS constraint, so they can't be auto-routed by host detection.
        if p.ends_with("-musl") {
            continue;
        }
        let cpu_constraint = match parts[1] {
            "aarch64" => "arm64",
            other => other,
        };
        by_os.entry(os).or_default().push((cpu_constraint, *p));
    }

    let total_branches: usize = by_os.values().map(|v| v.len()).sum();
    if total_branches == 0 {
        // All platforms are musllinux (e.g. the 03-musllinux fixture); emit an
        // empty list so the user's root PACKAGE still passes through
        // set_cfg_modifiers cleanly (and the cfg_constructor is registered).
        writeln!(s, "MUNTJAC_HOST_MODIFIERS = []").unwrap();
        return s;
    }

    writeln!(s, "MUNTJAC_HOST_MODIFIERS = [").unwrap();
    writeln!(s, "    {{").unwrap();
    writeln!(s, "        \"_type\": \"ModifiersMatch\",").unwrap();
    for (os, cpus) in &by_os {
        let os_key = format!("prelude//os/constraints:{}", os);
        writeln!(s, "        \"{}\": {{", os_key).unwrap();
        writeln!(s, "            \"_type\": \"ModifiersMatch\",").unwrap();
        let mut cpus_sorted: Vec<&(&str, &str)> = cpus.iter().collect();
        cpus_sorted.sort();
        for (cpu, plat_name) in cpus_sorted {
            let cpu_key = format!("prelude//cpu/constraints:{}", cpu);
            let target = format!("root//{}/config:{}", input.third_party_dir, plat_name);
            writeln!(s, "            \"{}\": \"{}\",", cpu_key, target).unwrap();
        }
        writeln!(s, "        }},").unwrap();
    }
    writeln!(s, "    }},").unwrap();
    writeln!(s, "]").unwrap();
    s
}

fn write_pypi_package(s: &mut String, pkg: &EmitPackage, pkg_third_party_dir: &str) {
    writeln!(s, "pypi_package(").unwrap();
    writeln!(s, "    name = \"{}\",", pkg.name).unwrap();
    writeln!(s, "    version = \"{}\",", pkg.version).unwrap();
    // Task 9: Render deps for Uniform variant (restored from S3).
    // Task 10: PerCell variant fills in select() rendering.
    match &pkg.deps {
        EmitDeps::Uniform(v) => {
            if v.is_empty() {
                writeln!(s, "    deps = [],").unwrap();
            } else {
                writeln!(s, "    deps = [").unwrap();
                for dep in v {
                    writeln!(s, "        \"{}\",", dep).unwrap();
                }
                writeln!(s, "    ],").unwrap();
            }
        }
        EmitDeps::PerCell(per_cell) => {
            writeln!(s, "    deps = select({{").unwrap();
            for (cell, deps_v) in per_cell {
                // select() branch keys are config target labels in the same cell.
                let key = format!("//{}/config:{}", pkg_third_party_dir, cell);
                if deps_v.is_empty() {
                    writeln!(s, "        \"{}\": [],", key).unwrap();
                } else {
                    writeln!(s, "        \"{}\": [", key).unwrap();
                    for d in deps_v {
                        writeln!(s, "            \"{}\",", d).unwrap();
                    }
                    writeln!(s, "        ],").unwrap();
                }
            }
            writeln!(s, "    }}),").unwrap();
        }
    }
    writeln!(s, "    wheels = {{").unwrap();
    for (cfg, wheel) in &pkg.wheels {
        writeln!(
            s,
            "        \"{}\": (\"{}\", \"{}\"),",
            cfg, wheel.url, wheel.hash
        )
        .unwrap();
    }
    writeln!(s, "    }},").unwrap();
    // S6 kwargs: render each only when non-default to keep generated BUCK readable.
    if let Some(overlay) = &pkg.overlay {
        writeln!(s, "    overlay_files = [").unwrap();
        for (in_wheel, src_rel) in &overlay.files {
            writeln!(s, "        (\"{}\", \"{}\"),", in_wheel, src_rel).unwrap();
        }
        writeln!(s, "    ],").unwrap();
    }
    if !pkg.entry_points.is_empty() {
        writeln!(s, "    entry_points = [").unwrap();
        for ep in &pkg.entry_points {
            writeln!(s, "        \"{}\",", ep).unwrap();
        }
        writeln!(s, "    ],").unwrap();
    }
    if !pkg.labels.is_empty() {
        writeln!(s, "    labels = [").unwrap();
        for l in &pkg.labels {
            writeln!(s, "        \"{}\",", l).unwrap();
        }
        writeln!(s, "    ],").unwrap();
    }
    if !pkg.runtime_env.is_empty() {
        writeln!(s, "    runtime_env = {{").unwrap();
        for (k, v) in &pkg.runtime_env {
            writeln!(s, "        \"{}\": \"{}\",", k, v).unwrap();
        }
        writeln!(s, "    }},").unwrap();
    }
    if let Some(vis) = &pkg.visibility {
        writeln!(s, "    visibility = [").unwrap();
        for v in vis {
            writeln!(s, "        \"{}\",", v).unwrap();
        }
        writeln!(s, "    ],").unwrap();
    } else {
        writeln!(s, "    visibility = [\"PUBLIC\"],").unwrap();
    }
    writeln!(s, ")").unwrap();
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::buck::emit::ConfigName;
    use crate::buck::emit::{EmitPackage, EmitWheel};
    use std::collections::BTreeMap;

    fn empty_input() -> EmitInput {
        EmitInput {
            tree: "default".into(),
            third_party_dir: "third-party/python".into(),
            configs: vec![ConfigName::new("3.12", "linux-x86_64-gnu")],
            packages: vec![],
        }
    }

    fn single_package_input() -> EmitInput {
        let cfg = ConfigName::new("3.12", "linux-x86_64-gnu");
        let mut wheels = BTreeMap::new();
        wheels.insert(
            cfg.clone(),
            EmitWheel {
                url: "https://files.pythonhosted.org/p/certifi-2025.4.26-py3-none-any.whl".into(),
                hash: "sha256:0123abcd".into(),
            },
        );
        EmitInput {
            tree: "default".into(),
            third_party_dir: "third-party/python".into(),
            configs: vec![cfg],
            packages: vec![EmitPackage {
                name: "certifi".into(),
                version: "2025.4.26".into(),
                deps: EmitDeps::Uniform(vec![]),
                wheels,
                overlay: None,
                entry_points: vec![],
                visibility: None,
                labels: vec![],
                runtime_env: std::collections::BTreeMap::new(),
            }],
        }
    }

    #[test]
    fn emitter_returns_four_strings() {
        let out = StringTemplateEmitter.emit(&empty_input());
        let _ = out.buck;
        let _ = out.muntjac_bzl;
        let _ = out.config_buck;
        let _ = out.wiring_bzl;
    }

    #[test]
    fn empty_input_buck_has_header_and_load() {
        let out = StringTemplateEmitter.emit(&empty_input());
        assert!(
            out.buck
                .starts_with("##\n## @generated by muntjac\n## Do not edit by hand.\n##\n\n"),
            "missing or malformed BUCK header:\n{}",
            out.buck
        );
        assert!(
            out.buck
                .contains(r#"load("//third-party/python:muntjac.bzl", "pypi_package")"#),
            "missing or wrong load() line:\n{}",
            out.buck
        );
    }

    #[test]
    fn single_package_buck_contains_pypi_package_call() {
        let out = StringTemplateEmitter.emit(&single_package_input());
        assert!(out.buck.contains("pypi_package("));
        assert!(out.buck.contains(r#"name = "certifi""#));
        assert!(out.buck.contains(r#"version = "2025.4.26""#));
        assert!(out.buck.contains(r#""py312-linux-x86_64-gnu":"#));
        assert!(out.buck.contains("sha256:0123abcd"));
        assert!(out.buck.contains(r#"visibility = ["PUBLIC"]"#));
    }

    #[test]
    fn muntjac_bzl_has_header_and_configs_list() {
        let out = StringTemplateEmitter.emit(&empty_input());
        assert!(
            out.muntjac_bzl
                .starts_with("##\n## @generated by muntjac\n##\n"),
            "missing muntjac.bzl header:\n{}",
            out.muntjac_bzl
        );
        // S4: header now includes the wiring contract for consumers.
        assert!(
            out.muntjac_bzl
                .contains("## Wiring contract for consumers:"),
            "missing wiring contract block:\n{}",
            out.muntjac_bzl
        );
        assert!(out.muntjac_bzl.contains("MUNTJAC_HOST_MODIFIERS"));
        assert!(out.muntjac_bzl.contains("set_cfg_modifiers"));
        assert!(out.muntjac_bzl.contains("_CONFIGS = ["));
        assert!(out.muntjac_bzl.contains("    \"py312-linux-x86_64-gnu\","));
        assert!(out.muntjac_bzl.contains("def pypi_package("));
        // S4: native.<rule> form, no bogus load()s.
        assert!(out.muntjac_bzl.contains("native.prebuilt_python_library"));
        assert!(out.muntjac_bzl.contains("native.http_file"));
        assert!(!out.muntjac_bzl.contains("expect("));
        assert!(out.muntjac_bzl.contains("if unknown:"));
        assert!(out.muntjac_bzl.contains("//third-party/python/config:"));
    }

    #[test]
    fn muntjac_bzl_configs_list_sorted_lex() {
        let mut input = empty_input();
        input.configs = vec![
            ConfigName::new("3.12", "linux-x86_64-gnu"),
            ConfigName::new("3.11", "linux-x86_64-gnu"),
        ];
        let out = StringTemplateEmitter.emit(&input);
        let p311 = out
            .muntjac_bzl
            .find("\"py311-linux-x86_64-gnu\"")
            .expect("py311 missing");
        let p312 = out
            .muntjac_bzl
            .find("\"py312-linux-x86_64-gnu\"")
            .expect("py312 missing");
        assert!(p311 < p312, "_CONFIGS not sorted:\n{}", out.muntjac_bzl);
    }

    #[test]
    fn config_buck_declares_per_cell_settings() {
        let mut input = empty_input();
        input.configs = vec![
            ConfigName::new("3.11", "linux-x86_64-gnu"),
            ConfigName::new("3.12", "linux-x86_64-gnu"),
        ];
        let out = StringTemplateEmitter.emit(&input);
        assert!(
            out.config_buck
                .starts_with("##\n## @generated by muntjac\n## Do not edit by hand.\n##\n\n"),
            "missing config/BUCK header:\n{}",
            out.config_buck
        );
        assert!(out.config_buck.contains("config_setting("));
        assert!(
            out.config_buck
                .contains(r#"name = "py311-linux-x86_64-gnu""#)
        );
        assert!(
            out.config_buck
                .contains(r#"name = "py312-linux-x86_64-gnu""#)
        );
        assert!(
            out.config_buck
                .contains(r#"constraint_setting(name = "python_version")"#)
        );
        assert!(
            out.config_buck
                .contains(r#"constraint_value(name = "py311""#)
        );
        assert!(
            out.config_buck
                .contains(r#"constraint_value(name = "py312""#)
        );
        assert!(
            out.config_buck
                .contains(r#"constraint_setting(name = "platform")"#)
        );
        assert!(
            out.config_buck
                .contains(r#"constraint_value(name = "linux-x86_64-gnu""#)
        );
    }

    #[test]
    fn config_buck_settings_sorted_by_name() {
        let mut input = empty_input();
        input.configs = vec![
            ConfigName::new("3.12", "linux-x86_64-gnu"),
            ConfigName::new("3.11", "linux-x86_64-gnu"),
        ];
        let out = StringTemplateEmitter.emit(&input);
        let p311 = out
            .config_buck
            .find(r#"name = "py311-linux-x86_64-gnu""#)
            .expect("py311 missing");
        let p312 = out
            .config_buck
            .find(r#"name = "py312-linux-x86_64-gnu""#)
            .expect("py312 missing");
        assert!(
            p311 < p312,
            "config_settings must be sorted:\n{}",
            out.config_buck
        );
    }

    #[test]
    fn wiring_bzl_has_header_and_host_modifiers() {
        let out = StringTemplateEmitter.emit(&empty_input());
        assert!(
            out.wiring_bzl
                .starts_with("##\n## @generated by muntjac\n## Do not edit by hand.\n##\n"),
            "missing wiring.bzl header:\n{}",
            out.wiring_bzl
        );
        assert!(
            out.wiring_bzl.contains("MUNTJAC_HOST_MODIFIERS"),
            "wiring.bzl should export MUNTJAC_HOST_MODIFIERS"
        );
        assert!(
            out.wiring_bzl.contains("set_cfg_modifiers"),
            "wiring.bzl docstring should reference set_cfg_modifiers"
        );
        assert!(
            out.wiring_bzl.contains("set_cfg_constructor"),
            "wiring.bzl docstring should reference set_cfg_constructor"
        );
    }

    #[test]
    fn two_packages_emitted_alphabetically() {
        let mut input = single_package_input();
        let mut wheels = BTreeMap::new();
        wheels.insert(
            input.configs[0].clone(),
            EmitWheel {
                url: "https://example.com/alpha-1.0-py3-none-any.whl".into(),
                hash: "sha256:aaaa".into(),
            },
        );
        input.packages.insert(
            0,
            EmitPackage {
                name: "alpha".into(),
                version: "1.0".into(),
                deps: EmitDeps::Uniform(vec![]),
                wheels,
                overlay: None,
                entry_points: vec![],
                visibility: None,
                labels: vec![],
                runtime_env: std::collections::BTreeMap::new(),
            },
        );
        let out = StringTemplateEmitter.emit(&input);
        let alpha_pos = out
            .buck
            .find("name = \"alpha\"")
            .expect("alpha not emitted");
        let certifi_pos = out
            .buck
            .find("name = \"certifi\"")
            .expect("certifi not emitted");
        assert!(
            alpha_pos < certifi_pos,
            "alpha must precede certifi in output:\n{}",
            out.buck
        );
    }

    fn multi_package_input() -> EmitInput {
        let cfg_311 = ConfigName::new("3.11", "linux-x86_64-gnu");
        let cfg_312 = ConfigName::new("3.12", "linux-x86_64-gnu");

        let mut requests_wheels = BTreeMap::new();
        requests_wheels.insert(
            cfg_311.clone(),
            EmitWheel {
                url: "https://example.com/requests-2.32.3-py3-none-any.whl".into(),
                hash: "sha256:rrrr".into(),
            },
        );
        requests_wheels.insert(
            cfg_312.clone(),
            EmitWheel {
                url: "https://example.com/requests-2.32.3-py3-none-any.whl".into(),
                hash: "sha256:rrrr".into(),
            },
        );

        let mut idna_wheels = BTreeMap::new();
        idna_wheels.insert(
            cfg_311.clone(),
            EmitWheel {
                url: "https://example.com/idna-3.7-py3-none-any.whl".into(),
                hash: "sha256:iiii".into(),
            },
        );
        idna_wheels.insert(
            cfg_312.clone(),
            EmitWheel {
                url: "https://example.com/idna-3.7-py3-none-any.whl".into(),
                hash: "sha256:iiii".into(),
            },
        );

        EmitInput {
            tree: "default".into(),
            third_party_dir: "third-party/python".into(),
            configs: vec![cfg_311, cfg_312],
            packages: vec![
                EmitPackage {
                    name: "idna".into(),
                    version: "3.7".into(),
                    deps: EmitDeps::Uniform(vec![]),
                    wheels: idna_wheels,
                    overlay: None,
                    entry_points: vec![],
                    visibility: None,
                    labels: vec![],
                    runtime_env: std::collections::BTreeMap::new(),
                },
                EmitPackage {
                    name: "requests".into(),
                    version: "2.32.3".into(),
                    deps: EmitDeps::Uniform(vec![":idna".into()]),
                    wheels: requests_wheels,
                    overlay: None,
                    entry_points: vec![],
                    visibility: None,
                    labels: vec![],
                    runtime_env: std::collections::BTreeMap::new(),
                },
            ],
        }
    }

    #[test]
    fn snapshot_empty_buck() {
        insta::assert_snapshot!(StringTemplateEmitter.emit(&empty_input()).buck);
    }

    #[test]
    fn snapshot_empty_muntjac_bzl() {
        insta::assert_snapshot!(StringTemplateEmitter.emit(&empty_input()).muntjac_bzl);
    }

    #[test]
    fn snapshot_empty_config_buck() {
        insta::assert_snapshot!(StringTemplateEmitter.emit(&empty_input()).config_buck);
    }

    #[test]
    fn wiring_bzl_emits_host_modifiers_for_three_platforms() {
        use crate::buck::emit::{ConfigName, EmitInput};

        let input = EmitInput {
            tree: "default".into(),
            third_party_dir: "third-party/python".into(),
            configs: vec![
                ConfigName::new("3.11", "linux-aarch64-gnu"),
                ConfigName::new("3.11", "linux-x86_64-gnu"),
                ConfigName::new("3.11", "macos-arm64"),
                ConfigName::new("3.12", "linux-aarch64-gnu"),
                ConfigName::new("3.12", "linux-x86_64-gnu"),
                ConfigName::new("3.12", "macos-arm64"),
            ],
            packages: vec![],
        };

        let out = StringTemplateEmitter.emit(&input);
        insta::assert_snapshot!("wiring_bzl_three_platforms", out.wiring_bzl);
    }

    #[test]
    fn wiring_bzl_emits_host_modifiers_for_single_platform() {
        use crate::buck::emit::{ConfigName, EmitInput};

        let input = EmitInput {
            tree: "default".into(),
            third_party_dir: "third-party/python".into(),
            configs: vec![
                ConfigName::new("3.11", "linux-x86_64-gnu"),
                ConfigName::new("3.12", "linux-x86_64-gnu"),
            ],
            packages: vec![],
        };

        let out = StringTemplateEmitter.emit(&input);
        insta::assert_snapshot!("wiring_bzl_single_platform", out.wiring_bzl);
    }

    #[test]
    fn wiring_bzl_emits_empty_host_modifiers_for_musllinux_only() {
        use crate::buck::emit::{ConfigName, EmitInput};

        let input = EmitInput {
            tree: "default".into(),
            third_party_dir: "third-party/python".into(),
            configs: vec![ConfigName::new("3.12", "linux-x86_64-musl")],
            packages: vec![],
        };

        let out = StringTemplateEmitter.emit(&input);
        insta::assert_snapshot!("wiring_bzl_musllinux_only", out.wiring_bzl);
    }

    #[test]
    fn snapshot_single_package_buck() {
        insta::assert_snapshot!(StringTemplateEmitter.emit(&single_package_input()).buck);
    }

    #[test]
    fn snapshot_multi_package_buck() {
        insta::assert_snapshot!(StringTemplateEmitter.emit(&multi_package_input()).buck);
    }

    #[test]
    fn snapshot_multi_package_muntjac_bzl() {
        insta::assert_snapshot!(
            StringTemplateEmitter
                .emit(&multi_package_input())
                .muntjac_bzl
        );
    }

    #[test]
    fn snapshot_multi_package_config_buck() {
        insta::assert_snapshot!(
            StringTemplateEmitter
                .emit(&multi_package_input())
                .config_buck
        );
    }

    #[test]
    fn renders_per_cell_deps_as_select() {
        let cells: Vec<ConfigName> = vec![
            ConfigName::new("3.11", "linux-x86_64-gnu"),
            ConfigName::new("3.12", "linux-x86_64-gnu"),
        ];

        let mut per_cell: BTreeMap<ConfigName, Vec<String>> = BTreeMap::new();
        per_cell.insert(
            cells[0].clone(),
            vec![":foo".into(), ":typing-extensions".into()],
        );
        per_cell.insert(cells[1].clone(), vec![":foo".into()]);

        let mut wheels: BTreeMap<ConfigName, EmitWheel> = BTreeMap::new();
        for cell in &cells {
            wheels.insert(
                cell.clone(),
                EmitWheel {
                    url: format!("https://example.com/rich-13.0-{}.whl", cell),
                    hash: "sha256:rich".into(),
                },
            );
        }

        let input = EmitInput {
            tree: "default".into(),
            third_party_dir: "third-party/python".into(),
            configs: cells,
            packages: vec![EmitPackage {
                name: "rich".into(),
                version: "13.0".into(),
                deps: EmitDeps::PerCell(per_cell),
                wheels,
                overlay: None,
                entry_points: vec![],
                visibility: None,
                labels: vec![],
                runtime_env: std::collections::BTreeMap::new(),
            }],
        };

        let out = StringTemplateEmitter.emit(&input);
        insta::assert_snapshot!("per_cell_deps_select", out.buck);
    }

    #[test]
    fn muntjac_bzl_emits_full_macro_with_header() {
        let input = EmitInput {
            tree: "default".into(),
            third_party_dir: "third-party/python".into(),
            configs: vec![
                ConfigName::new("3.11", "linux-x86_64-gnu"),
                ConfigName::new("3.12", "linux-x86_64-gnu"),
            ],
            packages: vec![],
        };

        let out = StringTemplateEmitter.emit(&input);
        insta::assert_snapshot!("muntjac_bzl_with_header_and_native", out.muntjac_bzl);
    }

    #[test]
    fn renders_uniform_deps_as_plain_list() {
        let cell = ConfigName::new("3.12", "linux-x86_64-gnu");
        let mut wheels: BTreeMap<ConfigName, EmitWheel> = BTreeMap::new();
        wheels.insert(
            cell.clone(),
            EmitWheel {
                url: "https://example.com/requests-2.32.3-py3-none-any.whl".into(),
                hash: "sha256:req".into(),
            },
        );

        let input = EmitInput {
            tree: "default".into(),
            third_party_dir: "third-party/python".into(),
            configs: vec![cell],
            packages: vec![EmitPackage {
                name: "requests".into(),
                version: "2.32.3".into(),
                deps: EmitDeps::Uniform(vec![":certifi".into(), ":idna".into()]),
                wheels,
                overlay: None,
                entry_points: vec![],
                visibility: None,
                labels: vec![],
                runtime_env: std::collections::BTreeMap::new(),
            }],
        };

        let out = StringTemplateEmitter.emit(&input);
        insta::assert_snapshot!("uniform_deps_plain_list", out.buck);
    }

    #[test]
    fn config_buck_emits_multi_platform_constraints() {
        let input = EmitInput {
            tree: "default".into(),
            third_party_dir: "third-party/python".into(),
            configs: vec![
                ConfigName::new("3.11", "linux-aarch64-gnu"),
                ConfigName::new("3.11", "linux-x86_64-gnu"),
                ConfigName::new("3.11", "macos-arm64"),
                ConfigName::new("3.12", "linux-aarch64-gnu"),
                ConfigName::new("3.12", "linux-x86_64-gnu"),
                ConfigName::new("3.12", "macos-arm64"),
            ],
            packages: vec![],
        };

        let out = StringTemplateEmitter.emit(&input);
        insta::assert_snapshot!("config_buck_six_cells", out.config_buck);
    }

    #[test]
    fn buck_render_emits_prebake_url_verbatim() {
        let cfg = ConfigName::new("3.12", "linux-x86_64-gnu");
        let mut wheels = BTreeMap::new();
        wheels.insert(
            cfg.clone(),
            EmitWheel {
                url: "prebake:tomli-2.0.1-py3-none-any.whl".to_string(),
                hash: "sha256:cafef00d".to_string(),
            },
        );
        let input = EmitInput {
            tree: "default".to_string(),
            third_party_dir: "third-party/python".to_string(),
            configs: vec![cfg],
            packages: vec![EmitPackage {
                name: "tomli".to_string(),
                version: "2.0.1".to_string(),
                deps: EmitDeps::Uniform(vec![]),
                wheels,
                overlay: None,
                entry_points: vec![],
                visibility: None,
                labels: vec![],
                runtime_env: std::collections::BTreeMap::new(),
            }],
        };
        let writer = StringTemplateEmitter;
        let out = writer.emit(&input);
        assert!(
            out.buck
                .contains("\"prebake:tomli-2.0.1-py3-none-any.whl\""),
            "BUCK output should contain prebake URL verbatim:\n{}",
            out.buck
        );
    }

    #[test]
    fn macro_definition_includes_overlay_and_entry_points_branches() {
        let input = empty_input(); // no packages; just check the bzl text
        let out = StringTemplateEmitter.emit(&input);
        // New kwargs in signature.
        assert!(
            out.muntjac_bzl.contains("overlay_files = []"),
            "macro signature should include overlay_files = [] kwarg"
        );
        assert!(
            out.muntjac_bzl.contains("entry_points = []"),
            "macro signature should include entry_points = [] kwarg"
        );
        assert!(
            out.muntjac_bzl.contains("labels = []"),
            "macro signature should include labels = [] kwarg"
        );
        assert!(
            out.muntjac_bzl.contains("runtime_env"),
            "macro signature should include runtime_env kwarg"
        );
        // Overlay branch: must reference unzip + zip and emit a genrule.
        assert!(
            out.muntjac_bzl.contains("if overlay_files"),
            "expected overlay branch (`if overlay_files:`)"
        );
        assert!(
            out.muntjac_bzl.contains("native.genrule"),
            "expected native.genrule for overlay"
        );
        assert!(
            out.muntjac_bzl.contains("unzip"),
            "expected unzip in overlay cmd"
        );
        assert!(
            out.muntjac_bzl.contains("zip -qrX"),
            "expected zip -qrX in overlay cmd (deterministic, strips timestamps)"
        );
        assert!(
            out.muntjac_bzl.contains("RECORD"),
            "expected RECORD exclusion in overlay cmd"
        );
        // Entry-points branch: must emit python_binary per name.
        assert!(
            out.muntjac_bzl.contains("for ep_name in entry_points"),
            "expected entry_points loop"
        );
        assert!(
            out.muntjac_bzl.contains("native.python_binary"),
            "expected python_binary for entry points"
        );
        assert!(
            out.muntjac_bzl.contains(".__main__"),
            "expected __main__ convention in main_module"
        );
    }

    #[test]
    fn per_package_call_site_renders_non_default_kwargs_only() {
        use crate::buck::emit::{EmitDeps, EmitOverlay, EmitPackage, EmitWheel};

        let cfg = ConfigName::new("3.12", "linux-x86_64-gnu");
        let mut wheels = BTreeMap::new();
        wheels.insert(
            cfg.clone(),
            EmitWheel {
                url: "https://example.com/fake-pillow-1.0-py3-none-any.whl".into(),
                hash: "sha256:fakehash".into(),
            },
        );

        let mut runtime_env = BTreeMap::new();
        runtime_env.insert("LIBJPEG_PATH".into(), "/opt/libjpeg/lib".into());

        let input = EmitInput {
            tree: "default".into(),
            third_party_dir: "third-party/python".into(),
            configs: vec![cfg],
            packages: vec![EmitPackage {
                name: "fake-pillow".into(),
                version: "1.0.0".into(),
                deps: EmitDeps::Uniform(vec![]),
                wheels,
                overlay: Some(EmitOverlay {
                    files: vec![(
                        "fake_pillow/_paths.py".into(),
                        "fixups/fake-pillow/overlay/fake_pillow/_paths.py".into(),
                    )],
                }),
                entry_points: vec!["fake-pillow-cli".into()],
                visibility: Some(vec!["//apps/imaging/...".into()]),
                labels: vec!["security-sensitive".into()],
                runtime_env,
            }],
        };
        let out = StringTemplateEmitter.emit(&input);

        // Required: each non-default field renders as a kwarg in the BUCK pypi_package call.
        assert!(
            out.buck.contains("overlay_files = ["),
            "missing overlay_files kwarg:\n{}",
            out.buck
        );
        assert!(
            out.buck.contains("\"fake_pillow/_paths.py\""),
            "missing overlay in_wheel path"
        );
        assert!(
            out.buck
                .contains("\"fixups/fake-pillow/overlay/fake_pillow/_paths.py\""),
            "missing overlay src path"
        );
        assert!(
            out.buck.contains("entry_points = ["),
            "missing entry_points kwarg"
        );
        assert!(
            out.buck.contains("\"fake-pillow-cli\""),
            "missing entry-point name"
        );
        assert!(
            out.buck.contains("visibility = ["),
            "missing visibility kwarg"
        );
        assert!(
            out.buck.contains("\"//apps/imaging/...\""),
            "missing visibility entry"
        );
        assert!(out.buck.contains("labels = ["), "missing labels kwarg");
        assert!(out.buck.contains("\"security-sensitive\""), "missing label");
        assert!(
            out.buck.contains("runtime_env = {"),
            "missing runtime_env kwarg"
        );
        assert!(
            out.buck.contains("\"LIBJPEG_PATH\""),
            "missing runtime_env key"
        );
        assert!(
            out.buck.contains("\"/opt/libjpeg/lib\""),
            "missing runtime_env value"
        );
    }

    #[test]
    fn per_package_call_site_omits_default_kwargs() {
        // single_package_input() helper creates a package with all-defaults
        // for the T10 fields (overlay: None, entry_points: vec![], etc.).
        let input = single_package_input();
        let out = StringTemplateEmitter.emit(&input);

        // Verifies the writer doesn't emit empty kwargs when the field is at default.
        assert!(
            !out.buck.contains("overlay_files"),
            "should not emit overlay_files when None"
        );
        assert!(
            !out.buck.contains("entry_points = ["),
            "should not emit entry_points kwarg when empty"
        );
        assert!(
            !out.buck.contains("labels = ["),
            "should not emit labels kwarg when empty"
        );
        assert!(
            !out.buck.contains("runtime_env = {"),
            "should not emit runtime_env kwarg when empty"
        );
    }

    #[test]
    fn macro_overlay_rebinds_binary_src() {
        let input = empty_input();
        let out = StringTemplateEmitter.emit(&input);
        // The per-cell prebuilt_python_library should use `overlay_label or :{src}`
        // pattern so overlay'd packages bind to the genrule output.
        assert!(
            out.muntjac_bzl.contains("overlay_label or "),
            "binary_src must conditionally use overlay_label:\n{}",
            out.muntjac_bzl
        );
    }
}