flatbed 0.0.5

Rust HTTP framework with FlatBuffer codegen, built on Hyper
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
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
/// FlatBuffers utilities and route registry for the flatbed framework.
///
/// This library provides helper functions and utilities for working with
/// FlatBuffers, plus the compile-time route registry that powers the
/// `#[route]` macro.
///
/// # Plain Struct API
///
/// The primary API uses plain Rust structs. Handlers work with regular structs:
///
/// ```rust,ignore
/// #[route("/ping")]
/// fn handle_ping(req: PingRequest) -> Result<PingResponse, Error> {
///     Ok(PingResponse {
///         message: Some(format!("pong: {}", req.message.unwrap_or_default())),
///         timestamp: req.timestamp,
///         success: true,
///     })
/// }
/// ```
///
/// FlatBuffer serialization is handled automatically by the framework.
use flatbuffers::FlatBufferBuilder;
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::ops::Deref;
#[cfg(feature = "telemetry")]
use std::sync::Arc;
use std::sync::LazyLock;

#[cfg(feature = "nats")]
pub mod nats;
#[cfg(feature = "nats")]
pub use nats::{run_stream_worker, HasJetStream, HasNatsClient, NatsResult, StreamWorker};

// Re-exported through `nats` rather than declared public here, so the managed
// connector has one canonical path.
#[cfg(feature = "nats")]
mod nats_connect;

#[cfg(feature = "nats")]
pub mod nats_route;
#[cfg(feature = "nats")]
pub use flatbed_macros::nats_route;
#[cfg(feature = "nats")]
pub use nats_route::{
    get_nats_routes, run_nats_route, validate_nats_routes, NatsEncoding, NatsRouteConflict,
    NatsRouteInfo,
};

#[cfg(feature = "nats")]
pub mod nats_request;
#[cfg(feature = "nats")]
pub use nats_request::{NatsRequest, NatsRequestError, NatsRequestExt};

// NATS JetStream KV cache worker (enabled with "nats" feature)
#[cfg(feature = "nats")]
pub mod kv;
#[cfg(feature = "nats")]
pub use kv::{run_kv_worker, KvWorker};

#[cfg(feature = "nats")]
#[doc(hidden)]
pub use async_nats;

// Re-export futures for use in generated macro code + by the k8s
// reconciler / watcher runtime executors.
#[cfg(any(feature = "nats", feature = "k8s"))]
#[doc(hidden)]
pub use futures;

// Kubernetes reconciler support. The `k8s` module itself only needs
// the kube client; the NATS-bound `KubeReconciler` trait and its
// runtime executor are further gated behind `feature = "nats"`
// inside the module.
#[cfg(feature = "k8s")]
pub mod k8s;
#[cfg(feature = "k8s")]
pub use k8s::{
    run_kube_native_reconciler, run_kube_watcher, wait_for_follower, wait_for_follower_loss,
    wait_for_leadership, wait_for_leadership_loss, HasKubeClient, HasLeaderElection,
    KubeNativeReconciler, KubeWatcher, ReconcileError,
};
#[cfg(all(feature = "nats", feature = "k8s"))]
pub use k8s::{run_kube_reconciler, KubeReconciler};

// Generic context wrapper (available when any service feature is enabled)
#[cfg(any(feature = "nats", feature = "k8s"))]
mod context;
#[cfg(any(feature = "nats", feature = "k8s"))]
pub use context::FlatbedContext;

// Re-export kube for use in generated macro code
#[cfg(feature = "k8s")]
#[doc(hidden)]
pub use kube;

// Hyper integration module
pub mod hyper;

pub mod readiness;
pub use readiness::{Readiness, ReadinessGate};

// Worker supervision
mod supervisor;
pub use supervisor::{worker_states, RestartPolicy, WorkerState};

// Telemetry module (enabled with "telemetry" feature)
#[cfg(feature = "telemetry")]
pub mod telemetry;
#[cfg(feature = "telemetry")]
pub use telemetry::{TelemetryConfig, TelemetryError, TelemetryService};

// Re-export dependencies so consumers don't need them directly
// The #[route] macro and generated types use these
pub use flatbuffers;
pub use serde;
pub use serde_json;
#[cfg(feature = "openapi")]
pub use utoipa;

// Re-export include_dir: the `embed` form of `static_route!` expands to its
// macro, so a consumer never names the crate.
#[doc(hidden)]
pub use include_dir;

// Re-export tokio for use in generated main macro code
#[doc(hidden)]
pub use tokio;

/// Boxed, Send future alias for trait return types.
///
/// Eliminates the need for `use std::future::Future; use std::pin::Pin;`
/// in every file that implements a Flatbed trait.
pub type BoxFuture<T> = std::pin::Pin<Box<dyn std::future::Future<Output = T> + Send>>;

// Re-export http types so users don't need to add the dependency
pub use http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode};

// Re-export uuid for use in generated code (request ID generation)
#[doc(hidden)]
pub use uuid;

/// A guard invoked before a matched `#[route]` handler runs.
///
/// Returning `Err` short-circuits the request with the error's status,
/// code, and message; the handler never runs. See
/// [`FlatbedConfig::before_request`].
pub type BeforeRequestHook =
    std::sync::Arc<dyn Fn(&RequestParts) -> Result<(), FlatbedRouteError> + Send + Sync>;

// ============================================================================
// OpenAPI Support Types
// ============================================================================

/// Configuration for flatbed routes and optional telemetry integration.
///
/// This replaces the old `ApiInfo` struct and adds support for automatic
/// health endpoint registration when telemetry is enabled.
///
/// # Example
///
/// ```rust,ignore
/// use flatbed::{FlatbedConfig, configure_flatbed_routes};
///
/// // Basic configuration
/// let config = FlatbedConfig::new("My API")
///     .description("API description")
///     .external_url("https://api.example.com");
///
/// // With telemetry (registers /healthz, /readyz, /metrics automatically)
/// let config = FlatbedConfig::new("My API")
///     .with_telemetry(telemetry_service);
/// ```
#[derive(Clone)]
pub struct FlatbedConfig {
    /// API title for OpenAPI spec
    pub title: &'static str,
    /// API description for OpenAPI spec
    pub description: Option<&'static str>,
    /// External URL for OpenAPI spec (e.g., public endpoint through Envoy/TLS)
    pub external_url: Option<String>,
    /// Host address to bind to (default: "0.0.0.0")
    pub host: String,
    /// Port to bind to (default: 8080)
    pub port: u16,
    /// Splash message printed on server startup (None = no splash)
    pub splash: Option<String>,
    /// Guard invoked before a matched route handler runs (see
    /// [`FlatbedConfig::before_request`]).
    pub before_request: Option<BeforeRequestHook>,
    /// Runtime dependencies readiness answers on, on top of the boot latch.
    /// The boot function receives this config by value, so it can register a
    /// gate for anything it connects (see [`Readiness::gate`]).
    pub readiness: Readiness,
    /// Telemetry service for health endpoints (when telemetry feature is enabled)
    #[cfg(feature = "telemetry")]
    pub telemetry: Option<Arc<dyn TelemetryService>>,
}

impl Default for FlatbedConfig {
    fn default() -> Self {
        Self {
            title: "API",
            description: None,
            external_url: None,
            host: "0.0.0.0".to_string(),
            port: 8080,
            splash: None,
            before_request: None,
            readiness: Readiness::new(),
            #[cfg(feature = "telemetry")]
            telemetry: None,
        }
    }
}

impl fmt::Debug for FlatbedConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = f.debug_struct("FlatbedConfig");
        debug
            .field("title", &self.title)
            .field("description", &self.description)
            .field("external_url", &self.external_url)
            .field("host", &self.host)
            .field("port", &self.port)
            .field("splash", &self.splash.as_ref().map(|_| "<splash>"))
            .field(
                "before_request",
                &self.before_request.as_ref().map(|_| "<hook>"),
            )
            .field("readiness", &self.readiness);
        #[cfg(feature = "telemetry")]
        debug.field(
            "telemetry",
            &self.telemetry.as_ref().map(|_| "<TelemetryService>"),
        );
        debug.finish()
    }
}

impl FlatbedConfig {
    /// Create a new FlatbedConfig with the given API title.
    pub fn new(title: &'static str) -> Self {
        Self {
            title,
            ..Self::default()
        }
    }

    /// Set the bind host address (default: "0.0.0.0").
    pub fn host(mut self, host: &str) -> Self {
        self.host = host.to_string();
        self
    }

    /// Set the bind port (default: 8080).
    pub fn port(mut self, port: u16) -> Self {
        self.port = port;
        self
    }

    /// Set the API description for OpenAPI spec.
    pub fn description(mut self, desc: &'static str) -> Self {
        self.description = Some(desc);
        self
    }

    /// Set a splash page returned at `GET /`.
    ///
    /// The splash is served as a plain text response when accessing the root URL.
    /// Use this to display API information, available endpoints, or ASCII art.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let config = FlatbedConfig::new("My API")
    ///     .host("0.0.0.0")
    ///     .port(8080)
    ///     .splash("My API Server\nEndpoints:\n  GET /healthz");
    /// ```
    pub fn splash(mut self, splash: impl Into<String>) -> Self {
        self.splash = Some(splash.into());
        self
    }

    /// Register a guard invoked before every matched `#[route]` handler runs.
    ///
    /// Returning `Err` short-circuits the request with the error's status,
    /// code, and message — the handler never runs. Built-in endpoints
    /// (`/healthz`, `/readyz`, `/metrics`, `/openapi.json`, `/schema.bfbs`)
    /// and `static_route!` mounts are not matched routes and skip the guard.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let config = FlatbedConfig::new("My API").before_request(|req| match req
    ///     .header("authorization")
    /// {
    ///     Some("Bearer secret") => Ok(()),
    ///     _ => Err(FlatbedRouteError::unauthorized("missing or invalid bearer token")),
    /// });
    /// ```
    pub fn before_request<F>(mut self, hook: F) -> Self
    where
        F: Fn(&RequestParts) -> Result<(), FlatbedRouteError> + Send + Sync + 'static,
    {
        self.before_request = Some(std::sync::Arc::new(hook));
        self
    }

    /// Answer readiness on an existing [`Readiness`] registry rather than the
    /// empty one every config starts with.
    ///
    /// Only needed when gates are registered before the config exists; a boot
    /// function can reach the default registry through the config it receives.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let readiness = Readiness::new();
    /// let nats_gate = readiness.gate("nats");
    /// let config = FlatbedConfig::new("My API").readiness(readiness);
    /// ```
    pub fn readiness(mut self, readiness: Readiness) -> Self {
        self.readiness = readiness;
        self
    }

    /// Set the external URL for OpenAPI spec (e.g., public endpoint through Envoy/TLS).
    pub fn external_url(mut self, url: impl Into<String>) -> Self {
        self.external_url = Some(url.into());
        self
    }

    /// Enable telemetry with automatic health endpoint registration.
    ///
    /// When telemetry is enabled, the following endpoints are automatically registered:
    /// - `GET /healthz` - Health check endpoint (returns "OK")
    /// - `GET /readyz` - Readiness probe endpoint (returns "Ready")
    /// - `GET /metrics` - Prometheus metrics endpoint
    #[cfg(feature = "telemetry")]
    pub fn with_telemetry(mut self, telemetry: Arc<dyn TelemetryService>) -> Self {
        self.telemetry = Some(telemetry);
        self
    }

    /// Get the bind address as a SocketAddr string.
    pub fn bind_address(&self) -> String {
        format!("{}:{}", self.host, self.port)
    }
}

// ============================================================================
// Flatbed Server Runner
// ============================================================================

/// Main entry point for running a Flatbed server with two-phase boot pattern.
///
/// The server starts immediately and begins accepting connections. The framework
/// automatically manages health and readiness probes during the boot lifecycle:
///
/// 1. Server starts listening — `/healthz` returns 200 (alive)
/// 2. Boot function runs — `/readyz` returns 503, user routes return 503
/// 3. Boot completes, context is stored — `/readyz` returns 200, routes accept traffic
/// 4. Workers are spawned after the ready signal
///
/// Step 3's latch is one-shot, but readiness is not: a boot function that
/// registers a [`Readiness`] gate for a runtime dependency keeps driving
/// `/readyz` for the life of the process, and `/readyz` returns 503 again
/// whenever a gate reports its dependency unusable.
///
/// If a worker fails, `/healthz` returns 503 to trigger Kubernetes restart.
///
/// # Context type
///
/// The context type `C` can be any `Clone + Send + Sync + 'static` type.
/// You have two options:
///
/// - **Custom struct**: Define your own struct and implement any required
///   traits (`HasJetStream`, `HasKubeClient`, `HasLeaderElection`) manually.
/// - **[`FlatbedContext<C>`]**: Use the provided wrapper which owns framework
///   clients and auto-implements the traits based on enabled features.
///   Your application data is accessed transparently via `Deref`.
///
/// # Example: custom context
///
/// ```rust,ignore
/// use flatbed::{Flatbed, FlatbedConfig};
///
/// #[derive(Clone)]
/// struct AppContext {
///     db: DatabasePool,
/// }
///
/// Flatbed::run(config, |_| async move {
///     Ok(AppContext { db: DatabasePool::connect().await? })
/// }).await?;
/// ```
///
/// # Example: FlatbedContext wrapper
///
/// ```rust,ignore
/// use flatbed::{Flatbed, FlatbedConfig, FlatbedContext};
///
/// #[derive(Clone)]
/// struct AppData { pub namespace: String }
/// type AppContext = FlatbedContext<AppData>;
///
/// Flatbed::run(config, |_| async move {
///     let ctx = FlatbedContext::builder(AppData { namespace: "default".into() })
///         .nats_client(nats_client)
///         .jetstream(jetstream)
///         .kube_client(kube_client)
///         .leader_election(is_leader_tx, is_leader_rx, ha_mode)
///         .build();
///     Ok(ctx)
/// }).await?;
/// ```
pub struct Flatbed;

impl Flatbed {
    /// Run the server with a boot function for two-phase initialization.
    ///
    /// The boot function receives a clone of the [`FlatbedConfig`] (for access to
    /// host, port, etc.) and returns the application context. The framework handles
    /// all probe signaling automatically:
    ///
    /// - `/healthz` → 200 as soon as the server starts listening
    /// - Boot function runs (probes: healthz=200, ready=503)
    /// - Context is stored, then `/readyz` → 200 and workers are spawned
    ///
    /// # Type Parameters
    ///
    /// - `C`: The application context type. Must be `Clone + Send + Sync + 'static`.
    /// - `F`: The boot function type.
    /// - `Fut`: The future returned by the boot function.
    ///
    /// # Arguments
    ///
    /// - `config`: Server configuration including host, port, and optional telemetry.
    /// - `boot`: Async function that receives a [`FlatbedConfig`] clone and returns
    ///   the application context.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Route validation fails (duplicate paths with different types)
    /// - The bind address is invalid
    /// - The server fails to start
    /// - The boot function returns an error
    pub async fn run<C, F, Fut>(config: FlatbedConfig, boot: F) -> Result<(), Error>
    where
        C: Clone + Send + Sync + 'static,
        F: FnOnce(FlatbedConfig) -> Fut + Send,
        Fut: std::future::Future<Output = Result<C, Box<dyn std::error::Error + Send + Sync>>>
            + Send,
    {
        use std::sync::Arc;
        use tokio::sync::{watch, RwLock};

        // Validate routes (fails fast on conflicts)
        crate::validate_routes().map_err(|e| Error::Custom(format!("Route conflict: {}", e)))?;
        crate::validate_type_registry()
            .map_err(|e| Error::Custom(format!("Type registry conflict: {}", e)))?;
        #[cfg(feature = "nats")]
        crate::validate_nats_routes()
            .map_err(|e| Error::Custom(format!("NATS subject conflict: {}", e)))?;

        // Build router from inventory-registered routes
        let router = Arc::new(hyper::build_router());

        // Parse bind address
        let addr: std::net::SocketAddr = config
            .bind_address()
            .parse()
            .map_err(|e| Error::Custom(format!("Invalid bind address: {}", e)))?;

        // Create watch channels for probes (start as unhealthy/not ready)
        let (healthz_tx, healthz_rx) = watch::channel(false);
        let (booted_tx, booted_rx) = watch::channel(false);

        // Create shared context storage (None until boot completes)
        let context: Arc<RwLock<Option<Arc<C>>>> = Arc::new(RwLock::new(None));

        // Clone config for the boot function before moving original into ServiceContext
        let boot_config = config.clone();

        // Create ServiceContext with probe receivers
        let service_ctx = hyper::ServiceContext {
            router,
            healthz_rx,
            booted_rx,
            context: Arc::clone(&context),
            config,
            static_routes: Arc::new(crate::get_static_routes()),
        };

        // Create and spawn the server
        let server = hyper::AutoServer::new(addr, service_ctx, healthz_tx.clone());
        let server_handle = tokio::spawn(async move { server.serve().await });

        // Server is listening — mark as alive immediately
        // (prevents Kubernetes from killing pod during slow boot)
        let _ = healthz_tx.send(true);

        // Run boot function (receives config clone, returns context)
        let ctx = boot(boot_config)
            .await
            .map_err(|e| Error::Custom(format!("Boot error: {}", e)))?;

        // Store context FIRST, then signal ready
        // This fixes the race condition where workers could start before context was set
        {
            let mut guard = context.write().await;
            *guard = Some(Arc::new(ctx));
        }
        let _ = booted_tx.send(true);

        // Await server completion
        server_handle
            .await
            .map_err(|e| Error::Custom(format!("Server task error: {}", e)))?
            .map_err(|e| Error::Custom(format!("Server error: {}", e)))
    }
}

/// Schema field info for OpenAPI generation
#[derive(Clone, Copy, Debug)]
pub struct FieldInfo {
    /// Field name as declared in the `.fbs` schema.
    pub name: &'static str,
    /// Adapter-language FlatBuffer type (`"uint64"`, `"[Address]"`, `"Severity"`).
    pub fbs_type: &'static str,
    /// True for scalars and enums; false for strings, tables and vectors,
    /// which are optional on the wire.
    pub required: bool,
}

/// Schema information
#[derive(Clone, Copy, Debug)]
pub struct SchemaInfo {
    /// Bare type name, used as the OpenAPI component key.
    pub name: &'static str,
    /// The type's fields, in declaration order.
    pub fields: &'static [FieldInfo],
}

/// A generated FlatBuffer table, registered at compile time so the full set
/// of types is discoverable at runtime.
///
/// One is submitted for *every* generated table — including tables that only
/// ever appear nested inside another and never as a route body — so the
/// registry is a complete inventory of the generated types. `name` is the bare
/// type name (the key routes use to reference their request/response types);
/// `namespace` is the FlatBuffer namespace (`"v_1"`, `"test"`).
#[derive(Clone, Copy, Debug)]
pub struct TypeSchema {
    pub name: &'static str,
    pub namespace: &'static str,
    pub fields: &'static [TypeFieldInfo],
}

/// A single field of a registered [`TypeSchema`].
///
/// `fbs_type` is the rich adapter-language string (`"uint64"`, `"[Address]"`,
/// `"Severity"`) — enough to recover the exact wire shape. `field_id` is the
/// FlatBuffer vtable slot; `required` is false for wire-optional fields
/// (strings, tables, vectors) and true for scalars and enums.
#[derive(Clone, Copy, Debug)]
pub struct TypeFieldInfo {
    pub name: &'static str,
    pub fbs_type: &'static str,
    pub field_id: u16,
    pub required: bool,
}

/// A generated FlatBuffer enum, registered at compile time alongside
/// [`TypeSchema`]. `variants` are listed in FlatBuffer value order.
#[derive(Clone, Copy, Debug)]
pub struct EnumSchema {
    pub name: &'static str,
    pub namespace: &'static str,
    pub variants: &'static [&'static str],
}

/// The FlatBuffer binary reflection (`.bfbs`) for a service's schemas, baked in
/// by generated code so the runtime can serve it at `/schema.bfbs`. The bytes
/// are the exact `flatc -b --schema` output — complete for the wire codec
/// (field ids, enum underlying types + values, defaults). One is submitted per
/// compiled root schema.
#[derive(Clone, Copy, Debug)]
pub struct FlatbedSchema {
    pub bfbs: &'static [u8],
}

inventory::collect!(TypeSchema);
inventory::collect!(EnumSchema);
inventory::collect!(FlatbedSchema);

/// The baked-in FlatBuffer reflection when a schema was compiled into this
/// service. Defined for the single-root case: flatc's `.bfbs` covers a root's
/// full include graph, so one submission describes everything.
/// With multiple root schemas the result is unspecified — `inventory` collection
/// order gives no defined choice among them.
#[must_use]
pub fn get_schema_bfbs() -> Option<&'static [u8]> {
    inventory::iter::<FlatbedSchema>
        .into_iter()
        .next()
        .map(|s| s.bfbs)
}

// ============================================================================
// Trait Definitions for JSON Companion Types
// ============================================================================

/// Trait for JSON companion types that can convert to FlatBuffer bytes
///
/// This trait is implemented by generated JSON companion structs (e.g., `PingRequestJson`)
/// and provides the interface for serialization and schema information.
///
/// # Example
///
/// ```rust,ignore
/// use flatbed::ToFlatBuffer;
///
/// // Generated companion type implements this trait
/// let json_req = PingRequestJson { message: Some("hello".into()), timestamp: 123 };
/// let bytes = json_req.to_flatbuffer();
/// ```
pub trait ToFlatBuffer: serde::de::DeserializeOwned + serde::Serialize {
    /// Schema fields for OpenAPI generation (as a const)
    const SCHEMA_FIELDS: &'static [FieldInfo];

    /// Schema name for OpenAPI generation (as a const)
    const SCHEMA_NAME: &'static str;

    /// Convert this JSON struct to FlatBuffer bytes
    fn to_flatbuffer(&self) -> Vec<u8>;

    /// Get schema field info for OpenAPI generation (runtime method)
    fn schema_fields() -> &'static [FieldInfo] {
        Self::SCHEMA_FIELDS
    }

    /// Get the schema name for OpenAPI (runtime method)
    fn schema_name() -> &'static str {
        Self::SCHEMA_NAME
    }
}

/// Implementation of ToFlatBuffer for unit type
///
/// This allows `FlatbedError<()>` (errors without details) to work with
/// the error response builder that requires ToFlatBuffer.
impl ToFlatBuffer for () {
    const SCHEMA_FIELDS: &'static [FieldInfo] = &[];
    const SCHEMA_NAME: &'static str = "Empty";

    fn to_flatbuffer(&self) -> Vec<u8> {
        Vec::new()
    }
}

/// Trait for JSON companion types that can be decoded from FlatBuffer bytes
///
/// The mirror of [`ToFlatBuffer`], implemented by the same generated companion
/// structs. It exists so code generic over a body type — a typed NATS reply,
/// for one — can decode without naming the concrete type.
///
/// # Example
///
/// ```rust,ignore
/// use flatbed::FromFlatBuffer;
///
/// let decoded = PingResponse::from_flatbuffer(&bytes)?;
/// ```
pub trait FromFlatBuffer: Sized {
    /// Decode this struct from a FlatBuffer payload.
    ///
    /// # Errors
    ///
    /// Returns [`flatbuffers::InvalidFlatbuffer`] when the bytes are not a
    /// valid buffer of this type.
    fn from_flatbuffer(bytes: &[u8]) -> Result<Self, flatbuffers::InvalidFlatbuffer>;
}

/// The mirror of [`ToFlatBuffer`]'s unit implementation, so a body-less
/// response is as decodable as it is encodable.
impl FromFlatBuffer for () {
    fn from_flatbuffer(_bytes: &[u8]) -> Result<Self, flatbuffers::InvalidFlatbuffer> {
        Ok(())
    }
}

/// Trait connecting FlatBuffer types to their plain struct companions
///
/// This allows the `#[route]` macro to discover the plain struct type
/// without hardcoding module paths, making flatbed reusable across projects.
///
/// # Example
///
/// ```rust,ignore
/// use flatbed::HasJsonCompanion;
///
/// // Generated automatically by flatbed_build:
/// impl<'a> HasJsonCompanion for __fb::v_1::PingRequest<'a> {
///     type Json = PingRequest;  // Plain struct
/// }
/// ```
pub trait HasJsonCompanion {
    /// The plain struct companion type for this FlatBuffer type
    type Json: ToFlatBuffer;
}

/// Trait connecting plain structs to their FlatBuffer types
///
/// This provides bidirectional type mapping for the plain struct API.
///
/// # Example
///
/// ```rust,ignore
/// impl HasPlainStruct for PingRequest {
///     type Plain = PingRequest;
///     type FlatBuffer<'a> = __fb::v_1::PingRequest<'a>;
/// }
/// ```
pub trait HasPlainStruct {
    /// The plain struct type (usually Self)
    type Plain: ToFlatBuffer;
    /// The FlatBuffer view type
    type FlatBuffer<'a>;
}

/// OpenAPI metadata for a route
#[derive(Clone, Copy, Debug, Default)]
pub struct OpenApiRouteInfo {
    pub version: Option<&'static str>, // e.g., "v1", "v2"
    pub tag: Option<&'static str>,
    pub summary: Option<&'static str>,
    pub operation_id: Option<&'static str>,
    pub deprecated: bool,
    pub request_schema: Option<SchemaInfo>,
    pub response_schema: Option<SchemaInfo>,
}

// Re-export the route macro from flatbed_macros
pub use flatbed_macros::route;

pub use flatbed_macros::static_route;

// Re-export the main macro from flatbed_macros
pub use flatbed_macros::main;

// Re-export inventory for use by the macro
#[doc(hidden)]
pub use inventory;

// ============================================================================
// HTTP Request/Response Wrapper Types
// ============================================================================

/// HTTP request wrapper providing context alongside the deserialized body
///
/// The generic parameter `T` is the request body type (flatbed-generated struct).
/// The optional parameter `C` is the application context type (defaults to `()`).
///
/// # Example
///
/// ```rust,ignore
/// // Simple handler without context
/// #[route("/ping")]
/// async fn handle_ping(req: Request<PingRequest>) -> Result<Response<PingResponse>, FlatbedError> {
///     Ok(Response::ok(PingResponse { message: Some("pong".into()), ... }))
/// }
///
/// // Handler with application context
/// #[route("/users")]
/// async fn handle_users(req: Request<UserRequest, AppCtx>) -> Result<Response<UserResponse>, FlatbedError> {
///     let user = req.ctx.db.find_user(&req.body.id).await?;
///     Ok(Response::ok(UserResponse { name: user.name, ... }))
/// }
/// ```
#[derive(Debug)]
pub struct Request<T, C = ()> {
    /// The deserialized request body
    pub body: T,
    /// Application context (zero-sized when C = ())
    pub ctx: C,
    /// HTTP headers from the request
    pub headers: HeaderMap,
    /// HTTP method
    pub method: Method,
    /// Request path
    pub path: String,
    /// Path parameters (e.g., /users/{id} -> {"id": "123"})
    pub path_params: HashMap<String, String>,
    /// Query string parameters
    pub query_params: HashMap<String, String>,
    /// Request ID (propagated or generated)
    pub request_id: String,
}

impl<T, C> Request<T, C> {
    /// Get a header value by name (case-insensitive)
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers.get(name).and_then(|v| v.to_str().ok())
    }

    /// Get a path parameter by name
    pub fn param(&self, name: &str) -> Option<&str> {
        self.path_params.get(name).map(|s| s.as_str())
    }

    /// Get a query parameter by name
    pub fn query(&self, name: &str) -> Option<&str> {
        self.query_params.get(name).map(|s| s.as_str())
    }

    /// Get the request ID
    pub fn request_id(&self) -> &str {
        &self.request_id
    }
}

impl<T, C> Deref for Request<T, C> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.body
    }
}

/// HTTP response wrapper with status code and headers
///
/// # Example
///
/// ```rust,ignore
/// // Simple 200 OK response
/// Response::ok(MyResponse { ... })
///
/// // 201 Created
/// Response::created(MyResponse { ... })
///
/// // Custom status and headers
/// Response::with_status(MyResponse { ... }, StatusCode::ACCEPTED)
///     .header("X-Custom", "value")
/// ```
#[derive(Debug)]
pub struct Response<T> {
    /// The response body
    pub body: T,
    /// HTTP status code (default: 200 OK)
    pub status: StatusCode,
    /// Response headers
    pub headers: HeaderMap,
    raw: Option<(Vec<u8>, Cow<'static, str>)>,
}

impl<T> Response<T> {
    /// Create a response with 200 OK status
    pub fn ok(body: T) -> Self {
        Self {
            body,
            status: StatusCode::OK,
            headers: HeaderMap::new(),
            raw: None,
        }
    }

    /// Create a response with 201 Created status
    pub fn created(body: T) -> Self {
        Self {
            body,
            status: StatusCode::CREATED,
            headers: HeaderMap::new(),
            raw: None,
        }
    }

    /// Create a response with 202 Accepted status
    pub fn accepted(body: T) -> Self {
        Self {
            body,
            status: StatusCode::ACCEPTED,
            headers: HeaderMap::new(),
            raw: None,
        }
    }

    /// Create a response with 204 No Content status
    pub fn no_content(body: T) -> Self {
        Self {
            body,
            status: StatusCode::NO_CONTENT,
            headers: HeaderMap::new(),
            raw: None,
        }
    }

    /// Create a response with custom status code
    pub fn with_status(body: T, status: StatusCode) -> Self {
        Self {
            body,
            status,
            headers: HeaderMap::new(),
            raw: None,
        }
    }

    /// Set the HTTP status code (builder pattern)
    pub fn status(mut self, status: StatusCode) -> Self {
        self.status = status;
        self
    }

    /// Add a header to the response (builder pattern)
    pub fn header(mut self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self {
        if let (Ok(name), Ok(val)) = (
            HeaderName::try_from(key.as_ref()),
            HeaderValue::try_from(value.as_ref()),
        ) {
            self.headers.insert(name, val);
        }
        self
    }

    /// Yields `Some((bytes, content_type))` only for a response constructed as a
    /// raw response, and `None` for all other constructors.
    #[doc(hidden)]
    pub fn take_raw(&mut self) -> Option<(Vec<u8>, Cow<'static, str>)> {
        self.raw.take()
    }
}

impl Response<()> {
    /// Create a response that emits `bytes` verbatim under `content_type`,
    /// bypassing JSON/FlatBuffer serialization.
    ///
    /// This is the escape hatch for handlers that need to return a body the
    /// typed path can't express — HTML, CSV, JavaScript, images, or any other
    /// media type. The `content_type` is written to the `Content-Type` header
    /// as-is.
    ///
    /// ```rust,ignore
    /// #[route("/report.csv", method = "POST")]
    /// async fn report(req: Request<ReportQuery>) -> Result<Response<()>, FlatbedRouteError> {
    ///     let csv = build_report_csv(&req.body);
    ///     Ok(Response::raw(csv.into_bytes(), "text/csv; charset=utf-8"))
    /// }
    /// ```
    pub fn raw(bytes: impl Into<Vec<u8>>, content_type: impl Into<Cow<'static, str>>) -> Self {
        Self {
            body: (),
            status: StatusCode::OK,
            headers: HeaderMap::new(),
            raw: Some((bytes.into(), content_type.into())),
        }
    }
}

// ============================================================================
// Worker Error Type
// ============================================================================

/// Simple error type for background workers
///
/// Workers use this simpler error type since they don't need HTTP-specific
/// fields like status codes or headers.
///
/// # Example
///
/// ```rust,ignore
/// use flatbed::{worker, FlatbedWorkerError};
/// use std::sync::Arc;
///
/// #[worker]
/// async fn my_worker(ctx: Arc<AppContext>) -> Result<(), FlatbedWorkerError> {
///     ctx.do_something().await
///         .map_err(|e| FlatbedWorkerError::new("TASK_ERROR", e.to_string()))?;
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone)]
pub struct FlatbedWorkerError {
    /// Application-defined error code (e.g., "CACHE_ERROR")
    pub code: String,
    /// Human-readable error message
    pub message: String,
}

impl FlatbedWorkerError {
    /// Create a new worker error with code and message
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
        }
    }
}

impl fmt::Display for FlatbedWorkerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[{}] {}", self.code, self.message)
    }
}

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

// ============================================================================
// HTTP Route Error Type
// ============================================================================

/// HTTP-conformant error type with status code, error code, and optional details
///
/// The generic parameter `D` is the type for structured error details (must be a
/// flatbed-generated struct implementing `ToFlatBuffer`). Defaults to `()` for
/// errors without structured details.
///
/// # Example
///
/// ```rust,ignore
/// // Simple error without details
/// return Err(FlatbedRouteError::bad_request("Invalid input"));
///
/// // Error with code
/// return Err(FlatbedRouteError::bad_request("Validation failed")
///     .code("VALIDATION_ERROR"));
///
/// // Error with typed details (flatbed-generated struct)
/// return Err(FlatbedRouteError::bad_request("Validation failed")
///     .code("VALIDATION_ERROR")
///     .with_details(ValidationErrorDetails {
///         field: Some("email".into()),
///         reason: Some("Invalid format".into()),
///     }));
/// ```
#[derive(Debug, Clone)]
pub struct FlatbedRouteError<D = ()> {
    /// HTTP status code
    pub status: StatusCode,
    /// Application-defined error code (e.g., "VALIDATION_ERROR")
    pub code: String,
    /// Human-readable error message
    pub message: String,
    /// Response headers
    pub headers: HeaderMap,
    /// Optional structured error details
    pub details: Option<D>,
}

/// Deprecated alias for `FlatbedRouteError`
///
/// Use `FlatbedRouteError` instead for new code.
#[deprecated(since = "0.2.0", note = "Use FlatbedRouteError instead")]
pub type FlatbedError<D = ()> = FlatbedRouteError<D>;

impl FlatbedRouteError<()> {
    /// Create a 400 Bad Request error
    pub fn bad_request(message: impl Into<String>) -> Self {
        Self::with_status(StatusCode::BAD_REQUEST, message)
    }

    /// Create a 401 Unauthorized error
    pub fn unauthorized(message: impl Into<String>) -> Self {
        Self::with_status(StatusCode::UNAUTHORIZED, message)
    }

    /// Create a 403 Forbidden error
    pub fn forbidden(message: impl Into<String>) -> Self {
        Self::with_status(StatusCode::FORBIDDEN, message)
    }

    /// Create a 404 Not Found error
    pub fn not_found(message: impl Into<String>) -> Self {
        Self::with_status(StatusCode::NOT_FOUND, message)
    }

    /// Create a 409 Conflict error
    pub fn conflict(message: impl Into<String>) -> Self {
        Self::with_status(StatusCode::CONFLICT, message)
    }

    /// Create a 422 Unprocessable Entity error
    pub fn unprocessable(message: impl Into<String>) -> Self {
        Self::with_status(StatusCode::UNPROCESSABLE_ENTITY, message)
    }

    /// Create a 500 Internal Server Error
    pub fn internal(message: impl Into<String>) -> Self {
        Self::with_status(StatusCode::INTERNAL_SERVER_ERROR, message)
    }

    /// Create an error with custom status code
    pub fn with_status(status: StatusCode, message: impl Into<String>) -> Self {
        Self {
            status,
            code: String::new(),
            message: message.into(),
            headers: HeaderMap::new(),
            details: None,
        }
    }
}

impl<D> FlatbedRouteError<D> {
    /// Set the error code (builder pattern)
    pub fn code(mut self, code: impl Into<String>) -> Self {
        self.code = code.into();
        self
    }

    /// Add a header to the error response (builder pattern)
    pub fn header(mut self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self {
        if let (Ok(name), Ok(val)) = (
            HeaderName::try_from(key.as_ref()),
            HeaderValue::try_from(value.as_ref()),
        ) {
            self.headers.insert(name, val);
        }
        self
    }

    /// Add structured details to the error, changing the type parameter
    pub fn with_details<D2>(self, details: D2) -> FlatbedRouteError<D2> {
        FlatbedRouteError {
            status: self.status,
            code: self.code,
            message: self.message,
            headers: self.headers,
            details: Some(details),
        }
    }

    /// Get the HTTP status code
    pub fn status_code(&self) -> StatusCode {
        self.status
    }
}

impl<D> fmt::Display for FlatbedRouteError<D> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.code.is_empty() {
            write!(f, "{}", self.message)
        } else {
            write!(f, "[{}] {}", self.code, self.message)
        }
    }
}

impl<D: fmt::Debug> std::error::Error for FlatbedRouteError<D> {}

/// Parts extracted from an HTTP request (used internally by macro)
#[derive(Debug, Clone)]
pub struct RequestParts {
    /// HTTP headers
    pub headers: HeaderMap,
    /// HTTP method
    pub method: Method,
    /// Request path
    pub path: String,
    /// Path parameters
    pub path_params: HashMap<String, String>,
    /// Query parameters
    pub query_params: HashMap<String, String>,
    /// Request ID (propagated or generated)
    pub request_id: String,
}

impl RequestParts {
    /// Create new RequestParts with generated request ID
    pub fn new(method: Method, path: String) -> Self {
        Self {
            headers: HeaderMap::new(),
            method,
            path,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            request_id: uuid::Uuid::new_v4().to_string(),
        }
    }

    /// Set request ID from header or keep generated one
    pub fn with_request_id_from_header(mut self) -> Self {
        if let Some(id) = self
            .headers
            .get("x-request-id")
            .and_then(|v| v.to_str().ok())
        {
            self.request_id = id.to_string();
        }
        self
    }

    /// Get a header value by name (case-insensitive)
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers.get(name).and_then(|v| v.to_str().ok())
    }
}

/// Parts for constructing an HTTP response (used internally by macro)
#[derive(Debug)]
pub struct ResponseParts {
    /// Response body bytes
    pub body: Vec<u8>,
    /// HTTP status code
    pub status: StatusCode,
    /// Response headers
    pub headers: HeaderMap,
    /// Content-Type header value
    pub content_type: Cow<'static, str>,
}

impl ResponseParts {
    /// Create new ResponseParts with 200 OK status
    pub fn ok(body: Vec<u8>, content_type: impl Into<Cow<'static, str>>) -> Self {
        Self {
            body,
            status: StatusCode::OK,
            headers: HeaderMap::new(),
            content_type: content_type.into(),
        }
    }

    /// Create new ResponseParts with custom status
    pub fn with_status(
        body: Vec<u8>,
        status: StatusCode,
        content_type: impl Into<Cow<'static, str>>,
    ) -> Self {
        Self {
            body,
            status,
            headers: HeaderMap::new(),
            content_type: content_type.into(),
        }
    }

    /// Add X-Request-ID header
    pub fn with_request_id(mut self, request_id: &str) -> Self {
        if let Ok(val) = HeaderValue::try_from(request_id) {
            self.headers.insert("x-request-id", val);
        }
        self
    }
}

// ============================================================================
// Legacy Error Type
// ============================================================================

/// Error type for flatbed operations
#[derive(Debug, Clone)]
pub enum Error {
    /// Failed to deserialize FlatBuffer
    DeserializationError(String),
    /// Failed to serialize FlatBuffer
    SerializationError(String),
    /// Handler returned an error
    HandlerError(String),
    /// Custom error with message
    Custom(String),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::DeserializationError(msg) => write!(f, "Deserialization error: {}", msg),
            Error::SerializationError(msg) => write!(f, "Serialization error: {}", msg),
            Error::HandlerError(msg) => write!(f, "Handler error: {}", msg),
            Error::Custom(msg) => write!(f, "{}", msg),
        }
    }
}

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

impl From<flatbuffers::InvalidFlatbuffer> for Error {
    fn from(err: flatbuffers::InvalidFlatbuffer) -> Self {
        Error::DeserializationError(err.to_string())
    }
}

impl From<String> for Error {
    fn from(msg: String) -> Self {
        Error::Custom(msg)
    }
}

impl From<&str> for Error {
    fn from(msg: &str) -> Self {
        Error::Custom(msg.to_string())
    }
}

/// Legacy response wrapper that contains a FlatBufferBuilder with a finalized response of type T
///
/// **Deprecated**: Use the new `Response<T>` struct instead, which works with plain structs.
///
/// This allows handlers to have type-safe signatures and include HTTP metadata:
/// ```ignore
/// fn handle(req: PingRequest) -> Result<LegacyResponse<PingResponse>, Error> {
///     // Build response...
///     LegacyResponse::new(builder)
///         .with_status(200)
///         .with_header("Content-Type", "application/octet-stream")
/// }
/// ```
///
/// The generic parameter T documents the FlatBuffer response type.
#[deprecated(since = "0.2.0", note = "Use the new Response<T> struct instead")]
pub struct LegacyResponse<T> {
    builder: FlatBufferBuilder<'static>,
    status_code: u16,
    headers: HashMap<String, String>,
    _phantom: std::marker::PhantomData<T>,
}

#[allow(deprecated)]
impl<T> LegacyResponse<T> {
    /// Create a new Response from a FlatBufferBuilder that has been finalized
    ///
    /// The builder should have already called `finish()` on the response of type T.
    /// Default status code is 200 OK.
    ///
    /// # Example
    /// ```ignore
    /// let mut builder = FlatBufferBuilder::new();
    /// let response = PingResponse::create(&mut builder, &args);
    /// builder.finish(response, None);
    /// Response::<PingResponse>::new(builder)
    /// ```
    pub fn new(builder: FlatBufferBuilder<'static>) -> Self {
        Self {
            builder,
            status_code: 200,
            headers: HashMap::new(),
            _phantom: std::marker::PhantomData,
        }
    }

    /// Create a Response by providing a closure that builds the response
    ///
    /// This encapsulates all the builder boilerplate. The closure receives a mutable
    /// reference to a FlatBufferBuilder and should create and finish the response.
    ///
    /// # Example
    /// ```ignore
    /// Response::with_body(|builder| {
    ///     let msg = builder.create_string("Hello");
    ///     let response = PingResponse::create(builder, &PingResponseArgs {
    ///         message: Some(msg),
    ///         timestamp: 123,
    ///         success: true,
    ///     });
    ///     builder.finish(response, None);
    /// })
    /// ```
    pub fn with_body<F>(f: F) -> Self
    where
        F: FnOnce(&mut FlatBufferBuilder<'static>),
    {
        let mut builder = FlatBufferBuilder::new();
        f(&mut builder);
        Self::new(builder)
    }

    /// Set the HTTP status code for this response
    ///
    /// # Example
    /// ```ignore
    /// Response::new(builder).with_status(201)  // Created
    /// Response::new(builder).with_status(404)  // Not Found
    /// ```
    pub fn with_status(mut self, status: u16) -> Self {
        self.status_code = status;
        self
    }

    /// Add an HTTP header to this response
    ///
    /// # Example
    /// ```ignore
    /// Response::new(builder)
    ///     .with_header("Content-Type", "application/octet-stream")
    ///     .with_header("X-Request-ID", "123")
    /// ```
    pub fn with_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.insert(key.into(), value.into());
        self
    }

    /// Get the HTTP status code
    pub fn status_code(&self) -> u16 {
        self.status_code
    }

    /// Get a reference to the headers
    pub fn headers(&self) -> &HashMap<String, String> {
        &self.headers
    }

    /// Get the serialized bytes from the response
    pub fn into_bytes(self) -> Vec<u8> {
        self.builder.finished_data().to_vec()
    }

    /// Get a reference to the serialized bytes
    pub fn as_bytes(&self) -> &[u8] {
        self.builder.finished_data()
    }

    /// Consume self and return (bytes, status_code, headers)
    pub fn into_parts(self) -> (Vec<u8>, u16, HashMap<String, String>) {
        let bytes = self.builder.finished_data().to_vec();
        (bytes, self.status_code, self.headers)
    }
}

/// Creates a new FlatBufferBuilder with the default capacity
pub fn new_builder() -> FlatBufferBuilder<'static> {
    FlatBufferBuilder::new()
}

/// Creates a new FlatBufferBuilder with a specific capacity
pub fn new_builder_with_capacity(capacity: usize) -> FlatBufferBuilder<'static> {
    FlatBufferBuilder::with_capacity(capacity)
}

/// Verifies a flatbuffer message
///
/// Returns true if the buffer is valid, false otherwise
pub fn verify_buffer<'a, T>(buf: &'a [u8]) -> bool
where
    T: flatbuffers::Follow<'a> + flatbuffers::Verifiable + 'a,
{
    flatbuffers::root::<T>(buf).is_ok()
}

/// Safely reads a root table from a buffer
///
/// This performs verification before returning the root
pub fn get_root<'a, T>(
    buf: &'a [u8],
) -> Result<<T as flatbuffers::Follow<'a>>::Inner, flatbuffers::InvalidFlatbuffer>
where
    T: flatbuffers::Follow<'a> + flatbuffers::Verifiable + 'a,
{
    flatbuffers::root::<T>(buf)
}

/// Handler function type for route registration
///
/// This represents the signature of handler functions that can be used with
/// the routing system. Handlers take raw bytes and content-type string,
/// and return a Result with response bytes and response content-type.
///
/// Supports both `application/json` and `application/x-flatbuffers` content types.
/// The response content-type matches the request content-type.
///
/// Note: The actual user-defined handlers return Result<Response, E>
/// where E can be converted to flatbed::Error. The macro wrapper handles
/// content-type negotiation and serialization/deserialization.
pub type HandlerFn = fn(Vec<u8>, &str) -> Result<(Vec<u8>, &'static str), Error>;

/// A wire encoding a route speaks.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Codec {
    /// `application/json`.
    Json,
    /// `application/x-flatbuffers`.
    FlatBuffer,
}

/// The codec a request's `accept` header asks the response to use, when it
/// names one flatbed serves. Both named, the earlier wins; neither named,
/// or no header, is `None` and the response follows the request's
/// `content-type`. A body is still decoded by `content-type` alone.
#[must_use]
pub fn accepted_codec(headers: &HeaderMap) -> Option<Codec> {
    let accept = headers.get("accept")?.to_str().ok()?;
    let json = accept.find("application/json");
    let flatbuffer = accept
        .find("application/x-flatbuffers")
        .or_else(|| accept.find("application/x-flat-buffers"));
    match (json, flatbuffer) {
        (Some(j), Some(f)) if f < j => Some(Codec::FlatBuffer),
        (Some(_), _) => Some(Codec::Json),
        (None, Some(_)) => Some(Codec::FlatBuffer),
        (None, None) => None,
    }
}

/// Async handler function type for hyper integration
///
/// Takes request parts, body bytes, content-type, application context, and
/// returns response parts. The context is passed as `Arc<dyn Any>` and
/// downcasted to the concrete type by the `#[route]` macro wrapper.
pub type AsyncHandlerFn = fn(
    RequestParts,
    Vec<u8>,
    &str,
    std::sync::Arc<dyn std::any::Any + Send + Sync>,
) -> std::pin::Pin<
    Box<dyn std::future::Future<Output = Result<ResponseParts, Error>> + Send>,
>;

/// HTTP method for route registration
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum HttpMethod {
    Get,
    Post,
    Put,
    Delete,
    Patch,
    Head,
    Options,
}

impl HttpMethod {
    /// Returns the method as an uppercase string
    pub fn as_str(&self) -> &'static str {
        match self {
            HttpMethod::Get => "GET",
            HttpMethod::Post => "POST",
            HttpMethod::Put => "PUT",
            HttpMethod::Delete => "DELETE",
            HttpMethod::Patch => "PATCH",
            HttpMethod::Head => "HEAD",
            HttpMethod::Options => "OPTIONS",
        }
    }
}

impl std::fmt::Display for HttpMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Route information collected from #[route] decorators
#[derive(Clone, Copy)]
pub struct RouteInfo {
    pub path: &'static str,
    pub method: HttpMethod,
    pub request_type: &'static str,
    pub response_type: &'static str,
    pub handler: HandlerFn,
    pub async_handler: AsyncHandlerFn,
    pub openapi: OpenApiRouteInfo,
}

// Manual Debug implementation to avoid printing function pointers
impl std::fmt::Debug for RouteInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RouteInfo")
            .field("path", &self.path)
            .field("method", &self.method)
            .field("request_type", &self.request_type)
            .field("response_type", &self.response_type)
            .field("handler", &"<function>")
            .field("async_handler", &"<async_function>")
            .field("openapi", &self.openapi)
            .finish()
    }
}

inventory::collect!(RouteInfo);

/// Where a static mount reads its files from.
#[derive(Clone, Copy, Debug)]
pub enum StaticSource {
    /// A directory on the container filesystem, read at request time
    /// (e.g. `/app/dist`).
    Dir(&'static str),
    /// A directory compiled into the binary, served from memory.
    Embedded(&'static include_dir::Dir<'static>),
}

/// A static-file mount registered by the `static_route!` macro.
///
/// Serves files from `source` under the `mount` URL prefix. Declared
/// `#[route]` routes always take precedence, so an API mounted under `/api`
/// keeps working alongside a static mount at `/`.
#[derive(Clone, Copy, Debug)]
pub struct StaticRouteInfo {
    /// URL prefix the mount answers under (e.g. `/` or `/assets`).
    pub mount: &'static str,
    /// The directory the files come from, on disk or in the binary.
    pub source: StaticSource,
    /// File served for unmatched sub-paths, enabling SPA history fallback
    /// (e.g. `index.html`). `None` returns 404 for a miss.
    pub fallback: Option<&'static str>,
    /// Mount-relative path prefixes under which a miss is a 404 and never
    /// the fallback, so a mistyped API path is not answered with the page
    /// shell (e.g. `&["/api/"]`, which under `mount = "/app"` covers
    /// `/app/api/...`).
    pub no_fallback: &'static [&'static str],
}

inventory::collect!(StaticRouteInfo);

/// Returns the static-file mounts registered via `static_route!`.
#[must_use]
pub fn get_static_routes() -> Vec<StaticRouteInfo> {
    inventory::iter::<StaticRouteInfo>
        .into_iter()
        .copied()
        .collect()
}

// ============================================================================
// Worker Registration Types
// ============================================================================

/// Worker function signature for background tasks
///
/// Workers receive the application context wrapped as `Arc<dyn Any + Send + Sync>`.
/// The `#[worker]` macro generates a wrapper that downcasts to the correct concrete type.
pub type WorkerFn = fn(
    std::sync::Arc<dyn std::any::Any + Send + Sync>,
) -> std::pin::Pin<
    Box<dyn std::future::Future<Output = Result<(), FlatbedWorkerError>> + Send>,
>;

/// Drain function signature for graceful shutdown of workers.
///
/// Called during shutdown to allow workers to finish in-progress work.
/// Receives the application context and returns a future that completes
/// when draining is done.
pub type DrainFn = fn(
    std::sync::Arc<dyn std::any::Any + Send + Sync>,
) -> std::pin::Pin<
    Box<dyn std::future::Future<Output = Result<(), FlatbedWorkerError>> + Send>,
>;

/// Worker metadata registered via the `register_*!` macros
///
/// This struct is collected via the `inventory` crate at runtime.
#[derive(Clone, Copy)]
pub struct WorkerInfo {
    /// Worker name (from attribute or function name)
    pub name: &'static str,
    /// Optional description of what the worker does
    pub description: Option<&'static str>,
    /// The worker function that receives the context
    pub worker: WorkerFn,
    /// Opt-in in-process restart policy. `None` makes the worker's first
    /// exit terminal.
    pub restart: Option<RestartPolicy>,
}

// Manual Debug implementation to avoid printing function pointers
impl std::fmt::Debug for WorkerInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WorkerInfo")
            .field("name", &self.name)
            .field("description", &self.description)
            .field("worker", &"<worker_fn>")
            .field("restart", &self.restart)
            .finish()
    }
}

/// Drain function metadata submitted by the `register_*!` macros alongside
/// the worker itself.
///
/// The shutdown path calls every registered drain once the server has stopped
/// accepting connections, so a worker trait's `drain` implementation is the
/// hook for finishing in-progress work. Workers that don't override it drain
/// as a no-op.
#[derive(Clone, Copy)]
pub struct WorkerDrainInfo {
    /// Worker name (must match the corresponding WorkerInfo name)
    pub name: &'static str,
    /// The drain function called during graceful shutdown
    pub drain: DrainFn,
}

inventory::collect!(WorkerDrainInfo);

/// Get all registered drain functions.
#[must_use]
pub fn get_worker_drains() -> Vec<&'static WorkerDrainInfo> {
    inventory::iter::<WorkerDrainInfo>.into_iter().collect()
}

inventory::collect!(WorkerInfo);

/// Get all registered workers
///
/// Returns a vector of all workers registered via `#[worker]` macros.
///
/// # Example
///
/// ```rust,ignore
/// for worker in get_workers() {
///     println!("Worker: {} - {:?}", worker.name, worker.description);
/// }
/// ```
#[must_use]
pub fn get_workers() -> Vec<&'static WorkerInfo> {
    inventory::iter::<WorkerInfo>.into_iter().collect()
}

// ============================================================================
// Worker Trait
// ============================================================================

/// Trait-based background worker.
///
/// Implement this trait to define a simple background worker without proc macros.
/// The runtime executor [`run_basic_worker`] handles context downcasting —
/// matching the behavior of `#[worker]`.
///
/// # Example
///
/// ```rust,ignore
/// use flatbed::{Worker, FlatbedWorkerError};
/// use std::sync::Arc;
///
/// struct HealthChecker;
///
/// impl Worker for HealthChecker {
///     type Context = AppContext;
///     const NAME: &'static str = "health-checker";
///     const DESCRIPTION: Option<&'static str> = Some("Periodically checks health");
///
///     fn run(
///         &self,
///         ctx: Arc<Self::Context>,
///     ) -> flatbed::BoxFuture<Result<(), FlatbedWorkerError>> {
///         Box::pin(async move {
///             // worker logic
///             Ok(())
///         })
///     }
/// }
///
/// flatbed::register_worker!(HealthChecker, AppContext);
/// ```
pub trait Worker: Send + Sync + 'static {
    /// The application context type.
    type Context: Send + Sync + 'static;

    /// Worker name used for logging and identification.
    const NAME: &'static str;

    /// Optional description of what this worker does.
    const DESCRIPTION: Option<&'static str> = None;

    /// Opt-in in-process restart policy. `None` — the default — makes the
    /// worker's first exit terminal, leaving Kubernetes to restart the pod.
    /// Registration puts this in a `static` initializer, so the expression
    /// has to be const-evaluatable; the [`RestartPolicy`] builders are
    /// `const fn`.
    ///
    /// ```rust,ignore
    /// const RESTART: Option<flatbed::RestartPolicy> = Some(
    ///     flatbed::RestartPolicy::backoff(
    ///         std::time::Duration::from_secs(1),
    ///         std::time::Duration::from_secs(60),
    ///     ),
    /// );
    /// ```
    const RESTART: ::core::option::Option<RestartPolicy> = ::core::option::Option::None;

    /// Run the worker. Called once after the server is ready, and expected to
    /// keep running for the life of the process — returning `Ok(())` marks the
    /// process unhealthy, and returning `Err` or panicking additionally starts
    /// graceful shutdown. One-shot initialisation belongs in the boot function
    /// passed to [`Flatbed::run`], not in a worker.
    fn run(&self, ctx: std::sync::Arc<Self::Context>) -> BoxFuture<Result<(), FlatbedWorkerError>>;

    /// Finish in-progress work during graceful shutdown, within the
    /// configured shutdown budget. Defaults to a no-op.
    fn drain(
        &self,
        _ctx: std::sync::Arc<Self::Context>,
    ) -> BoxFuture<Result<(), FlatbedWorkerError>> {
        Box::pin(async { Ok(()) })
    }
}

/// Run a [`Worker`] by downcasting the context and delegating to `Worker::run`.
pub fn run_basic_worker<W, C>(
    ctx: std::sync::Arc<dyn std::any::Any + Send + Sync>,
) -> BoxFuture<Result<(), FlatbedWorkerError>>
where
    W: Worker<Context = C> + Default,
    C: Send + Sync + 'static,
{
    Box::pin(async move {
        let ctx: std::sync::Arc<C> = ctx
            .downcast::<C>()
            .unwrap_or_else(|_| panic!("worker '{}' context type mismatch", W::NAME));
        let worker = W::default();
        worker.run(ctx).await
    })
}

/// Drain a [`Worker`] by downcasting the context and delegating to
/// `Worker::drain`.
pub fn run_basic_worker_drain<W, C>(
    ctx: std::sync::Arc<dyn std::any::Any + Send + Sync>,
) -> BoxFuture<Result<(), FlatbedWorkerError>>
where
    W: Worker<Context = C> + Default,
    C: Send + Sync + 'static,
{
    Box::pin(async move {
        let ctx: std::sync::Arc<C> = ctx
            .downcast::<C>()
            .unwrap_or_else(|_| panic!("worker '{}' context type mismatch", W::NAME));
        W::default().drain(ctx).await
    })
}

// ============================================================================
// Registration Macros
// ============================================================================

/// Register a [`KubeReconciler`] implementor with the Flatbed worker system.
///
/// Submits a [`WorkerInfo`] whose worker function delegates to
/// [`run_kube_reconciler`], plus a [`WorkerDrainInfo`] wired to the
/// reconciler's `drain`.
///
/// # Usage
///
/// ```rust,ignore
/// struct MyReconciler;
/// impl flatbed::KubeReconciler for MyReconciler { /* ... */ }
///
/// flatbed::register_kube_reconciler!(MyReconciler, AppContext);
/// ```
///
/// The worker's `RESTART` associated const decides whether it is restarted
/// in place; the macro takes no configuration of its own.
#[cfg(all(feature = "nats", feature = "k8s"))]
#[macro_export]
macro_rules! register_kube_reconciler {
    ($reconciler:ty, $context:ty) => {
        $crate::inventory::submit! {
            $crate::WorkerInfo {
                name: <$reconciler as $crate::k8s::KubeReconciler>::NAME,
                description: <$reconciler as $crate::k8s::KubeReconciler>::DESCRIPTION,
                restart: <$reconciler as $crate::k8s::KubeReconciler>::RESTART,
                worker: {
                    fn __worker(
                        ctx: ::std::sync::Arc<dyn ::std::any::Any + Send + Sync>,
                    ) -> ::std::pin::Pin<
                        Box<dyn ::std::future::Future<Output = Result<(), $crate::FlatbedWorkerError>> + Send>,
                    > {
                        Box::pin($crate::k8s::run_kube_reconciler::<$reconciler, $context>(ctx))
                    }
                    __worker
                },
            }
        }
        $crate::inventory::submit! {
            $crate::WorkerDrainInfo {
                name: <$reconciler as $crate::k8s::KubeReconciler>::NAME,
                drain: {
                    fn __drain(
                        ctx: ::std::sync::Arc<dyn ::std::any::Any + Send + Sync>,
                    ) -> ::std::pin::Pin<
                        Box<dyn ::std::future::Future<Output = Result<(), $crate::FlatbedWorkerError>> + Send>,
                    > {
                        $crate::k8s::run_kube_reconciler_drain::<$reconciler, $context>(ctx)
                    }
                    __drain
                },
            }
        }
    };
}

/// Register a [`KubeNativeReconciler`] implementor with the Flatbed
/// worker system.
///
/// Submits a [`WorkerInfo`] whose worker function delegates to
/// [`run_kube_native_reconciler`], plus a [`WorkerDrainInfo`] wired to the
/// reconciler's `drain`. Use this for reconcilers whose contexts implement
/// `HasKubeClient + HasLeaderElection` only — no JetStream context bound
/// required.
///
/// # Usage
///
/// ```rust,ignore
/// #[derive(Default)]
/// struct MyReconciler;
/// impl flatbed::KubeNativeReconciler for MyReconciler { /* ... */ }
///
/// flatbed::register_kube_native_reconciler!(MyReconciler, AppContext);
/// ```
///
/// The worker's `RESTART` associated const decides whether it is restarted
/// in place; the macro takes no configuration of its own.
///
/// [`KubeNativeReconciler`]: crate::k8s::KubeNativeReconciler
/// [`run_kube_native_reconciler`]: crate::k8s::run_kube_native_reconciler
#[cfg(feature = "k8s")]
#[macro_export]
macro_rules! register_kube_native_reconciler {
    ($reconciler:ty, $context:ty) => {
        $crate::inventory::submit! {
            $crate::WorkerInfo {
                name: <$reconciler as $crate::k8s::KubeNativeReconciler>::NAME,
                description: <$reconciler as $crate::k8s::KubeNativeReconciler>::DESCRIPTION,
                restart: <$reconciler as $crate::k8s::KubeNativeReconciler>::RESTART,
                worker: {
                    fn __worker(
                        ctx: ::std::sync::Arc<dyn ::std::any::Any + Send + Sync>,
                    ) -> ::std::pin::Pin<
                        Box<dyn ::std::future::Future<Output = Result<(), $crate::FlatbedWorkerError>> + Send>,
                    > {
                        Box::pin($crate::k8s::run_kube_native_reconciler::<$reconciler, $context>(ctx))
                    }
                    __worker
                },
            }
        }
        $crate::inventory::submit! {
            $crate::WorkerDrainInfo {
                name: <$reconciler as $crate::k8s::KubeNativeReconciler>::NAME,
                drain: {
                    fn __drain(
                        ctx: ::std::sync::Arc<dyn ::std::any::Any + Send + Sync>,
                    ) -> ::std::pin::Pin<
                        Box<dyn ::std::future::Future<Output = Result<(), $crate::FlatbedWorkerError>> + Send>,
                    > {
                        $crate::k8s::run_kube_native_reconciler_drain::<$reconciler, $context>(ctx)
                    }
                    __drain
                },
            }
        }
    };
}

/// Register a [`KubeWatcher`] implementor with the Flatbed worker system.
///
/// Mirrors `register_kube_reconciler!` but uses the watcher-based executor
/// — the right primitive when the watched resource is owned by
/// kube-controller-manager (no finalizer possible) and Delete events
/// matter for correctness.
///
/// # Requirements
///
/// The implementor must also implement `Default` — the executor calls
/// `R::default()` once per executor lifetime. State that needs to
/// reset per-watch-burst should reset inside `on_init` (which fires
/// on every list+watch, including reopens after a transient error).
///
/// # Usage
///
/// ```rust,ignore
/// #[derive(Default)]
/// struct EndpointWatcher { /* per-leader state behind Arc<Mutex<..>> */ }
/// impl flatbed::KubeWatcher for EndpointWatcher { /* ... */ }
///
/// flatbed::register_kube_watcher!(EndpointWatcher, AppContext);
/// ```
///
/// The worker's `RESTART` associated const decides whether it is restarted
/// in place; the macro takes no configuration of its own.
///
/// [`KubeWatcher`]: crate::k8s::KubeWatcher
#[cfg(feature = "k8s")]
#[macro_export]
macro_rules! register_kube_watcher {
    ($watcher:ty, $context:ty) => {
        $crate::inventory::submit! {
            $crate::WorkerInfo {
                name: <$watcher as $crate::k8s::KubeWatcher>::NAME,
                description: <$watcher as $crate::k8s::KubeWatcher>::DESCRIPTION,
                restart: <$watcher as $crate::k8s::KubeWatcher>::RESTART,
                worker: {
                    fn __worker(
                        ctx: ::std::sync::Arc<dyn ::std::any::Any + Send + Sync>,
                    ) -> ::std::pin::Pin<
                        Box<dyn ::std::future::Future<Output = Result<(), $crate::FlatbedWorkerError>> + Send>,
                    > {
                        Box::pin($crate::k8s::run_kube_watcher::<$watcher, $context>(ctx))
                    }
                    __worker
                },
            }
        }
        $crate::inventory::submit! {
            $crate::WorkerDrainInfo {
                name: <$watcher as $crate::k8s::KubeWatcher>::NAME,
                drain: {
                    fn __drain(
                        ctx: ::std::sync::Arc<dyn ::std::any::Any + Send + Sync>,
                    ) -> ::std::pin::Pin<
                        Box<dyn ::std::future::Future<Output = Result<(), $crate::FlatbedWorkerError>> + Send>,
                    > {
                        $crate::k8s::run_kube_watcher_drain::<$watcher, $context>(ctx)
                    }
                    __drain
                },
            }
        }
    };
}

/// Register a [`StreamWorker`] implementor with the Flatbed worker system.
///
/// Submits a [`WorkerInfo`] whose worker function delegates to
/// [`run_stream_worker`], plus a [`WorkerDrainInfo`] wired to the worker's
/// `drain`.
///
/// # Usage
///
/// ```rust,ignore
/// struct MyWorker;
/// impl flatbed::StreamWorker for MyWorker { /* ... */ }
///
/// flatbed::register_stream_worker!(MyWorker, AppContext);
/// ```
///
/// The worker's `RESTART` associated const decides whether it is restarted
/// in place; the macro takes no configuration of its own.
///
/// [`StreamWorker`]: crate::nats::StreamWorker
/// [`run_stream_worker`]: crate::nats::run_stream_worker
#[cfg(feature = "nats")]
#[macro_export]
macro_rules! register_stream_worker {
    ($stream_worker:ty, $context:ty) => {
        $crate::inventory::submit! {
            $crate::WorkerInfo {
                name: <$stream_worker as $crate::nats::StreamWorker>::NAME,
                description: <$stream_worker as $crate::nats::StreamWorker>::DESCRIPTION,
                restart: <$stream_worker as $crate::nats::StreamWorker>::RESTART,
                worker: {
                    fn __worker(
                        ctx: ::std::sync::Arc<dyn ::std::any::Any + Send + Sync>,
                    ) -> ::std::pin::Pin<
                        Box<dyn ::std::future::Future<Output = Result<(), $crate::FlatbedWorkerError>> + Send>,
                    > {
                        Box::pin($crate::nats::run_stream_worker::<$stream_worker, $context>(ctx))
                    }
                    __worker
                },
            }
        }
        $crate::inventory::submit! {
            $crate::WorkerDrainInfo {
                name: <$stream_worker as $crate::nats::StreamWorker>::NAME,
                drain: {
                    fn __drain(
                        ctx: ::std::sync::Arc<dyn ::std::any::Any + Send + Sync>,
                    ) -> ::std::pin::Pin<
                        Box<dyn ::std::future::Future<Output = Result<(), $crate::FlatbedWorkerError>> + Send>,
                    > {
                        $crate::nats::run_stream_worker_drain::<$stream_worker, $context>(ctx)
                    }
                    __drain
                },
            }
        }
    };
}

/// Register a [`KvWorker`] implementor with the Flatbed worker system.
///
/// Submits a [`WorkerInfo`] whose worker function delegates to
/// [`run_kv_worker`], plus a [`WorkerDrainInfo`] wired to the worker's
/// `drain`.
///
/// # Requirements
///
/// The implementor must also implement `Default` — the executor calls
/// `W::default()` once at spawn. `#[derive(Default)]` on the impl
/// struct is usually enough.
///
/// # Usage
///
/// ```rust,ignore
/// #[derive(Default)]
/// struct CacheSubscriber;
/// impl flatbed::KvWorker for CacheSubscriber { /* ... */ }
///
/// flatbed::register_kv_worker!(CacheSubscriber, AppContext);
/// ```
///
/// The worker's `RESTART` associated const decides whether it is restarted
/// in place; the macro takes no configuration of its own.
///
/// [`KvWorker`]: crate::kv::KvWorker
/// [`run_kv_worker`]: crate::kv::run_kv_worker
#[cfg(feature = "nats")]
#[macro_export]
macro_rules! register_kv_worker {
    ($kv_worker:ty, $context:ty) => {
        $crate::inventory::submit! {
            $crate::WorkerInfo {
                name: <$kv_worker as $crate::kv::KvWorker>::NAME,
                description: <$kv_worker as $crate::kv::KvWorker>::DESCRIPTION,
                restart: <$kv_worker as $crate::kv::KvWorker>::RESTART,
                worker: {
                    fn __worker(
                        ctx: ::std::sync::Arc<dyn ::std::any::Any + Send + Sync>,
                    ) -> ::std::pin::Pin<
                        Box<dyn ::std::future::Future<Output = Result<(), $crate::FlatbedWorkerError>> + Send>,
                    > {
                        Box::pin($crate::kv::run_kv_worker::<$kv_worker, $context>(ctx))
                    }
                    __worker
                },
            }
        }
        $crate::inventory::submit! {
            $crate::WorkerDrainInfo {
                name: <$kv_worker as $crate::kv::KvWorker>::NAME,
                drain: {
                    fn __drain(
                        ctx: ::std::sync::Arc<dyn ::std::any::Any + Send + Sync>,
                    ) -> ::std::pin::Pin<
                        Box<dyn ::std::future::Future<Output = Result<(), $crate::FlatbedWorkerError>> + Send>,
                    > {
                        $crate::kv::run_kv_worker_drain::<$kv_worker, $context>(ctx)
                    }
                    __drain
                },
            }
        }
    };
}

/// Register a [`Worker`] implementor with the Flatbed worker system.
///
/// Submits a [`WorkerInfo`] whose worker function delegates to
/// [`run_basic_worker`], plus a [`WorkerDrainInfo`] wired to the worker's
/// `drain`.
///
/// # Usage
///
/// ```rust,ignore
/// struct HealthChecker;
/// impl flatbed::Worker for HealthChecker { /* ... */ }
///
/// flatbed::register_worker!(HealthChecker, AppContext);
/// ```
///
/// Set the worker's [`RESTART`](Worker::RESTART) associated const to trade a
/// pod restart for an in-process retry with capped, jittered backoff; the
/// macro takes no configuration of its own.
#[macro_export]
macro_rules! register_worker {
    ($worker_type:ty, $context:ty) => {
        $crate::inventory::submit! {
            $crate::WorkerInfo {
                name: <$worker_type as $crate::Worker>::NAME,
                description: <$worker_type as $crate::Worker>::DESCRIPTION,
                restart: <$worker_type as $crate::Worker>::RESTART,
                worker: {
                    fn __worker(
                        ctx: ::std::sync::Arc<dyn ::std::any::Any + Send + Sync>,
                    ) -> ::std::pin::Pin<
                        Box<dyn ::std::future::Future<Output = Result<(), $crate::FlatbedWorkerError>> + Send>,
                    > {
                        $crate::run_basic_worker::<$worker_type, $context>(ctx)
                    }
                    __worker
                },
            }
        }
        $crate::inventory::submit! {
            $crate::WorkerDrainInfo {
                name: <$worker_type as $crate::Worker>::NAME,
                drain: {
                    fn __drain(
                        ctx: ::std::sync::Arc<dyn ::std::any::Any + Send + Sync>,
                    ) -> ::std::pin::Pin<
                        Box<dyn ::std::future::Future<Output = Result<(), $crate::FlatbedWorkerError>> + Send>,
                    > {
                        $crate::run_basic_worker_drain::<$worker_type, $context>(ctx)
                    }
                    __drain
                },
            }
        }
    };
}

/// Route map type: (path, method) -> RouteInfo with handler
pub type RouteMap = HashMap<(String, HttpMethod), RouteInfo>;

/// Validation error for route conflicts
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RouteConflict {
    pub path: String,
    pub method: HttpMethod,
    pub first_request: String,
    pub first_response: String,
    pub second_request: String,
    pub second_response: String,
}

impl std::fmt::Display for RouteConflict {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Route conflict at {} '{}': ({}, {}) vs ({}, {})",
            self.method,
            self.path,
            self.first_request,
            self.first_response,
            self.second_request,
            self.second_response
        )
    }
}

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

/// Get the route map with all registered routes
///
/// Returns a HashMap mapping path strings to RouteInfo containing
/// handler function pointers and type information.
/// This is populated at runtime from all #[route] decorated functions.
///
/// # Example
/// ```rust,ignore
/// use flatbed::{route, get_routes};
///
/// #[route("/ping")]
/// fn handle_ping(req: Vec<u8>) -> Vec<u8> { ... }
///
/// let routes = get_routes();
/// let route_info = routes.get(&("/ping".to_string(), flatbed::HttpMethod::Post)).unwrap();
/// // Use route_info.handler to call the function
/// // Use route_info.request_type / response_type for metadata
/// ```
#[must_use]
pub fn get_routes() -> &'static RouteMap {
    static ROUTES: LazyLock<RouteMap> = LazyLock::new(|| {
        let mut map = HashMap::new();
        for route in inventory::iter::<RouteInfo> {
            map.insert((route.path.to_string(), route.method), *route);
        }
        map
    });
    &ROUTES
}

/// Look up a registered [`TypeSchema`] by its bare type name.
///
/// Names are keyed bare (without the namespace), matching how routes reference
/// their request/response types. A bare name is therefore assumed unique across
/// namespaces; [`validate_type_registry`] enforces that at startup.
#[must_use]
pub fn get_type_schema(name: &str) -> Option<&'static TypeSchema> {
    static MAP: LazyLock<HashMap<&'static str, &'static TypeSchema>> = LazyLock::new(|| {
        let mut map = HashMap::new();
        for ty in inventory::iter::<TypeSchema> {
            map.insert(ty.name, ty);
        }
        map
    });
    MAP.get(name).copied()
}

/// Look up a registered [`EnumSchema`] by its bare name.
///
/// Names are keyed bare (without the namespace); a bare name is assumed unique
/// across namespaces, which [`validate_type_registry`] enforces at startup.
#[must_use]
pub fn get_enum_schema(name: &str) -> Option<&'static EnumSchema> {
    static MAP: LazyLock<HashMap<&'static str, &'static EnumSchema>> = LazyLock::new(|| {
        let mut map = HashMap::new();
        for en in inventory::iter::<EnumSchema> {
            map.insert(en.name, en);
        }
        map
    });
    MAP.get(name).copied()
}

/// A bare name registered under two different namespaces in the type registry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypeConflict {
    pub name: String,
    pub first_namespace: String,
    pub second_namespace: String,
    /// `"type"` or `"enum"` — which registry the collision is in.
    pub kind: &'static str,
}

impl std::fmt::Display for TypeConflict {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} name conflict: '{}' is registered in both namespace '{}' and '{}'",
            self.kind, self.name, self.first_namespace, self.second_namespace
        )
    }
}

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

/// Validate that every registered type and enum has a unique bare name.
///
/// [`get_type_schema`] and [`get_enum_schema`] key on the bare name, so two
/// same-named types in different namespaces shadow each other in the lookup —
/// and anything built from the registry would silently use whichever won the
/// insert race. This surfaces the collision as an error instead, at startup
/// before the server binds.
pub fn validate_type_registry() -> Result<(), TypeConflict> {
    let types = inventory::iter::<TypeSchema>
        .into_iter()
        .map(|t| (t.name, t.namespace));
    find_name_collision("type", types)?;
    let enums = inventory::iter::<EnumSchema>
        .into_iter()
        .map(|e| (e.name, e.namespace));
    find_name_collision("enum", enums)?;
    Ok(())
}

/// Return a [`TypeConflict`] if the same bare name appears under two different
/// namespaces in `entries` (`(name, namespace)` pairs). Repeats of an
/// identical `(name, namespace)` are not a conflict — only a name shared
/// across namespaces is, since that's what makes a bare-name lookup ambiguous.
fn find_name_collision<'a>(
    kind: &'static str,
    entries: impl IntoIterator<Item = (&'a str, &'a str)>,
) -> Result<(), TypeConflict> {
    let mut seen: HashMap<&str, &str> = HashMap::new();
    for (name, namespace) in entries {
        if let Some(prev) = seen.insert(name, namespace) {
            if prev != namespace {
                return Err(TypeConflict {
                    name: name.to_string(),
                    first_namespace: prev.to_string(),
                    second_namespace: namespace.to_string(),
                    kind,
                });
            }
        }
    }
    Ok(())
}

/// Validate that all routes are unique (no duplicate paths)
///
/// Returns Ok(()) if all routes are valid, or Err with the first conflict found.
///
/// # Example
/// ```rust,ignore
/// use flatbed::validate_routes;
///
/// match validate_routes() {
///     Ok(()) => println!("All routes valid!"),
///     Err(conflict) => eprintln!("Route conflict: {}", conflict),
/// }
/// ```
#[allow(clippy::result_large_err)]
pub fn validate_routes() -> Result<(), RouteConflict> {
    let mut seen: HashMap<(String, HttpMethod), RouteInfo> = HashMap::new();

    for route in inventory::iter::<RouteInfo> {
        let key = (route.path.to_string(), route.method);

        if let Some(first_route) = seen.get(&key) {
            // Found a duplicate (path, method) with different types
            if first_route.request_type != route.request_type
                || first_route.response_type != route.response_type
            {
                return Err(RouteConflict {
                    path: route.path.to_string(),
                    method: route.method,
                    first_request: first_route.request_type.to_string(),
                    first_response: first_route.response_type.to_string(),
                    second_request: route.request_type.to_string(),
                    second_response: route.response_type.to_string(),
                });
            }
        }

        seen.insert(key, *route);
    }

    Ok(())
}

// OpenAPI generation (enabled with "openapi" feature)
#[cfg(feature = "openapi")]
mod openapi_generation {
    use super::{
        get_routes, EnumSchema, FlatbedConfig, HttpMethod, RouteInfo, SchemaInfo, TypeFieldInfo,
        TypeSchema,
    };
    use std::collections::BTreeSet;
    use utoipa::openapi::{
        content::{Content, ContentBuilder},
        extensions::{Extensions, ExtensionsBuilder},
        path::{OperationBuilder, PathItemBuilder},
        request_body::RequestBodyBuilder,
        response::ResponseBuilder,
        schema::{
            AllOfBuilder, ArrayBuilder, KnownFormat, ObjectBuilder, Schema, SchemaFormat,
            SchemaType, Type,
        },
        server::ServerBuilder,
        ComponentsBuilder, Deprecated, InfoBuilder, OpenApi, OpenApiBuilder, PathsBuilder, Ref,
        RefOr, Required,
    };

    /// Get all unique versions from registered routes
    pub fn get_route_versions() -> BTreeSet<String> {
        let mut versions = BTreeSet::new();
        for route in get_routes().values() {
            let version = route.openapi.version.unwrap_or("v1");
            versions.insert(version.to_string());
        }
        if versions.is_empty() {
            versions.insert("v1".to_string());
        }
        versions
    }

    /// Get the latest version (lexicographically highest)
    pub fn get_latest_version() -> String {
        get_route_versions()
            .into_iter()
            .next_back()
            .unwrap_or_else(|| "v1".to_string())
    }

    /// Generate FBS schema text from field info
    fn generate_fbs_schema_text(schema: &SchemaInfo) -> String {
        let mut fbs = format!("table {} {{\n", schema.name.trim_end_matches("Json"));
        for field in schema.fields {
            fbs.push_str(&format!("  {}: {};\n", field.name, field.fbs_type));
        }
        fbs.push('}');
        fbs
    }

    /// Bare names of every registered table and enum (types, then enums).
    fn registered_names() -> (BTreeSet<&'static str>, BTreeSet<&'static str>) {
        let types = crate::inventory::iter::<TypeSchema>
            .into_iter()
            .map(|t| t.name)
            .collect();
        let enums = crate::inventory::iter::<EnumSchema>
            .into_iter()
            .map(|e| e.name)
            .collect();
        (types, enums)
    }

    /// Map a scalar `fbs_type` to an OpenAPI schema with the matching type and
    /// `format`. 64-bit integers get the `int64` format so a client generator
    /// can pick a wide-enough representation.
    fn scalar_schema(fbs_type: &str, extensions: Option<Extensions>) -> Schema {
        // Both the canonical widths from `flatc` reflection (`int32`, `uint64`,
        // …) and the FlatBuffer source aliases (`int`, `long`, `byte`, …) are
        // matched, since a hand-written `ToFlatBuffer` may use either.
        let (schema_type, format) = match fbs_type {
            "bool" => (Type::Boolean, None),
            "string" => (Type::String, None),
            // OpenAPI has no standard unsigned integer format; unsigned widths
            // map to the same int32/int64 format as their signed counterparts.
            "int8" | "byte" | "uint8" | "ubyte" | "int16" | "short" | "uint16" | "ushort"
            | "int32" | "int" | "uint32" | "uint" => (Type::Integer, Some(KnownFormat::Int32)),
            "int64" | "long" | "uint64" | "ulong" => (Type::Integer, Some(KnownFormat::Int64)),
            "float32" | "float" => (Type::Number, Some(KnownFormat::Float)),
            "float64" | "double" => (Type::Number, Some(KnownFormat::Double)),
            // Unknown scalar — fall back to string so the spec still validates.
            _ => (Type::String, None),
        };
        let mut builder = ObjectBuilder::new().schema_type(SchemaType::new(schema_type));
        if let Some(format) = format {
            builder = builder.format(Some(SchemaFormat::KnownFormat(format)));
        }
        Schema::Object(builder.extensions(extensions).build())
    }

    /// Schema for a bare `fbs_type`, carrying no field-level extensions (unlike
    /// a field's own schema): an array for `[T]`, a `$ref` for a registered
    /// table or enum, a scalar object otherwise.
    fn schema_for_fbs_type(
        fbs_type: &str,
        type_names: &BTreeSet<&str>,
        enum_names: &BTreeSet<&str>,
    ) -> RefOr<Schema> {
        if let Some(inner) = fbs_type.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
            let items = schema_for_fbs_type(inner, type_names, enum_names);
            return RefOr::T(Schema::Array(ArrayBuilder::new().items(items).build()));
        }
        if type_names.contains(fbs_type) || enum_names.contains(fbs_type) {
            RefOr::Ref(Ref::from_schema_name(fbs_type))
        } else {
            RefOr::T(scalar_schema(fbs_type, None))
        }
    }

    /// Build the property schema for one field, carrying `x-fbs-type` /
    /// `x-fbs-id` vendor extensions. A table/enum reference is wrapped in
    /// `allOf` so the `$ref` keeps its meaning while the extensions attach to
    /// the wrapper — a bare `$ref` can't carry sibling keywords.
    fn property_schema(
        field: &TypeFieldInfo,
        type_names: &BTreeSet<&str>,
        enum_names: &BTreeSet<&str>,
    ) -> RefOr<Schema> {
        let extensions = || {
            ExtensionsBuilder::new()
                .add("x-fbs-type", field.fbs_type)
                .add("x-fbs-id", field.field_id)
                .build()
        };

        if let Some(inner) = field
            .fbs_type
            .strip_prefix('[')
            .and_then(|s| s.strip_suffix(']'))
        {
            let items = schema_for_fbs_type(inner, type_names, enum_names);
            return RefOr::T(Schema::Array(
                ArrayBuilder::new()
                    .items(items)
                    .extensions(Some(extensions()))
                    .build(),
            ));
        }

        if type_names.contains(field.fbs_type) || enum_names.contains(field.fbs_type) {
            return RefOr::T(Schema::AllOf(
                AllOfBuilder::new()
                    .item(Ref::from_schema_name(field.fbs_type))
                    .extensions(Some(extensions()))
                    .build(),
            ));
        }

        RefOr::T(scalar_schema(field.fbs_type, Some(extensions())))
    }

    /// Register a component schema for every generated table and enum. Nested
    /// tables and enums are referenced by `$ref`, so the components form a
    /// closed, resolvable graph — including tables reachable only by nesting.
    fn add_type_components(
        components_builder: &mut ComponentsBuilder,
        type_names: &BTreeSet<&str>,
        enum_names: &BTreeSet<&str>,
    ) {
        for ty in crate::inventory::iter::<TypeSchema> {
            let mut obj = ObjectBuilder::new().schema_type(SchemaType::new(Type::Object));
            for field in ty.fields {
                obj = obj.property(field.name, property_schema(field, type_names, enum_names));
                if field.required {
                    obj = obj.required(field.name);
                }
            }
            *components_builder =
                std::mem::take(components_builder).schema(ty.name, Schema::Object(obj.build()));
        }

        for en in crate::inventory::iter::<EnumSchema> {
            // Enums cross the JSON wire as their variant-name string.
            let obj = ObjectBuilder::new()
                .schema_type(SchemaType::new(Type::String))
                .enum_values(Some(en.variants.iter().copied()))
                .build();
            *components_builder =
                std::mem::take(components_builder).schema(en.name, Schema::Object(obj));
        }
    }

    /// Convert our HttpMethod to utoipa's HttpMethod
    fn to_utoipa_method(method: &HttpMethod) -> utoipa::openapi::path::HttpMethod {
        match method {
            HttpMethod::Get => utoipa::openapi::path::HttpMethod::Get,
            HttpMethod::Post => utoipa::openapi::path::HttpMethod::Post,
            HttpMethod::Put => utoipa::openapi::path::HttpMethod::Put,
            HttpMethod::Delete => utoipa::openapi::path::HttpMethod::Delete,
            HttpMethod::Patch => utoipa::openapi::path::HttpMethod::Patch,
            HttpMethod::Head => utoipa::openapi::path::HttpMethod::Head,
            HttpMethod::Options => utoipa::openapi::path::HttpMethod::Options,
        }
    }

    /// The `application/x-flatbuffers` content entry. The `.fbs` text rides in
    /// the description because the binary body is otherwise opaque to readers.
    fn flatbuffers_content(schema: Option<&SchemaInfo>) -> Content {
        ContentBuilder::new()
            .schema(Some(Schema::Object(
                ObjectBuilder::new()
                    .schema_type(SchemaType::new(Type::String))
                    .format(Some(SchemaFormat::Custom("binary".to_string())))
                    .description(Some(format!(
                        "FlatBuffers binary data.\n\nSchema:\n```fbs\n{}\n```",
                        schema.map(generate_fbs_schema_text).unwrap_or_default()
                    )))
                    .build(),
            )))
            .build()
    }

    /// JSON content for a route body. Generated types reference their shared
    /// component by `$ref`; a hand-written `ToFlatBuffer` that never registered
    /// a component is inlined instead, so the `$ref` never dangles.
    fn json_ref_content(
        schema: Option<&SchemaInfo>,
        type_names: &BTreeSet<&str>,
        enum_names: &BTreeSet<&str>,
    ) -> Content {
        let mut content = ContentBuilder::new();
        if let Some(schema) = schema {
            let body: RefOr<Schema> = if type_names.contains(schema.name) {
                RefOr::Ref(Ref::from_schema_name(schema.name))
            } else {
                RefOr::T(inline_schema(schema, type_names, enum_names))
            };
            content = content.schema(Some(body));
        }
        content.build()
    }

    /// Inline object schema for a body type with no registered component;
    /// nested tables and enums still resolve by `$ref` where registered.
    fn inline_schema(
        schema: &SchemaInfo,
        type_names: &BTreeSet<&str>,
        enum_names: &BTreeSet<&str>,
    ) -> Schema {
        let mut obj = ObjectBuilder::new().schema_type(SchemaType::new(Type::Object));
        for field in schema.fields {
            obj = obj.property(
                field.name,
                schema_for_fbs_type(field.fbs_type, type_names, enum_names),
            );
            if field.required {
                obj = obj.required(field.name);
            }
        }
        Schema::Object(obj.build())
    }

    /// Build an OpenAPI operation from a route. Generated bodies reference the
    /// shared component schemas by `$ref`; those components are registered once,
    /// up front, when the spec is assembled.
    fn build_operation(
        route: &RouteInfo,
        type_names: &BTreeSet<&str>,
        enum_names: &BTreeSet<&str>,
    ) -> utoipa::openapi::path::Operation {
        let request_body = RequestBodyBuilder::new()
            .content(
                "application/json",
                json_ref_content(
                    route.openapi.request_schema.as_ref(),
                    type_names,
                    enum_names,
                ),
            )
            .content(
                "application/x-flatbuffers",
                flatbuffers_content(route.openapi.request_schema.as_ref()),
            )
            .required(Some(Required::True))
            .build();

        let response = ResponseBuilder::new()
            .description("Successful response")
            .content(
                "application/json",
                json_ref_content(
                    route.openapi.response_schema.as_ref(),
                    type_names,
                    enum_names,
                ),
            )
            .content(
                "application/x-flatbuffers",
                flatbuffers_content(route.openapi.response_schema.as_ref()),
            )
            .build();

        // Build operation
        let mut operation_builder = OperationBuilder::new()
            .request_body(Some(request_body))
            .response("200", response);

        if let Some(tag) = route.openapi.tag {
            operation_builder = operation_builder.tag(tag);
        }
        if let Some(summary) = route.openapi.summary {
            operation_builder = operation_builder.summary(Some(summary.to_string()));
        }
        if let Some(operation_id) = route.openapi.operation_id {
            operation_builder = operation_builder.operation_id(Some(operation_id.to_string()));
        }
        if route.openapi.deprecated {
            operation_builder = operation_builder.deprecated(Some(Deprecated::True));
        }

        operation_builder.build()
    }

    /// Generate OpenAPI spec for a specific version
    pub fn generate_openapi_spec(config: &FlatbedConfig, version: &str) -> OpenApi {
        let (type_names, enum_names) = registered_names();
        let mut paths_builder = PathsBuilder::new();
        let mut components_builder = ComponentsBuilder::new();
        add_type_components(&mut components_builder, &type_names, &enum_names);

        // Filter routes by version and group by path
        let routes: Vec<&RouteInfo> = get_routes()
            .values()
            .filter(|r| r.openapi.version.unwrap_or("v1") == version)
            .collect();

        // Group routes by path so multiple methods on the same path share a PathItem
        let mut path_groups: std::collections::BTreeMap<&str, Vec<&RouteInfo>> =
            std::collections::BTreeMap::new();
        for route in &routes {
            path_groups.entry(route.path).or_default().push(route);
        }

        for (path, path_routes) in &path_groups {
            let mut path_item_builder = PathItemBuilder::new();
            for route in path_routes {
                let operation = build_operation(route, &type_names, &enum_names);
                let http_method = to_utoipa_method(&route.method);
                path_item_builder = path_item_builder.operation(http_method, operation);
            }
            paths_builder = paths_builder.path(*path, path_item_builder.build());
        }

        // Build info
        let mut info_builder = InfoBuilder::new().title(config.title).version(version);

        if let Some(desc) = config.description {
            info_builder = info_builder.description(Some(desc.to_string()));
        }

        let mut builder = OpenApiBuilder::new()
            .info(info_builder.build())
            .paths(paths_builder.build())
            .components(Some(components_builder.build()));

        // Add external URL if provided
        if let Some(ref url) = config.external_url {
            builder = builder.servers(Some(vec![ServerBuilder::new().url(url.clone()).build()]));
        }

        builder.build()
    }

    /// Generate OpenAPI spec as JSON string
    pub fn get_openapi_json_for_version(config: &FlatbedConfig, version: &str) -> String {
        let spec = generate_openapi_spec(config, version);
        serde_json::to_string_pretty(&spec).unwrap_or_else(|_| "{}".to_string())
    }
}

#[cfg(feature = "openapi")]
pub use openapi_generation::{
    generate_openapi_spec, get_latest_version, get_openapi_json_for_version, get_route_versions,
};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new_builder() {
        let _builder = new_builder();
        // Builder created successfully
    }

    #[test]
    fn test_new_builder_with_capacity() {
        let _builder = new_builder_with_capacity(1024);
        // Builder with capacity created successfully
    }

    // ========================================================================
    // Request<T, C> tests
    // ========================================================================

    #[test]
    fn test_request_without_context() {
        let req: Request<String> = Request {
            body: "test body".to_string(),
            ctx: (),
            headers: HeaderMap::new(),
            method: Method::POST,
            path: "/test".to_string(),
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            request_id: "req-123".to_string(),
        };

        assert_eq!(*req, "test body");
        assert_eq!(req.body, "test body");
        assert_eq!(req.path, "/test");
        assert_eq!(req.request_id(), "req-123");
    }

    #[test]
    fn test_request_with_context() {
        #[derive(Debug)]
        struct AppCtx {
            app_name: String,
        }

        let ctx = AppCtx {
            app_name: "test-app".to_string(),
        };

        let req: Request<String, AppCtx> = Request {
            body: "test body".to_string(),
            ctx,
            headers: HeaderMap::new(),
            method: Method::POST,
            path: "/test".to_string(),
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            request_id: "req-456".to_string(),
        };

        assert_eq!(req.ctx.app_name, "test-app");
        assert_eq!(*req, "test body");
    }

    #[test]
    fn test_request_params_and_queries() {
        let mut path_params = HashMap::new();
        path_params.insert("id".to_string(), "123".to_string());

        let mut query_params = HashMap::new();
        query_params.insert("filter".to_string(), "active".to_string());

        let req: Request<String> = Request {
            body: "test".to_string(),
            ctx: (),
            headers: HeaderMap::new(),
            method: Method::POST,
            path: "/users/123".to_string(),
            path_params,
            query_params,
            request_id: "req-789".to_string(),
        };

        assert_eq!(req.param("id"), Some("123"));
        assert_eq!(req.param("nonexistent"), None);
        assert_eq!(req.query("filter"), Some("active"));
        assert_eq!(req.query("nonexistent"), None);
    }

    #[test]
    fn test_request_headers() {
        let mut headers = HeaderMap::new();
        headers.insert("x-custom", HeaderValue::from_static("custom-value"));

        let req: Request<String> = Request {
            body: "test".to_string(),
            ctx: (),
            headers,
            method: Method::POST,
            path: "/test".to_string(),
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            request_id: "req-abc".to_string(),
        };

        assert_eq!(req.header("x-custom"), Some("custom-value"));
        assert_eq!(req.header("nonexistent"), None);
    }

    // ========================================================================
    // Response<T> tests
    // ========================================================================

    #[test]
    fn test_response_ok() {
        let resp = Response::ok("success".to_string());
        assert_eq!(resp.body, "success");
        assert_eq!(resp.status, StatusCode::OK);
        assert!(resp.headers.is_empty());
    }

    #[test]
    fn test_response_created() {
        let resp = Response::created("new resource".to_string());
        assert_eq!(resp.status, StatusCode::CREATED);
    }

    #[test]
    fn test_response_with_status() {
        let resp = Response::with_status("accepted".to_string(), StatusCode::ACCEPTED);
        assert_eq!(resp.status, StatusCode::ACCEPTED);
    }

    #[test]
    fn test_response_builder_pattern() {
        let resp = Response::ok("test".to_string())
            .status(StatusCode::CREATED)
            .header("x-custom", "value");

        assert_eq!(resp.status, StatusCode::CREATED);
        assert_eq!(
            resp.headers.get("x-custom").and_then(|v| v.to_str().ok()),
            Some("value")
        );
    }

    // ========================================================================
    // FlatbedWorkerError tests
    // ========================================================================

    #[test]
    fn test_flatbed_worker_error_new() {
        let err = FlatbedWorkerError::new("TASK_ERROR", "task failed");
        assert_eq!(err.code, "TASK_ERROR");
        assert_eq!(err.message, "task failed");
    }

    #[test]
    fn test_flatbed_worker_error_display() {
        let err = FlatbedWorkerError::new("CACHE_ERROR", "cache warmup failed");
        assert_eq!(format!("{}", err), "[CACHE_ERROR] cache warmup failed");
    }

    // ========================================================================
    // FlatbedRouteError<D> tests
    // ========================================================================

    #[test]
    fn test_flatbed_route_error_bad_request() {
        let err = FlatbedRouteError::bad_request("invalid input");
        assert_eq!(err.status, StatusCode::BAD_REQUEST);
        assert_eq!(err.message, "invalid input");
        assert!(err.code.is_empty());
        assert!(err.details.is_none());
    }

    #[test]
    fn test_flatbed_route_error_not_found() {
        let err = FlatbedRouteError::not_found("resource not found");
        assert_eq!(err.status, StatusCode::NOT_FOUND);
    }

    #[test]
    fn test_flatbed_route_error_internal() {
        let err = FlatbedRouteError::internal("something went wrong");
        assert_eq!(err.status, StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn test_flatbed_route_error_with_code() {
        let err = FlatbedRouteError::bad_request("validation failed").code("VALIDATION_ERROR");
        assert_eq!(err.code, "VALIDATION_ERROR");
    }

    #[test]
    fn test_flatbed_route_error_with_details() {
        #[derive(Debug, Clone)]
        struct ErrorDetails {
            field: String,
        }

        let details = ErrorDetails {
            field: "email".to_string(),
        };

        let err = FlatbedRouteError::bad_request("validation failed").with_details(details);
        assert!(err.details.is_some());
        assert_eq!(err.details.as_ref().unwrap().field, "email");
    }

    #[test]
    fn test_flatbed_route_error_display() {
        let err1 = FlatbedRouteError::bad_request("simple error");
        assert_eq!(format!("{}", err1), "simple error");

        let err2 = FlatbedRouteError::bad_request("coded error").code("ERR_001");
        assert_eq!(format!("{}", err2), "[ERR_001] coded error");
    }

    #[test]
    fn test_flatbed_route_error_with_header() {
        let err =
            FlatbedRouteError::unauthorized("auth required").header("www-authenticate", "Bearer");
        assert!(err.headers.contains_key("www-authenticate"));
    }

    #[test]
    #[allow(deprecated)]
    fn test_flatbed_error_deprecated_alias() {
        // Test that the deprecated alias still works
        let err: FlatbedError = FlatbedError::bad_request("test");
        assert_eq!(err.status, StatusCode::BAD_REQUEST);
    }

    // ========================================================================
    // RequestParts tests
    // ========================================================================

    #[test]
    fn test_request_parts_new() {
        let parts = RequestParts::new(Method::POST, "/api/test".to_string());
        assert_eq!(parts.method, Method::POST);
        assert_eq!(parts.path, "/api/test");
        assert!(!parts.request_id.is_empty()); // UUID generated
    }

    #[test]
    fn test_request_parts_request_id_from_header() {
        let mut parts = RequestParts::new(Method::POST, "/test".to_string());
        parts
            .headers
            .insert("x-request-id", HeaderValue::from_static("custom-id-123"));

        let parts = parts.with_request_id_from_header();
        assert_eq!(parts.request_id, "custom-id-123");
    }

    // ========================================================================
    // ResponseParts tests
    // ========================================================================

    #[test]
    fn test_response_parts_ok() {
        let parts = ResponseParts::ok(vec![1, 2, 3], "application/json");
        assert_eq!(parts.body, vec![1, 2, 3]);
        assert_eq!(parts.status, StatusCode::OK);
        assert_eq!(parts.content_type, "application/json");
    }

    #[test]
    fn test_response_parts_owned_content_type() {
        let ext = "js";
        let parts = ResponseParts::ok(vec![], format!("application/{ext}"));
        assert_eq!(parts.content_type, "application/js");
    }

    #[test]
    fn test_response_raw() {
        let mut resp = Response::raw(b"<h1>hi</h1>".to_vec(), "text/html; charset=utf-8");
        assert_eq!(resp.status, StatusCode::OK);
        let (bytes, content_type) = resp.take_raw().expect("raw payload set");
        assert_eq!(bytes, b"<h1>hi</h1>");
        assert_eq!(content_type, "text/html; charset=utf-8");
    }

    #[test]
    fn test_response_ok_has_no_raw() {
        let mut resp = Response::ok(());
        assert!(resp.take_raw().is_none());
    }

    #[test]
    fn test_response_raw_status_builder_preserves_raw() {
        let mut resp = Response::raw(b"data".to_vec(), "text/plain").status(StatusCode::CREATED);
        assert_eq!(resp.status, StatusCode::CREATED);
        assert!(resp.take_raw().is_some(), "status() must preserve raw");
    }

    #[test]
    fn test_response_parts_with_request_id() {
        let parts = ResponseParts::ok(vec![], "application/json").with_request_id("req-123");
        assert_eq!(
            parts
                .headers
                .get("x-request-id")
                .and_then(|v| v.to_str().ok()),
            Some("req-123")
        );
    }

    // ========================================================================
    // FlatbedConfig tests
    // ========================================================================

    #[test]
    fn find_name_collision_flags_same_name_across_namespaces() {
        let entries = [("Foo", "v_1"), ("Bar", "v_1"), ("Foo", "v_2")];
        let err = find_name_collision("type", entries)
            .expect_err("a name shared across namespaces must be a conflict");
        assert_eq!(err.name, "Foo");
        assert_eq!(err.kind, "type");
        assert_eq!(err.first_namespace, "v_1");
        assert_eq!(err.second_namespace, "v_2");
    }

    #[test]
    fn find_name_collision_accepts_unique_names() {
        let entries = [("Foo", "v_1"), ("Bar", "v_1"), ("Baz", "v_2")];
        assert!(find_name_collision("type", entries).is_ok());
    }

    #[test]
    fn find_name_collision_ignores_identical_reregistration() {
        // The same (name, namespace) appearing twice is a harmless duplicate,
        // not an ambiguous lookup — only a name split across namespaces is.
        let entries = [("Foo", "v_1"), ("Foo", "v_1")];
        assert!(find_name_collision("enum", entries).is_ok());
    }

    #[test]
    fn test_flatbed_config_new() {
        let config = FlatbedConfig::new("Test API");
        assert_eq!(config.title, "Test API");
        assert_eq!(config.host, "0.0.0.0");
        assert_eq!(config.port, 8080);
        assert!(config.description.is_none());
        assert!(config.external_url.is_none());
    }

    #[test]
    fn test_flatbed_config_default() {
        let config = FlatbedConfig::default();
        assert_eq!(config.title, "API");
        assert_eq!(config.host, "0.0.0.0");
        assert_eq!(config.port, 8080);
    }

    #[test]
    fn test_flatbed_config_builder_pattern() {
        let config = FlatbedConfig::new("My API")
            .host("127.0.0.1")
            .port(3000)
            .description("A test API")
            .external_url("https://api.example.com");

        assert_eq!(config.title, "My API");
        assert_eq!(config.host, "127.0.0.1");
        assert_eq!(config.port, 3000);
        assert_eq!(config.description, Some("A test API"));
        assert_eq!(
            config.external_url,
            Some("https://api.example.com".to_string())
        );
    }

    #[test]
    fn test_flatbed_config_bind_address() {
        let config = FlatbedConfig::new("API").host("0.0.0.0").port(8080);
        assert_eq!(config.bind_address(), "0.0.0.0:8080");

        let config2 = FlatbedConfig::new("API").host("127.0.0.1").port(3000);
        assert_eq!(config2.bind_address(), "127.0.0.1:3000");
    }

    #[test]
    fn test_flatbed_config_debug() {
        let config = FlatbedConfig::new("Test API").host("localhost").port(9000);
        let debug_str = format!("{:?}", config);
        assert!(debug_str.contains("Test API"));
        assert!(debug_str.contains("localhost"));
        assert!(debug_str.contains("9000"));
    }

    // ========================================================================
    // Worker trait tests
    // ========================================================================

    /// Test context for Worker trait tests.
    struct TestWorkerCtx {
        pub label: String,
    }

    /// A Worker implementation that records whether it was called.
    struct RecordingWorker;

    impl Default for RecordingWorker {
        fn default() -> Self {
            RecordingWorker
        }
    }

    impl Worker for RecordingWorker {
        type Context = TestWorkerCtx;
        const NAME: &'static str = "recording-worker";
        const DESCRIPTION: Option<&'static str> = Some("Records calls for testing");

        fn run(
            &self,
            ctx: std::sync::Arc<Self::Context>,
        ) -> std::pin::Pin<
            Box<dyn std::future::Future<Output = Result<(), FlatbedWorkerError>> + Send>,
        > {
            Box::pin(async move {
                if ctx.label == "fail" {
                    return Err(FlatbedWorkerError::new("TEST", "intentional failure"));
                }
                Ok(())
            })
        }
    }

    #[tokio::test]
    async fn run_basic_worker_downcasts_and_runs() {
        let ctx = std::sync::Arc::new(TestWorkerCtx {
            label: "success".to_string(),
        });
        let dyn_ctx: std::sync::Arc<dyn std::any::Any + Send + Sync> = ctx;
        let result = run_basic_worker::<RecordingWorker, TestWorkerCtx>(dyn_ctx).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn run_basic_worker_propagates_error() {
        let ctx = std::sync::Arc::new(TestWorkerCtx {
            label: "fail".to_string(),
        });
        let dyn_ctx: std::sync::Arc<dyn std::any::Any + Send + Sync> = ctx;
        let result = run_basic_worker::<RecordingWorker, TestWorkerCtx>(dyn_ctx).await;
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().code, "TEST");
    }

    #[tokio::test]
    async fn run_basic_worker_panics_on_context_type_mismatch() {
        // Provide the wrong context type (String instead of TestWorkerCtx)
        let wrong_ctx: std::sync::Arc<dyn std::any::Any + Send + Sync> =
            std::sync::Arc::new("wrong type".to_string());

        let result = std::panic::AssertUnwindSafe(
            run_basic_worker::<RecordingWorker, TestWorkerCtx>(wrong_ctx),
        );
        let panic_result = futures::FutureExt::catch_unwind(result).await;
        assert!(
            panic_result.is_err(),
            "run_basic_worker should panic on context type mismatch"
        );
    }

    // ========================================================================
    // Worker trait defaults
    // ========================================================================

    #[test]
    fn worker_description_default_is_some_when_set() {
        assert_eq!(
            <RecordingWorker as Worker>::DESCRIPTION,
            Some("Records calls for testing")
        );
    }

    /// A worker with no description override to test the default.
    struct MinimalWorker;

    impl Default for MinimalWorker {
        fn default() -> Self {
            MinimalWorker
        }
    }

    impl Worker for MinimalWorker {
        type Context = TestWorkerCtx;
        const NAME: &'static str = "minimal-worker";

        fn run(
            &self,
            _ctx: std::sync::Arc<Self::Context>,
        ) -> std::pin::Pin<
            Box<dyn std::future::Future<Output = Result<(), FlatbedWorkerError>> + Send>,
        > {
            Box::pin(async { Ok(()) })
        }
    }

    #[test]
    fn worker_description_default_is_none() {
        assert!(<MinimalWorker as Worker>::DESCRIPTION.is_none());
    }

    // ========================================================================
    // register_worker! macro tests
    // ========================================================================

    // Register MinimalWorker via the macro so inventory picks it up.
    register_worker!(MinimalWorker, TestWorkerCtx);

    #[test]
    fn register_worker_macro_makes_worker_discoverable() {
        let workers = get_workers();
        let found = workers
            .iter()
            .find(|w| w.name == <MinimalWorker as Worker>::NAME);
        assert!(
            found.is_some(),
            "MinimalWorker should be discoverable via inventory"
        );
    }

    #[test]
    fn registered_worker_name_matches_trait_constant() {
        let workers = get_workers();
        let found = workers.iter().find(|w| w.name == "minimal-worker");
        assert!(found.is_some());
        let info = found.unwrap();
        assert_eq!(info.name, <MinimalWorker as Worker>::NAME);
        assert_eq!(info.description, <MinimalWorker as Worker>::DESCRIPTION);
    }

    #[tokio::test]
    async fn registered_worker_can_be_invoked_via_inventory() {
        let workers = get_workers();
        let info = workers
            .iter()
            .find(|w| w.name == "minimal-worker")
            .expect("MinimalWorker should be registered");

        let ctx = std::sync::Arc::new(TestWorkerCtx {
            label: "inventory-test".to_string(),
        });
        let dyn_ctx: std::sync::Arc<dyn std::any::Any + Send + Sync> = ctx;
        let result = (info.worker)(dyn_ctx).await;
        assert!(result.is_ok());
    }
}