hyperapp_macro 0.1.2

The macro for async, handler-based Hyperware Hyperapps.
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
2430
2431
2432
2433
2434
2435
#![allow(warnings)]
use proc_macro::TokenStream;
use quote::{format_ident, quote, ToTokens};
use syn::{
    parse_macro_input, punctuated::Punctuated, spanned::Spanned, token::Comma, Expr, ItemImpl,
    Meta, ReturnType,
};

//------------------------------------------------------------------------------
// Type Definitions
//------------------------------------------------------------------------------

/// Keywords for parsing attribute arguments
mod kw {
    syn::custom_keyword!(name);
    syn::custom_keyword!(icon);
    syn::custom_keyword!(widget);
    syn::custom_keyword!(ui);
    syn::custom_keyword!(ui_path);
    syn::custom_keyword!(endpoints);
    syn::custom_keyword!(save_config);
    syn::custom_keyword!(wit_world);
}

/// A wrapper for a punctuated list of Meta items
struct MetaList(Punctuated<Meta, Comma>);

/// Arguments for the hyperprocess macro
struct HyperProcessArgs {
    name: String,
    icon: Option<String>,
    widget: Option<String>,
    ui: Option<Expr>,
    ui_path: Option<String>,
    endpoints: Expr,
    save_config: Expr,
    wit_world: String,
}

/// Metadata for a function in the implementation block
#[derive(Clone)]
struct FunctionMetadata {
    name: syn::Ident,               // Original function name
    variant_name: String,           // CamelCase variant name
    params: Vec<syn::Type>,         // Parameter types (excluding &mut self)
    return_type: Option<syn::Type>, // Return type (None for functions returning ())
    is_async: bool,                 // Whether function is async
    is_local: bool,                 // Has #[local] attribute
    is_remote: bool,                // Has #[remote] attribute
    is_http: bool,                  // Has #[http] attribute
    is_eth: bool,                   // Has #[eth] attribute
    http_methods: Vec<String>,      // HTTP methods this handler accepts (GET, POST, etc.)
    http_path: Option<String>,      // Specific path this handler is bound to (optional)
}

/// Enum for the different handler types
#[derive(Copy, Clone)]
enum HandlerType {
    Local,
    Remote,
    Http,
    Eth,
}

/// Grouped handlers by type
struct HandlerGroups<'a> {
    local: Vec<&'a FunctionMetadata>,
    remote: Vec<&'a FunctionMetadata>,
    http: Vec<&'a FunctionMetadata>,
    // New group for combined handlers (used for local messages that can also use remote handlers)
    local_and_remote: Vec<&'a FunctionMetadata>,
}

impl<'a> HandlerGroups<'a> {
    fn from_function_metadata(metadata: &'a [FunctionMetadata]) -> Self {
        // Collect handlers that are explicitly marked as local
        let local: Vec<_> = metadata.iter().filter(|f| f.is_local).collect();

        // Collect handlers that are explicitly marked as remote
        let remote: Vec<_> = metadata.iter().filter(|f| f.is_remote).collect();

        // Collect HTTP handlers
        let http: Vec<_> = metadata.iter().filter(|f| f.is_http).collect();

        // Create a combined list of local and remote handlers for local messages
        // We first include all local handlers, then add remote handlers that aren't already covered
        let mut local_and_remote = local.clone();
        for handler in remote.iter() {
            // Check if this remote handler is already in the local_and_remote list
            if !local_and_remote
                .iter()
                .any(|h| h.variant_name == handler.variant_name)
            {
                local_and_remote.push(handler);
            }
        }

        HandlerGroups {
            local,
            remote,
            http,
            local_and_remote,
        }
    }
}

/// Handler dispatch code fragments
struct HandlerDispatch {
    local: proc_macro2::TokenStream,
    remote: proc_macro2::TokenStream,
    http: proc_macro2::TokenStream,
    local_and_remote: proc_macro2::TokenStream,
}

/// Init method details for code generation
struct InitMethodDetails {
    identifier: proc_macro2::TokenStream,
    call: proc_macro2::TokenStream,
}

/// WebSocket method info from analysis
#[derive(Clone)]
struct WsMethodInfo {
    name: syn::Ident,
    is_async: bool,
}

/// WebSocket client method info from analysis
#[derive(Clone)]
struct WsClientMethodInfo {
    name: syn::Ident,
    is_async: bool,
}

/// ETH method info from analysis
#[derive(Clone)]
struct EthMethodInfo {
    name: syn::Ident,
    is_async: bool,
}

/// WebSocket method details for code generation
struct WsMethodDetails {
    identifier: proc_macro2::TokenStream,
    call: proc_macro2::TokenStream,
}

/// WebSocket client method details for code generation
struct WsClientMethodDetails {
    identifier: proc_macro2::TokenStream,
    call: proc_macro2::TokenStream,
}

/// ETH method details for code generation
struct EthMethodDetails {
    identifier: proc_macro2::TokenStream,
    call: proc_macro2::TokenStream,
}

//------------------------------------------------------------------------------
// Parse Implementation
//------------------------------------------------------------------------------

/// Implement Parse for our MetaList newtype wrapper
impl syn::parse::Parse for MetaList {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let mut args = Punctuated::new();
        while !input.is_empty() {
            args.push_value(input.parse()?);
            if input.is_empty() {
                break;
            }
            args.push_punct(input.parse()?);
        }
        Ok(MetaList(args))
    }
}

//------------------------------------------------------------------------------
// Utility Functions
//------------------------------------------------------------------------------

/// Convert a snake_case string to CamelCase
fn to_camel_case(snake: &str) -> String {
    let mut camel = String::new();
    let mut capitalize_next = true;

    for c in snake.chars() {
        if c == '_' {
            capitalize_next = true;
        } else if capitalize_next {
            camel.push(c.to_ascii_uppercase());
            capitalize_next = false;
        } else {
            camel.push(c);
        }
    }

    camel
}

/// Parse a string literal from an expression
fn parse_string_literal(expr: &Expr, span: proc_macro2::Span) -> syn::Result<String> {
    if let Expr::Lit(expr_lit) = expr {
        if let syn::Lit::Str(lit) = &expr_lit.lit {
            Ok(lit.value())
        } else {
            Err(syn::Error::new(span, "Expected string literal"))
        }
    } else {
        Err(syn::Error::new(span, "Expected string literal"))
    }
}

/// Parse the UI expression (handling Some() wrapper)
fn parse_ui_expr(expr: &Expr) -> syn::Result<Option<Expr>> {
    if let Expr::Call(call) = expr {
        if let Expr::Path(path) = &*call.func {
            if path
                .path
                .segments
                .last()
                .map(|s| s.ident == "Some")
                .unwrap_or(false)
            {
                if call.args.len() == 1 {
                    return Ok(Some(call.args[0].clone()));
                } else {
                    return Err(syn::Error::new(
                        call.span(),
                        "Some must have exactly one argument",
                    ));
                }
            }
        }
    }
    Ok(Some(expr.clone()))
}

/// Check if a method has a specific attribute
fn has_attribute(method: &syn::ImplItemFn, attr_name: &str) -> bool {
    method
        .attrs
        .iter()
        .any(|attr| attr.path().is_ident(attr_name))
}

/// Parse HTTP methods and path from the #[http] attribute
/// Supports: #[http], #[http(method = "GET")], #[http(method = "POST", path = "/api")]
fn parse_http_attributes(method: &syn::ImplItemFn) -> (Vec<String>, Option<String>) {
    for attr in &method.attrs {
        if attr.path().is_ident("http") {
            // Handle #[http] with no arguments - defaults to ALL methods
            if matches!(&attr.meta, syn::Meta::Path(_)) {
                return (
                    vec![
                        "GET".to_string(),
                        "POST".to_string(),
                        "PUT".to_string(),
                        "DELETE".to_string(),
                        "PATCH".to_string(),
                        "HEAD".to_string(),
                        "OPTIONS".to_string(),
                    ],
                    None,
                );
            }

            // Handle #[http(method = "GET", path = "/api")]
            if let syn::Meta::List(list) = &attr.meta {
                let mut methods = None;
                let mut path = None;

                // Parse the token stream manually
                let tokens: Vec<_> = list.tokens.clone().into_iter().collect();
                let mut i = 0;

                while i < tokens.len() {
                    // Look for identifier (method or path)
                    if let proc_macro2::TokenTree::Ident(ident) = &tokens[i] {
                        let ident_str = ident.to_string();

                        // Check for = sign
                        if i + 2 < tokens.len() {
                            if let proc_macro2::TokenTree::Punct(punct) = &tokens[i + 1] {
                                if punct.as_char() == '=' {
                                    // Get the string literal
                                    if let proc_macro2::TokenTree::Literal(lit) = &tokens[i + 2] {
                                        let lit_str = lit.to_string();
                                        // Remove quotes from the literal
                                        let value = lit_str.trim_matches('"');

                                        if ident_str == "method" {
                                            let method = value.to_uppercase();
                                            if matches!(
                                                method.as_str(),
                                                "GET"
                                                    | "POST"
                                                    | "PUT"
                                                    | "DELETE"
                                                    | "PATCH"
                                                    | "HEAD"
                                                    | "OPTIONS"
                                            ) {
                                                methods = Some(vec![method]);
                                            }
                                        } else if ident_str == "path" {
                                            path = Some(value.to_string());
                                        }
                                    }
                                    i += 3; // Skip ident, =, and literal

                                    // Skip comma if present
                                    if i < tokens.len() {
                                        if let proc_macro2::TokenTree::Punct(punct) = &tokens[i] {
                                            if punct.as_char() == ',' {
                                                i += 1;
                                            }
                                        }
                                    }
                                    continue;
                                }
                            }
                        }
                    }
                    i += 1;
                }

                // Default to ALL methods if none specified
                let final_methods = methods.unwrap_or_else(|| {
                    vec![
                        "GET".to_string(),
                        "POST".to_string(),
                        "PUT".to_string(),
                        "DELETE".to_string(),
                        "PATCH".to_string(),
                        "HEAD".to_string(),
                        "OPTIONS".to_string(),
                    ]
                });

                return (final_methods, path);
            }

            // Default to ALL methods if parsing fails
            return (
                vec![
                    "GET".to_string(),
                    "POST".to_string(),
                    "PUT".to_string(),
                    "DELETE".to_string(),
                    "PATCH".to_string(),
                    "HEAD".to_string(),
                    "OPTIONS".to_string(),
                ],
                None,
            );
        }
    }
    (Vec::new(), None)
}

/// Remove our custom attributes from the implementation block
fn clean_impl_block(impl_block: &ItemImpl) -> ItemImpl {
    let mut cleaned_impl_block = impl_block.clone();
    for item in &mut cleaned_impl_block.items {
        if let syn::ImplItem::Fn(method) = item {
            method.attrs.retain(|attr| {
                !attr.path().is_ident("init")
                    && !attr.path().is_ident("http")
                    && !attr.path().is_ident("local")
                    && !attr.path().is_ident("remote")
                    && !attr.path().is_ident("eth")
                    && !attr.path().is_ident("ws")
                    && !attr.path().is_ident("ws_client")
            });
        }
    }
    cleaned_impl_block
}

/// Check if a method has a valid self receiver (&mut self)
fn has_valid_self_receiver(method: &syn::ImplItemFn) -> bool {
    method
        .sig
        .inputs
        .first()
        .map_or(false, |arg| matches!(arg, syn::FnArg::Receiver(_)))
}

//------------------------------------------------------------------------------
// Argument Parsing Functions
//------------------------------------------------------------------------------

/// Parse the arguments to the hyperprocess macro
fn parse_args(attr_args: MetaList) -> syn::Result<HyperProcessArgs> {
    let mut name = None;
    let mut icon = None;
    let mut widget = None;
    let mut ui = None;
    let mut ui_path = None;
    let mut endpoints = None;
    let mut save_config = None;
    let mut wit_world = None;

    let span = attr_args
        .0
        .first()
        .map_or_else(|| proc_macro2::Span::call_site(), |arg| arg.span());

    for arg in &attr_args.0 {
        if let Meta::NameValue(nv) = arg {
            let key = nv.path.get_ident().unwrap().to_string();
            match key.as_str() {
                "name" => {
                    name = Some(parse_string_literal(&nv.value, nv.value.span())?);
                }
                "icon" => {
                    icon = Some(parse_string_literal(&nv.value, nv.value.span())?);
                }
                "widget" => {
                    widget = Some(parse_string_literal(&nv.value, nv.value.span())?);
                }
                "ui" => {
                    ui = parse_ui_expr(&nv.value)?;
                }
                "ui_path" => {
                    ui_path = Some(parse_string_literal(&nv.value, nv.value.span())?);
                }
                "endpoints" => endpoints = Some(nv.value.clone()),
                "save_config" => save_config = Some(nv.value.clone()),
                "wit_world" => {
                    wit_world = Some(parse_string_literal(&nv.value, nv.value.span())?);
                }
                _ => return Err(syn::Error::new(nv.path.span(), "Unknown attribute")),
            }
        } else {
            return Err(syn::Error::new(arg.span(), "Expected name-value pair"));
        }
    }

    Ok(HyperProcessArgs {
        name: name.ok_or_else(|| syn::Error::new(span, "Missing 'name'"))?,
        icon,
        widget,
        ui,
        ui_path,
        endpoints: endpoints.ok_or_else(|| syn::Error::new(span, "Missing 'endpoints'"))?,
        save_config: save_config.ok_or_else(|| syn::Error::new(span, "Missing 'save_config'"))?,
        wit_world: wit_world.ok_or_else(|| syn::Error::new(span, "Missing 'wit_world'"))?,
    })
}

//------------------------------------------------------------------------------
// Method Validation Functions
//------------------------------------------------------------------------------

/// Validate the init method signature
fn validate_init_method(method: &syn::ImplItemFn) -> syn::Result<()> {
    // Ensure the method is async
    if method.sig.asyncness.is_none() {
        return Err(syn::Error::new_spanned(
            &method.sig,
            "Init method must be declared as async",
        ));
    }

    // Ensure first param is &mut self
    if !has_valid_self_receiver(method) {
        return Err(syn::Error::new_spanned(
            &method.sig,
            "Init method must take &mut self as first parameter",
        ));
    }

    // Ensure no other parameters
    if method.sig.inputs.len() > 1 {
        return Err(syn::Error::new_spanned(
            &method.sig,
            "Init method must not take any parameters other than &mut self",
        ));
    }

    // Validate return type
    if !matches!(method.sig.output, ReturnType::Default) {
        return Err(syn::Error::new_spanned(
            &method.sig,
            "Init method must not return a value",
        ));
    }

    Ok(())
}

/// Validate the websocket method signature
fn validate_websocket_method(method: &syn::ImplItemFn) -> syn::Result<()> {
    // Ensure first param is &mut self
    if !has_valid_self_receiver(method) {
        return Err(syn::Error::new_spanned(
            &method.sig,
            "WebSocket method must take &mut self as first parameter",
        ));
    }

    // Ensure there are exactly 4 parameters (including &mut self)
    if method.sig.inputs.len() != 4 {
        return Err(syn::Error::new_spanned(
            &method.sig,
            "WebSocket method must take exactly 3 additional parameters: channel_id, message_type, and blob",
        ));
    }

    // Get parameters (excluding &mut self)
    let params: Vec<_> = method.sig.inputs.iter().skip(1).collect();

    // Check parameter types (we're not doing exact type checking, just rough check)
    let channel_id_param = &params[0];
    let message_type_param = &params[1];
    let blob_param = &params[2];

    if let syn::FnArg::Typed(pat_type) = channel_id_param {
        if !pat_type.ty.to_token_stream().to_string().contains("u32") {
            return Err(syn::Error::new_spanned(
                pat_type,
                "First parameter of WebSocket method must be channel_id: u32",
            ));
        }
    }

    if let syn::FnArg::Typed(pat_type) = message_type_param {
        let type_str = pat_type.ty.to_token_stream().to_string();
        if !type_str.contains("WsMessageType") && !type_str.contains("MessageType") {
            return Err(syn::Error::new_spanned(
                pat_type,
                "Second parameter of WebSocket method must be message_type: WsMessageType",
            ));
        }
    }

    if let syn::FnArg::Typed(pat_type) = blob_param {
        if !pat_type
            .ty
            .to_token_stream()
            .to_string()
            .contains("LazyLoadBlob")
        {
            return Err(syn::Error::new_spanned(
                pat_type,
                "Third parameter of WebSocket method must be blob: LazyLoadBlob",
            ));
        }
    }

    // Validate return type (must be unit)
    if !matches!(method.sig.output, ReturnType::Default) {
        return Err(syn::Error::new_spanned(
            &method.sig.output,
            "WebSocket method must not return a value",
        ));
    }

    Ok(())
}

/// Validate the websocket client method signature
fn validate_websocket_client_method(method: &syn::ImplItemFn) -> syn::Result<()> {
    // Ensure first param is &mut self
    if !has_valid_self_receiver(method) {
        return Err(syn::Error::new_spanned(
            &method.sig,
            "WebSocket client method must take &mut self as first parameter",
        ));
    }

    // Ensure there are exactly 4 parameters (including &mut self)
    if method.sig.inputs.len() != 4 {
        return Err(syn::Error::new_spanned(
            &method.sig,
            "WebSocket client method must take exactly 3 additional parameters: channel_id, message_type, and blob",
        ));
    }

    // Get parameters (excluding &mut self)
    let params: Vec<_> = method.sig.inputs.iter().skip(1).collect();

    // Check parameter types (we're not doing exact type checking, just rough check)
    let channel_id_param = &params[0];
    let message_type_param = &params[1];
    let blob_param = &params[2];

    if let syn::FnArg::Typed(pat_type) = channel_id_param {
        if !pat_type.ty.to_token_stream().to_string().contains("u32") {
            return Err(syn::Error::new_spanned(
                pat_type,
                "First parameter of WebSocket client method must be channel_id: u32",
            ));
        }
    }

    if let syn::FnArg::Typed(pat_type) = message_type_param {
        let type_str = pat_type.ty.to_token_stream().to_string();
        if !type_str.contains("WsMessageType") && !type_str.contains("MessageType") {
            return Err(syn::Error::new_spanned(
                pat_type,
                "Second parameter of WebSocket client method must be message_type: WsMessageType",
            ));
        }
    }

    if let syn::FnArg::Typed(pat_type) = blob_param {
        if !pat_type
            .ty
            .to_token_stream()
            .to_string()
            .contains("LazyLoadBlob")
        {
            return Err(syn::Error::new_spanned(
                pat_type,
                "Third parameter of WebSocket client method must be blob: LazyLoadBlob",
            ));
        }
    }

    // Validate return type (must be unit)
    if !matches!(method.sig.output, ReturnType::Default) {
        return Err(syn::Error::new_spanned(
            &method.sig.output,
            "WebSocket client method must not return a value",
        ));
    }

    Ok(())
}

/// Validate a request-response function signature
fn validate_request_response_function(method: &syn::ImplItemFn) -> syn::Result<()> {
    // Ensure first param is &mut self
    if !has_valid_self_receiver(method) {
        return Err(syn::Error::new_spanned(
            &method.sig,
            "Request-response handlers must take &mut self as their first parameter",
        ));
    }

    // No limit on additional parameters - we support any number
    // No validation for return type - any return type is allowed

    Ok(())
}

/// Validate the ETH handler signature
fn validate_eth_handler(method: &syn::ImplItemFn) -> syn::Result<()> {
    // Ensure first param is &mut self
    if !has_valid_self_receiver(method) {
        return Err(syn::Error::new_spanned(
            &method.sig,
            "ETH handler must take &mut self as first parameter",
        ));
    }

    // Ensure there are exactly 2 parameters (&mut self + eth_sub_result)
    if method.sig.inputs.len() != 2 {
        return Err(syn::Error::new_spanned(
            &method.sig,
            "ETH handler must take exactly one parameter: eth_sub_result: EthSubResult",
        ));
    }

    // Get the second parameter (the eth_sub_result parameter)
    let params: Vec<_> = method.sig.inputs.iter().skip(1).collect();
    let eth_param = &params[0];

    if let syn::FnArg::Typed(pat_type) = eth_param {
        let type_str = pat_type.ty.to_token_stream().to_string();
        if !type_str.contains("EthSubResult") {
            return Err(syn::Error::new_spanned(
                pat_type,
                "ETH handler parameter must be eth_sub_result: EthSubResult",
            ));
        }
    } else {
        return Err(syn::Error::new_spanned(
            eth_param,
            "ETH handler parameter must be eth_sub_result: EthSubResult",
        ));
    }

    // Any return type is allowed
    Ok(())
}

//------------------------------------------------------------------------------
// Method Analysis Functions
//------------------------------------------------------------------------------

/// Analyze the methods in an implementation block
fn analyze_methods(
    impl_block: &ItemImpl,
) -> syn::Result<(
    Option<syn::Ident>,         // init method
    Option<WsMethodInfo>,       // ws method
    Option<WsClientMethodInfo>, // ws_client method
    Option<EthMethodInfo>,      // eth method
    Vec<FunctionMetadata>,      // metadata for request/response methods
    bool,                       // whether init method contains logging init
)> {
    let mut init_method = None;
    let mut ws_method = None;
    let mut ws_client_method = None;
    let mut eth_method = None;
    let mut has_init_logging = false;
    let mut function_metadata = Vec::new();

    for item in &impl_block.items {
        if let syn::ImplItem::Fn(method) = item {
            let ident = method.sig.ident.clone();

            // Check for method attributes
            let has_init = has_attribute(method, "init");
            let has_http = has_attribute(method, "http");
            let has_local = has_attribute(method, "local");
            let has_remote = has_attribute(method, "remote");
            let has_eth = has_attribute(method, "eth");
            let has_ws = has_attribute(method, "ws");
            let has_ws_client = has_attribute(method, "ws_client");

            // Handle init method
            if has_init {
                if has_http || has_local || has_remote || has_eth || has_ws || has_ws_client {
                    return Err(syn::Error::new_spanned(
                        method,
                        "#[init] cannot be combined with other attributes",
                    ));
                }
                validate_init_method(method)?;
                if init_method.is_some() {
                    return Err(syn::Error::new_spanned(
                        method,
                        "Multiple #[init] methods defined",
                    ));
                }
                init_method = Some(ident);

                // Check if init_method contains logging init
                has_init_logging = contains_init_logging(method);

                continue;
            }

            // Handle WebSocket method
            if has_ws {
                if has_http || has_local || has_remote || has_eth || has_init || has_ws_client {
                    return Err(syn::Error::new_spanned(
                        method,
                        "#[ws] cannot be combined with other attributes",
                    ));
                }
                validate_websocket_method(method)?;
                if ws_method.is_some() {
                    return Err(syn::Error::new_spanned(
                        method,
                        "Multiple #[ws] methods defined",
                    ));
                }
                ws_method = Some(WsMethodInfo {
                    name: ident,
                    is_async: method.sig.asyncness.is_some(),
                });
                continue;
            }

            // Handle WebSocket client method
            if has_ws_client {
                if has_http || has_local || has_remote || has_eth || has_init || has_ws {
                    return Err(syn::Error::new_spanned(
                        method,
                        "#[ws_client] cannot be combined with other attributes",
                    ));
                }
                validate_websocket_client_method(method)?;
                if ws_client_method.is_some() {
                    return Err(syn::Error::new_spanned(
                        method,
                        "Multiple #[ws_client] methods defined",
                    ));
                }
                ws_client_method = Some(WsClientMethodInfo {
                    name: ident,
                    is_async: method.sig.asyncness.is_some(),
                });
                continue;
            }

            // Handle ETH method
            if has_eth {
                if has_http || has_local || has_remote || has_init || has_ws || has_ws_client {
                    return Err(syn::Error::new_spanned(
                        method,
                        "#[eth] cannot be combined with other attributes",
                    ));
                }
                validate_eth_handler(method)?;
                if eth_method.is_some() {
                    return Err(syn::Error::new_spanned(
                        method,
                        "Multiple #[eth] methods defined",
                    ));
                }
                eth_method = Some(EthMethodInfo {
                    name: ident.clone(),
                    is_async: method.sig.asyncness.is_some(),
                });
                // Continue with regular processing for function metadata
            }

            // Handle request-response methods (local, remote, http - NOT eth)
            if has_http || has_local || has_remote {
                validate_request_response_function(method)?;
                let metadata =
                    extract_function_metadata(method, has_local, has_remote, has_http, false);

                // Parameter-less HTTP handlers can optionally specify a path, but it's not required
                // They can use get_path() and get_method() to handle requests dynamically

                function_metadata.push(metadata);
            }
        }
    }

    // Check if we have at least one handler
    if function_metadata.is_empty() {
        return Err(syn::Error::new(
            proc_macro2::Span::call_site(),
            "You must specify at least one handler with #[remote], #[local] or #[http] attribute. Without any handlers, this hyperprocess wouldn't respond to any requests.",
        ));
    }

    // Check for duplicate HTTP (method + path) combinations
    // Only validate specific paths - allow multiple method-only handlers for dynamic routing
    let mut http_routes = std::collections::HashMap::new();
    for func in &function_metadata {
        if func.is_http {
            // Only validate handlers with specific paths
            if let Some(path) = &func.http_path {
                for method in &func.http_methods {
                    let route_key = (method.clone(), path.clone());
                    if let Some(existing_handler) = http_routes.get(&route_key) {
                        return Err(syn::Error::new(
                            proc_macro2::Span::call_site(),
                            format!(
                                "Duplicate HTTP route detected: {} {}\n\
                                First handler: {}\n\
                                Second handler: {}\n\
                                \n\
                                Each (method + specific path) combination must map to exactly one handler.\n\
                                Consider:\n\
                                - Using different paths for different handlers\n\
                                - Combining the logic into a single handler\n\
                                - Using method-only handlers with get_path() for dynamic routing",
                                method, path, existing_handler, func.name
                            ),
                        ));
                    }
                    http_routes.insert(route_key, &func.name);
                }
            }
            // Method-only handlers (no specific path) are allowed to coexist
            // They can use get_path() at runtime to implement custom routing logic
        }
    }

    Ok((
        init_method,
        ws_method,
        ws_client_method,
        eth_method,
        function_metadata,
        has_init_logging,
    ))
}

/// Extract metadata from a function
fn extract_function_metadata(
    method: &syn::ImplItemFn,
    is_local: bool,
    is_remote: bool,
    is_http: bool,
    is_eth: bool,
) -> FunctionMetadata {
    let ident = method.sig.ident.clone();

    // Extract parameter types (skipping &mut self)
    let params = method
        .sig
        .inputs
        .iter()
        .skip(1)
        .filter_map(|input| {
            if let syn::FnArg::Typed(pat_type) = input {
                Some((*pat_type.ty).clone())
            } else {
                None
            }
        })
        .collect();

    // Extract return type
    let return_type = match &method.sig.output {
        ReturnType::Default => None, // () - no explicit return
        ReturnType::Type(_, ty) => Some((**ty).clone()),
    };

    // Create variant name (snake_case to CamelCase)
    let variant_name = to_camel_case(&ident.to_string());

    // Parse HTTP attributes if this is an HTTP handler
    let (http_methods, http_path) = if is_http {
        parse_http_attributes(method)
    } else {
        (Vec::new(), None)
    };

    FunctionMetadata {
        name: ident,
        variant_name,
        params,
        return_type,
        is_async: method.sig.asyncness.is_some(),
        is_local,
        is_remote,
        is_http,
        is_eth,
        http_methods,
        http_path,
    }
}

/// Check if a method contains a call to init_logging
fn contains_init_logging(method: &syn::ImplItemFn) -> bool {
    let mut contains_logging = false;

    // Visitor to find init_logging calls
    struct LoggingVisitor {
        found: bool,
    }

    impl<'ast> syn::visit::Visit<'ast> for LoggingVisitor {
        fn visit_expr_call(&mut self, call: &'ast syn::ExprCall) {
            if let syn::Expr::Path(path) = &*call.func {
                if path
                    .path
                    .segments
                    .last()
                    .map(|s| s.ident == "init_logging")
                    .unwrap_or(false)
                {
                    self.found = true;
                }
            }
            syn::visit::visit_expr_call(self, call);
        }
    }

    // Visit the method body to find init_logging calls
    let mut visitor = LoggingVisitor { found: false };
    syn::visit::visit_block(&mut visitor, &method.block);

    visitor.found
}

//------------------------------------------------------------------------------
// Enum Generation Functions
//------------------------------------------------------------------------------

/// Generate Request and Response enums based on function metadata
fn generate_request_response_enums(
    function_metadata: &[FunctionMetadata],
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    if function_metadata.is_empty() {
        return (quote! {}, quote! {});
    }

    // HPMRequest enum variants - ONLY include handlers that have parameters
    // Parameter-less handlers are dispatched directly in Phase 1, not through enum deserialization
    let request_variants = function_metadata
        .iter()
        //.filter(|func| !func.params.is_empty()) // Only include handlers with parameters
        .map(|func| {
            let variant_name = format_ident!("{}", &func.variant_name);
            generate_enum_variant(&variant_name, &func.params)
        });

    // HPMResponse enum variants - include ALL handlers since they all need to return responses
    let response_variants = function_metadata.iter().map(|func| {
        let variant_name = format_ident!("{}", &func.variant_name);

        if let Some(return_type) = &func.return_type {
            let type_str = return_type.to_token_stream().to_string();
            if type_str == "()" {
                // Unit variant for () return type
                quote! { #variant_name }
            } else {
                // Tuple variant with return type
                quote! { #variant_name(#return_type) }
            }
        } else {
            // Unit variant for no explicit return
            quote! { #variant_name }
        }
    });

    // Generate the enum definitions with serialization derives
    (
        quote! {
            #[derive(Debug, serde::Serialize, serde::Deserialize)]
            enum HPMRequest {
                #(#request_variants),*
            }
        },
        quote! {
            #[derive(Debug, serde::Serialize, serde::Deserialize)]
            enum HPMResponse {
                #(#response_variants),*
            }
        },
    )
}

/// Generate a token stream for an enum variant based on parameter types
fn generate_enum_variant(
    variant_name: &syn::Ident,
    params: &[syn::Type],
) -> proc_macro2::TokenStream {
    if params.is_empty() {
        // Changed to a struct variant with no fields for functions with no parameters
        // This matches the JSON format {"VariantName": {}} sent by the client
        quote! { #variant_name }
    } else if params.len() == 1 {
        // Simple tuple variant for single parameter
        let param_type = &params[0];
        quote! { #variant_name(#param_type) }
    } else {
        // Tuple variant with multiple types for multiple parameters
        quote! { #variant_name(#(#params),*) }
    }
}

//------------------------------------------------------------------------------
// Handler Generation Functions
//------------------------------------------------------------------------------

/// Generate handler match arms for request handling
fn generate_handler_dispatch(
    handlers: &[&FunctionMetadata],
    self_ty: &Box<syn::Type>,
    handler_type: HandlerType,
) -> proc_macro2::TokenStream {
    if handlers.is_empty() {
        let message = match handler_type {
            HandlerType::Local => "No local handlers defined but received a local request",
            HandlerType::Remote => "No remote handlers defined but received a remote request",
            HandlerType::Http => "No HTTP handlers defined but received an HTTP request",
            HandlerType::Eth => "No ETH handlers defined but received an ETH request",
        };
        return quote! {
            hyperware_process_lib::logging::warn!(#message);
        };
    }

    let type_name = match handler_type {
        HandlerType::Local => "local",
        HandlerType::Remote => "remote",
        HandlerType::Http => "http",
        HandlerType::Eth => "eth",
    };

    let dispatch_arms = handlers
        .iter()
        .map(|func| generate_handler_dispatch_arm(func, self_ty, handler_type, type_name));

    // Gracefully handle unexpected variants
    let unreachable_arm = match handler_type {
        HandlerType::Http => {
            quote! {
                unexpected => {
                    hyperware_process_lib::logging::error!(
                        "Unexpected {} request variant received in HTTP handler: {:?}",
                        #type_name,
                        unexpected
                    );

                    let error_body = serde_json::json!({
                        "error": format!("Unexpected {} request variant", #type_name),
                        "received": format!("{:?}", unexpected),
                    })
                    .to_string()
                    .into_bytes();

                    hyperware_process_lib::http::server::send_response(
                        hyperware_process_lib::http::StatusCode::BAD_REQUEST,
                        None,
                        error_body,
                    );

                    hyperware_process_lib::hyperapp::clear_http_request_context();
                }
            }
        }
        _ => {
            quote! {
                unexpected => {
                    hyperware_process_lib::logging::error!(
                        "Unexpected {} request variant received in {} handler: {:?}",
                        #type_name,
                        #type_name,
                        unexpected
                    );

                    let send_error_bytes = hyperware_process_lib::hyperapp::APP_HELPERS.with(|helpers| {
                        let helpers_ref = helpers.borrow();
                        helpers_ref.current_message.clone().map(|original_message| {
                            let send_error = hyperware_process_lib::SendError {
                                kind: hyperware_process_lib::SendErrorKind::Timeout,
                                target: original_message.source().clone(),
                                message: original_message,
                                lazy_load_blob: None,
                                context: None,
                            };
                            serde_json::to_vec(&send_error)
                        })
                    });

                    if let Some(Ok(payload_bytes)) = send_error_bytes {
                        if let Err(e) = hyperware_process_lib::Response::new().body(payload_bytes).send() {
                            hyperware_process_lib::logging::error!(
                                "Failed to send SendError for unexpected {} variant: {}",
                                #type_name,
                                e
                            );
                        }
                    } else {
                        hyperware_process_lib::logging::error!(
                            "Failed to construct a SendError for unexpected {} variant",
                            #type_name,
                        );
                    }
                }
            }
        }
    };

    quote! {
        match request {
            #(#dispatch_arms)*
            #unreachable_arm
        }
    }
}

/// Generate a match arm for a specific handler
fn generate_handler_dispatch_arm(
    func: &FunctionMetadata,
    self_ty: &Box<syn::Type>,
    handler_type: HandlerType,
    type_name: &str,
) -> proc_macro2::TokenStream {
    let fn_name = &func.name;
    let variant_name = format_ident!("{}", &func.variant_name);

    // Get the appropriate response handling code
    let response_handling =
        generate_response_handling(func, &variant_name, handler_type, type_name);

    if func.is_async {
        generate_async_handler_arm(func, self_ty, fn_name, &variant_name, response_handling)
    } else {
        generate_sync_handler_arm(func, fn_name, &variant_name, response_handling)
    }
}

/// Generate response handling code based on handler type
fn generate_response_handling(
    _func: &FunctionMetadata,
    variant_name: &syn::Ident,
    handler_type: HandlerType,
    type_name: &str,
) -> proc_macro2::TokenStream {
    match handler_type {
        HandlerType::Local | HandlerType::Remote => {
            quote! {
                // Instead of wrapping in HPMResponse enum, directly serialize the result
                let resp = hyperware_process_lib::Response::new()
                    .body(serde_json::to_vec(&result).unwrap());
                resp.send().unwrap();
            }
        }
        HandlerType::Eth => {
            quote! {
                // Instead of wrapping in HPMResponse enum, directly serialize the result
                let resp = hyperware_process_lib::Response::new()
                    .body(serde_json::to_vec(&result).unwrap());
                resp.send().unwrap();
            }
        }
        HandlerType::Http => {
            quote! {
                // Instead of wrapping in HPMResponse enum, directly serialize the result
                let response_bytes = serde_json::to_vec(&result).unwrap();

                // Get headers from the current HTTP context
                let headers_opt = hyperware_process_lib::hyperapp::APP_HELPERS.with(|helpers| {
                    helpers.borrow().current_http_context.as_ref().and_then(|ctx| {
                        if ctx.response_headers.is_empty() {
                            None
                        } else {
                            Some(ctx.response_headers.clone())
                        }
                    })
                });

                // Get status code from the current HTTP context
                let response_status = hyperware_process_lib::hyperapp::APP_HELPERS.with(|helpers| {
                    helpers
                        .borrow()
                        .current_http_context
                        .as_ref()
                        .map(|ctx| ctx.response_status)
                        .unwrap_or(hyperware_process_lib::http::StatusCode::OK)
                });

                hyperware_process_lib::http::server::send_response(
                    response_status,
                    headers_opt,
                    response_bytes
                );

                // Clear HTTP context immediately after sending the response
                hyperware_process_lib::hyperapp::clear_http_request_context();
            }
        }
    }
}

/// Generate a match arm for an async handler
fn generate_async_handler_arm(
    func: &FunctionMetadata,
    self_ty: &Box<syn::Type>,
    fn_name: &syn::Ident,
    variant_name: &syn::Ident,
    response_handling: proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
    if func.params.is_empty() {
        // Updated pattern to match struct variant with no fields
        quote! {
            HPMRequest::#variant_name{} => {
                // Create a raw pointer to state for use in the async block
                let state_ptr: *mut #self_ty = state;
                hyperware_process_lib::hyperapp::spawn(async move {
                    // Inside the async block, use the pointer to access state
                    let result = unsafe { (*state_ptr).#fn_name().await };
                    #response_handling
                });
            }
        }
    } else if func.params.len() == 1 {
        // Async function with a single parameter
        quote! {
            HPMRequest::#variant_name(param) => {
                let param_captured = param;  // Capture param before moving into async block
                // Create a raw pointer to state for use in the async block
                let state_ptr: *mut #self_ty = state;
                hyperware_process_lib::hyperapp::spawn(async move {
                    // Inside the async block, use the pointer to access state
                    let result = unsafe { (*state_ptr).#fn_name(param_captured).await };
                    #response_handling
                });
            }
        }
    } else {
        // Async function with multiple parameters
        let param_count = func.params.len();
        let param_names = (0..param_count).map(|i| format_ident!("param{}", i));
        let capture_statements = (0..param_count).map(|i| {
            let param = format_ident!("param{}", i);
            let captured = format_ident!("param{}_captured", i);
            quote! { let #captured = #param; }
        });
        let captured_names = (0..param_count).map(|i| format_ident!("param{}_captured", i));

        quote! {
            HPMRequest::#variant_name(#(#param_names),*) => {
                // Capture all parameters before moving into async block
                #(#capture_statements)*
                // Create a raw pointer to state for use in the async block
                let state_ptr: *mut #self_ty = state;
                hyperware_process_lib::hyperapp::spawn(async move {
                    // Inside the async block, use the pointer to access state
                    let result = unsafe { (*state_ptr).#fn_name(#(#captured_names),*).await };
                    #response_handling
                });
            }
        }
    }
}

/// Generate a match arm for a sync handler
fn generate_sync_handler_arm(
    func: &FunctionMetadata,
    fn_name: &syn::Ident,
    variant_name: &syn::Ident,
    response_handling: proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
    if func.params.is_empty() {
        // Updated pattern to match struct variant with no fields
        quote! {
            HPMRequest::#variant_name{} => {
                let result = unsafe { (*state).#fn_name() };
                #response_handling
            }
        }
    } else if func.params.len() == 1 {
        quote! {
            HPMRequest::#variant_name(param) => {
                let result = unsafe { (*state).#fn_name(param) };
                #response_handling
            }
        }
    } else {
        let param_count = func.params.len();
        let param_names = (0..param_count).map(|i| format_ident!("param{}", i));
        let param_names2 = param_names.clone();

        quote! {
            HPMRequest::#variant_name(#(#param_names),*) => {
                let result = unsafe { (*state).#fn_name(#(#param_names2),*) };
                #response_handling
            }
        }
    }
}

//------------------------------------------------------------------------------
// Component Generation Functions
//------------------------------------------------------------------------------

/// Convert optional init method to token stream for identifier
fn init_method_opt_to_token(init_method: &Option<syn::Ident>) -> proc_macro2::TokenStream {
    if let Some(method_name) = init_method {
        quote! { Some(stringify!(#method_name)) }
    } else {
        quote! { None::<&str> }
    }
}

/// Convert optional init method to token stream for method call
fn init_method_opt_to_call(
    init_method: &Option<syn::Ident>,
    self_ty: &Box<syn::Type>,
) -> proc_macro2::TokenStream {
    if let Some(method_name) = init_method {
        quote! {
            // Create a pointer to state for use in the async block
            let state_ptr: *mut #self_ty = &mut state;
            hyperware_process_lib::hyperapp::spawn(async move {
                // Inside the async block, use the pointer to access state
                unsafe { (*state_ptr).#method_name().await };
            });
        }
    } else {
        quote! {}
    }
}

/// Convert optional WebSocket method to token stream for identifier
fn ws_method_opt_to_token(ws_method: &Option<WsMethodInfo>) -> proc_macro2::TokenStream {
    if let Some(method_info) = ws_method {
        let method_name = &method_info.name;
        quote! { Some(stringify!(#method_name)) }
    } else {
        quote! { None::<&str> }
    }
}

/// Convert optional WebSocket method to token stream for method call
fn ws_method_opt_to_call(
    ws_method: &Option<WsMethodInfo>,
    self_ty: &Box<syn::Type>,
) -> proc_macro2::TokenStream {
    if let Some(method_info) = ws_method {
        let method_name = &method_info.name;
        if method_info.is_async {
            quote! {
                // Create a raw pointer to state for use in the async block
                let state_ptr: *mut #self_ty = state;
                hyperware_process_lib::hyperapp::spawn(async move {
                    // Inside the async block, use the pointer to access state
                    unsafe { (*state_ptr).#method_name(channel_id, message_type, blob).await };
                });
            }
        } else {
            quote! { unsafe { (*state).#method_name(channel_id, message_type, blob) }; }
        }
    } else {
        quote! {}
    }
}

/// Convert optional WebSocket client method to token stream for identifier
fn ws_client_method_opt_to_token(
    ws_client_method: &Option<WsClientMethodInfo>,
) -> proc_macro2::TokenStream {
    if let Some(method_info) = ws_client_method {
        let method_name = &method_info.name;
        quote! { Some(stringify!(#method_name)) }
    } else {
        quote! { None::<&str> }
    }
}

/// Convert optional WebSocket client method to token stream for method call
fn ws_client_method_opt_to_call(
    ws_client_method: &Option<WsClientMethodInfo>,
    self_ty: &Box<syn::Type>,
) -> proc_macro2::TokenStream {
    if let Some(method_info) = ws_client_method {
        let method_name = &method_info.name;
        if method_info.is_async {
            quote! {
                // Create a raw pointer to state for use in the async block
                let state_ptr: *mut #self_ty = state;
                hyperware_process_lib::hyperapp::spawn(async move {
                    // Inside the async block, use the pointer to access state
                    unsafe { (*state_ptr).#method_name(channel_id, message_type, blob).await };
                });
            }
        } else {
            quote! { unsafe { (*state).#method_name(channel_id, message_type, blob) }; }
        }
    } else {
        quote! {}
    }
}

/// Convert optional ETH method to token stream for identifier
fn eth_method_opt_to_token(eth_method: &Option<EthMethodInfo>) -> proc_macro2::TokenStream {
    if let Some(method_info) = eth_method {
        let method_name = &method_info.name;
        quote! { Some(stringify!(#method_name)) }
    } else {
        quote! { None::<&str> }
    }
}

/// Convert optional ETH method to token stream for method call
fn eth_method_opt_to_call(
    eth_method: &Option<EthMethodInfo>,
    self_ty: &Box<syn::Type>,
) -> proc_macro2::TokenStream {
    if let Some(method_info) = eth_method {
        let method_name = &method_info.name;
        if method_info.is_async {
            quote! {
                // Create a raw pointer to state for use in the async block
                let state_ptr: *mut #self_ty = state;
                hyperware_process_lib::hyperapp::spawn(async move {
                    // Inside the async block, use the pointer to access state
                    unsafe { (*state_ptr).#method_name(eth_sub_result).await };
                });
            }
        } else {
            quote! { unsafe { (*state).#method_name(eth_sub_result) }; }
        }
    } else {
        quote! {}
    }
}

//------------------------------------------------------------------------------
// HTTP Helper Functions
//------------------------------------------------------------------------------

/// Generate HTTP context setup code
fn generate_http_context_setup() -> proc_macro2::TokenStream {
    quote! {
        hyperware_process_lib::hyperapp::APP_HELPERS.with(|helpers| {
            helpers.borrow_mut().current_http_context = Some(hyperware_process_lib::hyperapp::HttpRequestContext {
                request: http_request,
                response_headers: std::collections::HashMap::new(),
                response_status: hyperware_process_lib::http::StatusCode::OK,
            });
        });
        hyperware_process_lib::logging::debug!("HTTP context established");
    }
}

/// Generate HTTP context cleanup code
fn generate_http_context_cleanup() -> proc_macro2::TokenStream {
    quote! {
        hyperware_process_lib::hyperapp::clear_http_request_context();
    }
}

/// Generate HTTP error response handling
fn generate_http_error_response(
    status: &str,
    message: proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
    let status_ident = format_ident!("{}", status);
    let cleanup = generate_http_context_cleanup();
    quote! {
        hyperware_process_lib::http::server::send_response(
            hyperware_process_lib::http::StatusCode::#status_ident,
            None,
            #message.into_bytes()
        );
        #cleanup
    }
}

/// Generate HTTP method and path parsing code
fn generate_http_request_parsing() -> proc_macro2::TokenStream {
    quote! {
        let http_method = hyperware_process_lib::hyperapp::get_http_method()
            .unwrap_or_else(|| {
                hyperware_process_lib::logging::warn!("Failed to get HTTP method from request context");
                "UNKNOWN".to_string()
            });

        let current_path = match hyperware_process_lib::hyperapp::get_path() {
            Some(path) => {
                hyperware_process_lib::logging::debug!("Successfully parsed HTTP path: '{}'", path);
                path
            },
            None => {
                hyperware_process_lib::logging::error!("Failed to get HTTP path: no HTTP context available");
                hyperware_process_lib::http::server::send_response(
                    hyperware_process_lib::http::StatusCode::BAD_REQUEST,
                    None,
                    b"Invalid path: no HTTP context available".to_vec(),
                );
                hyperware_process_lib::hyperapp::clear_http_request_context();
                return;
            }
        };
    }
}

/// Generate parameterized handler dispatch arms
fn generate_parameterized_handler_dispatch(
    parameterized_handlers: &[&&FunctionMetadata],
    self_ty: &Box<syn::Type>,
    http_request_match_arms: &proc_macro2::TokenStream,
    specific_paths: &[&String],
) -> proc_macro2::TokenStream {
    let mut sorted_handlers = parameterized_handlers.to_vec();
    sorted_handlers.sort_by_key(|handler| handler.http_path.is_none());

    let dispatch_arms: Vec<_> = sorted_handlers.iter().map(|handler| {
        let fn_name = &handler.name;
        let variant_name = format_ident!("{}", &handler.variant_name);
        let path_check = if let Some(path) = &handler.http_path {
            quote! { &current_path == #path }
        } else {
            quote! { ![#(#specific_paths),*].contains(&current_path.as_str()) }
        };
        let methods = &handler.http_methods;
        let method_check = quote! { [#(#methods),*].contains(&http_method.as_str()) };

        quote! {
            hyperware_process_lib::logging::debug!("Checking parameterized handler {} for {} {} - path_check: {}, method_check: {}",
                stringify!(#fn_name), http_method, current_path, (#path_check), (#method_check));
            if #path_check && #method_check {
                hyperware_process_lib::logging::debug!("Matched parameterized handler {} for {} {}", stringify!(#fn_name), http_method, current_path);

                if let Some(ref blob) = blob_opt {
                    hyperware_process_lib::logging::debug!("Got blob with {} bytes: {}", blob.bytes.len(), String::from_utf8_lossy(&blob.bytes));
                    match serde_json::from_slice::<HPMRequest>(&blob.bytes) {
                        Ok(request) => {
                            match request {
                                HPMRequest::#variant_name(..) => {
                                    unsafe {
                                        #http_request_match_arms
                                        hyperware_process_lib::hyperapp::maybe_save_state(&mut *state);
                                    }
                                },
                                _ => {
                                    hyperware_process_lib::logging::error!("Request body contains wrong handler name for {} {}", http_method, current_path);
                                    hyperware_process_lib::http::server::send_response(
                                        hyperware_process_lib::http::StatusCode::BAD_REQUEST,
                                        None,
                                        format!("Expected handler name '{}' in request body", stringify!(#variant_name)).into_bytes()
                                    );
                                }
                            }
                        },
                        Err(e) => {
                            let error_details = if blob.bytes.is_empty() {
                                "Request body is empty but was expected to contain handler parameters.".to_string()
                            } else if let Ok(json_value) = serde_json::from_slice::<serde_json::Value>(&blob.bytes) {
                                format!(
                                    "Invalid request format. Expected one of the parameterized handler formats, but got: {}",
                                    serde_json::to_string(&json_value).unwrap_or_else(|_| "invalid JSON".to_string())
                                )
                            } else {
                                format!(
                                    "Invalid JSON in request body. Parse error: {}",
                                    e
                                )
                            };

                            hyperware_process_lib::logging::error!("Failed to parse request body for {} {}: {}", http_method, current_path, error_details);

                            hyperware_process_lib::http::server::send_response(
                                hyperware_process_lib::http::StatusCode::BAD_REQUEST,
                                None,
                                error_details.into_bytes()
                            );
                            hyperware_process_lib::hyperapp::clear_http_request_context();
                            return;
                        }
                    }
                } else {
                    hyperware_process_lib::logging::error!("Handler {} requires a request body", stringify!(#fn_name));
                    hyperware_process_lib::http::server::send_response(
                        hyperware_process_lib::http::StatusCode::BAD_REQUEST,
                        None,
                        format!("Handler {} requires a request body", stringify!(#fn_name)).into_bytes()
                    );
                }
                return;
            }
        }
    }).collect();

    quote! { #(#dispatch_arms)* }
}

/// Generate parameterless handler dispatch arms
fn generate_parameterless_handler_dispatch(
    parameterless_handlers: &[&&FunctionMetadata],
    self_ty: &Box<syn::Type>,
    specific_paths: &[&String],
) -> proc_macro2::TokenStream {
    let mut sorted_handlers = parameterless_handlers.to_vec();
    sorted_handlers.sort_by_key(|handler| handler.http_path.is_none());

    let dispatch_arms: Vec<_> = sorted_handlers.iter().map(|handler| {
        let fn_name = &handler.name;
        let path_check = if let Some(path) = &handler.http_path {
            quote! { &current_path == #path }
        } else {
            quote! { ![#(#specific_paths),*].contains(&current_path.as_str()) }
        };
        let methods = &handler.http_methods;
        let method_check = quote! { [#(#methods),*].contains(&http_method.as_str()) };

        let response_handling = quote! {
            let response_bytes = match serde_json::to_vec(&result) {
                Ok(bytes) => bytes,
                Err(e) => {
                    hyperware_process_lib::logging::error!("Failed to serialize response: {}", e);
                    hyperware_process_lib::http::server::send_response(
                        hyperware_process_lib::http::StatusCode::INTERNAL_SERVER_ERROR,
                        None,
                        "Failed to serialize response".as_bytes().to_vec(),
                    );
                    return;
                }
            };

            let headers_opt = hyperware_process_lib::hyperapp::APP_HELPERS.with(|helpers| {
                helpers.borrow().current_http_context.as_ref().and_then(|ctx| {
                    if ctx.response_headers.is_empty() {
                        None
                    } else {
                        Some(ctx.response_headers.clone())
                    }
                })
            });

            let response_status = hyperware_process_lib::hyperapp::APP_HELPERS.with(|helpers| {
                helpers
                    .borrow()
                    .current_http_context
                    .as_ref()
                    .map(|ctx| ctx.response_status)
                    .unwrap_or(hyperware_process_lib::http::StatusCode::OK)
            });

            hyperware_process_lib::http::server::send_response(
                response_status,
                headers_opt,
                response_bytes
            );

            hyperware_process_lib::hyperapp::clear_http_request_context();
        };

        let handler_body = if handler.is_async {
            quote! {
                let state_ptr: *mut #self_ty = state;
                hyperware_process_lib::hyperapp::spawn(async move {
                    let result = unsafe { (*state_ptr).#fn_name().await };
                    #response_handling
                });
                unsafe { hyperware_process_lib::hyperapp::maybe_save_state(&mut *state); }
            }
        } else {
            quote! {
                let result = unsafe { (*state).#fn_name() };
                #response_handling
                unsafe { hyperware_process_lib::hyperapp::maybe_save_state(&mut *state); }
            }
        };

        quote! {
            hyperware_process_lib::logging::debug!("Checking parameter-less handler {} for {} {} - path_check: {}, method_check: {}",
                stringify!(#fn_name), http_method, current_path, (#path_check), (#method_check));
            if #path_check && #method_check {
                hyperware_process_lib::logging::debug!("Matched parameter-less handler {} for {} {}", stringify!(#fn_name), http_method, current_path);
                #handler_body
                return;
            }
        }
    }).collect();

    quote! { #(#dispatch_arms)* }
}

/// Generate HTTP handler dispatcher
fn generate_http_handler_dispatcher(
    http_handlers: &[&FunctionMetadata],
    self_ty: &Box<syn::Type>,
    http_request_match_arms: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
    let specific_paths: Vec<_> = http_handlers
        .iter()
        .filter_map(|h| h.http_path.as_ref())
        .collect();

    let parameterized_handlers: Vec<_> = http_handlers
        .iter()
        .filter(|h| !h.params.is_empty())
        .collect();

    let parameterless_handlers: Vec<_> = http_handlers
        .iter()
        .filter(|h| h.params.is_empty())
        .collect();

    let parameterized_dispatch = generate_parameterized_handler_dispatch(
        &parameterized_handlers,
        self_ty,
        http_request_match_arms,
        &specific_paths,
    );

    let parameterless_dispatch =
        generate_parameterless_handler_dispatch(&parameterless_handlers, self_ty, &specific_paths);

    quote! {
        hyperware_process_lib::logging::debug!("Starting handler matching for {} {}", http_method, current_path);

        if blob_opt.is_some() && !blob_opt.as_ref().unwrap().bytes.is_empty() {
            hyperware_process_lib::logging::debug!("Request has body, using two-phase matching");

            if let Some(ref blob) = blob_opt {
                match serde_json::from_slice::<HPMRequest>(&blob.bytes) {
                    Ok(request) => {
                        hyperware_process_lib::logging::debug!("Successfully parsed request body, dispatching to specific handler");
                        unsafe {
                            #http_request_match_arms
                            hyperware_process_lib::hyperapp::maybe_save_state(&mut *state);
                        }
                        return;
                    },
                    Err(e) => {
                        let error_details = if blob.bytes.is_empty() {
                            "Request body is empty but was expected to contain handler parameters.".to_string()
                        } else if let Ok(json_value) = serde_json::from_slice::<serde_json::Value>(&blob.bytes) {
                            format!(
                                "Invalid request format. Expected one of the parameterized handler formats, but got: {}",
                                serde_json::to_string(&json_value).unwrap_or_else(|_| "invalid JSON".to_string())
                            )
                        } else {
                            format!(
                                "Invalid JSON in request body. Parse error: {}",
                                e
                            )
                        };

                        hyperware_process_lib::logging::error!("Failed to parse request body for {} {}: {}", http_method, current_path, error_details);

                        hyperware_process_lib::http::server::send_response(
                            hyperware_process_lib::http::StatusCode::BAD_REQUEST,
                            None,
                            error_details.into_bytes()
                        );
                        hyperware_process_lib::hyperapp::clear_http_request_context();
                        return;
                    }
                }
            }
        } else {
            hyperware_process_lib::logging::debug!("Request has no body, trying parameter-less handlers first");
            #parameterless_dispatch
        }

        hyperware_process_lib::logging::error!("No handler found for {} {} - all handlers checked", http_method, current_path);
        hyperware_process_lib::http::server::send_response(
            hyperware_process_lib::http::StatusCode::NOT_FOUND,
            None,
            format!("No handler found for {} {}", http_method, current_path).into_bytes(),
        );
        hyperware_process_lib::hyperapp::clear_http_request_context();
    }
}

//------------------------------------------------------------------------------
// WebSocket Helper Functions
//------------------------------------------------------------------------------

/// Generate WebSocket client message handler
fn generate_websocket_client_handler(
    ws_client_method_call: &proc_macro2::TokenStream,
    self_ty: &Box<syn::Type>,
) -> proc_macro2::TokenStream {
    quote! {
        let blob_opt = message.blob();

        match serde_json::from_slice::<hyperware_process_lib::http::client::HttpClientRequest>(message.body()) {
            Ok(request) => {
                match request {
                    hyperware_process_lib::http::client::HttpClientRequest::WebSocketPush { channel_id, message_type } => {
                        hyperware_process_lib::logging::debug!("Received WebSocket client push on channel {}, type: {:?}", channel_id, message_type);

                        if message_type == hyperware_process_lib::http::server::WsMessageType::Pong {
                            return;
                        }

                        if message_type == hyperware_process_lib::http::server::WsMessageType::Ping {
                            // Respond to Pings with Pongs
                            hyperware_process_lib::http::client::send_ws_client_push(
                                channel_id,
                                hyperware_process_lib::http::server::WsMessageType::Pong,
                                hyperware_process_lib::LazyLoadBlob::default(),
                            );
                            return;
                        }

                        let Some(blob) = blob_opt else {
                            hyperware_process_lib::logging::error!(
                                "Failed to get blob for WebSocket client push on channel {}. This indicates a malformed WebSocket message.",
                                channel_id
                            );
                            return;
                        };

                        hyperware_process_lib::logging::debug!("Processing WebSocket client message with {} bytes", blob.bytes.len());

                        #ws_client_method_call

                        unsafe {
                            hyperware_process_lib::hyperapp::maybe_save_state(&mut *state);
                        }
                    },
                    hyperware_process_lib::http::client::HttpClientRequest::WebSocketClose { channel_id } => {
                        hyperware_process_lib::logging::debug!("WebSocket client connection closed on channel {}", channel_id);

                        // Call the handler with a special Close message type and empty blob
                        let message_type = hyperware_process_lib::http::server::WsMessageType::Close;
                        let blob = hyperware_process_lib::LazyLoadBlob::default();

                        #ws_client_method_call

                        unsafe {
                            hyperware_process_lib::hyperapp::maybe_save_state(&mut *state);
                        }
                    }
                }
            },
            Err(e) => {
                hyperware_process_lib::logging::error!(
                    "Failed to parse WebSocket client request: {}\n\
                    Source: {:?}\n\
                    This usually indicates a malformed message from the http-client service.",
                    e, message.source()
                );
            }
        }
    }
}

/// Generate WebSocket message handler
fn generate_websocket_handler(
    ws_method_call: &proc_macro2::TokenStream,
    self_ty: &Box<syn::Type>,
) -> proc_macro2::TokenStream {
    quote! {
        hyperware_process_lib::http::server::HttpServerRequest::WebSocketPush { channel_id, message_type } => {
            hyperware_process_lib::logging::debug!("Received WebSocket message on channel {}, type: {:?}", channel_id, message_type);

            if message_type == hyperware_process_lib::http::server::WsMessageType::Pong {
                return;
            }

            if message_type == hyperware_process_lib::http::server::WsMessageType::Ping {
                // Respond to Pings with Pongs
                hyperware_process_lib::http::server::send_ws_push(
                    channel_id,
                    hyperware_process_lib::http::server::WsMessageType::Pong,
                    hyperware_process_lib::LazyLoadBlob::default(),
                );
                return;
            }

            let Some(blob) = blob_opt else {
                hyperware_process_lib::logging::error!(
                    "Failed to get blob for WebSocketPush on channel {}. This indicates a malformed WebSocket message.",
                    channel_id
                );
                return;
            };

            hyperware_process_lib::logging::debug!("Processing WebSocket message with {} bytes", blob.bytes.len());
            #ws_method_call

            unsafe {
                hyperware_process_lib::hyperapp::maybe_save_state(&mut *state);
            }
        },
        hyperware_process_lib::http::server::HttpServerRequest::WebSocketOpen { path, channel_id, source_socket_addr, forwarded_for } => {
            hyperware_process_lib::logging::debug!("WebSocket connection opened on path '{}' with channel {}", path, channel_id);
            match hyperware_process_lib::hyperapp::get_server() {
                Some(server) => server.handle_websocket_open(&path, channel_id, source_socket_addr, forwarded_for),
                None => hyperware_process_lib::logging::error!("Failed to get server instance for WebSocket open event")
            }
        },
        hyperware_process_lib::http::server::HttpServerRequest::WebSocketClose(channel_id) => {
            hyperware_process_lib::logging::debug!("WebSocket connection closed on channel {}", channel_id);
            match hyperware_process_lib::hyperapp::get_server() {
                Some(server) => server.handle_websocket_close(channel_id),
                None => hyperware_process_lib::logging::error!("Failed to get server instance for WebSocket close event")
            }
        }
    }
}

//------------------------------------------------------------------------------
// Local/Remote Message Helper Functions
//------------------------------------------------------------------------------

/// Generate local message handler
fn generate_local_message_handler(
    self_ty: &Box<syn::Type>,
    match_arms: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
    quote! {
        /// Handle local messages
        fn handle_local_message(state: *mut #self_ty, message: hyperware_process_lib::Message) {
            hyperware_process_lib::logging::debug!("Processing local message from: {:?}", message.source());
            match serde_json::from_slice::<HPMRequest>(message.body()) {
                Ok(request) => {
                    unsafe {
                        #match_arms
                        hyperware_process_lib::hyperapp::maybe_save_state(&mut *state);
                    }
                },
                Err(e) => {
                    let raw_body = String::from_utf8_lossy(message.body());
                    hyperware_process_lib::logging::error!(
                        "Failed to deserialize local request into HPMRequest enum.\n\
                        Error: {}\n\
                        Source: {:?}\n\
                        Body: {}\n\
                        \n\
                        💡 This usually means the message format doesn't match any of your #[local] or #[remote] handlers.\n\
                        💡 If you are sending an HTTP message, if it is malformed, it might have ended up in the local message handler.",
                        e, message.source(), raw_body
                    );
                }
            }
        }
    }
}

/// Generate remote message handler
fn generate_remote_message_handler(
    self_ty: &Box<syn::Type>,
    match_arms: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
    quote! {
        /// Handle remote messages
        fn handle_remote_message(state: *mut #self_ty, message: hyperware_process_lib::Message) {
            hyperware_process_lib::logging::debug!("Processing remote message from: {:?}", message.source());
            match serde_json::from_slice::<HPMRequest>(message.body()) {
                Ok(request) => {
                    unsafe {
                        #match_arms
                        hyperware_process_lib::hyperapp::maybe_save_state(&mut *state);
                    }
                },
                Err(e) => {
                    let raw_body = String::from_utf8_lossy(message.body());
                    hyperware_process_lib::logging::error!(
                        "Failed to deserialize remote request into HPMRequest enum.\n\
                        Error: {}\n\
                        Source: {:?}\n\
                        Body: {}\n\
                        \n\
                        💡 This usually means the message format doesn't match any of your #[remote] handlers.",
                        e, message.source(), raw_body
                    );
                }
            }
        }
    }
}

/// Generate message handler functions for message types
fn generate_message_handlers(
    self_ty: &Box<syn::Type>,
    handler_arms: &HandlerDispatch,
    ws_method_call: &proc_macro2::TokenStream,
    ws_client_method_call: &proc_macro2::TokenStream,
    eth_method_call: &proc_macro2::TokenStream,
    http_handlers: &[&FunctionMetadata],
) -> proc_macro2::TokenStream {
    let http_request_match_arms = &handler_arms.http;
    let local_and_remote_request_match_arms = &handler_arms.local_and_remote;
    let remote_request_match_arms = &handler_arms.remote;

    let http_context_setup = generate_http_context_setup();
    let http_request_parsing = generate_http_request_parsing();
    let http_dispatcher =
        generate_http_handler_dispatcher(http_handlers, self_ty, http_request_match_arms);
    let websocket_handlers = generate_websocket_handler(ws_method_call, self_ty);
    let websocket_client_handler =
        generate_websocket_client_handler(ws_client_method_call, self_ty);
    let local_message_handler =
        generate_local_message_handler(self_ty, local_and_remote_request_match_arms);
    let remote_message_handler =
        generate_remote_message_handler(self_ty, remote_request_match_arms);
    let eth_message_handler = generate_eth_message_handler(self_ty, eth_method_call);

    quote! {
        /// Handle WebSocket client messages
        fn handle_websocket_client_message(state: *mut #self_ty, message: hyperware_process_lib::Message) {
            #websocket_client_handler
        }
        /// Handle messages from the HTTP server
        fn handle_http_server_message(state: *mut #self_ty, http_server_request: hyperware_process_lib::http::server::HttpServerRequest, blob_opt: Option<hyperware_process_lib::LazyLoadBlob>) {
            match http_server_request {
                hyperware_process_lib::http::server::HttpServerRequest::Http(http_request) => {
                    hyperware_process_lib::logging::debug!("Processing HTTP request, message has blob: {}", blob_opt.is_some());
                    if let Some(ref blob) = blob_opt {
                        hyperware_process_lib::logging::debug!("Blob size: {} bytes, content: {}", blob.bytes.len(), String::from_utf8_lossy(&blob.bytes[..std::cmp::min(200, blob.bytes.len())]));
                    }
                    #http_context_setup
                    #http_request_parsing
                    #http_dispatcher
                },
                #websocket_handlers
            }
        }
        
        #local_message_handler
        #remote_message_handler
        #eth_message_handler
    }
}

/// Generate ETH message handler
fn generate_eth_message_handler(
    self_ty: &Box<syn::Type>,
    eth_method_call: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
    quote! {
        /// Handle ETH messages
        fn handle_eth_message(state: *mut #self_ty, message: hyperware_process_lib::Message) {
            hyperware_process_lib::logging::debug!("Processing ETH message from: {:?}", message.source());

            // ETH messages contain EthSubResult directly, not wrapped in HPMRequest
            match serde_json::from_slice::<hyperware_process_lib::eth::EthSubResult>(message.body()) {
                Ok(eth_sub_result) => {
                    hyperware_process_lib::logging::debug!("Successfully parsed EthSubResult, calling ETH handler");
                    #eth_method_call
                    unsafe {
                        hyperware_process_lib::hyperapp::maybe_save_state(&mut *state);
                    }
                },
                Err(e) => {
                    let raw_body = String::from_utf8_lossy(message.body());
                    hyperware_process_lib::logging::error!(
                        "Failed to deserialize ETH message into EthSubResult.\n\
                        Error: {}\n\
                        Source: {:?}\n\
                        Body: {}\n\
                        \n\
                        💡 This usually means the message format from eth:distro:sys doesn't match EthSubResult.",
                        e, message.source(), raw_body
                    );
                }
            }
        }
    }
}

/// Helper function to determine if an Expr is "None"
fn is_none_literal(expr: &Expr) -> bool {
    if let Expr::Path(expr_path) = expr {
        if let Some(ident) = expr_path.path.get_ident() {
            return ident == "None";
        }
    }
    false
}

/// Generate the full component implementation
fn generate_component_impl(
    args: &HyperProcessArgs,
    self_ty: &Box<syn::Type>,
    cleaned_impl_block: &ItemImpl,
    request_enum: &proc_macro2::TokenStream,
    response_enum: &proc_macro2::TokenStream,
    init_method_details: &InitMethodDetails,
    ws_method_details: &WsMethodDetails,
    ws_client_method_details: &WsClientMethodDetails,
    eth_method_details: &EthMethodDetails,
    handler_arms: &HandlerDispatch,
    has_init_logging: bool,
    http_handlers: &[&FunctionMetadata],
) -> proc_macro2::TokenStream {
    // Extract values from args for use in the quote macro
    let name = &args.name;
    let endpoints = &args.endpoints;
    let save_config = &args.save_config;
    let wit_world = &args.wit_world;

    let icon = match &args.icon {
        Some(icon_str) => quote! { Some(#icon_str.to_string()) },
        None => quote! { None },
    };

    let widget = match &args.widget {
        Some(widget_str) => quote! { Some(#widget_str.to_string()) },
        None => quote! { None },
    };

    let ui = match &args.ui {
        Some(ui_expr) => {
            if is_none_literal(ui_expr) {
                quote! { None }
            } else {
                quote! { Some(#ui_expr) }
            }
        }
        None => quote! { None },
    };

    let ui_path = match &args.ui_path {
        Some(path_str) => quote! { Some(#path_str.to_string()) },
        None => quote! { None },
    };

    let init_method_ident = &init_method_details.identifier;
    let init_method_call = &init_method_details.call;
    let ws_method_call = &ws_method_details.call;
    let ws_client_method_call = &ws_client_method_details.call;
    let eth_method_call = &eth_method_details.call;

    // Generate message handler functions
    let message_handlers = generate_message_handlers(
        self_ty,
        handler_arms,
        ws_method_call,
        ws_client_method_call,
        eth_method_call,
        http_handlers,
    );

    // Generate the logging initialization conditionally
    let logging_init = if !has_init_logging {
        quote! {
            // Initialize logging
            hyperware_process_lib::logging::init_logging(
                hyperware_process_lib::logging::Level::DEBUG,
                hyperware_process_lib::logging::Level::INFO,
                None, Some((0, 0, 1, 1)), None
            ).unwrap();
        }
    } else {
        // Empty if init_method already does logging initialization
        quote! {}
    };

    quote! {
        wit_bindgen::generate!({
            path: "../target/wit",
            world: #wit_world,
            generate_unused_types: true,
            additional_derives: [serde::Deserialize, serde::Serialize, process_macros::SerdeJsonInto],
        });

        use hyperware_process_lib::http::server::HttpBindingConfig;
        use hyperware_process_lib::http::server::WsBindingConfig;
        use hyperware_process_lib::hyperapp::Binding;

        #cleaned_impl_block

        // Add our generated request/response enums
        #request_enum
        #response_enum

        #message_handlers

        struct Component;
        impl Guest for Component {
            fn init(_our: String) {
                // Initialize our state
                let mut state = hyperware_process_lib::hyperapp::initialize_state::<#self_ty>();

                // Set to persist state according to user setting
                hyperware_process_lib::hyperapp::APP_CONTEXT.with(|ctx| {
                    ctx.borrow_mut().hidden_state = Some(
                        hyperware_process_lib::hyperapp::HiddenState::new(#save_config)
                    );
                });

                // Set up necessary components
                let app_name = #name;
                let app_icon = #icon;
                let app_widget = #widget;
                let ui_config = #ui;
                let ui_path = #ui_path;
                let endpoints = #endpoints;

                // Setup UI if needed
                if app_icon.is_some() && app_widget.is_some() {
                    hyperware_process_lib::homepage::add_to_homepage(app_name, app_icon, Some("/"), app_widget);
                }

                #logging_init

                // Setup server with endpoints
                let mut server = hyperware_process_lib::hyperapp::setup_server(ui_config.as_ref(), ui_path, &endpoints);
                hyperware_process_lib::hyperapp::APP_HELPERS.with(|ctx| {
                    ctx.borrow_mut().current_server = Some(&mut server);
                });

                // Initialize app state
                if #init_method_ident.is_some() {
                    #init_method_call
                }

                // Main event loop
                loop {
                    hyperware_process_lib::hyperapp::APP_CONTEXT.with(|ctx| {
                        ctx.borrow_mut().executor.poll_all_tasks();
                    });

                    match hyperware_process_lib::await_message() {
                        Ok(message) => {
                            hyperware_process_lib::hyperapp::APP_HELPERS.with(|ctx| {
                                ctx.borrow_mut().current_message = Some(message.clone());
                            });

                            // Store old state if needed (for OnDiff save option)
                            // This only stores if old_state is None (first time or after a save)
                            hyperware_process_lib::hyperapp::store_old_state(&state);

                            match message {
                                hyperware_process_lib::Message::Response { body, context, .. } => {
                                    let correlation_id = context
                                        .as_deref()
                                        .map(|bytes| String::from_utf8_lossy(bytes).to_string())
                                        .unwrap_or_else(|| "no context".to_string());
                                    let was_cancelled =
                                        hyperware_process_lib::hyperapp::CANCELLED_RESPONSES.with(|set| {
                                            set.borrow_mut().remove(&correlation_id)
                                        });
                                    if !was_cancelled {
                                        hyperware_process_lib::hyperapp::RESPONSE_REGISTRY.with(|registry| {
                                            registry.borrow_mut().insert(correlation_id, body);
                                        });
                                    }
                                }
                                hyperware_process_lib::Message::Request { .. } => {
                                    if message.is_local() && message.source().process == "http-server:distro:sys" {
                                        if let Ok(http_server_request) = serde_json::from_slice::<hyperware_process_lib::http::server::HttpServerRequest>(message.body()) {
                                            handle_http_server_message(&mut state, http_server_request, message.blob());
                                        } else {
                                            handle_local_message(&mut state, message);
                                        }
                                    } else if message.is_local() && message.source().process == "http-client:distro:sys" {
                                        handle_websocket_client_message(&mut state, message);
                                    } else if message.is_local() && message.source().process == "eth:distro:sys" {
                                        handle_eth_message(&mut state, message);
                                    } else if message.is_local() {
                                        handle_local_message(&mut state, message);
                                    } else {
                                        handle_remote_message(&mut state, message);
                                    }
                                }
                            }
                        },
                        Err(ref error) => {
                            if let hyperware_process_lib::SendError {
                                context: Some(context),
                                ..
                            } = error
                            {
                                let correlation_id = String::from_utf8_lossy(context)
                                    .to_string();
                                let was_cancelled =
                                    hyperware_process_lib::hyperapp::CANCELLED_RESPONSES.with(|set| {
                                        set.borrow_mut().remove(&correlation_id)
                                    });
                                if !was_cancelled {
                                    hyperware_process_lib::hyperapp::RESPONSE_REGISTRY.with(|registry| {
                                        registry.borrow_mut().insert(
                                            correlation_id,
                                            serde_json::to_vec(error).unwrap(),
                                        );
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }

        export!(Component);
    }
}

//------------------------------------------------------------------------------
// Main Macro Implementation
//------------------------------------------------------------------------------

/// The main procedural macro
#[proc_macro_attribute]
pub fn hyperapp(attr: TokenStream, item: TokenStream) -> TokenStream {
    // Parse the input
    let attr_args = parse_macro_input!(attr as MetaList);
    let impl_block = parse_macro_input!(item as ItemImpl);

    // Parse the macro arguments
    let args = match parse_args(attr_args) {
        Ok(args) => args,
        Err(e) => return e.to_compile_error().into(),
    };

    // Get the self type from the implementation block
    let self_ty = &impl_block.self_ty;

    // Analyze the methods in the implementation block
    let (init_method, ws_method, ws_client_method, eth_method, function_metadata, has_init_logging) =
        match analyze_methods(&impl_block) {
            Ok(methods) => methods,
            Err(e) => return e.to_compile_error().into(),
        };

    // Filter functions by handler type
    let handlers = HandlerGroups::from_function_metadata(&function_metadata);

    // HTTP handlers with parameters will be part of the HPMRequest enum and dispatched via body deserialization.
    let http_handlers_with_params: Vec<_> = handlers.http.iter().cloned().collect();

    // Collect all function metadata that will be represented in the HPMRequest enum.
    // This includes all local and remote handlers, plus HTTP handlers that have parameters.
    let metadata_for_enum: Vec<_> = function_metadata.iter().cloned().collect();

    // Generate HPMRequest and HPMResponse enums from the filtered list of functions
    let (request_enum, response_enum) = generate_request_response_enums(&metadata_for_enum);

    // Generate handler match arms
    let handler_arms = HandlerDispatch {
        local: generate_handler_dispatch(&handlers.local, self_ty, HandlerType::Local),
        remote: generate_handler_dispatch(&handlers.remote, self_ty, HandlerType::Remote),
        // HTTP dispatch arms are only generated for handlers with parameters.
        http: generate_handler_dispatch(&http_handlers_with_params, self_ty, HandlerType::Http),
        // Generate dispatch for combined local and remote handlers
        local_and_remote: generate_handler_dispatch(
            &handlers.local_and_remote,
            self_ty,
            HandlerType::Local,
        ),
    };

    // Clean the implementation block
    let cleaned_impl_block = clean_impl_block(&impl_block);

    // Prepare init method details for code generation
    let init_method_details = InitMethodDetails {
        identifier: init_method_opt_to_token(&init_method),
        call: init_method_opt_to_call(&init_method, self_ty),
    };

    // Prepare WebSocket method details for code generation
    let ws_method_details = WsMethodDetails {
        identifier: ws_method_opt_to_token(&ws_method),
        call: ws_method_opt_to_call(&ws_method, self_ty),
    };

    // Prepare WebSocket client method details for code generation
    let ws_client_method_details = WsClientMethodDetails {
        identifier: ws_client_method_opt_to_token(&ws_client_method),
        call: ws_client_method_opt_to_call(&ws_client_method, self_ty),
    };

    // Prepare ETH method details for code generation
    let eth_method_details = EthMethodDetails {
        identifier: eth_method_opt_to_token(&eth_method),
        call: eth_method_opt_to_call(&eth_method, self_ty),
    };

    // Generate the final output
    generate_component_impl(
        &args,
        self_ty,
        &cleaned_impl_block,
        &request_enum,
        &response_enum,
        &init_method_details,
        &ws_method_details,
        &ws_client_method_details,
        &eth_method_details,
        &handler_arms,
        has_init_logging,
        &handlers.http,
    )
    .into()
}