flutmax-codegen 0.1.1

Code generator: analyzed graph -> .maxpat JSON
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
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
/// .maxpat JSON generation
///
/// Generate a `.maxpat` JSON string that Max/MSP can load from a `PatchGraph`.
/// Conforms to the schema defined in experiment E01.
use std::collections::HashMap;

use flutmax_sema::graph::{PatchGraph, PatchNode};
use serde_json::{json, Map, Value};

use crate::layout::sugiyama_layout;

/// UI layout and decorative attribute data from .uiflutmax sidecar file.
pub struct UiData {
    /// Patcher-level settings (window rect, etc.)
    pub patcher: HashMap<String, Value>,
    /// Per-wire UI data: wire_name -> { "rect": [...], "background": 0, ... }
    pub entries: HashMap<String, Value>,
    /// Comment boxes with text and position for .maxpat reconstruction.
    pub comments: Vec<Value>,
    /// Visual-only panel boxes for .maxpat reconstruction.
    pub panels: Vec<Value>,
    /// Visual-only image boxes (fpic) for .maxpat reconstruction.
    pub images: Vec<Value>,
}

impl UiData {
    /// Parse a .uiflutmax JSON string into UiData.
    /// Returns None if the JSON is invalid or not an object.
    pub fn from_json(json_str: &str) -> Option<Self> {
        let root: Value = serde_json::from_str(json_str).ok()?;
        let obj = root.as_object()?;

        let mut patcher = HashMap::new();
        let mut entries = HashMap::new();

        let comments = obj
            .get("_comments")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();
        let panels = obj
            .get("_panels")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();
        let images = obj
            .get("_images")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();

        for (key, value) in obj {
            if key == "_patcher" {
                if let Some(inner) = value.as_object() {
                    for (k, v) in inner {
                        patcher.insert(k.clone(), v.clone());
                    }
                }
            } else if key == "_comments" || key == "_panels" || key == "_images" {
                // Already parsed above
            } else {
                entries.insert(key.clone(), value.clone());
            }
        }

        Some(UiData {
            patcher,
            entries,
            comments,
            panels,
            images,
        })
    }
}

/// Code generation error
#[derive(Debug)]
pub enum CodegenError {
    /// JSON serialization failed
    Serialization(String),
}

impl std::fmt::Display for CodegenError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CodegenError::Serialization(msg) => write!(f, "codegen error: {}", msg),
        }
    }
}

impl std::error::Error for CodegenError {}

// ─── Layout constants ───

const LAYOUT_X: f64 = 100.0;
const LAYOUT_Y_START: f64 = 50.0;
const LAYOUT_Y_STEP: f64 = 70.0;

const BOX_WIDTH_INLET_OUTLET: f64 = 30.0;
const BOX_HEIGHT_INLET_OUTLET: f64 = 30.0;
const BOX_WIDTH_NEWOBJ: f64 = 80.0;
const BOX_HEIGHT_NEWOBJ: f64 = 22.0;
const BOX_WIDTH_EZDAC: f64 = 45.0;
const BOX_HEIGHT_EZDAC: f64 = 45.0;

/// Options for .maxpat generation.
pub struct GenerateOptions {
    /// Patcher classnamespace: "box" (standard Max) or "rnbo" (RNBO subset).
    pub classnamespace: String,
}

impl Default for GenerateOptions {
    fn default() -> Self {
        Self {
            classnamespace: "box".to_string(),
        }
    }
}

/// Generate a .maxpat JSON string from a PatchGraph.
pub fn generate(graph: &PatchGraph) -> Result<String, CodegenError> {
    generate_with_options(graph, &GenerateOptions::default())
}

/// Generate a .maxpat JSON string from a PatchGraph (with options).
pub fn generate_with_options(
    graph: &PatchGraph,
    opts: &GenerateOptions,
) -> Result<String, CodegenError> {
    generate_with_ui(graph, opts, None)
}

/// Generate a .maxpat JSON string from a PatchGraph (with UiData).
///
/// When `ui_data` is provided, position and decoration attributes loaded from .uiflutmax
/// are reflected in the generated .maxpat. When None, automatic layout is used.
pub fn generate_with_ui(
    graph: &PatchGraph,
    opts: &GenerateOptions,
    ui_data: Option<&UiData>,
) -> Result<String, CodegenError> {
    let patcher = build_patcher(graph, opts, ui_data)?;
    let root = json!({ "patcher": patcher });
    serde_json::to_string_pretty(&root).map_err(|e| CodegenError::Serialization(e.to_string()))
}

/// Build the patcher object.
fn build_patcher(
    graph: &PatchGraph,
    opts: &GenerateOptions,
    ui_data: Option<&UiData>,
) -> Result<Value, CodegenError> {
    let is_rnbo = opts.classnamespace == "rnbo";
    let is_gen = opts.classnamespace == "dsp.gen";
    let needs_port_indices = is_rnbo || is_gen;
    let ordered_nodes = topological_order(graph);

    // RNBO/gen~ mode: pre-calculate inlet/outlet port indices
    let inlet_indices: HashMap<String, usize> = if needs_port_indices {
        let mut control_idx = 0usize;
        let mut signal_idx = 0usize;
        let mut map = HashMap::new();
        for node in &ordered_nodes {
            match node.object_name.as_str() {
                "inlet" => {
                    map.insert(node.id.clone(), control_idx);
                    control_idx += 1;
                }
                "inlet~" => {
                    map.insert(node.id.clone(), signal_idx);
                    signal_idx += 1;
                }
                _ => {}
            }
        }
        map
    } else {
        HashMap::new()
    };

    let outlet_indices: HashMap<String, usize> = if needs_port_indices {
        let mut control_idx = 0usize;
        let mut signal_idx = 0usize;
        let mut map = HashMap::new();
        for node in &ordered_nodes {
            match node.object_name.as_str() {
                "outlet" => {
                    map.insert(node.id.clone(), control_idx);
                    control_idx += 1;
                }
                "outlet~" => {
                    map.insert(node.id.clone(), signal_idx);
                    signal_idx += 1;
                }
                _ => {}
            }
        }
        map
    } else {
        HashMap::new()
    };

    // Node ID -> sequential ID mapping ("obj-1", "obj-2", ...)
    let mut id_map: HashMap<String, String> = HashMap::new();
    for (i, node) in ordered_nodes.iter().enumerate() {
        id_map.insert(node.id.clone(), format!("obj-{}", i + 1));
    }

    // Sugiyama auto-layout
    let layout = sugiyama_layout(graph);

    // Box generation
    let classnamespace = opts.classnamespace.as_str();
    let mut boxes: Vec<Value> = ordered_nodes
        .iter()
        .enumerate()
        .map(|(i, node)| {
            let mapped_id = format!("obj-{}", i + 1);
            let (x, y) = layout
                .positions
                .get(&node.id)
                .copied()
                .unwrap_or((LAYOUT_X, LAYOUT_Y_START + (i as f64) * LAYOUT_Y_STEP));
            let serial = i + 1; // rnbo_serial: 1-based monotonically increasing
            let port_index = inlet_indices
                .get(&node.id)
                .or_else(|| outlet_indices.get(&node.id))
                .copied();
            build_box(
                node,
                &BoxContext {
                    id: &mapped_id,
                    x,
                    y,
                    classnamespace,
                    serial,
                    port_index,
                    ui_data,
                },
            )
        })
        .collect();

    // Append visual-only boxes from UI data (comments, panels, images)
    if let Some(ui) = ui_data {
        let mut visual_counter = ordered_nodes.len() + 1;

        // Restore comment boxes
        for comment in &ui.comments {
            let rect = comment
                .get("rect")
                .cloned()
                .unwrap_or(json!([50, 50, 200, 20]));
            let text = comment.get("text").and_then(|t| t.as_str()).unwrap_or("");
            let id = format!("obj-{}", visual_counter);
            visual_counter += 1;
            boxes.push(json!({
                "box": {
                    "id": id,
                    "maxclass": "comment",
                    "text": text,
                    "numinlets": 1,
                    "numoutlets": 0,
                    "outlettype": [],
                    "patching_rect": rect,
                }
            }));
        }

        // Restore panel boxes
        for panel in &ui.panels {
            let rect = panel
                .get("rect")
                .cloned()
                .unwrap_or(json!([50, 50, 200, 200]));
            let id = format!("obj-{}", visual_counter);
            visual_counter += 1;
            let mut box_obj = serde_json::Map::new();
            box_obj.insert("id".into(), json!(id));
            box_obj.insert("maxclass".into(), json!("panel"));
            box_obj.insert("numinlets".into(), json!(1));
            box_obj.insert("numoutlets".into(), json!(0));
            box_obj.insert("outlettype".into(), json!([]));
            box_obj.insert("patching_rect".into(), rect);
            // Restore panel attributes
            if let Some(obj) = panel.as_object() {
                for (k, v) in obj {
                    if k != "rect" {
                        box_obj.insert(k.clone(), v.clone());
                    }
                }
            }
            boxes.push(json!({ "box": Value::Object(box_obj) }));
        }

        // Restore image boxes (fpic)
        for image in &ui.images {
            let rect = image
                .get("rect")
                .cloned()
                .unwrap_or(json!([50, 50, 200, 200]));
            let pic = image.get("pic").and_then(|p| p.as_str()).unwrap_or("");
            let id = format!("obj-{}", visual_counter);
            visual_counter += 1;
            let mut box_obj = serde_json::Map::new();
            box_obj.insert("id".into(), json!(id));
            box_obj.insert("maxclass".into(), json!("fpic"));
            box_obj.insert("numinlets".into(), json!(1));
            box_obj.insert("numoutlets".into(), json!(1));
            box_obj.insert("outlettype".into(), json!(["jit_matrix"]));
            box_obj.insert("patching_rect".into(), rect);
            if !pic.is_empty() {
                box_obj.insert("pic".into(), json!(pic));
            }
            boxes.push(json!({ "box": Value::Object(box_obj) }));
        }

        // Suppress unused variable warning
        let _ = visual_counter;
    }

    // Line generation
    let lines: Vec<Value> = graph
        .edges
        .iter()
        .map(|edge| {
            let source_id = id_map
                .get(&edge.source_id)
                .cloned()
                .unwrap_or_else(|| edge.source_id.clone());
            let dest_id = id_map
                .get(&edge.dest_id)
                .cloned()
                .unwrap_or_else(|| edge.dest_id.clone());
            let mut patchline = serde_json::Map::new();
            patchline.insert("source".into(), json!([source_id, edge.source_outlet]));
            patchline.insert("destination".into(), json!([dest_id, edge.dest_inlet]));
            if let Some(order) = edge.order {
                patchline.insert("order".into(), json!(order));
            }
            json!({ "patchline": Value::Object(patchline) })
        })
        .collect();

    // Combine fixed template + dynamic fields
    let mut patcher = Map::new();
    patcher.insert("fileversion".into(), json!(1));
    patcher.insert(
        "appversion".into(),
        json!({
            "major": 8,
            "minor": 6,
            "revision": 0,
            "architecture": "x64",
            "modernui": 1
        }),
    );
    patcher.insert("classnamespace".into(), json!(&opts.classnamespace));
    // Use patcher rect from UI data if available, otherwise derive from Sugiyama layout
    let patcher_rect = ui_data
        .and_then(|ui| ui.patcher.get("rect"))
        .cloned()
        .unwrap_or_else(|| {
            json!([
                100.0,
                100.0,
                layout.patcher_size.0.max(640.0),
                layout.patcher_size.1.max(480.0)
            ])
        });
    patcher.insert("rect".into(), patcher_rect);
    patcher.insert("bglocked".into(), json!(0));
    patcher.insert("openinpresentation".into(), json!(0));
    patcher.insert("default_fontsize".into(), json!(12.0));
    patcher.insert("default_fontface".into(), json!(0));
    patcher.insert("default_fontname".into(), json!("Arial"));
    patcher.insert("gridonopen".into(), json!(1));
    patcher.insert("gridsize".into(), json!([15.0, 15.0]));
    patcher.insert("gridsnaponopen".into(), json!(1));
    patcher.insert("objectsnaponopen".into(), json!(1));
    patcher.insert("statusbarvisible".into(), json!(2));
    patcher.insert("toolbarvisible".into(), json!(1));
    patcher.insert("lefttoolbarpinned".into(), json!(0));
    patcher.insert("toptoolbarpinned".into(), json!(0));
    patcher.insert("righttoolbarpinned".into(), json!(0));
    patcher.insert("bottomtoolbarpinned".into(), json!(0));
    patcher.insert("toolbars_unpinned_last_save".into(), json!(0));
    patcher.insert("tallnewobj".into(), json!(0));
    patcher.insert("boxanimatetime".into(), json!(200));
    patcher.insert("enablehscroll".into(), json!(1));
    patcher.insert("enablevscroll".into(), json!(1));
    patcher.insert("devicewidth".into(), json!(0.0));
    patcher.insert("description".into(), json!(""));
    patcher.insert("digest".into(), json!(""));
    patcher.insert("tags".into(), json!(""));
    patcher.insert("style".into(), json!(""));
    patcher.insert("subpatcher_template".into(), json!(""));
    patcher.insert("assistshowspatchername".into(), json!(0));
    patcher.insert("boxes".into(), Value::Array(boxes));
    patcher.insert("lines".into(), Value::Array(lines));
    patcher.insert("dependency_cache".into(), json!([]));
    patcher.insert("autosave".into(), json!(0));

    Ok(Value::Object(patcher))
}

/// Layout and rendering context for generating a box.
struct BoxContext<'a> {
    id: &'a str,
    x: f64,
    y: f64,
    classnamespace: &'a str,
    serial: usize,
    port_index: Option<usize>,
    ui_data: Option<&'a UiData>,
}

/// Generate box JSON from a PatchNode.
fn build_box(node: &PatchNode, ctx: &BoxContext) -> Value {
    let is_rnbo = ctx.classnamespace == "rnbo";
    let is_gen = ctx.classnamespace == "dsp.gen";
    let (maxclass, width, height) = classify_maxclass(node, ctx.classnamespace);
    let outlettype = compute_outlettype(node, is_rnbo, is_gen);

    // RNBO mode: outlet/outport has numoutlets=0 (sink)
    // gen~ mode: `out N` has numoutlets=0 (sink)
    // RNBO inlet/inlet~ boxes expose a single outlet on the host side.
    let effective_num_outlets =
        if (is_rnbo || is_gen) && matches!(node.object_name.as_str(), "outlet" | "outlet~") {
            0
        } else if is_rnbo && matches!(node.object_name.as_str(), "inlet" | "inlet~") {
            1
        } else {
            node.num_outlets
        };

    // RNBO inlet/outlet boxes always present a single inlet on the host side.
    let effective_num_inlets = if is_rnbo
        && matches!(
            node.object_name.as_str(),
            "inlet" | "inlet~" | "outlet" | "outlet~"
        ) {
        1
    } else {
        node.num_inlets
    };

    let mut box_obj = Map::new();
    box_obj.insert("id".into(), json!(ctx.id));
    box_obj.insert("maxclass".into(), json!(maxclass));
    box_obj.insert("numinlets".into(), json!(effective_num_inlets));
    box_obj.insert("numoutlets".into(), json!(effective_num_outlets));

    if !outlettype.is_empty() {
        box_obj.insert("outlettype".into(), json!(outlettype));
    }

    box_obj.insert("patching_rect".into(), json!([ctx.x, ctx.y, width, height]));

    // text field: for newobj and message
    if maxclass == "newobj" {
        let text = if is_rnbo {
            // RNBO mode: inlet/outlet → inport/outport or in~/out~ text
            match node.object_name.as_str() {
                "inlet" => {
                    let name = node
                        .varname
                        .clone()
                        .unwrap_or_else(|| format!("port_{}", ctx.port_index.unwrap_or(0)));
                    format!("inport {}", name)
                }
                "inlet~" => {
                    let idx = ctx.port_index.unwrap_or(0) + 1; // RNBO uses 1-based
                    format!("in~ {}", idx)
                }
                "outlet" => {
                    let name = node
                        .varname
                        .clone()
                        .unwrap_or_else(|| format!("port_{}", ctx.port_index.unwrap_or(0)));
                    format!("outport {}", name)
                }
                "outlet~" => {
                    let idx = ctx.port_index.unwrap_or(0) + 1; // RNBO uses 1-based
                    format!("out~ {}", idx)
                }
                _ => {
                    let mut t = build_object_text(node);
                    if !node.attrs.is_empty() {
                        let attr_str: String = node
                            .attrs
                            .iter()
                            .map(|(k, v)| format!("@{} {}", k, v))
                            .collect::<Vec<_>>()
                            .join(" ");
                        t = format!("{} {}", t, attr_str);
                    }
                    t
                }
            }
        } else if is_gen {
            // gen~ mode: inlet/outlet → `in N` / `out N` (1-based)
            match node.object_name.as_str() {
                "inlet" | "inlet~" => {
                    let idx = ctx.port_index.unwrap_or(0) + 1; // gen~ uses 1-based
                    format!("in {}", idx)
                }
                "outlet" | "outlet~" => {
                    let idx = ctx.port_index.unwrap_or(0) + 1; // gen~ uses 1-based
                    format!("out {}", idx)
                }
                "history" => {
                    // gen~ history needs an explicit name. If the user didn't
                    // pass one as a literal first arg, synthesize one from the
                    // node id (or varname) so the resulting patch is valid.
                    let first_arg_is_name = node
                        .args
                        .first()
                        .map(|a| a.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_'))
                        .unwrap_or(false);
                    let mut t = if first_arg_is_name {
                        build_object_text(node)
                    } else {
                        let name = node.varname.clone().unwrap_or_else(|| {
                            let suffix = node.id.trim_start_matches(|c: char| !c.is_ascii_digit());
                            if suffix.is_empty() {
                                format!("h_{}", node.id.replace('-', "_"))
                            } else {
                                format!("h_{}", suffix)
                            }
                        });
                        if node.args.is_empty() {
                            format!("history {}", name)
                        } else {
                            format!("history {} {}", name, node.args.join(" "))
                        }
                    };
                    if !node.attrs.is_empty() {
                        let attr_str: String = node
                            .attrs
                            .iter()
                            .map(|(k, v)| format!("@{} {}", k, v))
                            .collect::<Vec<_>>()
                            .join(" ");
                        t = format!("{} {}", t, attr_str);
                    }
                    t
                }
                _ => {
                    let mut t = build_object_text(node);
                    if !node.attrs.is_empty() {
                        let attr_str: String = node
                            .attrs
                            .iter()
                            .map(|(k, v)| format!("@{} {}", k, v))
                            .collect::<Vec<_>>()
                            .join(" ");
                        t = format!("{} {}", t, attr_str);
                    }
                    t
                }
            }
        } else {
            let mut t = build_object_text(node);
            // newobj: append .attr() attributes as @key value to text
            if !node.attrs.is_empty() {
                let attr_str: String = node
                    .attrs
                    .iter()
                    .map(|(k, v)| format!("@{} {}", k, v))
                    .collect::<Vec<_>>()
                    .join(" ");
                t = format!("{} {}", t, attr_str);
            }
            t
        };
        box_obj.insert("text".into(), json!(text));
    } else if maxclass == "message" {
        // message box: text uses the content (args[0]) as-is
        let text = if node.args.is_empty() {
            String::new()
        } else {
            node.args.join(" ")
        };
        box_obj.insert("text".into(), json!(text));
    }

    // varname: output flutmax wire name as Max varname attribute
    if let Some(ref vn) = node.varname {
        box_obj.insert("varname".into(), json!(vn));
    }

    // UI objects (non-newobj): output .attr() attributes as top-level fields in box JSON
    if maxclass != "newobj" && !node.attrs.is_empty() {
        for (key, value) in &node.attrs {
            // Output as number if parseable, otherwise as string
            if let Ok(f) = value.parse::<f64>() {
                box_obj.insert(key.clone(), json!(f));
            } else {
                box_obj.insert(key.clone(), json!(value));
            }
        }
    }

    // Codebox: emit code field and special attributes
    if matches!(maxclass, "v8.codebox" | "codebox") {
        if let Some(ref code) = node.code {
            box_obj.insert("code".into(), json!(code));
        }
        if maxclass == "v8.codebox" {
            box_obj.insert("filename".into(), json!("none"));
            // v8.codebox uses empty text (code is in the code field)
            if !box_obj.contains_key("text") {
                box_obj.insert("text".into(), json!(""));
            }
        }
    }

    // .uiflutmax UI data: override position and add decorative attributes
    if let Some(ui_entry) = ctx
        .ui_data
        .and_then(|ui| node.varname.as_ref().and_then(|vn| ui.entries.get(vn)))
    {
        // Override position from UI data
        if let Some(rect) = ui_entry.get("rect") {
            box_obj.insert("patching_rect".into(), rect.clone());
        }
        // Add decorative attributes (everything except "rect")
        if let Some(obj) = ui_entry.as_object() {
            for (k, v) in obj {
                if k != "rect" {
                    box_obj.insert(k.clone(), v.clone());
                }
            }
        }
    }

    // RNBO mode: add rnbo_serial and rnbo_uniqueid
    if is_rnbo {
        box_obj.insert("rnbo_serial".into(), json!(ctx.serial));
        box_obj.insert(
            "rnbo_uniqueid".into(),
            json!(format!(
                "{}_{}",
                node.object_name.replace('~', "_tilde"),
                ctx.id
            )),
        );
    }

    json!({ "box": Value::Object(box_obj) })
}

/// Determine maxclass from PatchNode object_name.
/// Returns: (maxclass, width, height)
fn classify_maxclass(node: &PatchNode, classnamespace: &str) -> (&'static str, f64, f64) {
    let is_rnbo = classnamespace == "rnbo";
    let is_gen = classnamespace == "dsp.gen";
    match node.object_name.as_str() {
        "inlet" | "inlet~" if is_rnbo || is_gen => ("newobj", BOX_WIDTH_NEWOBJ, BOX_HEIGHT_NEWOBJ),
        "outlet" | "outlet~" if is_rnbo || is_gen => {
            ("newobj", BOX_WIDTH_NEWOBJ, BOX_HEIGHT_NEWOBJ)
        }
        "inlet" => ("inlet", BOX_WIDTH_INLET_OUTLET, BOX_HEIGHT_INLET_OUTLET),
        "inlet~" => ("inlet", BOX_WIDTH_INLET_OUTLET, BOX_HEIGHT_INLET_OUTLET),
        "outlet" => ("outlet", BOX_WIDTH_INLET_OUTLET, BOX_HEIGHT_INLET_OUTLET),
        "outlet~" => ("outlet", BOX_WIDTH_INLET_OUTLET, BOX_HEIGHT_INLET_OUTLET),
        "ezdac~" => ("ezdac~", BOX_WIDTH_EZDAC, BOX_HEIGHT_EZDAC),
        "message" => ("message", 50.0, 22.0),
        "button" => ("button", 50.0, 50.0),
        "flonum" => ("flonum", 80.0, 22.0),
        "number" => ("number", 50.0, 22.0),
        "toggle" => ("toggle", 20.0, 20.0),
        "umenu" => ("umenu", 100.0, 22.0),
        "panel" => ("panel", 100.0, 50.0),
        "jsui" => ("jsui", 64.0, 64.0),
        // Additional UI objects
        "textbutton" => ("textbutton", 100.0, 20.0),
        "live.text" => ("live.text", 44.0, 15.0),
        "live.dial" => ("live.dial", 47.0, 48.0),
        "live.toggle" => ("live.toggle", 15.0, 15.0),
        "live.menu" => ("live.menu", 100.0, 15.0),
        "live.numbox" => ("live.numbox", 44.0, 15.0),
        "live.tab" => ("live.tab", 100.0, 20.0),
        "live.comment" => ("live.comment", 100.0, 18.0),
        "slider" => ("slider", 20.0, 140.0),
        "dial" => ("dial", 40.0, 40.0),
        "multislider" => ("multislider", 120.0, 100.0),
        "kslider" => ("kslider", 168.0, 53.0),
        "tab" => ("tab", 200.0, 24.0),
        "rslider" => ("rslider", 100.0, 22.0),
        "filtergraph~" => ("filtergraph~", 256.0, 128.0),
        "spectroscope~" => ("spectroscope~", 300.0, 100.0),
        "scope~" => ("scope~", 130.0, 130.0),
        "meter~" => ("meter~", 13.0, 80.0),
        "gain~" => ("gain~", 22.0, 140.0),
        "ezadc~" => ("ezadc~", BOX_WIDTH_EZDAC, BOX_HEIGHT_EZDAC),
        "number~" => ("number~", 56.0, 22.0),
        "bpatcher" => ("bpatcher", 128.0, 128.0),
        "fpic" => ("fpic", 100.0, 100.0),
        "textedit" => ("textedit", 100.0, 22.0),
        "attrui" => ("attrui", 150.0, 22.0),
        "nslider" => ("nslider", 50.0, 120.0),
        "preset" => ("preset", 100.0, 40.0),
        // Codebox objects
        "v8.codebox" => ("v8.codebox", 200.0, 100.0),
        "codebox" => ("codebox", 200.0, 100.0),
        _ => ("newobj", BOX_WIDTH_NEWOBJ, BOX_HEIGHT_NEWOBJ),
    }
}

/// Compute the outlettype array for an object.
fn compute_outlettype(node: &PatchNode, is_rnbo: bool, is_gen: bool) -> Vec<&'static str> {
    // RNBO mode: outlet/outport is a sink, so no outlettype
    // gen~ mode: `out N` is a sink, so no outlettype
    if (is_rnbo || is_gen) && matches!(node.object_name.as_str(), "outlet" | "outlet~") {
        return vec![];
    }

    if node.num_outlets == 0 {
        return vec![];
    }

    match node.object_name.as_str() {
        // RNBO mode: inport (control inlet) → outlettype = [""]
        "inlet" if is_rnbo => vec![""],
        // RNBO mode: in~ (signal inlet) → outlettype = ["signal"]
        "inlet~" if is_rnbo => vec!["signal"],

        // gen~ mode: `in N` (all I/O is signal) → outlettype = [""]
        "inlet" | "inlet~" if is_gen => vec![""],

        // inlet/inlet~ has one outlettype
        "inlet" => vec![""],
        "inlet~" => vec!["signal"],

        // message box
        "message" => vec![""],

        // UI objects
        "button" => vec!["bang"],
        "toggle" => vec!["int"],
        "umenu" => vec!["int", "", ""],
        "flonum" => vec!["", "bang"],
        "number" => vec!["", "bang"],
        "textbutton" => vec!["", "", "int"],
        "live.text" => vec!["", ""],
        "live.dial" => vec!["", ""],
        "live.toggle" => vec![""],
        "live.menu" => vec!["", "", ""],
        "live.numbox" => vec!["", ""],
        "live.tab" => vec!["", "", ""],
        "live.comment" => vec![],
        "slider" => vec![""],
        "dial" => vec![""],
        "multislider" => vec!["", ""],
        "kslider" => vec!["", ""],
        "tab" => vec!["", "", ""],
        "rslider" => vec!["", ""],
        "bpatcher" => {
            // bpatcher outlet count depends on the patch. Use node.num_outlets
            vec![""; node.num_outlets as usize]
        }

        // Signal objects: all outlets are "signal"
        name if name.ends_with('~') => {
            let mut types = vec!["signal"];
            // For objects like line~ with 2+ outlets: the last may be "bang"
            if name == "line~" && node.num_outlets >= 2 {
                types = vec!["signal", "bang"];
            }
            // Keep as-is if already sufficient, otherwise pad with signal
            while types.len() < node.num_outlets as usize {
                types.push("signal");
            }
            types.truncate(node.num_outlets as usize);
            types
        }

        // Codebox objects
        "v8.codebox" | "codebox" => {
            vec![""; node.num_outlets as usize]
        }

        // Control objects
        "trigger" | "t" => {
            // trigger outlet types depend on arg types; simplified to "" padding
            vec![""; node.num_outlets as usize]
        }

        _ => {
            // Use "signal" when is_signal is set (e.g., for Abstractions)
            if node.is_signal {
                vec!["signal"; node.num_outlets as usize]
            } else {
                // Default: set all outlets to "" (generic message)
                vec![""; node.num_outlets as usize]
            }
        }
    }
}

/// Generate object text from a PatchNode.
/// e.g., object_name="cycle~", args=["440"] -> "cycle~ 440"
fn build_object_text(node: &PatchNode) -> String {
    if node.args.is_empty() {
        node.object_name.clone()
    } else {
        format!("{} {}", node.object_name, node.args.join(" "))
    }
}

/// Sort nodes in topological order.
/// inlet -> processing objects -> outlet order.
/// Not a full topological sort; a simplified classification-based reordering.
fn topological_order(graph: &PatchGraph) -> Vec<&PatchNode> {
    let mut inlets: Vec<&PatchNode> = Vec::new();
    let mut outlets: Vec<&PatchNode> = Vec::new();
    let mut others: Vec<&PatchNode> = Vec::new();

    for node in &graph.nodes {
        match node.object_name.as_str() {
            "inlet" | "inlet~" => inlets.push(node),
            "outlet" | "outlet~" => outlets.push(node),
            _ => others.push(node),
        }
    }

    // Maintain original order within each category
    let mut result = Vec::with_capacity(graph.nodes.len());
    result.extend(inlets);
    result.extend(others);
    result.extend(outlets);
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use flutmax_sema::graph::{NodePurity, PatchEdge, PatchNode};

    /// Minimal graph: cycle~ 440 -> ezdac~
    fn make_minimal_graph() -> PatchGraph {
        let mut g = PatchGraph::new();
        g.add_node(PatchNode {
            id: "osc".into(),
            object_name: "cycle~".into(),
            args: vec!["440".into()],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });
        g.add_node(PatchNode {
            id: "dac".into(),
            object_name: "ezdac~".into(),
            args: vec![],
            num_inlets: 2,
            num_outlets: 0,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });
        g.add_edge(PatchEdge {
            source_id: "osc".into(),
            source_outlet: 0,
            dest_id: "dac".into(),
            dest_inlet: 0,
            is_feedback: false,
            order: None,
        });
        g.add_edge(PatchEdge {
            source_id: "osc".into(),
            source_outlet: 0,
            dest_id: "dac".into(),
            dest_inlet: 1,
            is_feedback: false,
            order: None,
        });
        g
    }

    /// Graph: inlet -> cycle~ -> *~ -> outlet~
    fn make_l2_graph() -> PatchGraph {
        let mut g = PatchGraph::new();
        g.add_node(PatchNode {
            id: "in_freq".into(),
            object_name: "inlet".into(),
            args: vec![],
            num_inlets: 0,
            num_outlets: 1,
            is_signal: false,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });
        g.add_node(PatchNode {
            id: "cycle".into(),
            object_name: "cycle~".into(),
            args: vec![],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });
        g.add_node(PatchNode {
            id: "mul".into(),
            object_name: "*~".into(),
            args: vec!["0.5".into()],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });
        g.add_node(PatchNode {
            id: "out_audio".into(),
            object_name: "outlet~".into(),
            args: vec![],
            num_inlets: 1,
            num_outlets: 0,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });
        g.add_edge(PatchEdge {
            source_id: "in_freq".into(),
            source_outlet: 0,
            dest_id: "cycle".into(),
            dest_inlet: 0,
            is_feedback: false,
            order: None,
        });
        g.add_edge(PatchEdge {
            source_id: "cycle".into(),
            source_outlet: 0,
            dest_id: "mul".into(),
            dest_inlet: 0,
            is_feedback: false,
            order: None,
        });
        g.add_edge(PatchEdge {
            source_id: "mul".into(),
            source_outlet: 0,
            dest_id: "out_audio".into(),
            dest_inlet: 0,
            is_feedback: false,
            order: None,
        });
        g
    }

    #[test]
    fn test_generate_valid_json() {
        let graph = make_minimal_graph();
        let json_str = generate(&graph).unwrap();

        // Must be parseable JSON
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        assert!(parsed.is_object());
        assert!(parsed.get("patcher").is_some());
    }

    #[test]
    fn test_patcher_fixed_fields() {
        let graph = make_minimal_graph();
        let json_str = generate(&graph).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let patcher = parsed.get("patcher").unwrap();

        assert_eq!(patcher["fileversion"], 1);
        assert_eq!(patcher["appversion"]["major"], 8);
        assert_eq!(patcher["appversion"]["minor"], 6);
        assert_eq!(patcher["classnamespace"], "box");
        assert_eq!(patcher["default_fontname"], "Arial");
        assert_eq!(patcher["autosave"], 0);
    }

    #[test]
    fn test_boxes_count() {
        let graph = make_minimal_graph();
        let json_str = generate(&graph).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();
        assert_eq!(boxes.len(), 2);
    }

    #[test]
    fn test_box_structure() {
        let graph = make_minimal_graph();
        let json_str = generate(&graph).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();

        // cycle~ box
        let cycle_box = &boxes[0]["box"];
        assert_eq!(cycle_box["id"], "obj-1");
        assert_eq!(cycle_box["maxclass"], "newobj");
        assert_eq!(cycle_box["numinlets"], 2);
        assert_eq!(cycle_box["numoutlets"], 1);
        assert_eq!(cycle_box["text"], "cycle~ 440");
        let outlettype = cycle_box["outlettype"].as_array().unwrap();
        assert_eq!(outlettype.len(), 1);
        assert_eq!(outlettype[0], "signal");

        // ezdac~ box
        let dac_box = &boxes[1]["box"];
        assert_eq!(dac_box["id"], "obj-2");
        assert_eq!(dac_box["maxclass"], "ezdac~");
        assert_eq!(dac_box["numinlets"], 2);
        assert_eq!(dac_box["numoutlets"], 0);
        // ezdac~ has no outlettype (0 outlets)
        assert!(dac_box.get("outlettype").is_none());
    }

    #[test]
    fn test_lines_count() {
        let graph = make_minimal_graph();
        let json_str = generate(&graph).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let lines = parsed["patcher"]["lines"].as_array().unwrap();
        assert_eq!(lines.len(), 2);
    }

    #[test]
    fn test_line_structure() {
        let graph = make_minimal_graph();
        let json_str = generate(&graph).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let lines = parsed["patcher"]["lines"].as_array().unwrap();

        // Both have source "obj-1" (cycle~), dest "obj-2" (ezdac~)
        for line in lines {
            let patchline = &line["patchline"];
            let source = patchline["source"].as_array().unwrap();
            let dest = patchline["destination"].as_array().unwrap();

            assert_eq!(source[0], "obj-1");
            assert_eq!(source[1], 0);
            assert_eq!(dest[0], "obj-2");
            // dest_inlet is 0 or 1
            let inlet = dest[1].as_u64().unwrap();
            assert!(inlet == 0 || inlet == 1);
        }
    }

    #[test]
    fn test_patching_rect_layout() {
        let graph = make_minimal_graph();
        let json_str = generate(&graph).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();

        let rect0 = boxes[0]["box"]["patching_rect"].as_array().unwrap();
        let rect1 = boxes[1]["box"]["patching_rect"].as_array().unwrap();

        // Sugiyama layout: linear chain → both at same x column
        let x0 = rect0[0].as_f64().unwrap();
        let x1 = rect1[0].as_f64().unwrap();
        assert_eq!(x0, x1, "linear chain nodes should share the same x");

        // Y increases sequentially (osc in layer 0, dac in layer 1)
        let y0 = rect0[1].as_f64().unwrap();
        let y1 = rect1[1].as_f64().unwrap();
        assert!(y1 > y0, "downstream node should have larger y");
    }

    #[test]
    fn test_l2_topological_order() {
        let graph = make_l2_graph();
        let json_str = generate(&graph).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();

        // Topological order: inlet -> cycle~ -> *~ -> outlet~
        assert_eq!(boxes[0]["box"]["maxclass"], "inlet");
        assert_eq!(boxes[1]["box"]["text"], "cycle~");
        assert_eq!(boxes[2]["box"]["text"], "*~ 0.5");
        assert_eq!(boxes[3]["box"]["maxclass"], "outlet");
    }

    #[test]
    fn test_inlet_outlettype() {
        let graph = make_l2_graph();
        let json_str = generate(&graph).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();

        // inlet outlettype is [""]
        let inlet_box = &boxes[0]["box"];
        assert_eq!(inlet_box["maxclass"], "inlet");
        let outlettype = inlet_box["outlettype"].as_array().unwrap();
        assert_eq!(outlettype.len(), 1);
        assert_eq!(outlettype[0], "");
    }

    #[test]
    fn test_outlet_tilde_maxclass() {
        let graph = make_l2_graph();
        let json_str = generate(&graph).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();

        // outlet~ maxclass is "outlet~"
        let outlet_box = &boxes[3]["box"];
        assert_eq!(outlet_box["maxclass"], "outlet");
        assert_eq!(outlet_box["numinlets"], 1);
        assert_eq!(outlet_box["numoutlets"], 0);
    }

    #[test]
    fn test_empty_graph() {
        let graph = PatchGraph::new();
        let json_str = generate(&graph).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();

        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();
        let lines = parsed["patcher"]["lines"].as_array().unwrap();
        assert_eq!(boxes.len(), 0);
        assert_eq!(lines.len(), 0);
    }

    #[test]
    fn test_dependency_cache_empty() {
        let graph = make_minimal_graph();
        let json_str = generate(&graph).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();

        let dep_cache = parsed["patcher"]["dependency_cache"].as_array().unwrap();
        assert_eq!(dep_cache.len(), 0);
    }

    #[test]
    fn test_build_object_text_no_args() {
        let node = PatchNode {
            id: "test".into(),
            object_name: "cycle~".into(),
            args: vec![],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        assert_eq!(build_object_text(&node), "cycle~");
    }

    #[test]
    fn test_build_object_text_with_args() {
        let node = PatchNode {
            id: "test".into(),
            object_name: "cycle~".into(),
            args: vec!["440".into()],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        assert_eq!(build_object_text(&node), "cycle~ 440");
    }

    #[test]
    fn test_build_object_text_multiple_args() {
        let node = PatchNode {
            id: "test".into(),
            object_name: "trigger".into(),
            args: vec!["b".into(), "b".into(), "b".into()],
            num_inlets: 1,
            num_outlets: 3,
            is_signal: false,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        assert_eq!(build_object_text(&node), "trigger b b b");
    }

    #[test]
    fn test_classify_maxclass_inlet() {
        let node = PatchNode {
            id: "test".into(),
            object_name: "inlet".into(),
            args: vec![],
            num_inlets: 0,
            num_outlets: 1,
            is_signal: false,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        let (maxclass, _, _) = classify_maxclass(&node, "box");
        assert_eq!(maxclass, "inlet");
    }

    #[test]
    fn test_classify_maxclass_inlet_tilde() {
        // inlet~ uses the same maxclass "inlet" internally in Max,
        // In actual Max patches, signal inlets also use "inlet" maxclass.
        let node = PatchNode {
            id: "test".into(),
            object_name: "inlet~".into(),
            args: vec![],
            num_inlets: 1,
            num_outlets: 1,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        let (maxclass, _, _) = classify_maxclass(&node, "box");
        assert_eq!(maxclass, "inlet");
    }

    #[test]
    fn test_classify_maxclass_newobj() {
        let node = PatchNode {
            id: "test".into(),
            object_name: "cycle~".into(),
            args: vec!["440".into()],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        let (maxclass, _, _) = classify_maxclass(&node, "box");
        assert_eq!(maxclass, "newobj");
    }

    #[test]
    fn test_compute_outlettype_signal() {
        let node = PatchNode {
            id: "test".into(),
            object_name: "cycle~".into(),
            args: vec![],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        let types = compute_outlettype(&node, false, false);
        assert_eq!(types, vec!["signal"]);
    }

    #[test]
    fn test_compute_outlettype_no_outlets() {
        let node = PatchNode {
            id: "test".into(),
            object_name: "ezdac~".into(),
            args: vec![],
            num_inlets: 2,
            num_outlets: 0,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        let types = compute_outlettype(&node, false, false);
        assert!(types.is_empty());
    }

    #[test]
    fn test_roundtrip_l2() {
        // AST -> PatchGraph -> JSON -> parse -> structural verification
        use crate::builder::build_graph;
        use flutmax_ast::*;

        let prog = Program {
            in_decls: vec![InDecl {
                index: 0,
                name: "freq".to_string(),
                port_type: PortType::Float,
            }],
            out_decls: vec![OutDecl {
                index: 0,
                name: "audio".to_string(),
                port_type: PortType::Signal,
                value: None,
            }],
            wires: vec![
                Wire {
                    name: "osc".to_string(),
                    value: Expr::Call {
                        object: "cycle~".to_string(),
                        args: vec![CallArg::positional(Expr::Ref("freq".to_string()))],
                    },
                    span: None,
                    attrs: vec![],
                },
                Wire {
                    name: "amp".to_string(),
                    value: Expr::Call {
                        object: "mul~".to_string(),
                        args: vec![
                            CallArg::positional(Expr::Ref("osc".to_string())),
                            CallArg::positional(Expr::Lit(LitValue::Float(0.5))),
                        ],
                    },
                    span: None,
                    attrs: vec![],
                },
            ],
            destructuring_wires: vec![],
            msg_decls: vec![],
            out_assignments: vec![OutAssignment {
                index: 0,
                value: Expr::Ref("amp".to_string()),
                span: None,
            }],
            direct_connections: vec![],
            feedback_decls: vec![],
            feedback_assignments: vec![],
            state_decls: vec![],
            state_assignments: vec![],
        };

        let graph = build_graph(&prog).unwrap();
        let json_str = generate(&graph).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();

        let patcher = &parsed["patcher"];
        let boxes = patcher["boxes"].as_array().unwrap();
        let lines = patcher["lines"].as_array().unwrap();

        // 4 nodes: inlet, cycle~, *~, outlet~
        assert_eq!(boxes.len(), 4);
        // 3 edges: inlet->cycle~, cycle~->*~, *~->outlet~
        assert_eq!(lines.len(), 3);

        // First box is inlet
        assert_eq!(boxes[0]["box"]["maxclass"], "inlet");

        // Last box is outlet~
        assert_eq!(boxes[3]["box"]["maxclass"], "outlet");
    }

    #[test]
    fn test_unique_ids() {
        let graph = make_l2_graph();
        let json_str = generate(&graph).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();

        let ids: Vec<&str> = boxes
            .iter()
            .map(|b| b["box"]["id"].as_str().unwrap())
            .collect();

        // All IDs are unique
        let mut unique_ids = ids.clone();
        unique_ids.sort();
        unique_ids.dedup();
        assert_eq!(ids.len(), unique_ids.len());
    }

    #[test]
    fn test_message_box_output() {
        let mut g = PatchGraph::new();
        g.add_node(PatchNode {
            id: "msg1".into(),
            object_name: "message".into(),
            args: vec!["bang".into()],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: false,
            varname: Some("click".into()),
            hot_inlets: vec![true, false],
            purity: NodePurity::Stateful,
            attrs: vec![],
            code: None,
        });

        let json_str = generate(&g).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();

        let msg_box = &boxes[0]["box"];
        assert_eq!(msg_box["maxclass"], "message");
        assert_eq!(msg_box["text"], "bang");
        assert_eq!(msg_box["numinlets"], 2);
        assert_eq!(msg_box["numoutlets"], 1);
        assert_eq!(msg_box["varname"], "click");

        let outlettype = msg_box["outlettype"].as_array().unwrap();
        assert_eq!(outlettype.len(), 1);
        assert_eq!(outlettype[0], "");
    }

    #[test]
    fn test_fanout_patchline_has_order() {
        // cycle~ -> ezdac~ (inlet 0 and inlet 1) fanout
        let mut graph = make_minimal_graph();
        // Set order on fanout edges
        graph.edges[0].order = Some(0);
        graph.edges[1].order = Some(1);

        let json_str = generate(&graph).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let lines = parsed["patcher"]["lines"].as_array().unwrap();

        // Both lines have an order field
        for (i, line) in lines.iter().enumerate() {
            let patchline = &line["patchline"];
            let order = patchline.get("order");
            assert!(order.is_some(), "patchline {} should have order field", i);
            assert_eq!(order.unwrap().as_u64().unwrap(), i as u64);
        }
    }

    #[test]
    fn test_non_fanout_patchline_no_order() {
        // Single-connection edges have no order
        let graph = make_l2_graph();
        let json_str = generate(&graph).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let lines = parsed["patcher"]["lines"].as_array().unwrap();

        for (i, line) in lines.iter().enumerate() {
            let patchline = &line["patchline"];
            assert!(
                patchline.get("order").is_none(),
                "patchline {} should not have order field",
                i
            );
        }
    }

    // ================================================
    // .attr() chain codegen tests
    // ================================================

    #[test]
    fn test_newobj_attrs_in_text() {
        // newobj: attrs should be appended as @key value in text field
        let mut g = PatchGraph::new();
        g.add_node(PatchNode {
            id: "osc".into(),
            object_name: "cycle~".into(),
            args: vec!["440".into()],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: true,
            varname: Some("osc".into()),
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![("phase".into(), "0.5".into())],
            code: None,
        });

        let json_str = generate(&g).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();

        let text = boxes[0]["box"]["text"].as_str().unwrap();
        assert_eq!(text, "cycle~ 440 @phase 0.5");
    }

    #[test]
    fn test_newobj_multiple_attrs_in_text() {
        let mut g = PatchGraph::new();
        g.add_node(PatchNode {
            id: "osc".into(),
            object_name: "cycle~".into(),
            args: vec![],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![
                ("frequency".into(), "440.".into()),
                ("phase".into(), "0.5".into()),
            ],
            code: None,
        });

        let json_str = generate(&g).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();

        let text = boxes[0]["box"]["text"].as_str().unwrap();
        assert_eq!(text, "cycle~ @frequency 440. @phase 0.5");
    }

    #[test]
    fn test_ui_object_attrs_as_fields() {
        // UI object (flonum): attrs should be top-level box JSON fields
        let mut g = PatchGraph::new();
        g.add_node(PatchNode {
            id: "fnum".into(),
            object_name: "flonum".into(),
            args: vec![],
            num_inlets: 1,
            num_outlets: 2,
            is_signal: false,
            varname: Some("w".into()),
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![
                ("minimum".into(), "0.".into()),
                ("maximum".into(), "100.".into()),
            ],
            code: None,
        });

        let json_str = generate(&g).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();
        let box_obj = &boxes[0]["box"];

        assert_eq!(box_obj["maxclass"], "flonum");
        assert_eq!(box_obj["minimum"], 0.0);
        assert_eq!(box_obj["maximum"], 100.0);
        // UI objects should NOT have attrs in text (no text field for flonum)
        assert!(box_obj.get("text").is_none());
    }

    #[test]
    fn test_ui_object_string_attr() {
        let mut g = PatchGraph::new();
        g.add_node(PatchNode {
            id: "dial".into(),
            object_name: "live.dial".into(),
            args: vec![],
            num_inlets: 1,
            num_outlets: 2,
            is_signal: false,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![("parameter_longname".into(), "Cutoff".into())],
            code: None,
        });

        let json_str = generate(&g).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();
        let box_obj = &boxes[0]["box"];

        assert_eq!(box_obj["maxclass"], "live.dial");
        assert_eq!(box_obj["parameter_longname"], "Cutoff");
    }

    #[test]
    fn test_no_attrs_unchanged() {
        // When no attrs, output should be unchanged
        let mut g = PatchGraph::new();
        g.add_node(PatchNode {
            id: "osc".into(),
            object_name: "cycle~".into(),
            args: vec!["440".into()],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });

        let json_str = generate(&g).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();

        let text = boxes[0]["box"]["text"].as_str().unwrap();
        assert_eq!(text, "cycle~ 440");
    }

    // ================================================
    // RNBO codegen tests
    // ================================================

    /// Graph: inlet -> cycle~ -> outlet~ (for RNBO tests)
    fn make_rnbo_graph() -> PatchGraph {
        let mut g = PatchGraph::new();
        g.add_node(PatchNode {
            id: "in_freq".into(),
            object_name: "inlet".into(),
            args: vec![],
            num_inlets: 0,
            num_outlets: 1,
            is_signal: false,
            varname: Some("freq".into()),
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });
        g.add_node(PatchNode {
            id: "osc".into(),
            object_name: "cycle~".into(),
            args: vec!["440".into()],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: true,
            varname: Some("osc".into()),
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });
        g.add_node(PatchNode {
            id: "out_audio".into(),
            object_name: "outlet~".into(),
            args: vec![],
            num_inlets: 1,
            num_outlets: 0,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });
        g.add_edge(PatchEdge {
            source_id: "in_freq".into(),
            source_outlet: 0,
            dest_id: "osc".into(),
            dest_inlet: 0,
            is_feedback: false,
            order: None,
        });
        g.add_edge(PatchEdge {
            source_id: "osc".into(),
            source_outlet: 0,
            dest_id: "out_audio".into(),
            dest_inlet: 0,
            is_feedback: false,
            order: None,
        });
        g
    }

    fn rnbo_opts() -> GenerateOptions {
        GenerateOptions {
            classnamespace: "rnbo".to_string(),
        }
    }

    #[test]
    fn test_generate_rnbo_classnamespace() {
        let graph = make_rnbo_graph();
        let json_str = generate_with_options(&graph, &rnbo_opts()).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let patcher = parsed.get("patcher").unwrap();

        assert_eq!(patcher["classnamespace"], "rnbo");
    }

    #[test]
    fn test_rnbo_inport_outport() {
        let graph = make_rnbo_graph();
        let json_str = generate_with_options(&graph, &rnbo_opts()).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();

        // inlet (control) → "inport freq" (uses varname)
        let inlet_box = &boxes[0]["box"];
        assert_eq!(inlet_box["maxclass"], "newobj");
        assert_eq!(inlet_box["text"], "inport freq");

        // outlet~ (signal) → "out~ 1" (1-based index)
        let outlet_box = &boxes[2]["box"];
        assert_eq!(outlet_box["maxclass"], "newobj");
        assert_eq!(outlet_box["text"], "out~ 1");
    }

    #[test]
    fn test_rnbo_signal_io() {
        // Graph with signal inlet~ and signal outlet~
        let mut g = PatchGraph::new();
        g.add_node(PatchNode {
            id: "in_sig".into(),
            object_name: "inlet~".into(),
            args: vec![],
            num_inlets: 1,
            num_outlets: 1,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });
        g.add_node(PatchNode {
            id: "out_sig".into(),
            object_name: "outlet~".into(),
            args: vec![],
            num_inlets: 1,
            num_outlets: 0,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });
        g.add_edge(PatchEdge {
            source_id: "in_sig".into(),
            source_outlet: 0,
            dest_id: "out_sig".into(),
            dest_inlet: 0,
            is_feedback: false,
            order: None,
        });

        let json_str = generate_with_options(&g, &rnbo_opts()).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();

        // inlet~ → "in~ 1"
        let inlet_box = &boxes[0]["box"];
        assert_eq!(inlet_box["maxclass"], "newobj");
        assert_eq!(inlet_box["text"], "in~ 1");
        let outlettype = inlet_box["outlettype"].as_array().unwrap();
        assert_eq!(outlettype, &[json!("signal")]);

        // outlet~ → "out~ 1"
        let outlet_box = &boxes[1]["box"];
        assert_eq!(outlet_box["maxclass"], "newobj");
        assert_eq!(outlet_box["text"], "out~ 1");
        // outlet is sink: numoutlets = 0, no outlettype
        assert_eq!(outlet_box["numoutlets"], 0);
        assert!(outlet_box.get("outlettype").is_none());
    }

    #[test]
    fn test_rnbo_serial() {
        let graph = make_rnbo_graph();
        let json_str = generate_with_options(&graph, &rnbo_opts()).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();

        // Each box should have rnbo_serial (1-based) and rnbo_uniqueid
        for (i, boxval) in boxes.iter().enumerate() {
            let b = &boxval["box"];
            let serial = b["rnbo_serial"].as_u64().unwrap();
            assert_eq!(serial, (i + 1) as u64, "rnbo_serial for box {}", i);

            let uniqueid = b["rnbo_uniqueid"].as_str().unwrap();
            assert!(!uniqueid.is_empty(), "rnbo_uniqueid should not be empty");
        }

        // Verify specific uniqueid format: "object_name_obj-N"
        let inlet_uid = boxes[0]["box"]["rnbo_uniqueid"].as_str().unwrap();
        assert_eq!(inlet_uid, "inlet_obj-1");

        let cycle_uid = boxes[1]["box"]["rnbo_uniqueid"].as_str().unwrap();
        assert_eq!(cycle_uid, "cycle_tilde_obj-2");

        let outlet_uid = boxes[2]["box"]["rnbo_uniqueid"].as_str().unwrap();
        assert_eq!(outlet_uid, "outlet_tilde_obj-3");
    }

    #[test]
    fn test_standard_unchanged() {
        // Verify generate() (default options) produces standard Max output
        let graph = make_rnbo_graph();
        let json_str = generate(&graph).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let patcher = parsed.get("patcher").unwrap();

        // classnamespace should be "box"
        assert_eq!(patcher["classnamespace"], "box");

        let boxes = patcher["boxes"].as_array().unwrap();

        // inlet should use "inlet" maxclass, not "newobj"
        let inlet_box = &boxes[0]["box"];
        assert_eq!(inlet_box["maxclass"], "inlet");
        // No text field for standard inlet
        assert!(inlet_box.get("text").is_none());

        // outlet~ should use "outlet" maxclass
        let outlet_box = &boxes[2]["box"];
        assert_eq!(outlet_box["maxclass"], "outlet");

        // No rnbo_serial or rnbo_uniqueid in standard mode
        for boxval in boxes {
            let b = &boxval["box"];
            assert!(
                b.get("rnbo_serial").is_none(),
                "standard mode should not have rnbo_serial"
            );
            assert!(
                b.get("rnbo_uniqueid").is_none(),
                "standard mode should not have rnbo_uniqueid"
            );
        }
    }

    #[test]
    fn test_rnbo_control_outlet() {
        // Test control outlet → "outport name"
        let mut g = PatchGraph::new();
        g.add_node(PatchNode {
            id: "out_ctrl".into(),
            object_name: "outlet".into(),
            args: vec![],
            num_inlets: 1,
            num_outlets: 1,
            is_signal: false,
            varname: Some("result".into()),
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });

        let json_str = generate_with_options(&g, &rnbo_opts()).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();

        let outlet_box = &boxes[0]["box"];
        assert_eq!(outlet_box["maxclass"], "newobj");
        assert_eq!(outlet_box["text"], "outport result");
        // Control outlet in RNBO is sink: numoutlets = 0
        assert_eq!(outlet_box["numoutlets"], 0);
    }

    #[test]
    fn test_rnbo_inport_fallback_name() {
        // When no varname, use port_N as fallback
        let mut g = PatchGraph::new();
        g.add_node(PatchNode {
            id: "in_unnamed".into(),
            object_name: "inlet".into(),
            args: vec![],
            num_inlets: 0,
            num_outlets: 1,
            is_signal: false,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });

        let json_str = generate_with_options(&g, &rnbo_opts()).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();

        let inlet_box = &boxes[0]["box"];
        assert_eq!(inlet_box["text"], "inport port_0");
    }

    // ================================================
    // Codebox tests
    // ================================================

    #[test]
    fn test_classify_maxclass_codebox() {
        // v8.codebox should return "v8.codebox" maxclass
        let node = PatchNode {
            id: "cb1".into(),
            object_name: "v8.codebox".into(),
            args: vec![],
            num_inlets: 1,
            num_outlets: 1,
            is_signal: false,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        let (maxclass, width, height) = classify_maxclass(&node, "box");
        assert_eq!(maxclass, "v8.codebox");
        assert_eq!(width, 200.0);
        assert_eq!(height, 100.0);

        // codebox (gen~) should return "codebox" maxclass
        let node2 = PatchNode {
            id: "cb2".into(),
            object_name: "codebox".into(),
            args: vec![],
            num_inlets: 1,
            num_outlets: 1,
            is_signal: false,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        let (maxclass2, _, _) = classify_maxclass(&node2, "box");
        assert_eq!(maxclass2, "codebox");
    }

    #[test]
    fn test_build_box_codebox_with_code() {
        // v8.codebox with code field should emit code, filename, and text in JSON
        let node = PatchNode {
            id: "cb1".into(),
            object_name: "v8.codebox".into(),
            args: vec![],
            num_inlets: 1,
            num_outlets: 1,
            is_signal: false,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: Some("function bang() { outlet(0, 42); }".into()),
        };

        let box_json = build_box(
            &node,
            &BoxContext {
                id: "obj-1",
                x: 100.0,
                y: 50.0,
                classnamespace: "box",
                serial: 1,
                port_index: None,
                ui_data: None,
            },
        );
        let box_obj = &box_json["box"];

        assert_eq!(box_obj["maxclass"], "v8.codebox");
        assert_eq!(box_obj["code"], "function bang() { outlet(0, 42); }");
        assert_eq!(box_obj["filename"], "none");
        assert_eq!(box_obj["text"], "");
    }

    #[test]
    fn test_build_box_codebox_without_code() {
        // codebox (gen~) without code field should not emit code/filename
        let node = PatchNode {
            id: "cb1".into(),
            object_name: "codebox".into(),
            args: vec![],
            num_inlets: 1,
            num_outlets: 1,
            is_signal: false,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };

        let box_json = build_box(
            &node,
            &BoxContext {
                id: "obj-1",
                x: 100.0,
                y: 50.0,
                classnamespace: "box",
                serial: 1,
                port_index: None,
                ui_data: None,
            },
        );
        let box_obj = &box_json["box"];

        assert_eq!(box_obj["maxclass"], "codebox");
        assert!(box_obj.get("code").is_none());
        assert!(box_obj.get("filename").is_none());
    }

    #[test]
    fn test_standard_codegen_unchanged() {
        // Standard generate() still works with existing PatchGraph
        let mut g = PatchGraph::new();
        g.add_node(PatchNode {
            id: "osc".into(),
            object_name: "cycle~".into(),
            args: vec!["440".into()],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: true,
            varname: Some("osc".into()),
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });

        let json_str = generate(&g).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();
        assert_eq!(boxes.len(), 1);
        assert_eq!(boxes[0]["box"]["maxclass"], "newobj");
        assert_eq!(boxes[0]["box"]["text"], "cycle~ 440");
        // No code field for regular objects
        assert!(boxes[0]["box"].get("code").is_none());
    }

    #[test]
    fn test_gen_mode_classify_inlet_outlet() {
        // In gen~ mode, inlet/outlet should become "newobj"
        let inlet_node = PatchNode {
            id: "in".into(),
            object_name: "inlet~".into(),
            args: vec![],
            num_inlets: 0,
            num_outlets: 1,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        let (maxclass, _, _) = classify_maxclass(&inlet_node, "dsp.gen");
        assert_eq!(maxclass, "newobj");

        let outlet_node = PatchNode {
            id: "out".into(),
            object_name: "outlet~".into(),
            args: vec![],
            num_inlets: 1,
            num_outlets: 0,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        let (maxclass, _, _) = classify_maxclass(&outlet_node, "dsp.gen");
        assert_eq!(maxclass, "newobj");
    }

    #[test]
    fn test_gen_mode_build_box_text() {
        // gen~ mode should generate "in N" / "out N" text
        let inlet_node = PatchNode {
            id: "in".into(),
            object_name: "inlet~".into(),
            args: vec![],
            num_inlets: 0,
            num_outlets: 1,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        let box_json = build_box(
            &inlet_node,
            &BoxContext {
                id: "obj-1",
                x: 100.0,
                y: 50.0,
                classnamespace: "dsp.gen",
                serial: 1,
                port_index: Some(0),
                ui_data: None,
            },
        );
        let box_obj = &box_json["box"];
        assert_eq!(box_obj["maxclass"], "newobj");
        assert_eq!(box_obj["text"], "in 1");
        // gen~ should NOT have rnbo_serial/rnbo_uniqueid
        assert!(box_obj.get("rnbo_serial").is_none());

        let outlet_node = PatchNode {
            id: "out".into(),
            object_name: "outlet~".into(),
            args: vec![],
            num_inlets: 1,
            num_outlets: 0,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        let box_json = build_box(
            &outlet_node,
            &BoxContext {
                id: "obj-2",
                x: 100.0,
                y: 120.0,
                classnamespace: "dsp.gen",
                serial: 2,
                port_index: Some(0),
                ui_data: None,
            },
        );
        let box_obj = &box_json["box"];
        assert_eq!(box_obj["maxclass"], "newobj");
        assert_eq!(box_obj["text"], "out 1");
        assert_eq!(box_obj["numoutlets"], 0); // sink
    }

    #[test]
    fn test_gen_mode_codegen() {
        // Full gen~ codegen roundtrip
        let mut g = PatchGraph::new();
        g.add_node(PatchNode {
            id: "in1".into(),
            object_name: "inlet~".into(),
            args: vec![],
            num_inlets: 0,
            num_outlets: 1,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });
        g.add_node(PatchNode {
            id: "mul".into(),
            object_name: "*".into(),
            args: vec!["0.5".into()],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: false,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });
        g.add_node(PatchNode {
            id: "out1".into(),
            object_name: "outlet~".into(),
            args: vec![],
            num_inlets: 1,
            num_outlets: 0,
            is_signal: true,
            varname: None,
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });
        g.add_edge(PatchEdge {
            source_id: "in1".into(),
            source_outlet: 0,
            dest_id: "mul".into(),
            dest_inlet: 0,
            is_feedback: false,
            order: None,
        });
        g.add_edge(PatchEdge {
            source_id: "mul".into(),
            source_outlet: 0,
            dest_id: "out1".into(),
            dest_inlet: 0,
            is_feedback: false,
            order: None,
        });

        let opts = GenerateOptions {
            classnamespace: "dsp.gen".to_string(),
        };
        let json_str = generate_with_options(&g, &opts).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();

        assert_eq!(parsed["patcher"]["classnamespace"], "dsp.gen");

        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();
        assert_eq!(boxes.len(), 3);

        // First box: inlet~ → "in 1"
        assert_eq!(boxes[0]["box"]["maxclass"], "newobj");
        assert_eq!(boxes[0]["box"]["text"], "in 1");

        // Second box: * 0.5
        assert_eq!(boxes[1]["box"]["maxclass"], "newobj");
        assert_eq!(boxes[1]["box"]["text"], "* 0.5");

        // Third box: outlet~ → "out 1"
        assert_eq!(boxes[2]["box"]["maxclass"], "newobj");
        assert_eq!(boxes[2]["box"]["text"], "out 1");
        assert_eq!(boxes[2]["box"]["numoutlets"], 0);
    }

    // ─── UiData tests ───

    #[test]
    fn test_ui_data_from_json_basic() {
        let json_str = r#"{
            "_patcher": { "rect": [50, 50, 800, 600] },
            "osc": { "rect": [100, 200, 80, 22] },
            "dac": { "rect": [100, 400, 45, 45], "background": 0 }
        }"#;
        let ui = UiData::from_json(json_str).unwrap();

        // Patcher-level settings
        assert_eq!(ui.patcher["rect"], json!([50, 50, 800, 600]));

        // Per-wire entries
        assert!(ui.entries.contains_key("osc"));
        assert!(ui.entries.contains_key("dac"));
        assert!(!ui.entries.contains_key("_patcher"));
        assert_eq!(ui.entries["osc"]["rect"], json!([100, 200, 80, 22]));
        assert_eq!(ui.entries["dac"]["background"], json!(0));
    }

    #[test]
    fn test_ui_data_from_json_empty() {
        let ui = UiData::from_json("{}").unwrap();
        assert!(ui.patcher.is_empty());
        assert!(ui.entries.is_empty());
    }

    #[test]
    fn test_ui_data_from_json_invalid() {
        assert!(UiData::from_json("not json").is_none());
        assert!(UiData::from_json("42").is_none());
        assert!(UiData::from_json("[]").is_none());
    }

    #[test]
    fn test_ui_data_from_json_no_patcher() {
        let json_str = r#"{ "osc": { "rect": [10, 20, 80, 22] } }"#;
        let ui = UiData::from_json(json_str).unwrap();
        assert!(ui.patcher.is_empty());
        assert_eq!(ui.entries.len(), 1);
    }

    #[test]
    fn test_build_box_with_ui_data_rect_override() {
        let node = PatchNode {
            id: "osc".into(),
            object_name: "cycle~".into(),
            args: vec!["440".into()],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: true,
            varname: Some("osc".into()),
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        let ui = UiData::from_json(r#"{ "osc": { "rect": [250, 350, 90, 24] } }"#).unwrap();

        let box_json = build_box(
            &node,
            &BoxContext {
                id: "obj-1",
                x: 100.0,
                y: 50.0,
                classnamespace: "box",
                serial: 1,
                port_index: None,
                ui_data: Some(&ui),
            },
        );
        let rect = box_json["box"]["patching_rect"].as_array().unwrap();

        // Should use UI data rect, not auto-layout position
        assert_eq!(rect[0], json!(250));
        assert_eq!(rect[1], json!(350));
        assert_eq!(rect[2], json!(90));
        assert_eq!(rect[3], json!(24));
    }

    #[test]
    fn test_build_box_with_ui_data_decorative_attrs() {
        let node = PatchNode {
            id: "osc".into(),
            object_name: "cycle~".into(),
            args: vec!["440".into()],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: true,
            varname: Some("osc".into()),
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        let ui = UiData::from_json(
            r#"{
            "osc": {
                "rect": [250, 350, 90, 24],
                "background": 0,
                "fontsize": 14
            }
        }"#,
        )
        .unwrap();

        let box_json = build_box(
            &node,
            &BoxContext {
                id: "obj-1",
                x: 100.0,
                y: 50.0,
                classnamespace: "box",
                serial: 1,
                port_index: None,
                ui_data: Some(&ui),
            },
        );
        let box_obj = &box_json["box"];

        // Decorative attributes should be present
        assert_eq!(box_obj["background"], json!(0));
        assert_eq!(box_obj["fontsize"], json!(14));
    }

    #[test]
    fn test_build_box_without_varname_ignores_ui_data() {
        let node = PatchNode {
            id: "osc".into(),
            object_name: "cycle~".into(),
            args: vec!["440".into()],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: true,
            varname: None, // no varname
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        };
        let ui = UiData::from_json(r#"{ "osc": { "rect": [250, 350, 90, 24] } }"#).unwrap();

        let box_json = build_box(
            &node,
            &BoxContext {
                id: "obj-1",
                x: 100.0,
                y: 50.0,
                classnamespace: "box",
                serial: 1,
                port_index: None,
                ui_data: Some(&ui),
            },
        );
        let rect = box_json["box"]["patching_rect"].as_array().unwrap();

        // Should use auto-layout position since there's no varname to match
        assert_eq!(rect[0], json!(100.0));
        assert_eq!(rect[1], json!(50.0));
    }

    #[test]
    fn test_build_patcher_with_ui_data_patcher_rect() {
        let mut g = PatchGraph::new();
        g.add_node(PatchNode {
            id: "osc".into(),
            object_name: "cycle~".into(),
            args: vec!["440".into()],
            num_inlets: 2,
            num_outlets: 1,
            is_signal: true,
            varname: Some("osc".into()),
            hot_inlets: vec![],
            purity: NodePurity::Unknown,
            attrs: vec![],
            code: None,
        });

        let ui = UiData::from_json(
            r#"{
            "_patcher": { "rect": [50, 50, 800, 600] },
            "osc": { "rect": [200, 300, 80, 22] }
        }"#,
        )
        .unwrap();

        let json_str = generate_with_ui(&g, &GenerateOptions::default(), Some(&ui)).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();

        // Patcher rect should come from UI data
        assert_eq!(parsed["patcher"]["rect"], json!([50, 50, 800, 600]));

        // Box rect should come from UI data
        let boxes = parsed["patcher"]["boxes"].as_array().unwrap();
        assert_eq!(boxes[0]["box"]["patching_rect"], json!([200, 300, 80, 22]));
    }

    #[test]
    fn test_generate_with_ui_none_is_same_as_generate() {
        let graph = make_minimal_graph();

        let json_without = generate(&graph).unwrap();
        let json_with_none = generate_with_ui(&graph, &GenerateOptions::default(), None).unwrap();

        // Both should produce identical output
        assert_eq!(json_without, json_with_none);
    }
}