celers 0.1.0

Celery-compatible distributed task queue for Rust (Facade crate)
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
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
//! # CeleRS - Celery-Compatible Distributed Task Queue for Rust
//!
//! **CeleRS** is a production-ready, Celery-compatible distributed task queue library
//! providing binary-level protocol compatibility with Python Celery while delivering
//! superior performance, type safety, and reliability.
//!
//! ## Quick Start
//!
//! ### 1. Add CeleRS to your Cargo.toml
//!
//! ```toml
//! [dependencies]
//! celers = { version = "0.1", features = ["redis", "backend-redis", "json"] }
//! tokio = { version = "1", features = ["full"] }
//! serde = { version = "1", features = ["derive"] }
//! ```
//!
//! ### 2. Define a Task
//!
//! ```rust,no_run
//! use celers::prelude::*;
//!
//! #[derive(Clone, Serialize, Deserialize, Debug)]
//! struct AddArgs {
//!     x: i32,
//!     y: i32,
//! }
//!
//! #[celers::task]
//! async fn add(args: AddArgs) -> Result<i32, Box<dyn std::error::Error>> {
//!     Ok(args.x + args.y)
//! }
//! ```
//!
//! ### 3. Create a Worker
//!
//! ```rust,ignore
//! use celers::prelude::*;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     // Create broker from environment variables
//!     let broker = create_broker_from_env().await?;
//!
//!     // Configure and start worker
//!     let worker = WorkerConfigBuilder::new()
//!         .concurrency(4)
//!         .prefetch_count(10)
//!         .build(broker)?;
//!
//!     worker.start().await?;
//!     Ok(())
//! }
//! ```
//!
//! ### 4. Send Tasks
//!
//! ```rust,ignore
//! use celers::prelude::*;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let broker = create_broker_from_env().await?;
//!
//!     // Send a single task
//!     let task = add::new(AddArgs { x: 1, y: 2 });
//!     broker.enqueue(task).await?;
//!
//!     // Send a workflow
//!     let workflow = Chain::new()
//!         .add(add::new(AddArgs { x: 1, y: 2 }))
//!         .add(add::new(AddArgs { x: 3, y: 4 }));
//!     workflow.apply_async(&broker).await?;
//!
//!     Ok(())
//! }
//! ```
//!
//! ## Features
//!
//! - **Type-Safe**: Compile-time guarantees for task signatures
//! - **Celery-Compatible**: Binary protocol compatibility with Python Celery
//! - **High Performance**: 10x throughput compared to Python Celery
//! - **Multiple Brokers**: Redis, PostgreSQL, MySQL, RabbitMQ (AMQP), AWS SQS
//! - **Multiple Backends**: Redis, PostgreSQL/MySQL (Database), gRPC
//! - **Workflow Primitives**: Chain, Group, Chord, Map, Starmap
//! - **Observability**: Prometheus metrics, distributed tracing
//! - **Production Features**: Batch operations, persistent scheduler, progress tracking
//!
//! ## Architecture
//!
//! CeleRS follows a layered architecture:
//!
//! ```text
//! Application Layer (Your Tasks)
//!//! Runtime Layer (celers-worker, celers-canvas)
//!//! Messaging Layer (celers-kombu, celers-broker-*)
//!//! Protocol Layer (celers-protocol)
//! ```
//!
//! ## Feature Selection Guide
//!
//! Choose features based on your infrastructure and requirements:
//!
//! ### Broker Selection
//!
//! | Feature    | Use When                                    | Performance |
//! |------------|---------------------------------------------|-------------|
//! | `redis`    | Simple setup, high throughput needed        | ⭐⭐⭐⭐⭐        |
//! | `postgres` | PostgreSQL infrastructure exists            | ⭐⭐⭐⭐          |
//! | `mysql`    | MySQL infrastructure exists                 | ⭐⭐⭐⭐          |
//! | `amqp`     | Enterprise messaging, complex routing       | ⭐⭐⭐⭐          |
//! | `sqs`      | AWS cloud, serverless, high availability    | ⭐⭐⭐           |
//!
//! ### Backend Selection
//!
//! | Feature         | Use When                              | Latency |
//! |-----------------|---------------------------------------|---------|
//! | `backend-redis` | With Redis broker (recommended)       | Low     |
//! | `backend-db`    | With PostgreSQL/MySQL broker          | Medium  |
//! | `backend-rpc`   | Distributed systems, microservices    | Medium  |
//!
//! ### Configuration Examples
//!
//! ```rust,ignore
//! use celers::prelude::*;
//!
//! // Example 1: Simple Redis Setup
//! let broker = RedisBroker::new("redis://localhost:6379", "celery")?;
//!
//! // Example 2: PostgreSQL with Connection Pool
//! let broker = PostgresBroker::with_queue(
//!     "postgres://user:pass@localhost/celery",
//!     "celery"
//! ).await?;
//!
//! // Example 3: Environment-based Configuration
//! // Set: CELERS_BROKER_TYPE=redis
//! //      CELERS_BROKER_URL=redis://localhost:6379
//! //      CELERS_BROKER_QUEUE=celery
//! let broker = create_broker_from_env().await?;
//!
//! // Example 4: Worker with Validation
//! let result = validate_worker_config(Some(4), Some(10));
//! if let Err(errors) = result {
//!     for error in errors {
//!         eprintln!("Configuration error: {}", error);
//!     }
//! }
//!
//! // Example 5: Feature Compatibility Check
//! println!("{}", feature_compatibility_matrix());
//! ```
//!
//! ## Testing
//!
//! CeleRS provides development utilities for testing:
//!
//! ```rust
//! #[cfg(test)]
//! mod tests {
//!     use celers::dev_utils::{MockBroker, TaskBuilder};
//!     use celers::prelude::*;
//!
//!     #[tokio::test]
//!     async fn test_task_execution() {
//!         let broker = MockBroker::new();
//!
//!         // Create and enqueue a test task
//!         let task = TaskBuilder::new("my.task")
//!             .max_retries(3)
//!             .build();
//!
//!         let task_id = broker.enqueue(task).await.unwrap();
//!
//!         // Verify task was enqueued
//!         assert_eq!(broker.queue_len(), 1);
//!
//!         // Dequeue and process
//!         let msg = broker.dequeue().await.unwrap().unwrap();
//!         assert_eq!(msg.task.metadata.name, "my.task");
//!     }
//! }
//! ```
//!
//! ## Production Deployment Guide
//!
//! ### Infrastructure Setup
//!
//! #### 1. Broker Selection and Configuration
//!
//! **Redis (Recommended for Most Use Cases)**
//! ```bash
//! # Install Redis
//! sudo apt-get install redis-server
//!
//! # Configure for production
//! # /etc/redis/redis.conf
//! maxmemory 2gb
//! maxmemory-policy allkeys-lru
//! appendonly yes
//! appendfsync everysec
//!
//! # Enable persistence
//! save 900 1
//! save 300 10
//! save 60 10000
//! ```
//!
//! **PostgreSQL (For Database-Centric Deployments)**
//! ```sql
//! -- Create database and tables
//! CREATE DATABASE celers_broker;
//! CREATE TABLE celery_tasks (
//!     id SERIAL PRIMARY KEY,
//!     task_id UUID UNIQUE NOT NULL,
//!     task_name VARCHAR(255) NOT NULL,
//!     payload BYTEA NOT NULL,
//!     created_at TIMESTAMP DEFAULT NOW(),
//!     INDEX idx_created_at (created_at)
//! );
//! ```
//!
//! #### 2. Worker Configuration
//!
//! ```rust,ignore
//! use celers::prelude::*;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     // Initialize logging
//!     env_logger::init();
//!
//!     // Create broker with connection pooling
//!     let broker = RedisBroker::new(
//!         &std::env::var("BROKER_URL")?,
//!         &std::env::var("QUEUE_NAME")?
//!     )?;
//!
//!     // Configure worker for production
//!     let worker = WorkerConfigBuilder::new()
//!         .concurrency(num_cpus::get()) // Use all CPU cores
//!         .prefetch_count(10) // Balance throughput and memory
//!         .max_retries(3)
//!         .retry_delay_seconds(60)
//!         .build(broker)?;
//!
//!     // Start worker with graceful shutdown
//!     worker.start().await?;
//!     Ok(())
//! }
//! ```
//!
//! #### 3. Systemd Service Configuration
//!
//! Create `/etc/systemd/system/celers-worker.service`:
//!
//! ```ini
//! [Unit]
//! Description=CeleRS Worker
//! After=network.target redis.service
//!
//! [Service]
//! Type=simple
//! User=celers
//! WorkingDirectory=/opt/celers
//! Environment="RUST_LOG=info"
//! Environment="BROKER_URL=redis://localhost:6379"
//! Environment="QUEUE_NAME=celery"
//! ExecStart=/opt/celers/bin/worker
//! Restart=always
//! RestartSec=10
//! StandardOutput=journal
//! StandardError=journal
//!
//! [Install]
//! WantedBy=multi-user.target
//! ```
//!
//! Enable and start:
//! ```bash
//! sudo systemctl enable celers-worker
//! sudo systemctl start celers-worker
//! sudo systemctl status celers-worker
//! ```
//!
//! ### Monitoring and Observability
//!
//! #### Metrics Integration
//!
//! ```rust,ignore
//! use celers::prelude::*;
//!
//! // Enable metrics
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     // Start Prometheus metrics server
//!     tokio::spawn(async {
//!         let addr = ([0, 0, 0, 0], 9090).into();
//!         // Serve metrics at /metrics
//!     });
//!
//!     // Your worker code
//!     Ok(())
//! }
//! ```
//!
//! #### Distributed Tracing
//!
//! ```rust,ignore
//! use celers::tracing::*;
//!
//! // Initialize tracing
//! init_tracing("celers-worker")?;
//!
//! // Tasks automatically get traced
//! #[celers::task]
//! async fn my_task(args: Args) -> Result<(), Error> {
//!     // Span is automatically created and propagated
//!     Ok(())
//! }
//! ```
//!
//! ### Performance Tuning
//!
//! #### Worker Concurrency
//!
//! ```rust,ignore
//! // CPU-bound tasks
//! .concurrency(num_cpus::get())
//!
//! // I/O-bound tasks
//! .concurrency(num_cpus::get() * 4)
//!
//! // Mixed workload
//! .concurrency(num_cpus::get() * 2)
//! ```
//!
//! #### Prefetch Configuration
//!
//! ```rust,ignore
//! // Low memory systems
//! .prefetch_count(5)
//!
//! // Standard configuration
//! .prefetch_count(10)
//!
//! // High throughput
//! .prefetch_count(20)
//! ```
//!
//! ### High Availability
//!
//! #### Multiple Workers
//!
//! Deploy multiple worker instances for redundancy:
//!
//! ```bash
//! # Worker 1
//! WORKER_ID=worker-1 cargo run --release
//!
//! # Worker 2
//! WORKER_ID=worker-2 cargo run --release
//!
//! # Worker 3
//! WORKER_ID=worker-3 cargo run --release
//! ```
//!
//! #### Redis Cluster
//!
//! ```rust,ignore
//! // Use Redis cluster for high availability
//! let broker = RedisBroker::with_cluster(&[
//!     "redis://node1:6379",
//!     "redis://node2:6379",
//!     "redis://node3:6379",
//! ], "celery")?;
//! ```
//!
//! ### Security Best Practices
//!
//! #### 1. Secure Connections
//!
//! ```bash
//! # Use TLS for Redis
//! BROKER_URL=rediss://user:password@redis.example.com:6380
//!
//! # Use SSL for PostgreSQL
//! BROKER_URL=postgresql://user:password@db.example.com:5432/celers?sslmode=require
//! ```
//!
//! #### 2. Authentication
//!
//! ```rust,ignore
//! // Use environment variables for credentials
//! let broker_url = std::env::var("BROKER_URL")?;
//! let broker = create_broker("redis", &broker_url, "celery").await?;
//! ```
//!
//! #### 3. Network Isolation
//!
//! - Run workers in private network
//! - Use VPN or SSH tunnels for remote access
//! - Implement firewall rules
//!
//! ### Scaling Strategies
//!
//! #### Horizontal Scaling
//!
//! ```yaml
//! # Kubernetes deployment
//! apiVersion: apps/v1
//! kind: Deployment
//! metadata:
//!   name: celers-worker
//! spec:
//!   replicas: 5  # Scale up/down as needed
//!   selector:
//!     matchLabels:
//!       app: celers-worker
//!   template:
//!     metadata:
//!       labels:
//!         app: celers-worker
//!     spec:
//!       containers:
//!       - name: worker
//!         image: myapp/celers-worker:latest
//!         env:
//!         - name: BROKER_URL
//!           valueFrom:
//!             secretKeyRef:
//!               name: celers-secrets
//!               key: broker-url
//!         resources:
//!           limits:
//!             memory: "1Gi"
//!             cpu: "1000m"
//! ```
//!
//! #### Auto-scaling with Kubernetes HPA
//!
//! ```yaml
//! apiVersion: autoscaling/v2
//! kind: HorizontalPodAutoscaler
//! metadata:
//!   name: celers-worker-hpa
//! spec:
//!   scaleTargetRef:
//!     apiVersion: apps/v1
//!     kind: Deployment
//!     name: celers-worker
//!   minReplicas: 2
//!   maxReplicas: 10
//!   metrics:
//!   - type: Resource
//!     resource:
//!       name: cpu
//!       target:
//!         type: Utilization
//!         averageUtilization: 70
//! ```
//!
//! ### Troubleshooting
//!
//! #### Common Issues
//!
//! **High Memory Usage**
//! - Reduce `prefetch_count`
//! - Implement chunked processing
//! - Use streaming for large datasets
//!
//! **Slow Task Processing**
//! - Increase worker concurrency
//! - Profile task execution
//! - Optimize database queries
//!
//! **Task Failures**
//! - Check logs: `journalctl -u celers-worker`
//! - Increase retry limits
//! - Implement proper error handling
//!
//! **Queue Backlog**
//! - Add more workers
//! - Optimize task execution time
//! - Implement rate limiting
//!
//! ## Migration Guide from Python Celery
//!
//! ### Feature Comparison
//!
//! | Feature | Python Celery | CeleRS | Notes |
//! |---------|--------------|--------|-------|
//! | Task Definition | `@task` decorator | `#[celers::task]` macro | Type-safe in Rust |
//! | Brokers | Redis, RabbitMQ, SQS | Redis, PostgreSQL, MySQL, AMQP, SQS | Same protocol |
//! | Result Backends | Redis, Database, RPC | Redis, Database, gRPC | Binary compatible |
//! | Canvas Primitives | chain, group, chord | Chain, Group, Chord, Map, Starmap | Same semantics |
//! | Periodic Tasks | Celery Beat | CeleRS Beat | Compatible schedules |
//! | Rate Limiting | ✅ | ✅ | Token bucket & sliding window |
//! | Task Routing | ✅ | ✅ | Glob & regex patterns |
//! | Retries | ✅ | ✅ | Exponential backoff |
//! | Monitoring | Flower | Prometheus + Grafana | Standard metrics |
//! | Performance | Baseline | **10x faster** | Native async |
//!
//! ### API Mapping
//!
//! #### Task Definition
//!
//! **Python Celery:**
//! ```python
//! from celery import Celery
//!
//! app = Celery('tasks', broker='redis://localhost:6379')
//!
//! @app.task
//! def add(x, y):
//!     return x + y
//! ```
//!
//! **CeleRS:**
//! ```rust,ignore
//! use celers::prelude::*;
//!
//! #[derive(Serialize, Deserialize)]
//! struct AddArgs { x: i32, y: i32 }
//!
//! #[celers::task]
//! async fn add(args: AddArgs) -> Result<i32, Box<dyn Error>> {
//!     Ok(args.x + args.y)
//! }
//! ```
//!
//! #### Sending Tasks
//!
//! **Python Celery:**
//! ```python
//! # Simple task
//! result = add.delay(4, 4)
//!
//! # With options
//! result = add.apply_async(
//!     args=(4, 4),
//!     countdown=10,
//!     retry=True,
//!     retry_policy={'max_retries': 3}
//! )
//! ```
//!
//! **CeleRS:**
//! ```rust,ignore
//! // Simple task
//! let task = SerializedTask::new("add", serde_json::to_vec(&AddArgs { x: 4, y: 4 })?);
//! broker.enqueue(task).await?;
//!
//! // With options (using Signature)
//! let sig = Signature::new("add".to_string())
//!     .with_args(vec![json!(4), json!(4)])
//!     .with_countdown(10)
//!     .with_max_retries(3);
//! ```
//!
//! #### Canvas Primitives
//!
//! **Python Celery:**
//! ```python
//! from celery import chain, group, chord
//!
//! # Chain
//! workflow = chain(add.s(2, 2), add.s(4), add.s(8))
//! workflow.apply_async()
//!
//! # Group
//! job = group(add.s(i, i) for i in range(10))
//! result = job.apply_async()
//!
//! # Chord
//! callback = tsum.s()
//! header = [add.s(i, i) for i in range(10)]
//! result = chord(header)(callback)
//! ```
//!
//! **CeleRS:**
//! ```rust,ignore
//! use celers::prelude::*;
//!
//! // Chain
//! let workflow = Chain::new()
//!     .add("add", vec![json!(2), json!(2)])
//!     .add("add", vec![json!(4)])
//!     .add("add", vec![json!(8)]);
//! workflow.apply(&broker).await?;
//!
//! // Group
//! let mut group = Group::new();
//! for i in 0..10 {
//!     group = group.add("add", vec![json!(i), json!(i)]);
//! }
//! group.apply(&broker).await?;
//!
//! // Chord
//! let mut header = Group::new();
//! for i in 0..10 {
//!     header = header.add("add", vec![json!(i), json!(i)]);
//! }
//! let callback = Signature::new("tsum".to_string());
//! let chord = Chord::new(header, callback);
//! ```
//!
//! #### Worker Configuration
//!
//! **Python Celery:**
//! ```bash
//! celery -A tasks worker \
//!     --concurrency=4 \
//!     --loglevel=info \
//!     --max-tasks-per-child=1000
//! ```
//!
//! **CeleRS:**
//! ```rust,ignore
//! let worker = WorkerConfigBuilder::new()
//!     .concurrency(4)
//!     .prefetch_count(10)
//!     .build(broker)?;
//!
//! worker.start().await?;
//! ```
//!
//! ### Code Conversion Examples
//!
//! #### Example 1: Simple Task with Retry
//!
//! **Python:**
//! ```python
//! @app.task(bind=True, max_retries=3)
//! def send_email(self, email, subject, body):
//!     try:
//!         mail_client.send(email, subject, body)
//!     except Exception as exc:
//!         raise self.retry(exc=exc, countdown=60)
//! ```
//!
//! **Rust:**
//! ```rust,ignore
//! #[derive(Serialize, Deserialize)]
//! struct EmailArgs {
//!     email: String,
//!     subject: String,
//!     body: String,
//! }
//!
//! #[celers::task]
//! async fn send_email(args: EmailArgs) -> Result<(), Box<dyn Error>> {
//!     mail_client.send(&args.email, &args.subject, &args.body).await?;
//!     Ok(())
//! }
//!
//! // Configure retry in task signature
//! let sig = Signature::new("send_email".to_string())
//!     .with_max_retries(3)
//!     .with_retry_delay(60);
//! ```
//!
//! #### Example 2: Periodic Tasks
//!
//! **Python:**
//! ```python
//! from celery.schedules import crontab
//!
//! app.conf.beat_schedule = {
//!     'cleanup-every-midnight': {
//!         'task': 'tasks.cleanup',
//!         'schedule': crontab(hour=0, minute=0),
//!     },
//! }
//! ```
//!
//! **Rust:**
//! ```rust,ignore
//! use celers::prelude::*;
//!
//! let scheduler = BeatScheduler::new();
//! scheduler.add_task(ScheduledTask {
//!     name: "cleanup".to_string(),
//!     schedule: Schedule::Crontab {
//!         minute: "0".to_string(),
//!         hour: "0".to_string(),
//!         day: "*".to_string(),
//!         month: "*".to_string(),
//!         weekday: "*".to_string(),
//!     },
//! });
//! ```
//!
//! ### Performance Differences
//!
//! #### Throughput Comparison
//!
//! | Metric | Python Celery | CeleRS | Improvement |
//! |--------|--------------|--------|-------------|
//! | Tasks/sec (simple) | ~1,000 | ~10,000 | **10x** |
//! | Tasks/sec (I/O) | ~5,000 | ~50,000 | **10x** |
//! | Memory per worker | ~50 MB | ~5 MB | **10x less** |
//! | Startup time | ~2 sec | ~50 ms | **40x faster** |
//! | Message latency | ~10 ms | ~1 ms | **10x faster** |
//!
//! #### Why CeleRS is Faster
//!
//! 1. **Native Async**: Tokio's async runtime vs Python's asyncio
//! 2. **Zero-copy Serialization**: Direct memory access without Python object overhead
//! 3. **Compiled Code**: No runtime interpretation
//! 4. **Efficient Memory**: Stack allocation and no GC pauses
//! 5. **Type Safety**: Compile-time optimization opportunities
//!
//! ### Migration Checklist
//!
//! ✅ **Phase 1: Setup**
//! - [ ] Install Rust toolchain
//! - [ ] Create new Rust project with CeleRS
//! - [ ] Configure broker connection
//! - [ ] Set up development environment
//!
//! ✅ **Phase 2: Task Migration**
//! - [ ] Identify all Celery tasks
//! - [ ] Define Rust task argument structs
//! - [ ] Convert task logic to async Rust
//! - [ ] Add error handling
//! - [ ] Configure retry policies
//!
//! ✅ **Phase 3: Worker Deployment**
//! - [ ] Build CeleRS worker binary
//! - [ ] Configure worker settings (concurrency, prefetch)
//! - [ ] Set up monitoring (Prometheus)
//! - [ ] Deploy alongside Python workers
//! - [ ] Gradual traffic migration
//!
//! ✅ **Phase 4: Validation**
//! - [ ] Monitor task success rates
//! - [ ] Compare performance metrics
//! - [ ] Verify result backend compatibility
//! - [ ] Test retry behavior
//! - [ ] Validate error handling
//!
//! ✅ **Phase 5: Optimization**
//! - [ ] Tune worker concurrency
//! - [ ] Optimize database queries
//! - [ ] Implement rate limiting
//! - [ ] Set up distributed tracing
//!
//! ### Compatibility Notes
//!
//! **Binary Protocol Compatibility:**
//! - CeleRS uses the same message format as Python Celery
//! - Tasks can be sent from Python and consumed by Rust (and vice versa)
//! - Result backends are fully compatible
//!
//! **Limitations:**
//! - Pickle serialization not supported (use JSON or MessagePack)
//! - Some advanced Python-specific features unavailable
//! - Canvas primitives have same semantics but different API
//!
//! **Best Practices:**
//! - Start with stateless, CPU-bound tasks
//! - Use JSON for serialization (most compatible)
//! - Keep Python workers for Python-specific tasks
//! - Gradually migrate high-throughput tasks to Rust
//!
//! ## Architecture Documentation
//!
//! ### System Design Overview
//!
//! CeleRS follows a layered architecture for modularity and maintainability:
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────┐
//! │                     Application Layer                        │
//! │              (Your Tasks and Workflows)                      │
//! └─────────────────────────────────────────────────────────────┘
//!//! ┌─────────────────────────────────────────────────────────────┐
//! │                    Canvas Layer                              │
//! │        (Chain, Group, Chord, Map, Starmap)                  │
//! │         celers-canvas                                        │
//! └─────────────────────────────────────────────────────────────┘
//!//! ┌─────────────────────────────────────────────────────────────┐
//! │                     Worker Layer                             │
//! │    (Task Execution, Concurrency, Retry Logic)               │
//! │         celers-worker                                        │
//! └─────────────────────────────────────────────────────────────┘
//!//! ┌─────────────────────────────────────────────────────────────┐
//! │                   Messaging Layer                            │
//! │         (Producer, Consumer, Transport)                      │
//! │              celers-kombu                                    │
//! └─────────────────────────────────────────────────────────────┘
//!//! ┌─────────────────────────────────────────────────────────────┐
//! │                   Broker Layer                               │
//! │    (Redis, PostgreSQL, MySQL, AMQP, SQS)                    │
//! │  celers-broker-{redis,postgres,sql,amqp,sqs}                │
//! └─────────────────────────────────────────────────────────────┘
//!//! ┌─────────────────────────────────────────────────────────────┐
//! │                   Protocol Layer                             │
//! │         (Message Format, Serialization)                      │
//! │            celers-protocol                                   │
//! └─────────────────────────────────────────────────────────────┘
//!//! ┌─────────────────────────────────────────────────────────────┐
//! │                     Core Layer                               │
//! │      (Task Metadata, State, Common Types)                   │
//! │              celers-core                                     │
//! └─────────────────────────────────────────────────────────────┘
//! ```
//!
//! ### Component Interactions
//!
//! #### Task Submission Flow
//!
//! ```text
//! Application
//!//!     │ 1. Create task with args
//!//! SerializedTask
//!//!     │ 2. Serialize to protocol format
//!//! Protocol Layer (Message)
//!//!     │ 3. Enqueue to broker
//!//! Broker (Redis/PostgreSQL/etc)
//!//!     │ 4. Store in queue
//!//! Queue
//! ```
//!
//! #### Task Execution Flow
//!
//! ```text
//! Worker
//!//!     │ 1. Dequeue task
//!//! Broker
//!//!     │ 2. Return BrokerMessage
//!//! Worker
//!//!     │ 3. Deserialize & validate
//!//! Task Handler
//!//!     │ 4. Execute async task
//!//! Result
//!//!     │ 5. Store in result backend
//!//! Result Backend (Redis/DB)
//!//!     │ 6. ACK/NACK to broker
//!//! Broker
//! ```
//!
//! #### Workflow Execution (Chord Example)
//!
//! ```text
//! Chord { header: Group, callback: Task }
//!//!     │ 1. Execute Group tasks in parallel
//!//! ┌─────────┬─────────┬─────────┐
//! │ Task 1  │ Task 2  │ Task 3  │
//! └─────────┴─────────┴─────────┘
//!     │         │         │
//!     │ 2. Collect results
//!     ▼         ▼         ▼
//! Result Aggregator
//!//!     │ 3. Trigger callback when all complete
//!//! Callback Task
//! ```
//!
//! ### Data Flow Diagrams
//!
//! #### Message Format (Protocol Layer)
//!
//! ```text
//! Message {
//!     headers: {
//!         id: UUID,
//!         task: String,
//!         origin: String,
//!         ...
//!     },
//!     properties: {
//!         correlation_id: String,
//!         reply_to: String,
//!         content_type: "application/json",
//!         content_encoding: "utf-8",
//!     },
//!     body: Vec<u8>  // Serialized task args
//! }
//! ```
//!
//! #### Worker Pool Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────┐
//! │              Worker Manager                  │
//! │  ┌──────────────────────────────────────┐  │
//! │  │      Prefetch Queue (Bounded)         │  │
//! │  │    [Task] [Task] [Task] ...          │  │
//! │  └──────────────────────────────────────┘  │
//! │              │         │         │          │
//! │              ▼         ▼         ▼          │
//! │  ┌─────────┬─────────┬─────────┬─────────┐ │
//! │  │Worker 1 │Worker 2 │Worker 3 │Worker 4 │ │
//! │  │(Tokio  │(Tokio  │(Tokio  │(Tokio  │ │
//! │  │ Task)   │ Task)   │ Task)   │ Task)   │ │
//! │  └─────────┴─────────┴─────────┴─────────┘ │
//! └─────────────────────────────────────────────┘
//! ```
//!
//! ### Scalability Patterns
//!
//! #### Horizontal Scaling
//!
//! ```text
//! Load Balancer
//!//!     ├─────────────┬─────────────┬─────────────┐
//!     ▼             ▼             ▼             ▼
//! Worker 1      Worker 2      Worker 3      Worker 4
//!     │             │             │             │
//!     └─────────────┴─────────────┴─────────────┘
//!//!//!              Shared Broker Queue
//! ```
//!
//! #### Vertical Scaling
//!
//! - Increase worker concurrency (more Tokio tasks per worker)
//! - Increase prefetch count (more tasks buffered)
//! - Optimize task execution (reduce CPU/memory usage)
//!
//! #### Queue-Based Load Balancing
//!
//! ```text
//! ┌──────────────────────────────────────┐
//! │         Task Router                   │
//! │  (Based on task name or priority)    │
//! └──────────────────────────────────────┘
//!     │         │         │         │
//!     ▼         ▼         ▼         ▼
//! [Queue 1] [Queue 2] [Queue 3] [Queue 4]
//!     │         │         │         │
//!     ▼         ▼         ▼         ▼
//! Worker    Worker    Worker    Worker
//!  Pool      Pool      Pool      Pool
//! ```

// Re-export core types
pub use celers_core::{
    ActiveTaskInfo, AsyncResult, Broker, BrokerStats, CompositeEventEmitter, ControlCommand,
    ControlResponse, DeliveryInfo, Event, EventEmitter, GlobPattern, InMemoryEventEmitter,
    InspectCommand, InspectResponse, LogLevel, LoggingEventEmitter, NoOpEventEmitter,
    PatternMatcher, PoolStats, QueueStats, RateLimitConfig, RateLimiter, RegexPattern, RequestInfo,
    ReservedTaskInfo, ResultStore, RouteResult, RouteRule, Router, RouterBuilder, RoutingConfig,
    ScheduledTaskInfo, SerializedTask, SlidingWindow, TaskEvent, TaskEventBuilder, TaskRateLimiter,
    TaskResultValue, TaskState, TokenBucket, WorkerConf, WorkerEvent, WorkerEventBuilder,
    WorkerRateLimiter, WorkerReport, WorkerStats,
};

// Re-export protocol types
pub use celers_protocol::{
    ContentEncoding, ContentType, Message, MessageHeaders, MessageProperties, ProtocolVersion,
    TaskArgs,
};

// Re-export kombu types
pub use celers_kombu::{
    utils, BrokerError, Consumer, Envelope, Producer, QueueConfig, QueueMode, Result, Transport,
};

// Re-export worker types
pub use celers_worker::{Worker, WorkerConfig};

// Re-export canvas types
pub use celers_canvas::{
    Chain, Chord, Chunks, Group, Map, Signature, Starmap, TaskOptions, XMap, XStarmap,
};

// Re-export macros
pub use celers_macros::{task, Task};

// Optional broker re-exports
#[cfg(feature = "redis")]
pub use celers_broker_redis::{
    circuit_breaker, dedup, health, monitoring as redis_monitoring, utilities as redis_utilities,
    RedisBroker,
};

#[cfg(feature = "postgres")]
pub use celers_broker_postgres::{
    monitoring as postgres_monitoring, utilities as postgres_utilities, PostgresBroker,
};

#[cfg(feature = "mysql")]
pub use celers_broker_sql::{
    monitoring as mysql_monitoring, utilities as mysql_utilities, MysqlBroker,
};

#[cfg(feature = "amqp")]
pub use celers_broker_amqp::{
    monitoring as amqp_monitoring, utilities as amqp_utilities, AmqpBroker,
};

#[cfg(feature = "sqs")]
pub use celers_broker_sqs::{
    monitoring as sqs_monitoring, optimization, utilities as sqs_utilities, SqsBroker,
};

// Optional backend re-exports
#[cfg(feature = "backend-redis")]
pub use celers_backend_redis::{
    batch_size,
    event_transport::{RedisEventConfig, RedisEventEmitter, RedisEventReceiver},
    ttl, ChordState, RedisResultBackend, ResultBackend, TaskMeta, TaskResult,
};

#[cfg(feature = "backend-db")]
pub use celers_backend_db::{MysqlResultBackend, PostgresResultBackend};

#[cfg(feature = "backend-rpc")]
pub use celers_backend_rpc::GrpcResultBackend;

// Optional beat re-exports
#[cfg(feature = "beat")]
pub use celers_beat::{BeatScheduler, Schedule, ScheduledTask};

// Optional metrics re-exports
#[cfg(feature = "metrics")]
pub use celers_metrics::{gather_metrics, reset_metrics};

/// Prelude module for common imports
pub mod prelude {
    // Core types
    pub use crate::AsyncResult;
    pub use crate::Broker;
    pub use crate::CompositeEventEmitter;
    pub use crate::ControlCommand;
    pub use crate::ControlResponse;
    pub use crate::Event;
    pub use crate::EventEmitter;
    pub use crate::InMemoryEventEmitter;
    pub use crate::InspectCommand;
    pub use crate::InspectResponse;
    pub use crate::LogLevel;
    pub use crate::LoggingEventEmitter;
    pub use crate::NoOpEventEmitter;
    pub use crate::ResultStore;
    pub use crate::SerializedTask;
    pub use crate::TaskEvent;
    pub use crate::TaskEventBuilder;
    pub use crate::TaskResultValue;
    pub use crate::TaskState;
    pub use crate::WorkerEvent;
    pub use crate::WorkerEventBuilder;
    pub use crate::WorkerStats;

    // Rate limiting types
    pub use crate::RateLimitConfig;
    pub use crate::RateLimiter;
    pub use crate::SlidingWindow;
    pub use crate::TaskRateLimiter;
    pub use crate::TokenBucket;
    pub use crate::WorkerRateLimiter;

    // Task routing types
    pub use crate::GlobPattern;
    pub use crate::PatternMatcher;
    pub use crate::RegexPattern;
    pub use crate::RouteResult;
    pub use crate::RouteRule;
    pub use crate::Router;
    pub use crate::RouterBuilder;
    pub use crate::RoutingConfig;

    // Worker types
    pub use crate::Worker;
    pub use crate::WorkerConfig;
    pub use celers_worker::WorkerConfigBuilder;

    // Broker helper functions
    pub use crate::broker_helper::{create_broker, create_broker_from_env, BrokerConfigError};

    // Configuration validation
    pub use crate::config_validation::{
        check_feature_compatibility, feature_compatibility_matrix, validate_broker_url,
        validate_worker_config, ConfigValidator, ValidationError,
    };

    // Broker implementations
    // Note: monitoring and utilities modules are available at crate root level
    // when the corresponding broker feature is enabled, but not re-exported in
    // prelude to avoid naming conflicts when multiple brokers are used.
    #[cfg(feature = "redis")]
    pub use crate::{circuit_breaker, dedup, health, rate_limit, RedisBroker};

    #[cfg(feature = "postgres")]
    pub use crate::PostgresBroker;

    #[cfg(feature = "mysql")]
    pub use crate::MysqlBroker;

    #[cfg(feature = "amqp")]
    pub use crate::AmqpBroker;

    #[cfg(feature = "sqs")]
    pub use crate::{optimization, SqsBroker};

    // Backend implementations
    #[cfg(feature = "backend-redis")]
    pub use crate::{
        batch_size, ttl, ChordState, RedisEventConfig, RedisEventEmitter, RedisEventReceiver,
        RedisResultBackend, ResultBackend, TaskMeta,
    };

    #[cfg(feature = "backend-db")]
    pub use crate::{MysqlResultBackend, PostgresResultBackend};

    #[cfg(feature = "backend-rpc")]
    pub use crate::GrpcResultBackend;

    // Beat scheduler
    #[cfg(feature = "beat")]
    pub use crate::{BeatScheduler, Schedule, ScheduledTask};

    // Metrics
    #[cfg(feature = "metrics")]
    pub use crate::{gather_metrics, reset_metrics};

    // Tracing
    #[cfg(feature = "tracing")]
    pub use crate::tracing::{
        create_tracer_provider, extract_trace_context, init_tracing, inject_trace_context,
        publish_span, task_span,
    };

    // Macros (task attribute and Task derive)
    pub use celers_macros::{task, Task};

    // Canvas primitives
    pub use crate::{
        Chain, Chord, Chunks, Group, Map, Signature, Starmap, TaskOptions, XMap, XStarmap,
    };

    // Error types
    pub use crate::BrokerError;

    // Common external crates
    pub use async_trait::async_trait;
    pub use serde::{Deserialize, Serialize};
    pub use serde_json;
    pub use serde_json::json;
    pub use tokio;
    pub use uuid::Uuid;

    // Development utilities (test/dev-utils feature)
    #[cfg(any(test, feature = "dev-utils"))]
    pub use crate::dev_utils::{
        create_test_task, EventTracker, MockBroker, PerformanceProfiler, QueueInspector,
        TaskBuilder, TaskDebugger,
    };

    // Type aliases for common patterns
    /// Result type for task execution with thread-safe error handling
    pub type TaskResult<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
    /// Async task function signature
    pub type AsyncTaskFn<T> =
        fn(Vec<u8>) -> std::pin::Pin<Box<dyn std::future::Future<Output = TaskResult<T>> + Send>>;

    // Re-export common Result type from kombu
    pub use celers_kombu::Result as KombuResult;

    // Kombu utility functions
    pub use crate::utils;

    // Convenience functions for ergonomic workflow creation
    pub use crate::convenience::{
        batch, best_effort, chain, chain_from, chord, chunks, critical, delay, expire_in, fan_in,
        fan_out, group, group_from, high_priority, low_priority, map, options, parallel, pipeline,
        retry_with_backoff, starmap, task, task_with_options, transient, with_countdown,
        with_expires, with_priority, with_retry, with_timeout,
    };

    // Beat-specific convenience functions
    #[cfg(feature = "beat-cron")]
    pub use crate::convenience::recurring;

    #[cfg(feature = "beat")]
    pub use crate::convenience::recurring_interval;

    // Workflow templates for common patterns
    pub use crate::workflow_templates::{
        batch_processing, etl_pipeline, map_reduce_workflow, priority_workflow, scatter_gather,
        sequential_pipeline,
    };

    // Task composition utilities
    pub use crate::task_composition::{
        circuit_breaker_group, rate_limited_workflow, retry_wrapper, timeout_wrapper,
    };

    // Error recovery patterns
    pub use crate::error_recovery::{
        ignore_errors, with_dlq, with_exponential_backoff, with_fallback,
    };

    // Workflow validation utilities
    pub use crate::workflow_validation::{
        check_performance_concerns_chain, check_performance_concerns_group, validate_chain,
        validate_chord, validate_group, ValidationError as WorkflowValidationError,
    };

    // Result aggregation helpers
    pub use crate::result_helpers::{
        create_result_collector, create_result_filter, create_result_reducer,
        create_result_transformer,
    };

    // Advanced workflow patterns
    pub use crate::advanced_patterns::{
        create_conditional_workflow, create_dynamic_workflow, create_parallel_chains,
        create_saga_workflow,
    };

    // Monitoring and observability helpers
    pub use crate::monitoring_helpers::TaskMonitor;

    // Batch processing helpers
    pub use crate::batch_helpers::{
        create_adaptive_batches, create_dynamic_batches, create_prioritized_batches,
    };

    // Health check utilities
    pub use crate::health_check::{
        DependencyChecker, HealthCheckResult, HealthStatus, WorkerHealthChecker,
    };

    // Resource management utilities
    pub use crate::resource_management::{ResourceLimits, ResourcePool, ResourceTracker};

    // Task lifecycle hooks
    pub use crate::task_hooks::{
        HookRegistry, HookResult, LoggingHook, PostExecutionHook, PreExecutionHook, ValidationHook,
    };

    // Metrics aggregation utilities
    pub use crate::metrics_aggregation::{DataPoint, Histogram, MetricsAggregator};

    // Task cancellation utilities
    pub use crate::task_cancellation::{CancellationToken, ExecutionGuard, TimeoutManager};

    // Advanced retry strategies
    pub use crate::retry_strategies::{
        DefaultRetryPolicy, ErrorPatternRetryPolicy, RetryPolicy, RetryStrategy,
    };

    // Task dependency management
    pub use crate::task_dependencies::DependencyGraph;

    // Performance profiling utilities
    // Note: PerformanceProfiler conflicts with dev_utils::PerformanceProfiler
    // Access via crate::performance_profiling::PerformanceProfiler
    pub use crate::performance_profiling::{PerformanceProfile, ProfileSpan};
}

/// Convenience functions module
pub mod convenience {
    /// Create a task signature with fluent API
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::task;
    ///
    /// let sig = task("my_task")
    ///     .with_args(vec![json!(1), json!(2)])
    ///     .with_priority(5)
    ///     .with_max_retries(3);
    /// ```
    pub fn task(name: impl Into<String>) -> crate::Signature {
        crate::Signature::new(name.into())
    }

    /// Create a chain workflow
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::chain;
    ///
    /// let workflow = chain()
    ///     .add("task1", vec![json!(1)])
    ///     .add("task2", vec![json!(2)]);
    /// ```
    pub fn chain() -> crate::Chain {
        crate::Chain::new()
    }

    /// Create a group workflow
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::group;
    ///
    /// let workflow = group()
    ///     .add("task1", vec![json!(1)])
    ///     .add("task2", vec![json!(2)]);
    /// ```
    pub fn group() -> crate::Group {
        crate::Group::new()
    }

    /// Create a chord workflow with header and callback
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::{group, task, chord};
    ///
    /// let header = group()
    ///     .add("task1", vec![json!(1)])
    ///     .add("task2", vec![json!(2)]);
    ///
    /// let callback = task("aggregate_results");
    ///
    /// let workflow = chord(header, callback);
    /// ```
    pub fn chord(header: crate::Group, callback: crate::Signature) -> crate::Chord {
        crate::Chord::new(header, callback)
    }

    /// Create a chunks workflow for processing items in batches
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::chunks;
    /// use serde_json::json;
    ///
    /// // Process items in chunks of 10
    /// let items = vec![json!(1), json!(2), json!(3)];
    /// let workflow = chunks("process_item", items, 10);
    /// ```
    pub fn chunks<T: serde::Serialize>(
        task_name: impl Into<String>,
        items: Vec<T>,
        chunk_size: usize,
    ) -> crate::Chunks {
        let sig = crate::Signature::new(task_name.into());
        let serialized_items: Vec<serde_json::Value> = items
            .into_iter()
            .filter_map(|item| serde_json::to_value(item).ok())
            .collect();
        crate::Chunks::new(sig, serialized_items, chunk_size)
    }

    /// Create a map workflow for applying a task to each item
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::map;
    /// use serde_json::json;
    ///
    /// let items = vec![json!(1), json!(2), json!(3)];
    /// let workflow = map("square", items);
    /// ```
    pub fn map<T: serde::Serialize>(task_name: impl Into<String>, items: Vec<T>) -> crate::Map {
        let sig = crate::Signature::new(task_name.into());
        let serialized_items: Vec<Vec<serde_json::Value>> = items
            .into_iter()
            .filter_map(|item| serde_json::to_value(item).ok().map(|v| vec![v]))
            .collect();
        crate::Map::new(sig, serialized_items)
    }

    /// Create a starmap workflow for applying a task with multiple arguments
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::starmap;
    /// use serde_json::json;
    ///
    /// let args = vec![
    ///     vec![json!(1), json!(2)],
    ///     vec![json!(3), json!(4)],
    /// ];
    /// let workflow = starmap("add", args);
    /// ```
    pub fn starmap<T: serde::Serialize>(
        task_name: impl Into<String>,
        args: Vec<Vec<T>>,
    ) -> crate::Starmap {
        let sig = crate::Signature::new(task_name.into());
        let serialized_args: Vec<Vec<serde_json::Value>> = args
            .into_iter()
            .map(|arg_list| {
                arg_list
                    .into_iter()
                    .filter_map(|item| serde_json::to_value(item).ok())
                    .collect()
            })
            .collect();
        crate::Starmap::new(sig, serialized_args)
    }

    /// Create task options for configuring task execution
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::options;
    ///
    /// let opts = options()
    ///     .max_retries(3)
    ///     .countdown(60)
    ///     .priority(5);
    /// ```
    pub fn options() -> crate::TaskOptions {
        crate::TaskOptions::default()
    }

    /// Create task options with retry configuration
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::with_retry;
    ///
    /// let opts = with_retry(5, 60);  // 5 retries with 60s delay
    /// ```
    pub fn with_retry(max_retries: u32, retry_delay_secs: u64) -> crate::TaskOptions {
        crate::TaskOptions {
            max_retries: Some(max_retries),
            countdown: Some(retry_delay_secs),
            ..Default::default()
        }
    }

    /// Create task options with timeout configuration
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::with_timeout;
    ///
    /// let opts = with_timeout(300);  // 5 minute timeout
    /// ```
    pub fn with_timeout(timeout_secs: u64) -> crate::TaskOptions {
        crate::TaskOptions {
            time_limit: Some(timeout_secs),
            ..Default::default()
        }
    }

    /// Create task options with priority
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::with_priority;
    ///
    /// let opts = with_priority(9);  // High priority task
    /// ```
    pub fn with_priority(priority: u8) -> crate::TaskOptions {
        crate::TaskOptions {
            priority: Some(priority),
            ..Default::default()
        }
    }

    /// Create task options with countdown (delay in seconds)
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::with_countdown;
    ///
    /// let opts = with_countdown(60);  // Run after 60 seconds
    /// ```
    pub fn with_countdown(countdown_secs: u64) -> crate::TaskOptions {
        crate::TaskOptions {
            countdown: Some(countdown_secs),
            ..Default::default()
        }
    }

    /// Create task options with expires (expiration time in seconds)
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::with_expires;
    ///
    /// let opts = with_expires(7200);  // Expire after 2 hours
    /// ```
    pub fn with_expires(expires_secs: u64) -> crate::TaskOptions {
        crate::TaskOptions {
            expires: Some(expires_secs),
            ..Default::default()
        }
    }

    /// Create a batch of task signatures from a collection
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::batch;
    /// use serde_json::json;
    ///
    /// let items = vec![
    ///     vec![json!(1), json!(2)],
    ///     vec![json!(3), json!(4)],
    /// ];
    /// let tasks = batch("add", items);
    /// ```
    pub fn batch<T: serde::Serialize>(
        task_name: impl Into<String>,
        args_list: Vec<Vec<T>>,
    ) -> Vec<crate::Signature> {
        let task_name = task_name.into();
        args_list
            .into_iter()
            .map(|args| {
                let sig = crate::Signature::new(task_name.clone());
                let serialized_args: Vec<serde_json::Value> = args
                    .into_iter()
                    .filter_map(|arg| serde_json::to_value(arg).ok())
                    .collect();
                sig.with_args(serialized_args)
            })
            .collect()
    }

    /// Create a chain from a list of task names and their arguments
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::chain_from;
    /// use serde_json::json;
    ///
    /// let tasks = vec![
    ///     ("task1", vec![json!(1), json!(2)]),
    ///     ("task2", vec![json!(3), json!(4)]),
    /// ];
    /// let workflow = chain_from(tasks);
    /// ```
    pub fn chain_from<T: serde::Serialize>(tasks: Vec<(&str, Vec<T>)>) -> crate::Chain {
        let mut chain = crate::Chain::new();
        for (task_name, args) in tasks {
            let serialized_args: Vec<serde_json::Value> = args
                .into_iter()
                .filter_map(|arg| serde_json::to_value(arg).ok())
                .collect();
            chain = chain.then(task_name, serialized_args);
        }
        chain
    }

    /// Create a group from a list of task names and their arguments
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::group_from;
    /// use serde_json::json;
    ///
    /// let tasks = vec![
    ///     ("task1", vec![json!(1)]),
    ///     ("task2", vec![json!(2)]),
    ///     ("task3", vec![json!(3)]),
    /// ];
    /// let workflow = group_from(tasks);
    /// ```
    pub fn group_from<T: serde::Serialize>(tasks: Vec<(&str, Vec<T>)>) -> crate::Group {
        let mut group = crate::Group::new();
        for (task_name, args) in tasks {
            let serialized_args: Vec<serde_json::Value> = args
                .into_iter()
                .filter_map(|arg| serde_json::to_value(arg).ok())
                .collect();
            group = group.add(task_name, serialized_args);
        }
        group
    }

    /// Create a signature with common task options applied
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::task_with_options;
    /// use serde_json::json;
    ///
    /// let sig = task_with_options(
    ///     "my_task",
    ///     vec![json!(1), json!(2)],
    ///     3,  // max_retries
    ///     5   // priority
    /// );
    /// ```
    pub fn task_with_options(
        name: impl Into<String>,
        args: Vec<serde_json::Value>,
        max_retries: u32,
        priority: u8,
    ) -> crate::Signature {
        let mut sig = crate::Signature::new(name.into()).with_args(args);
        sig.options.max_retries = Some(max_retries);
        sig.options.priority = Some(priority);
        sig
    }

    /// Create a recurring task using crontab components (requires beat and beat-cron features)
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::recurring;
    ///
    /// // Run every day at midnight
    /// let schedule = recurring("cleanup_task", "0", "0", "*", "*", "*");
    /// ```
    #[cfg(all(feature = "beat", feature = "beat-cron"))]
    pub fn recurring(
        task_name: impl Into<String>,
        minute: &str,
        hour: &str,
        day_of_week: &str,
        day_of_month: &str,
        month_of_year: &str,
    ) -> crate::ScheduledTask {
        crate::ScheduledTask::new(
            task_name.into(),
            crate::Schedule::crontab(minute, hour, day_of_week, day_of_month, month_of_year),
        )
    }

    /// Create a recurring task with an interval schedule
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::recurring_interval;
    ///
    /// // Execute every 60 seconds
    /// let task = recurring_interval("process_data", 60);
    /// ```
    #[cfg(feature = "beat")]
    pub fn recurring_interval(task_name: impl Into<String>, seconds: u64) -> crate::ScheduledTask {
        crate::ScheduledTask::new(task_name.into(), crate::Schedule::interval(seconds))
    }

    /// Create a delayed task (delayed execution by specified seconds)
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::delay;
    /// use serde_json::json;
    ///
    /// // Execute after 60 seconds
    /// let sig = delay("send_email", vec![json!("user@example.com")], 60);
    /// ```
    pub fn delay(
        task_name: impl Into<String>,
        args: Vec<serde_json::Value>,
        delay_secs: u64,
    ) -> crate::Signature {
        let mut sig = crate::Signature::new(task_name.into()).with_args(args);
        sig.options.countdown = Some(delay_secs);
        sig
    }

    /// Create a task with expiration time
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::expire_in;
    /// use serde_json::json;
    ///
    /// // Expire after 2 hours
    /// let sig = expire_in("process_data", vec![json!({"id": 123})], 7200);
    /// ```
    pub fn expire_in(
        task_name: impl Into<String>,
        args: Vec<serde_json::Value>,
        expires_secs: u64,
    ) -> crate::Signature {
        let mut sig = crate::Signature::new(task_name.into()).with_args(args);
        sig.options.expires = Some(expires_secs);
        sig
    }

    /// Create a high priority task (priority level 9)
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::high_priority;
    /// use serde_json::json;
    ///
    /// let sig = high_priority("urgent_task", vec![json!({"alert": true})]);
    /// ```
    pub fn high_priority(
        task_name: impl Into<String>,
        args: Vec<serde_json::Value>,
    ) -> crate::Signature {
        let mut sig = crate::Signature::new(task_name.into()).with_args(args);
        sig.options.priority = Some(9);
        sig
    }

    /// Create a low priority task (priority level 1)
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::low_priority;
    /// use serde_json::json;
    ///
    /// let sig = low_priority("background_cleanup", vec![json!({})]);
    /// ```
    pub fn low_priority(
        task_name: impl Into<String>,
        args: Vec<serde_json::Value>,
    ) -> crate::Signature {
        let mut sig = crate::Signature::new(task_name.into()).with_args(args);
        sig.options.priority = Some(1);
        sig
    }

    /// Create a parallel workflow (alias for group)
    ///
    /// This is a more intuitive name for the group workflow pattern.
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::parallel;
    ///
    /// let workflow = parallel()
    ///     .add("task1", vec![json!(1)])
    ///     .add("task2", vec![json!(2)])
    ///     .add("task3", vec![json!(3)]);
    /// ```
    pub fn parallel() -> crate::Group {
        crate::Group::new()
    }

    /// Create a critical task (high priority with maximum retries)
    ///
    /// Critical tasks are executed with priority 9 and retry up to 5 times.
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::critical;
    /// use serde_json::json;
    ///
    /// let sig = critical("process_payment", vec![json!({"amount": 100})]);
    /// ```
    pub fn critical(
        task_name: impl Into<String>,
        args: Vec<serde_json::Value>,
    ) -> crate::Signature {
        let mut sig = crate::Signature::new(task_name.into()).with_args(args);
        sig.options.priority = Some(9);
        sig.options.max_retries = Some(5);
        sig
    }

    /// Create a best-effort task (low priority with no retries)
    ///
    /// Best-effort tasks run at low priority and don't retry on failure.
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::best_effort;
    /// use serde_json::json;
    ///
    /// let sig = best_effort("update_cache", vec![json!({"key": "value"})]);
    /// ```
    pub fn best_effort(
        task_name: impl Into<String>,
        args: Vec<serde_json::Value>,
    ) -> crate::Signature {
        let mut sig = crate::Signature::new(task_name.into()).with_args(args);
        sig.options.priority = Some(1);
        sig.options.max_retries = Some(0);
        sig
    }

    /// Create a transient task (with expiration time)
    ///
    /// Transient tasks expire if not executed within the specified TTL.
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::transient;
    /// use serde_json::json;
    ///
    /// // Task expires after 5 minutes
    /// let sig = transient("temp_notification", vec![json!({"msg": "hi"})], 300);
    /// ```
    pub fn transient(
        task_name: impl Into<String>,
        args: Vec<serde_json::Value>,
        ttl_secs: u64,
    ) -> crate::Signature {
        let mut sig = crate::Signature::new(task_name.into()).with_args(args);
        sig.options.expires = Some(ttl_secs);
        sig
    }

    /// Create task options with retry and exponential backoff
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::retry_with_backoff;
    ///
    /// // Retry up to 5 times, starting with 60s delay
    /// let opts = retry_with_backoff(5, 60);
    /// ```
    pub fn retry_with_backoff(max_retries: u32, initial_delay_secs: u64) -> crate::TaskOptions {
        crate::TaskOptions {
            max_retries: Some(max_retries),
            countdown: Some(initial_delay_secs),
            // Note: Exponential backoff is handled by the retry mechanism
            ..Default::default()
        }
    }

    /// Create a pipeline workflow (modern alias for chain)
    ///
    /// Pipeline is a more modern/intuitive name for sequential task execution.
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::pipeline;
    ///
    /// let workflow = pipeline()
    ///     .then("fetch_data", vec![])
    ///     .then("process_data", vec![])
    ///     .then("save_results", vec![]);
    /// ```
    pub fn pipeline() -> crate::Chain {
        crate::Chain::new()
    }

    /// Create a fan-out workflow (parallel execution with map pattern)
    ///
    /// More intuitive name for the map pattern - fan out to process multiple items.
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::fan_out;
    /// use serde_json::json;
    ///
    /// let items = vec![json!(1), json!(2), json!(3)];
    /// let workflow = fan_out("process_item", items);
    /// ```
    pub fn fan_out<T: serde::Serialize>(task_name: impl Into<String>, items: Vec<T>) -> crate::Map {
        map(task_name, items)
    }

    /// Create a fan-in workflow (gather results with chord pattern)
    ///
    /// More intuitive name for chord - fan out tasks then fan in to callback.
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::convenience::{parallel, task, fan_in};
    ///
    /// let tasks = parallel()
    ///     .add("task1", vec![])
    ///     .add("task2", vec![]);
    ///
    /// let callback = task("aggregate_results");
    /// let workflow = fan_in(tasks, callback);
    /// ```
    pub fn fan_in(tasks: crate::Group, callback: crate::Signature) -> crate::Chord {
        crate::Chord::new(tasks, callback)
    }
}

/// Quick start helpers for common use cases
pub mod quick_start {
    /// Quick Redis broker setup with sensible defaults
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::quick_start::redis_broker;
    ///
    /// let broker = redis_broker("localhost:6379", "celery")?;
    /// ```
    #[cfg(feature = "redis")]
    pub fn redis_broker(
        url: &str,
        queue: &str,
    ) -> std::result::Result<crate::RedisBroker, celers_core::error::CelersError> {
        let full_url = if url.starts_with("redis://") {
            url.to_string()
        } else {
            format!("redis://{}", url)
        };
        crate::RedisBroker::new(&full_url, queue)
    }

    /// Quick PostgreSQL broker setup
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::quick_start::postgres_broker;
    ///
    /// let broker = postgres_broker(
    ///     "postgresql://user:pass@localhost/db",
    ///     "celery"
    /// ).await?;
    /// ```
    #[cfg(feature = "postgres")]
    pub async fn postgres_broker(
        url: &str,
        queue: &str,
    ) -> std::result::Result<crate::PostgresBroker, celers_core::error::CelersError> {
        crate::PostgresBroker::with_queue(url, queue).await
    }

    /// Quick MySQL broker setup
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::quick_start::mysql_broker;
    ///
    /// let broker = mysql_broker(
    ///     "mysql://user:pass@localhost/db",
    ///     "celery"
    /// ).await?;
    /// ```
    #[cfg(feature = "mysql")]
    pub async fn mysql_broker(
        url: &str,
        queue: &str,
    ) -> std::result::Result<crate::MysqlBroker, celers_core::error::CelersError> {
        crate::MysqlBroker::with_queue(url, queue).await
    }

    /// Quick AMQP (RabbitMQ) broker setup
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::quick_start::amqp_broker;
    ///
    /// let broker = amqp_broker(
    ///     "amqp://guest:guest@localhost:5672",
    ///     "celery"
    /// ).await?;
    /// ```
    #[cfg(feature = "amqp")]
    pub async fn amqp_broker(
        url: &str,
        queue: &str,
    ) -> std::result::Result<crate::AmqpBroker, celers_core::error::CelersError> {
        crate::AmqpBroker::new(url, queue)
            .await
            .map_err(|e| celers_core::error::CelersError::Broker(e.to_string()))
    }

    /// Quick SQS broker setup
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::quick_start::sqs_broker;
    ///
    /// let broker = sqs_broker("celery").await?;
    /// ```
    #[cfg(feature = "sqs")]
    pub async fn sqs_broker(
        queue: &str,
    ) -> std::result::Result<crate::SqsBroker, celers_core::error::CelersError> {
        crate::SqsBroker::new(queue)
            .await
            .map_err(|e| celers_core::error::CelersError::Broker(e.to_string()))
    }

    /// Build a WorkerConfig with sensible defaults
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::quick_start::{redis_broker, default_worker_config};
    ///
    /// let config = default_worker_config()?;
    /// // Use config to create worker
    /// ```
    pub fn default_worker_config() -> std::result::Result<crate::WorkerConfig, String> {
        use celers_worker::WorkerConfigBuilder;

        WorkerConfigBuilder::new()
            .concurrency(num_cpus::get())
            .build()
    }

    /// Build a WorkerConfig with custom concurrency
    ///
    /// # Example
    /// ```rust,ignore
    /// use celers::quick_start::worker_config_with_concurrency;
    ///
    /// let config = worker_config_with_concurrency(8)?;
    /// ```
    pub fn worker_config_with_concurrency(
        concurrency: usize,
    ) -> std::result::Result<crate::WorkerConfig, String> {
        use celers_worker::WorkerConfigBuilder;

        WorkerConfigBuilder::new().concurrency(concurrency).build()
    }
}

/// Production-ready configuration presets
pub mod presets {
    /// Production worker configuration preset
    ///
    /// Optimized for production workloads with:
    /// - Concurrency matching CPU cores
    /// - Standard polling interval
    /// - Graceful shutdown enabled
    pub fn production_config() -> std::result::Result<crate::WorkerConfig, String> {
        use celers_worker::WorkerConfigBuilder;

        WorkerConfigBuilder::new()
            .concurrency(num_cpus::get())
            .poll_interval_ms(1000)
            .graceful_shutdown(true)
            .build()
    }

    /// High-throughput worker configuration preset
    ///
    /// Optimized for maximum throughput:
    /// - High concurrency (4x CPU cores)
    /// - Fast polling interval
    /// - Suitable for I/O-bound tasks
    pub fn high_throughput_config() -> std::result::Result<crate::WorkerConfig, String> {
        use celers_worker::WorkerConfigBuilder;

        let concurrency = num_cpus::get() * 4;

        WorkerConfigBuilder::new()
            .concurrency(concurrency)
            .poll_interval_ms(100)
            .build()
    }

    /// Low-latency worker configuration preset
    ///
    /// Optimized for low latency:
    /// - Moderate concurrency
    /// - Very fast polling for quick response
    /// - Suitable for real-time tasks
    pub fn low_latency_config() -> std::result::Result<crate::WorkerConfig, String> {
        use celers_worker::WorkerConfigBuilder;

        WorkerConfigBuilder::new()
            .concurrency(num_cpus::get() * 2)
            .poll_interval_ms(50)
            .build()
    }

    /// Memory-constrained worker configuration preset
    ///
    /// Optimized for low memory usage:
    /// - Conservative concurrency
    /// - Slower polling to reduce overhead
    /// - Suitable for resource-limited environments
    pub fn memory_constrained_config() -> std::result::Result<crate::WorkerConfig, String> {
        use celers_worker::WorkerConfigBuilder;

        WorkerConfigBuilder::new()
            .concurrency(num_cpus::get())
            .poll_interval_ms(2000)
            .build()
    }

    /// CPU-bound worker configuration preset
    ///
    /// Optimized for CPU-intensive tasks:
    /// - Concurrency matches CPU cores (no oversubscription)
    /// - Standard polling interval
    /// - Suitable for computation-heavy tasks
    pub fn cpu_bound_config() -> std::result::Result<crate::WorkerConfig, String> {
        use celers_worker::WorkerConfigBuilder;

        WorkerConfigBuilder::new()
            .concurrency(num_cpus::get())
            .poll_interval_ms(500)
            .build()
    }

    /// I/O-bound worker configuration preset
    ///
    /// Optimized for I/O-intensive tasks:
    /// - High concurrency (4x CPU cores) for async I/O
    /// - Fast polling for quick task pickup
    /// - Suitable for network/database operations
    pub fn io_bound_config() -> std::result::Result<crate::WorkerConfig, String> {
        use celers_worker::WorkerConfigBuilder;

        let concurrency = num_cpus::get() * 4;

        WorkerConfigBuilder::new()
            .concurrency(concurrency)
            .poll_interval_ms(200)
            .build()
    }

    /// Balanced worker configuration preset
    ///
    /// Optimized for mixed workloads:
    /// - Moderate concurrency (2x CPU cores)
    /// - Balanced polling interval
    /// - Good default for varied task types
    pub fn balanced_config() -> std::result::Result<crate::WorkerConfig, String> {
        use celers_worker::WorkerConfigBuilder;

        let concurrency = num_cpus::get() * 2;

        WorkerConfigBuilder::new()
            .concurrency(concurrency)
            .poll_interval_ms(500)
            .build()
    }

    /// Development worker configuration preset
    ///
    /// Optimized for development and testing:
    /// - Low concurrency for easier debugging
    /// - Slower polling to reduce noise
    /// - Suitable for local development
    pub fn development_config() -> std::result::Result<crate::WorkerConfig, String> {
        use celers_worker::WorkerConfigBuilder;

        WorkerConfigBuilder::new()
            .concurrency(2)
            .poll_interval_ms(1000)
            .build()
    }
}

/// Error types re-exported from celers-kombu
pub mod error {
    pub use celers_kombu::BrokerError;
}

/// Protocol types for advanced usage
pub mod protocol {
    pub use celers_protocol::*;
}

/// Canvas workflow types
pub mod canvas {
    pub use celers_canvas::*;
}

/// Worker runtime types
pub mod worker {
    pub use celers_worker::*;
}

/// Rate limiting types
pub mod rate_limit {
    pub use celers_core::rate_limit::*;
}

/// Task routing types
pub mod router {
    pub use celers_core::router::*;
}

/// Distributed tracing support with OpenTelemetry
#[cfg(feature = "tracing")]
pub mod tracing {
    pub use opentelemetry;
    pub use opentelemetry_sdk;
    pub use tracing;
    pub use tracing_opentelemetry;
    pub use tracing_subscriber;

    use opentelemetry::trace::SpanKind;
    use opentelemetry::KeyValue;
    use opentelemetry_sdk::trace::{RandomIdGenerator, Sampler, SdkTracerProvider};
    use opentelemetry_sdk::Resource;
    use tracing::Span;
    use tracing_opentelemetry::OpenTelemetrySpanExt;
    use tracing_subscriber::layer::SubscriberExt;
    use tracing_subscriber::util::SubscriberInitExt;

    /// Initialize basic tracing with OpenTelemetry support
    ///
    /// This sets up tracing with console output. For production use,
    /// configure your own exporter (e.g., Jaeger, OTLP) using the
    /// opentelemetry_sdk crate directly.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::tracing::init_tracing;
    ///
    /// init_tracing("my-service").expect("Failed to initialize tracing");
    /// ```
    pub fn init_tracing(_service_name: &str) -> Result<(), Box<dyn std::error::Error>> {
        // Initialize tracing subscriber with basic formatting
        // Note: service_name is accepted for API consistency but not used
        // in the basic setup. For production use with service identification,
        // use create_tracer_provider() to build a custom TracerProvider.
        tracing_subscriber::registry()
            .with(tracing_subscriber::EnvFilter::from_default_env())
            .with(tracing_subscriber::fmt::layer())
            .try_init()
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;

        Ok(())
    }

    /// Create a TracerProvider with the given service name and exporter
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::tracing::create_tracer_provider;
    /// use opentelemetry_sdk::trace::Sampler;
    ///
    /// // Configure your own exporter here
    /// let provider = create_tracer_provider("my-service");
    /// ```
    pub fn create_tracer_provider(service_name: &str) -> SdkTracerProvider {
        let resource = Resource::builder()
            .with_attributes([KeyValue::new("service.name", service_name.to_string())])
            .build();

        SdkTracerProvider::builder()
            .with_sampler(Sampler::AlwaysOn)
            .with_id_generator(RandomIdGenerator::default())
            .with_resource(resource)
            .build()
    }

    /// Create a new span for task execution
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::tracing::task_span;
    ///
    /// let span = task_span("my_task", "task-id-123");
    /// let _guard = span.enter();
    /// // Task execution code here
    /// ```
    pub fn task_span(task_name: &str, task_id: &str) -> Span {
        tracing::info_span!(
            "task.execute",
            task.name = task_name,
            task.id = task_id,
            otel.kind = ?SpanKind::Consumer
        )
    }

    /// Create a new span for task publish
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::tracing::publish_span;
    ///
    /// let span = publish_span("my_task", "task-id-123");
    /// let _guard = span.enter();
    /// // Publish code here
    /// ```
    pub fn publish_span(task_name: &str, task_id: &str) -> Span {
        tracing::info_span!(
            "task.publish",
            task.name = task_name,
            task.id = task_id,
            otel.kind = ?SpanKind::Producer
        )
    }

    /// Extract trace context from message headers
    ///
    /// This allows distributed tracing across task boundaries
    pub fn extract_trace_context(headers: &std::collections::HashMap<String, String>) {
        use opentelemetry::propagation::TextMapPropagator;
        use opentelemetry_sdk::propagation::TraceContextPropagator;

        let propagator = TraceContextPropagator::new();
        let context = propagator.extract(headers);
        let _ = tracing::Span::current().set_parent(context);
    }

    /// Inject trace context into message headers
    ///
    /// This allows distributed tracing across task boundaries
    pub fn inject_trace_context(headers: &mut std::collections::HashMap<String, String>) {
        use opentelemetry::propagation::TextMapPropagator;
        use opentelemetry_sdk::propagation::TraceContextPropagator;

        let propagator = TraceContextPropagator::new();
        let context = tracing::Span::current().context();
        propagator.inject_context(&context, headers);
    }
}

/// Development utilities for testing
#[cfg(any(test, feature = "dev-utils"))]
pub mod dev_utils {
    use crate::{Broker, SerializedTask};
    use async_trait::async_trait;
    use celers_core::broker::BrokerMessage;
    use celers_core::error::CelersError;
    use celers_core::task::TaskId;
    use std::collections::VecDeque;
    use std::sync::{Arc, Mutex};

    type Result<T> = std::result::Result<T, CelersError>;

    /// Mock broker for testing
    ///
    /// This broker stores tasks in memory and provides inspection capabilities
    /// for testing task execution.
    #[derive(Clone)]
    pub struct MockBroker {
        queue: Arc<Mutex<VecDeque<SerializedTask>>>,
        published_tasks: Arc<Mutex<Vec<SerializedTask>>>,
    }

    impl MockBroker {
        /// Create a new mock broker
        pub fn new() -> Self {
            Self {
                queue: Arc::new(Mutex::new(VecDeque::new())),
                published_tasks: Arc::new(Mutex::new(Vec::new())),
            }
        }

        /// Get the number of tasks in the queue
        pub fn queue_len(&self) -> usize {
            self.queue
                .lock()
                .expect("lock should not be poisoned")
                .len()
        }

        /// Get all published tasks
        pub fn published_tasks(&self) -> Vec<SerializedTask> {
            self.published_tasks
                .lock()
                .expect("lock should not be poisoned")
                .clone()
        }

        /// Clear all tasks
        pub fn clear(&self) {
            self.queue
                .lock()
                .expect("lock should not be poisoned")
                .clear();
            self.published_tasks
                .lock()
                .expect("lock should not be poisoned")
                .clear();
        }

        /// Push a task to the front of the queue (for testing)
        pub fn push_task(&self, task: SerializedTask) {
            self.queue
                .lock()
                .expect("lock should not be poisoned")
                .push_back(task);
        }
    }

    impl Default for MockBroker {
        fn default() -> Self {
            Self::new()
        }
    }

    #[async_trait]
    impl Broker for MockBroker {
        async fn enqueue(&self, task: SerializedTask) -> Result<TaskId> {
            let task_id = task.metadata.id;
            self.published_tasks
                .lock()
                .expect("lock should not be poisoned")
                .push(task.clone());
            self.queue
                .lock()
                .expect("lock should not be poisoned")
                .push_back(task);
            Ok(task_id)
        }

        async fn dequeue(&self) -> Result<Option<BrokerMessage>> {
            let task = self
                .queue
                .lock()
                .expect("lock should not be poisoned")
                .pop_front();
            Ok(task.map(BrokerMessage::new))
        }

        async fn ack(&self, _task_id: &TaskId, _receipt_handle: Option<&str>) -> Result<()> {
            Ok(())
        }

        async fn reject(
            &self,
            _task_id: &TaskId,
            _receipt_handle: Option<&str>,
            _requeue: bool,
        ) -> Result<()> {
            Ok(())
        }

        async fn queue_size(&self) -> Result<usize> {
            Ok(self
                .queue
                .lock()
                .expect("lock should not be poisoned")
                .len())
        }

        async fn cancel(&self, task_id: &TaskId) -> Result<bool> {
            let mut queue = self.queue.lock().expect("lock should not be poisoned");
            let original_len = queue.len();
            queue.retain(|t| &t.metadata.id != task_id);
            Ok(queue.len() < original_len)
        }
    }

    /// Task builder for testing
    pub struct TaskBuilder {
        name: String,
        id: Option<String>,
        max_retries: u32,
        payload: Vec<u8>,
    }

    impl TaskBuilder {
        /// Create a new task builder
        pub fn new(task_name: &str) -> Self {
            Self {
                name: task_name.to_string(),
                id: None,
                max_retries: 0,
                payload: Vec::new(),
            }
        }

        /// Set task ID
        pub fn id(mut self, id: String) -> Self {
            self.id = Some(id);
            self
        }

        /// Set max retries
        pub fn max_retries(mut self, max_retries: u32) -> Self {
            self.max_retries = max_retries;
            self
        }

        /// Set payload
        pub fn payload(mut self, payload: Vec<u8>) -> Self {
            self.payload = payload;
            self
        }

        /// Build the task
        pub fn build(self) -> SerializedTask {
            use uuid::Uuid;

            let mut task = SerializedTask::new(self.name, self.payload);
            if let Some(id) = self.id {
                task.metadata.id = Uuid::parse_str(&id).unwrap_or_else(|_| Uuid::new_v4());
            }
            task.metadata.max_retries = self.max_retries;
            task
        }
    }

    /// Helper to create a simple test task
    pub fn create_test_task(name: &str) -> SerializedTask {
        TaskBuilder::new(name).build()
    }

    /// Task debugger for inspecting task state and execution
    pub struct TaskDebugger {
        task_history: Arc<Mutex<Vec<TaskDebugInfo>>>,
    }

    /// Debug information for a task
    #[derive(Debug, Clone)]
    pub struct TaskDebugInfo {
        /// Unique identifier for the task
        pub task_id: String,
        /// Name of the task
        pub task_name: String,
        /// Current state of the task
        pub state: String,
        /// Timestamp when this debug info was captured
        pub timestamp: std::time::SystemTime,
        /// Additional metadata about the task
        pub metadata: std::collections::HashMap<String, String>,
    }

    impl TaskDebugger {
        /// Create a new task debugger
        pub fn new() -> Self {
            Self {
                task_history: Arc::new(Mutex::new(Vec::new())),
            }
        }

        /// Record task execution
        pub fn record_task(&self, task: &SerializedTask, state: &str) {
            let mut history = self
                .task_history
                .lock()
                .expect("lock should not be poisoned");
            history.push(TaskDebugInfo {
                task_id: task.metadata.id.to_string(),
                task_name: task.metadata.name.clone(),
                state: state.to_string(),
                timestamp: std::time::SystemTime::now(),
                metadata: std::collections::HashMap::new(),
            });
        }

        /// Get task history
        pub fn history(&self) -> Vec<TaskDebugInfo> {
            self.task_history
                .lock()
                .expect("lock should not be poisoned")
                .clone()
        }

        /// Clear history
        pub fn clear(&self) {
            self.task_history
                .lock()
                .expect("lock should not be poisoned")
                .clear();
        }

        /// Get tasks by state
        pub fn tasks_by_state(&self, state: &str) -> Vec<TaskDebugInfo> {
            self.task_history
                .lock()
                .unwrap()
                .iter()
                .filter(|info| info.state == state)
                .cloned()
                .collect()
        }

        /// Print task history in a formatted table
        pub fn print_history(&self) {
            let history = self.history();
            println!("\n╔══════════════════════════════════════════════════════════════════════════════╗");
            println!(
                "║                            Task Execution History                             ║"
            );
            println!("╚══════════════════════════════════════════════════════════════════════════════╝\n");

            for (idx, info) in history.iter().enumerate() {
                println!("Task #{}", idx + 1);
                println!("  ID:        {}", info.task_id);
                println!("  Name:      {}", info.task_name);
                println!("  State:     {}", info.state);
                println!("  Timestamp: {:?}", info.timestamp);
                if !info.metadata.is_empty() {
                    println!("  Metadata:");
                    for (key, value) in &info.metadata {
                        println!("    {}: {}", key, value);
                    }
                }
                println!();
            }
        }
    }

    impl Default for TaskDebugger {
        fn default() -> Self {
            Self::new()
        }
    }

    /// Event tracker for debugging task events
    pub struct EventTracker {
        events: Arc<Mutex<Vec<TrackedEvent>>>,
    }

    /// Tracked event information
    #[derive(Debug, Clone)]
    pub struct TrackedEvent {
        /// Type of the event (e.g., "task_received", "task_started", "task_completed")
        pub event_type: String,
        /// Optional task ID associated with this event
        pub task_id: Option<String>,
        /// Human-readable message describing the event
        pub message: String,
        /// Timestamp when this event occurred
        pub timestamp: std::time::SystemTime,
    }

    impl EventTracker {
        /// Create a new event tracker
        pub fn new() -> Self {
            Self {
                events: Arc::new(Mutex::new(Vec::new())),
            }
        }

        /// Track an event
        pub fn track(&self, event_type: &str, task_id: Option<String>, message: String) {
            let mut events = self.events.lock().expect("lock should not be poisoned");
            events.push(TrackedEvent {
                event_type: event_type.to_string(),
                task_id,
                message,
                timestamp: std::time::SystemTime::now(),
            });
        }

        /// Get all events
        pub fn events(&self) -> Vec<TrackedEvent> {
            self.events
                .lock()
                .expect("lock should not be poisoned")
                .clone()
        }

        /// Get events by type
        pub fn events_by_type(&self, event_type: &str) -> Vec<TrackedEvent> {
            self.events
                .lock()
                .unwrap()
                .iter()
                .filter(|e| e.event_type == event_type)
                .cloned()
                .collect()
        }

        /// Clear events
        pub fn clear(&self) {
            self.events
                .lock()
                .expect("lock should not be poisoned")
                .clear();
        }

        /// Print events in a formatted table
        pub fn print_events(&self) {
            let events = self.events();
            println!("\n╔══════════════════════════════════════════════════════════════════════════════╗");
            println!(
                "║                              Event Log                                        ║"
            );
            println!("╚══════════════════════════════════════════════════════════════════════════════╝\n");

            for (idx, event) in events.iter().enumerate() {
                println!("Event #{}", idx + 1);
                println!("  Type:      {}", event.event_type);
                if let Some(ref task_id) = event.task_id {
                    println!("  Task ID:   {}", task_id);
                }
                println!("  Message:   {}", event.message);
                println!("  Timestamp: {:?}", event.timestamp);
                println!();
            }
        }
    }

    impl Default for EventTracker {
        fn default() -> Self {
            Self::new()
        }
    }

    /// Performance profiler for debugging task execution time
    pub struct PerformanceProfiler {
        measurements: Arc<Mutex<Vec<PerformanceMeasurement>>>,
    }

    /// Performance measurement data
    #[derive(Debug, Clone)]
    pub struct PerformanceMeasurement {
        /// Name of the operation being measured
        pub name: String,
        /// Duration of the operation in milliseconds
        pub duration_ms: u128,
        /// Timestamp when this measurement was taken
        pub timestamp: std::time::SystemTime,
        /// Additional metadata about the measurement
        pub metadata: std::collections::HashMap<String, String>,
    }

    impl PerformanceProfiler {
        /// Create a new performance profiler
        pub fn new() -> Self {
            Self {
                measurements: Arc::new(Mutex::new(Vec::new())),
            }
        }

        /// Start a measurement
        pub fn start_measurement(&self, name: &str) -> MeasurementGuard {
            MeasurementGuard {
                name: name.to_string(),
                start: std::time::Instant::now(),
                profiler: self.clone(),
            }
        }

        /// Record a measurement
        fn record(&self, name: String, duration_ms: u128) {
            let mut measurements = self
                .measurements
                .lock()
                .expect("lock should not be poisoned");
            measurements.push(PerformanceMeasurement {
                name,
                duration_ms,
                timestamp: std::time::SystemTime::now(),
                metadata: std::collections::HashMap::new(),
            });
        }

        /// Get all measurements
        pub fn measurements(&self) -> Vec<PerformanceMeasurement> {
            self.measurements
                .lock()
                .expect("lock should not be poisoned")
                .clone()
        }

        /// Clear measurements
        pub fn clear(&self) {
            self.measurements
                .lock()
                .expect("lock should not be poisoned")
                .clear();
        }

        /// Get average duration for a measurement name
        pub fn average_duration(&self, name: &str) -> Option<u128> {
            let measurements = self
                .measurements
                .lock()
                .expect("lock should not be poisoned");
            let matching: Vec<_> = measurements
                .iter()
                .filter(|m| m.name == name)
                .map(|m| m.duration_ms)
                .collect();

            if matching.is_empty() {
                None
            } else {
                Some(matching.iter().sum::<u128>() / matching.len() as u128)
            }
        }

        /// Print performance summary
        pub fn print_summary(&self) {
            let measurements = self.measurements();
            println!("\n╔══════════════════════════════════════════════════════════════════════════════╗");
            println!(
                "║                          Performance Summary                                  ║"
            );
            println!("╚══════════════════════════════════════════════════════════════════════════════╝\n");

            // Group by name
            let mut grouped: std::collections::HashMap<String, Vec<u128>> =
                std::collections::HashMap::new();

            for m in measurements {
                grouped.entry(m.name).or_default().push(m.duration_ms);
            }

            for (name, durations) in grouped {
                let count = durations.len();
                let total: u128 = durations.iter().sum();
                let avg = total / count as u128;
                let min = *durations
                    .iter()
                    .min()
                    .expect("collection validated to be non-empty");
                let max = *durations
                    .iter()
                    .max()
                    .expect("collection validated to be non-empty");

                println!("{}", name);
                println!("  Count: {}", count);
                println!("  Avg:   {} ms", avg);
                println!("  Min:   {} ms", min);
                println!("  Max:   {} ms", max);
                println!("  Total: {} ms", total);
                println!();
            }
        }
    }

    impl Clone for PerformanceProfiler {
        fn clone(&self) -> Self {
            Self {
                measurements: Arc::clone(&self.measurements),
            }
        }
    }

    impl Default for PerformanceProfiler {
        fn default() -> Self {
            Self::new()
        }
    }

    /// RAII guard for performance measurements
    pub struct MeasurementGuard {
        name: String,
        start: std::time::Instant,
        profiler: PerformanceProfiler,
    }

    impl Drop for MeasurementGuard {
        fn drop(&mut self) {
            let duration_ms = self.start.elapsed().as_millis();
            self.profiler.record(self.name.clone(), duration_ms);
        }
    }

    /// Queue inspector for debugging broker queues
    pub struct QueueInspector {
        snapshots: Arc<Mutex<Vec<QueueSnapshot>>>,
    }

    /// Snapshot of queue state
    #[derive(Debug, Clone)]
    pub struct QueueSnapshot {
        /// Number of tasks in the queue at the time of snapshot
        pub queue_size: usize,
        /// Timestamp when this snapshot was taken
        pub timestamp: std::time::SystemTime,
        /// Additional metadata about the queue state
        pub metadata: std::collections::HashMap<String, String>,
    }

    impl QueueInspector {
        /// Create a new queue inspector
        pub fn new() -> Self {
            Self {
                snapshots: Arc::new(Mutex::new(Vec::new())),
            }
        }

        /// Take a snapshot of the queue
        pub async fn snapshot(&self, broker: &MockBroker) {
            let size = broker.queue_len();
            let mut snapshots = self.snapshots.lock().expect("lock should not be poisoned");
            snapshots.push(QueueSnapshot {
                queue_size: size,
                timestamp: std::time::SystemTime::now(),
                metadata: std::collections::HashMap::new(),
            });
        }

        /// Get all snapshots
        pub fn snapshots(&self) -> Vec<QueueSnapshot> {
            self.snapshots
                .lock()
                .expect("lock should not be poisoned")
                .clone()
        }

        /// Clear snapshots
        pub fn clear(&self) {
            self.snapshots
                .lock()
                .expect("lock should not be poisoned")
                .clear();
        }

        /// Print queue history
        pub fn print_history(&self) {
            let snapshots = self.snapshots();
            println!("\n╔══════════════════════════════════════════════════════════════════════════════╗");
            println!(
                "║                            Queue Size History                                 ║"
            );
            println!("╚══════════════════════════════════════════════════════════════════════════════╝\n");

            for (idx, snapshot) in snapshots.iter().enumerate() {
                println!("Snapshot #{}", idx + 1);
                println!("  Queue Size: {}", snapshot.queue_size);
                println!("  Timestamp:  {:?}", snapshot.timestamp);
                println!();
            }
        }
    }

    impl Default for QueueInspector {
        fn default() -> Self {
            Self::new()
        }
    }
}

/// Configuration validation helpers
pub mod config_validation {
    /// Validation error
    #[derive(Debug, thiserror::Error)]
    pub enum ValidationError {
        /// Invalid configuration error
        #[error("Invalid configuration: {0}")]
        InvalidConfig(String),

        /// Missing required field error
        #[error("Missing required field: {0}")]
        MissingField(String),

        /// Invalid value for a specific field
        #[error("Invalid value for {field}: {message}")]
        InvalidValue {
            /// The field name that has an invalid value
            field: String,
            /// Error message describing why the value is invalid
            message: String,
        },

        /// Incompatible configuration detected
        #[error("Incompatible configuration: {0}")]
        IncompatibleConfig(String),
    }

    /// Configuration validator
    pub struct ConfigValidator {
        errors: Vec<ValidationError>,
        warnings: Vec<String>,
    }

    impl ConfigValidator {
        /// Create a new validator
        pub fn new() -> Self {
            Self {
                errors: Vec::new(),
                warnings: Vec::new(),
            }
        }

        /// Check if a required field is present
        pub fn require_field(&mut self, field_name: &str, value: Option<&str>) {
            if value.is_none() || value == Some("") {
                self.errors
                    .push(ValidationError::MissingField(field_name.to_string()));
            }
        }

        /// Add a validation error
        pub fn add_error(&mut self, error: ValidationError) {
            self.errors.push(error);
        }

        /// Add a warning
        pub fn add_warning(&mut self, message: String) {
            self.warnings.push(message);
        }

        /// Check if validation passed
        pub fn is_valid(&self) -> bool {
            self.errors.is_empty()
        }

        /// Get all errors
        pub fn errors(&self) -> &[ValidationError] {
            &self.errors
        }

        /// Get all warnings
        pub fn warnings(&self) -> &[String] {
            &self.warnings
        }

        /// Validate and return result
        pub fn validate(self) -> Result<Vec<String>, Vec<ValidationError>> {
            if self.errors.is_empty() {
                Ok(self.warnings)
            } else {
                Err(self.errors)
            }
        }
    }

    impl Default for ConfigValidator {
        fn default() -> Self {
            Self::new()
        }
    }

    /// Validate worker configuration
    pub fn validate_worker_config(
        concurrency: Option<usize>,
        prefetch_count: Option<usize>,
    ) -> Result<Vec<String>, Vec<ValidationError>> {
        let mut validator = ConfigValidator::new();

        if let Some(c) = concurrency {
            if c == 0 {
                validator.add_error(ValidationError::InvalidValue {
                    field: "concurrency".to_string(),
                    message: "must be greater than 0".to_string(),
                });
            }
            if c > 1000 {
                validator.add_warning(format!(
                    "High concurrency value ({}). Consider if this is intentional.",
                    c
                ));
            }
        }

        if let Some(p) = prefetch_count {
            if p == 0 {
                validator.add_error(ValidationError::InvalidValue {
                    field: "prefetch_count".to_string(),
                    message: "must be greater than 0".to_string(),
                });
            }
            if p > 1000 {
                validator.add_warning(format!(
                    "High prefetch_count value ({}). This may consume significant memory.",
                    p
                ));
            }
        }

        validator.validate()
    }

    /// Validate broker URL format
    pub fn validate_broker_url(url: &str) -> Result<String, ValidationError> {
        if url.is_empty() {
            return Err(ValidationError::InvalidValue {
                field: "broker_url".to_string(),
                message: "cannot be empty".to_string(),
            });
        }

        // Basic URL format validation
        if !url.contains("://") {
            return Err(ValidationError::InvalidValue {
                field: "broker_url".to_string(),
                message: "invalid URL format (missing scheme)".to_string(),
            });
        }

        // Extract scheme
        let scheme = url.split("://").next().unwrap_or("");

        // Validate known schemes
        match scheme {
            "redis" | "rediss" | "postgres" | "postgresql" | "mysql" | "amqp" | "amqps" | "sqs" => {
                Ok(format!("Valid {} URL", scheme))
            }
            _ => Err(ValidationError::InvalidValue {
                field: "broker_url".to_string(),
                message: format!("unsupported scheme: {}", scheme),
            }),
        }
    }

    /// Check feature compatibility
    pub fn check_feature_compatibility(features: &[&str]) -> Result<Vec<String>, ValidationError> {
        let mut warnings = Vec::new();

        // Check for multiple broker features enabled
        let broker_features: Vec<_> = features
            .iter()
            .filter(|f| ["redis", "postgres", "mysql", "amqp", "sqs"].contains(f))
            .collect();

        if broker_features.len() > 1 {
            warnings.push(format!(
                "Multiple broker features enabled: {:?}. Ensure you're using the correct broker.",
                broker_features
            ));
        }

        // Check for multiple backend features enabled
        let backend_features: Vec<_> = features
            .iter()
            .filter(|f| ["backend-redis", "backend-db", "backend-rpc"].contains(f))
            .collect();

        if backend_features.len() > 1 {
            warnings.push(format!(
                "Multiple backend features enabled: {:?}. Ensure you're using the correct backend.",
                backend_features
            ));
        }

        Ok(warnings)
    }

    /// Get feature compatibility matrix documentation
    ///
    /// Returns a formatted string documenting which features are compatible
    /// and which combinations are recommended.
    ///
    /// # Example
    ///
    /// ```rust
    /// use celers::config_validation::feature_compatibility_matrix;
    ///
    /// println!("{}", feature_compatibility_matrix());
    /// ```
    pub fn feature_compatibility_matrix() -> String {
        r#"
╔══════════════════════════════════════════════════════════════════════════════╗
║                      CeleRS Feature Compatibility Matrix                      ║
╚══════════════════════════════════════════════════════════════════════════════╝

BROKER FEATURES (Choose ONE):
  ✓ redis      - Redis broker (recommended for most use cases)
  ✓ postgres   - PostgreSQL broker (good for existing PostgreSQL infrastructure)
  ✓ mysql      - MySQL broker (good for existing MySQL infrastructure)
  ✓ amqp       - RabbitMQ/AMQP broker (enterprise messaging)
  ✓ sqs        - AWS SQS broker (cloud-native, serverless)

BACKEND FEATURES (Choose ONE):
  ✓ backend-redis  - Redis result backend (recommended with redis broker)
  ✓ backend-db     - PostgreSQL/MySQL backend (use with postgres/mysql broker)
  ✓ backend-rpc    - gRPC result backend (distributed systems)

SERIALIZATION FEATURES (Can combine):
  ✓ json           - JSON serialization (default, always available)
  ✓ msgpack        - MessagePack serialization (compact binary format)

OBSERVABILITY FEATURES (Can combine):
  ✓ metrics        - Prometheus metrics
  ✓ tracing        - OpenTelemetry distributed tracing

OTHER FEATURES (Can combine):
  ✓ beat           - Periodic task scheduler
  ✓ dev-utils      - Development and testing utilities

RECOMMENDED COMBINATIONS:
  1. Simple Setup:
     features = ["redis", "backend-redis", "json"]

  2. Production Ready:
     features = ["redis", "backend-redis", "json", "metrics", "tracing"]

  3. PostgreSQL Stack:
     features = ["postgres", "backend-db", "json", "metrics"]

  4. AWS Cloud:
     features = ["sqs", "backend-rpc", "json", "msgpack", "metrics"]

  5. Full Featured:
     features = ["full"]  # Enables all features

NOTES:
  - Multiple brokers can be compiled but only one should be used at runtime
  - Multiple backends can be compiled but only one should be used at runtime
  - json + msgpack enables both serialization formats
  - metrics + tracing provides comprehensive observability
"#
        .to_string()
    }
}

pub mod compile_time_validation {
    //! Compile-time feature validation and conflict detection
    //!
    //! Compile-time feature validation to detect conflicts and ensure correct feature usage.
    //!
    //! This module uses Rust's const evaluation to perform compile-time checks for:
    //! - Feature conflicts (e.g., using incompatible brokers together)
    //! - Missing required features
    //! - Dead code elimination opportunities
    //!
    //! # Example
    //!
    //! ```rust
    //! use celers::compile_time_validation::*;
    //!
    //! // This will pass compilation checks
    //! const VALID_CONFIG: () = validate_feature_config();
    //! ```

    /// Validates that at least one broker feature is enabled
    #[inline]
    pub const fn has_broker_feature() -> bool {
        cfg!(any(
            feature = "redis",
            feature = "postgres",
            feature = "mysql",
            feature = "amqp",
            feature = "sqs"
        ))
    }

    /// Validates that at least one serialization format is enabled
    #[inline]
    pub const fn has_serialization_feature() -> bool {
        cfg!(any(feature = "json", feature = "msgpack"))
    }

    /// Count how many broker features are enabled
    #[inline]
    pub const fn count_broker_features() -> usize {
        let mut count = 0;
        if cfg!(feature = "redis") {
            count += 1;
        }
        if cfg!(feature = "postgres") {
            count += 1;
        }
        if cfg!(feature = "mysql") {
            count += 1;
        }
        if cfg!(feature = "amqp") {
            count += 1;
        }
        if cfg!(feature = "sqs") {
            count += 1;
        }
        count
    }

    /// Count how many backend features are enabled
    #[inline]
    pub const fn count_backend_features() -> usize {
        let mut count = 0;
        if cfg!(feature = "backend-redis") {
            count += 1;
        }
        if cfg!(feature = "backend-db") {
            count += 1;
        }
        if cfg!(feature = "backend-rpc") {
            count += 1;
        }
        count
    }

    /// Validates feature configuration at compile time
    ///
    /// This function is designed to be called in a const context to ensure
    /// compile-time validation of feature flags.
    #[inline]
    pub const fn validate_feature_config() {
        // Ensure at least one broker is available
        if !has_broker_feature() {
            panic!(
                "At least one broker feature must be enabled: redis, postgres, mysql, amqp, or sqs"
            );
        }

        // Ensure at least one serialization format is available
        if !has_serialization_feature() {
            panic!("At least one serialization feature must be enabled: json or msgpack");
        }
    }

    /// Returns a human-readable string describing the current feature configuration
    pub fn feature_summary() -> String {
        let broker_count = count_broker_features();
        let backend_count = count_backend_features();

        let mut brokers = Vec::new();
        if cfg!(feature = "redis") {
            brokers.push("redis");
        }
        if cfg!(feature = "postgres") {
            brokers.push("postgres");
        }
        if cfg!(feature = "mysql") {
            brokers.push("mysql");
        }
        if cfg!(feature = "amqp") {
            brokers.push("amqp");
        }
        if cfg!(feature = "sqs") {
            brokers.push("sqs");
        }

        let mut backends = Vec::new();
        if cfg!(feature = "backend-redis") {
            backends.push("redis");
        }
        if cfg!(feature = "backend-db") {
            backends.push("database");
        }
        if cfg!(feature = "backend-rpc") {
            backends.push("grpc");
        }

        let mut formats = Vec::new();
        if cfg!(feature = "json") {
            formats.push("json");
        }
        if cfg!(feature = "msgpack") {
            formats.push("msgpack");
        }

        let mut features = Vec::new();
        if cfg!(feature = "beat") {
            features.push("beat");
        }
        if cfg!(feature = "metrics") {
            features.push("metrics");
        }
        if cfg!(feature = "tracing") {
            features.push("tracing");
        }
        if cfg!(feature = "dev-utils") {
            features.push("dev-utils");
        }

        format!(
            "CeleRS Configuration:\n\
             Brokers ({}): {}\n\
             Backends ({}): {}\n\
             Formats ({}): {}\n\
             Features: {}",
            broker_count,
            if brokers.is_empty() {
                "none".to_string()
            } else {
                brokers.join(", ")
            },
            backend_count,
            if backends.is_empty() {
                "none".to_string()
            } else {
                backends.join(", ")
            },
            formats.len(),
            if formats.is_empty() {
                "none".to_string()
            } else {
                formats.join(", ")
            },
            if features.is_empty() {
                "none".to_string()
            } else {
                features.join(", ")
            }
        )
    }
}

// Validate feature configuration at compile time
#[allow(dead_code)]
const _FEATURE_VALIDATION: () = compile_time_validation::validate_feature_config();

/// Broker selection helpers
pub mod broker_helper {
    use std::env;

    /// Broker configuration error with helpful suggestions
    #[derive(Debug, thiserror::Error)]
    pub enum BrokerConfigError {
        /// Missing required environment variable
        #[error("Missing environment variable: {0}\n\nSuggestion: Set the environment variable before running:\n  export {0}=<value>")]
        MissingEnvVar(String),

        /// Unsupported broker type requested
        #[error("Unsupported broker type: {broker_type}\n\nSupported types: redis, postgres, mysql, amqp, sqs\nNote: {note}")]
        UnsupportedBrokerType {
            /// The broker type that was requested
            broker_type: String,
            /// Additional note about the error
            note: String,
        },

        /// Required feature not enabled in Cargo.toml
        #[error("Feature not enabled: {feature}\n\nTo enable this feature, add it to your Cargo.toml:\n  celers = {{ version = \"0.1\", features = [\"{feature}\"] }}\n\nAvailable features: redis, postgres, mysql, amqp, sqs, backend-redis, backend-db, backend-rpc")]
        FeatureNotEnabled {
            /// The feature name that needs to be enabled
            feature: String,
        },

        /// Broker creation failed with detailed error information
        #[error("Broker creation failed: {message}\n\nPossible causes:\n{suggestions}")]
        CreationFailed {
            /// Error message from the broker creation attempt
            message: String,
            /// Suggestions for resolving the error
            suggestions: String,
        },
    }

    /// Create a broker from environment variables
    ///
    /// Environment variables:
    /// - `CELERS_BROKER_TYPE`: Type of broker (redis, postgres, mysql, amqp, sqs)
    /// - `CELERS_BROKER_URL`: Connection URL for the broker
    /// - `CELERS_BROKER_QUEUE`: Queue name (default: "celers")
    ///
    /// # Example
    ///
    /// ```bash
    /// export CELERS_BROKER_TYPE=redis
    /// export CELERS_BROKER_URL=redis://localhost:6379
    /// export CELERS_BROKER_QUEUE=my_queue
    /// ```
    ///
    /// ```rust,ignore
    /// use celers::broker_helper::create_broker_from_env;
    ///
    /// let broker = create_broker_from_env().await?;
    /// ```
    pub async fn create_broker_from_env() -> Result<Box<dyn crate::Broker>, BrokerConfigError> {
        let broker_type = env::var("CELERS_BROKER_TYPE")
            .map_err(|_| BrokerConfigError::MissingEnvVar("CELERS_BROKER_TYPE".to_string()))?;

        let broker_url = env::var("CELERS_BROKER_URL")
            .map_err(|_| BrokerConfigError::MissingEnvVar("CELERS_BROKER_URL".to_string()))?;

        let queue_name = env::var("CELERS_BROKER_QUEUE").unwrap_or_else(|_| "celers".to_string());

        create_broker(&broker_type, &broker_url, &queue_name).await
    }

    /// Create a broker with explicit configuration
    ///
    /// # Arguments
    ///
    /// * `broker_type` - Type of broker: "redis", "postgres", "mysql", "amqp", "sqs"
    /// * `broker_url` - Connection URL for the broker
    /// * `queue_name` - Name of the queue to use
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::broker_helper::create_broker;
    ///
    /// let broker = create_broker("redis", "redis://localhost:6379", "my_queue").await?;
    /// ```
    pub async fn create_broker(
        broker_type: &str,
        broker_url: &str,
        queue_name: &str,
    ) -> Result<Box<dyn crate::Broker>, BrokerConfigError> {
        match broker_type.to_lowercase().as_str() {
            #[cfg(feature = "redis")]
            "redis" => {
                use crate::RedisBroker;

                RedisBroker::new(broker_url, queue_name)
                    .map(|b| Box::new(b) as Box<dyn crate::Broker>)
                    .map_err(|e| BrokerConfigError::CreationFailed {
                        message: e.to_string(),
                        suggestions: "- Check that Redis server is running\n  - Verify the connection URL format: redis://host:port\n  - Ensure network connectivity to Redis server".to_string(),
                    })
            }

            #[cfg(feature = "postgres")]
            "postgres" | "postgresql" => {
                use crate::PostgresBroker;

                PostgresBroker::with_queue(broker_url, queue_name)
                    .await
                    .map(|b| Box::new(b) as Box<dyn crate::Broker>)
                    .map_err(|e| BrokerConfigError::CreationFailed {
                        message: e.to_string(),
                        suggestions: "- Check that PostgreSQL server is running\n  - Verify the connection URL format: postgres://user:pass@host:port/db\n  - Ensure database exists and user has permissions".to_string(),
                    })
            }

            #[cfg(feature = "mysql")]
            "mysql" => {
                use crate::MysqlBroker;

                MysqlBroker::with_queue(broker_url, queue_name)
                    .await
                    .map(|b| Box::new(b) as Box<dyn crate::Broker>)
                    .map_err(|e| BrokerConfigError::CreationFailed {
                        message: e.to_string(),
                        suggestions: "- Check that MySQL server is running\n  - Verify the connection URL format: mysql://user:pass@host:port/db\n  - Ensure database exists and user has permissions".to_string(),
                    })
            }

            _ => {
                // Check if it's a known type but feature not enabled
                #[cfg(not(feature = "redis"))]
                if broker_type.to_lowercase() == "redis" {
                    return Err(BrokerConfigError::FeatureNotEnabled {
                        feature: "redis".to_string(),
                    });
                }

                #[cfg(not(feature = "postgres"))]
                if broker_type.to_lowercase() == "postgres"
                    || broker_type.to_lowercase() == "postgresql"
                {
                    return Err(BrokerConfigError::FeatureNotEnabled {
                        feature: "postgres".to_string(),
                    });
                }

                #[cfg(not(feature = "mysql"))]
                if broker_type.to_lowercase() == "mysql" {
                    return Err(BrokerConfigError::FeatureNotEnabled {
                        feature: "mysql".to_string(),
                    });
                }

                // AMQP and SQS use celers-kombu Transport trait, not Broker trait
                if broker_type.to_lowercase() == "amqp" || broker_type.to_lowercase() == "rabbitmq"
                {
                    return Err(BrokerConfigError::UnsupportedBrokerType {
                        broker_type: broker_type.to_string(),
                        note: "AMQP brokers use the Transport trait. Import and use AmqpBroker directly from celers::AmqpBroker".to_string(),
                    });
                }

                if broker_type.to_lowercase() == "sqs" {
                    return Err(BrokerConfigError::UnsupportedBrokerType {
                        broker_type: broker_type.to_string(),
                        note: "SQS brokers use the Transport trait. Import and use SqsBroker directly from celers::SqsBroker".to_string(),
                    });
                }

                Err(BrokerConfigError::UnsupportedBrokerType {
                    broker_type: broker_type.to_string(),
                    note: "Check the broker type name for typos".to_string(),
                })
            }
        }
    }
}

/// Startup time optimization utilities
///
/// This module provides utilities and patterns for optimizing application startup time,
/// including lazy initialization and caching strategies.
pub mod startup_optimization {
    use std::sync::OnceLock;

    /// Type alias for async initialization tasks used in parallel_init
    pub type AsyncInitTask<T, E> = Box<
        dyn FnOnce() -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<T, E>> + Send>>
            + Send,
    >;

    /// Lazy initialization helper using OnceLock for thread-safe static initialization
    ///
    /// # Example
    ///
    /// ```rust
    /// use celers::startup_optimization::LazyInit;
    ///
    /// static MY_CONFIG: LazyInit<String> = LazyInit::new();
    ///
    /// fn get_config() -> &'static String {
    ///     MY_CONFIG.get_or_init(|| {
    ///         // Expensive initialization happens only once
    ///         String::from("config_value")
    ///     })
    /// }
    /// ```
    pub struct LazyInit<T> {
        cell: OnceLock<T>,
    }

    impl<T> LazyInit<T> {
        /// Create a new lazy initialization wrapper
        pub const fn new() -> Self {
            Self {
                cell: OnceLock::new(),
            }
        }

        /// Get the value, initializing it if necessary
        #[inline]
        pub fn get_or_init<F>(&self, f: F) -> &T
        where
            F: FnOnce() -> T,
        {
            self.cell.get_or_init(f)
        }

        /// Try to get the value if it's already initialized
        #[inline]
        pub fn get(&self) -> Option<&T> {
            self.cell.get()
        }
    }

    impl<T> Default for LazyInit<T> {
        fn default() -> Self {
            Self::new()
        }
    }

    /// Pre-compiled pattern cache for faster startup
    ///
    /// Note: For regex caching, add the `regex` crate to your dependencies
    /// and implement a similar pattern using `OnceLock<Mutex<HashMap<String, &'static Regex>>>`.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::sync::OnceLock;
    /// use std::collections::HashMap;
    /// use std::sync::Mutex;
    /// use regex::Regex;
    ///
    /// pub fn cached_regex(pattern: &str) -> &'static Regex {
    ///     static CACHE: OnceLock<Mutex<HashMap<String, &'static Regex>>> = OnceLock::new();
    ///     let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
    ///     let mut cache = cache.lock().expect("lock should not be poisoned");
    ///
    ///     if let Some(regex) = cache.get(pattern) {
    ///         return regex;
    ///     }
    ///
    ///     let regex = Box::leak(Box::new(Regex::new(pattern).expect("Invalid regex")));
    ///     cache.insert(pattern.to_string(), regex);
    ///     regex
    /// }
    /// ```
    #[allow(dead_code)]
    fn _cached_pattern_example() {
        // This is a documentation placeholder
    }

    /// Parallel initialization helper for running multiple initialization tasks concurrently
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use celers::startup_optimization::parallel_init;
    ///
    /// # async fn example() {
    /// let results = parallel_init(vec![
    ///     Box::new(|| Box::pin(async { /* Initialize DB */ Ok::<(), String>(()) })),
    ///     Box::new(|| Box::pin(async { /* Connect to broker */ Ok::<(), String>(()) })),
    ///     Box::new(|| Box::pin(async { /* Load config */ Ok::<(), String>(()) })),
    /// ]).await;
    /// # }
    /// ```
    pub async fn parallel_init<T, E>(tasks: Vec<AsyncInitTask<T, E>>) -> Vec<Result<T, E>>
    where
        T: Send + 'static,
        E: Send + 'static,
    {
        let handles: Vec<_> = tasks
            .into_iter()
            .map(|task| tokio::spawn(async move { task().await }))
            .collect();

        let mut results = Vec::new();
        for handle in handles {
            match handle.await {
                Ok(result) => results.push(result),
                Err(e) => {
                    // Handle join error - convert to result type
                    // For now, we'll panic as this indicates a serious issue
                    panic!("Task panicked: {:?}", e);
                }
            }
        }
        results
    }

    /// Startup performance metrics
    #[derive(Debug, Clone)]
    pub struct StartupMetrics {
        /// Time spent initializing brokers
        pub broker_init_ms: u64,
        /// Time spent loading configuration
        pub config_load_ms: u64,
        /// Time spent connecting to backends
        pub backend_init_ms: u64,
        /// Total startup time
        pub total_ms: u64,
    }

    impl StartupMetrics {
        /// Create a new startup metrics tracker
        pub fn new() -> Self {
            Self {
                broker_init_ms: 0,
                config_load_ms: 0,
                backend_init_ms: 0,
                total_ms: 0,
            }
        }

        /// Report the metrics as a formatted string
        pub fn report(&self) -> String {
            format!(
                "Startup Performance:\n\
                 - Broker Init: {}ms\n\
                 - Config Load: {}ms\n\
                 - Backend Init: {}ms\n\
                 - Total: {}ms",
                self.broker_init_ms, self.config_load_ms, self.backend_init_ms, self.total_ms
            )
        }
    }

    impl Default for StartupMetrics {
        fn default() -> Self {
            Self::new()
        }
    }

    /// Helper macro for timing initialization steps
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::time_init;
    ///
    /// let duration = time_init!({
    ///     // Expensive initialization code
    ///     initialize_database().await
    /// });
    /// println!("Initialization took {}ms", duration.as_millis());
    /// ```
    #[macro_export]
    macro_rules! time_init {
        ($block:block) => {{
            let start = std::time::Instant::now();
            let result = $block;
            let duration = start.elapsed();
            (result, duration)
        }};
    }
}

/// IDE support and type hints module
///
/// This module provides comprehensive type aliases, trait bounds, and documentation
/// to improve IDE autocomplete, type inference, and developer experience.
pub mod ide_support {
    use std::future::Future;
    use std::pin::Pin;

    /// Common result type for async operations with Send + Sync error bounds
    ///
    /// This type alias helps IDEs provide better autocomplete and type hints.
    ///
    /// # Example
    ///
    /// ```rust
    /// use celers::ide_support::BoxedResult;
    ///
    /// async fn my_operation() -> BoxedResult<String> {
    ///     Ok("success".to_string())
    /// }
    /// ```
    pub type BoxedResult<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;

    /// Pinned boxed future for async task functions
    ///
    /// This is the standard return type for async task implementations.
    ///
    /// # Example
    ///
    /// ```rust
    /// use celers::ide_support::BoxedFuture;
    ///
    /// fn create_task() -> BoxedFuture<String> {
    ///     Box::pin(async { Ok("result".to_string()) })
    /// }
    /// ```
    pub type BoxedFuture<T> = Pin<Box<dyn Future<Output = BoxedResult<T>> + Send + 'static>>;

    /// Task function signature for type hints
    ///
    /// Use this when defining task handler functions for better IDE support.
    pub type TaskFn<Args, Output> =
        fn(Args) -> Pin<Box<dyn Future<Output = BoxedResult<Output>> + Send>>;

    /// Broker instance type for common use cases
    ///
    /// This type alias helps with IDE autocomplete when working with brokers.
    pub type BoxedBroker = Box<dyn crate::Broker>;

    /// Result backend instance type
    ///
    /// Use this when working with result backends for better type hints.
    #[cfg(feature = "backend-redis")]
    pub type BoxedResultBackend = Box<dyn crate::ResultBackend>;

    /// Worker configuration builder type for fluent API
    ///
    /// This alias improves IDE support when building worker configurations.
    pub type WorkerBuilder = celers_worker::WorkerConfigBuilder;

    /// Signature builder type for creating task signatures
    ///
    /// Use this for better autocomplete when building task signatures.
    pub type TaskSignature = crate::Signature;

    /// Chain workflow builder type
    pub type ChainBuilder = crate::Chain;

    /// Group workflow builder type
    pub type GroupBuilder = crate::Group;

    /// Chord workflow builder type
    pub type ChordBuilder = crate::Chord;

    /// Serialized task type for queue operations
    pub type QueueTask = crate::SerializedTask;

    /// Task metadata type
    pub use crate::TaskState;

    /// Broker error type
    pub use crate::BrokerError;

    /// Task ID type for tracking tasks
    pub type TaskId = uuid::Uuid;

    /// Task result value type
    pub use crate::TaskResultValue;

    /// Event emitter type for task events
    pub type EventEmitter = Box<dyn crate::EventEmitter>;

    /// Async result type for task result retrieval
    pub use crate::AsyncResult;

    /// Worker statistics type
    pub use crate::WorkerStats;

    /// Task options type for task configuration
    pub use crate::TaskOptions;

    /// Rate limiter configuration type
    pub use crate::RateLimitConfig;

    /// Router type for task routing
    pub use crate::Router;

    /// Queue name type for better readability
    ///
    /// Use this when defining queue names for clearer code intent.
    pub type QueueName = String;

    /// Broker URL type for configuration
    ///
    /// Use this when defining broker connection strings.
    pub type BrokerUrl = String;

    /// Retry count type for task configuration
    ///
    /// Use this when specifying maximum retry attempts.
    pub type RetryCount = u32;

    /// Priority level type for task prioritization
    ///
    /// Valid range: 0-9, where 9 is highest priority.
    pub type PriorityLevel = u8;

    /// Timeout duration in seconds
    ///
    /// Use this when specifying task time limits and countdowns.
    pub type TimeoutSeconds = u64;

    /// Task name type for task identification
    ///
    /// Use this when defining or referencing task names.
    pub type TaskName = String;

    /// Concurrency level type for worker configuration
    ///
    /// Represents the number of concurrent tasks a worker can execute.
    pub type ConcurrencyLevel = usize;

    /// Prefetch count type for worker configuration
    ///
    /// Number of tasks to prefetch from the broker.
    pub type PrefetchCount = usize;

    /// Type trait bounds helper for task arguments
    ///
    /// This trait bound helps IDEs understand the requirements for task arguments.
    pub trait TaskArgs:
        serde::Serialize + serde::de::DeserializeOwned + Send + Sync + 'static
    {
    }
    impl<T> TaskArgs for T where
        T: serde::Serialize + serde::de::DeserializeOwned + Send + Sync + 'static
    {
    }

    /// Type trait bounds helper for task results
    ///
    /// This trait bound helps IDEs understand the requirements for task results.
    pub trait TaskResult: serde::Serialize + serde::de::DeserializeOwned + Send + 'static {}
    impl<T> TaskResult for T where T: serde::Serialize + serde::de::DeserializeOwned + Send + 'static {}

    /// Marker trait for broker implementations
    ///
    /// Helps IDEs identify valid broker types.
    pub trait BrokerImpl: crate::Broker + Send + Sync {}

    /// Helper constants for common configuration values
    pub mod defaults {
        /// Default concurrency level (number of CPU cores)
        pub const DEFAULT_CONCURRENCY: usize = 4;

        /// Default prefetch count
        pub const DEFAULT_PREFETCH: usize = 10;

        /// Default max retries
        pub const DEFAULT_MAX_RETRIES: u32 = 3;

        /// Default retry delay in seconds
        pub const DEFAULT_RETRY_DELAY_SECS: u64 = 60;

        /// Default task timeout in seconds
        pub const DEFAULT_TASK_TIMEOUT_SECS: u64 = 3600;

        /// Default broker port for Redis
        pub const DEFAULT_REDIS_PORT: u16 = 6379;

        /// Default broker port for PostgreSQL
        pub const DEFAULT_POSTGRES_PORT: u16 = 5432;

        /// Default broker port for MySQL
        pub const DEFAULT_MYSQL_PORT: u16 = 3306;

        /// Default broker port for RabbitMQ
        pub const DEFAULT_RABBITMQ_PORT: u16 = 5672;

        /// Default queue name
        pub const DEFAULT_QUEUE_NAME: &str = "celery";
    }

    /// Common configuration patterns and examples
    pub mod examples {
        /// Example broker URL for Redis
        pub const REDIS_URL_EXAMPLE: &str = "redis://localhost:6379";

        /// Example broker URL for PostgreSQL
        pub const POSTGRES_URL_EXAMPLE: &str = "postgres://user:password@localhost:5432/celery";

        /// Example broker URL for MySQL
        pub const MYSQL_URL_EXAMPLE: &str = "mysql://user:password@localhost:3306/celery";

        /// Example broker URL for RabbitMQ
        pub const RABBITMQ_URL_EXAMPLE: &str = "amqp://guest:guest@localhost:5672/";

        /// Example broker URL for SQS
        pub const SQS_URL_EXAMPLE: &str =
            "https://sqs.us-east-1.amazonaws.com/123456789012/my-queue";
    }
}

/// Quick reference documentation module
///
/// This module provides quick reference guides and cheat sheets for common operations.
pub mod quick_reference {
    pub mod patterns {
        //! Quick start guide for common patterns
        //!
        //! # Common Patterns
        //!
        //! ## Creating a Simple Task
        //! ```rust,ignore
        //! use celers::prelude::*;
        //!
        //! #[derive(Serialize, Deserialize)]
        //! struct Args { x: i32, y: i32 }
        //!
        //! #[celers::task]
        //! async fn add(args: Args) -> TaskResult<i32> {
        //!     Ok(args.x + args.y)
        //! }
        //! ```
        //!
        //! ## Creating a Worker
        //! ```rust,ignore
        //! use celers::prelude::*;
        //!
        //! let broker = create_broker_from_env().await?;
        //! let worker = WorkerConfigBuilder::new()
        //!     .concurrency(4)
        //!     .prefetch_count(10)
        //!     .build(broker)?;
        //! worker.start().await?;
        //! ```
        //!
        //! ## Sending Tasks
        //! ```rust,ignore
        //! let task = my_task::new(Args { x: 1, y: 2 });
        //! broker.enqueue(task).await?;
        //! ```
        //!
        //! ## Creating Workflows
        //! ```rust,ignore
        //! // Chain: Sequential execution
        //! let chain = Chain::new()
        //!     .then("task1", vec![])
        //!     .then("task2", vec![]);
        //!
        //! // Group: Parallel execution
        //! let group = Group::new()
        //!     .add("task1", vec![])
        //!     .add("task2", vec![]);
        //!
        //! // Chord: Parallel + callback
        //! let chord = Chord::new(group, callback);
        //! ```
    }

    pub mod config_examples {
        //! Configuration examples and snippets
        //!
        //! # Configuration Examples
        //!
        //! ## Environment Variables
        //! ```bash
        //! export CELERS_BROKER_TYPE=redis
        //! export CELERS_BROKER_URL=redis://localhost:6379
        //! export CELERS_BROKER_QUEUE=celery
        //! ```
        //!
        //! ## Worker Presets
        //! ```rust,ignore
        //! use celers::presets::*;
        //!
        //! // Production config
        //! let config = production_config();
        //!
        //! // High throughput
        //! let config = high_throughput_config();
        //!
        //! // Low latency
        //! let config = low_latency_config();
        //!
        //! // Memory constrained
        //! let config = memory_constrained_config();
        //! ```
    }

    pub mod troubleshooting {
        //! Troubleshooting guide
        //!
        //! # Troubleshooting Guide
        //!
        //! ## Common Issues
        //!
        //! ### Connection Refused
        //! - Check broker is running: `redis-cli ping` or `psql`
        //! - Verify connection URL format
        //! - Check firewall rules
        //!
        //! ### Tasks Not Processing
        //! - Verify worker is running
        //! - Check queue name matches
        //! - Inspect worker logs
        //!
        //! ### High Memory Usage
        //! - Reduce prefetch_count
        //! - Implement chunked processing
        //! - Monitor task memory usage
        //!
        //! ### Slow Task Execution
        //! - Increase worker concurrency
        //! - Profile task execution time
        //! - Optimize database queries
    }
}

#[cfg(feature = "dev-utils")]
pub mod assembly_inspection {
    //! Assembly inspection utilities for verifying zero-cost abstractions
    //!
    //! This module provides tools and documentation for inspecting generated assembly
    //! to verify that Rust's zero-cost abstractions are working as expected.
    //!
    //! # Assembly Inspection Guide
    //!
    //! This module helps you verify zero-cost abstractions by inspecting generated assembly.
    //!
    //! ## Generating Assembly Output
    //!
    //! ### Method 1: Using cargo-asm (Recommended)
    //!
    //! ```bash
    //! # Install cargo-asm
    //! cargo install cargo-asm
    //!
    //! # Generate assembly for a specific function
    //! cargo asm --release celers::dev_utils::TaskBuilder::new
    //!
    //! # Generate assembly with Intel syntax (easier to read)
    //! cargo asm --release --intel celers::dev_utils::TaskBuilder::new
    //! ```
    //!
    //! ### Method 2: Using rustc directly
    //!
    //! ```bash
    //! # Generate assembly for the entire crate
    //! cargo rustc --release -- --emit asm
    //!
    //! # Output will be in target/release/deps/*.s
    //! ```
    //!
    //! ### Method 3: Using Compiler Explorer (Godbolt)
    //!
    //! Visit <https://rust.godbolt.org/> and paste your code to see assembly interactively.
    //!
    //! ## What to Look For
    //!
    //! ### 1. Function Inlining
    //!
    //! Zero-cost abstractions should be inlined. Look for:
    //! - Direct instructions instead of `call` instructions
    //! - No function preamble/epilogue for simple wrappers
    //!
    //! Example of good inlining:
    //! ```asm
    //! # Simple arithmetic directly in caller
    //! add    rdi, rsi
    //! mov    rax, rdi
    //! ```
    //!
    //! Example of poor inlining (overhead):
    //! ```asm
    //! # Function call overhead
    //! call   my_wrapper_function
    //! push   rbp
    //! mov    rbp, rsp
    //! ```
    //!
    //! ### 2. Dead Code Elimination
    //!
    //! Unused code should be completely removed:
    //! - No assembly generated for unused branches
    //! - Constant propagation should eliminate runtime checks
    //!
    //! ### 3. Iterator Optimization
    //!
    //! Iterator chains should compile to simple loops:
    //! ```asm
    //! # Should see a tight loop, not iterator machinery
    //! .LBB0_1:
    //!     add    rax, 1
    //!     cmp    rax, rcx
    //!     jne    .LBB0_1
    //! ```
    //!
    //! ### 4. Monomorphization
    //!
    //! Generic functions should be specialized:
    //! - No dynamic dispatch (vtable calls) unless using trait objects
    //! - Type parameters resolved at compile time
    //!
    //! ## Example Commands for CeleRS
    //!
    //! ```bash
    //! # Verify TaskBuilder is zero-cost
    //! cargo asm --release --intel celers::dev_utils::TaskBuilder::build
    //!
    //! # Verify chain workflow construction
    //! cargo asm --release --intel celers::canvas::Chain::new
    //!
    //! # Compare debug vs release
    //! cargo asm celers::dev_utils::TaskBuilder::build > debug.asm
    //! cargo asm --release celers::dev_utils::TaskBuilder::build > release.asm
    //! diff debug.asm release.asm
    //! ```
    //!
    //! ## Automated Verification
    //!
    //! Use these helper functions to automate assembly inspection:

    use std::process::Command;

    /// Generate assembly output for a specific function
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "dev-utils")]
    /// # {
    /// use celers::assembly_inspection::generate_asm;
    ///
    /// let asm = generate_asm("celers::dev_utils::TaskBuilder::new", true).unwrap();
    /// println!("Assembly:\n{}", asm);
    /// # }
    /// ```
    pub fn generate_asm(function_path: &str, release: bool) -> Result<String, std::io::Error> {
        let mut cmd = Command::new("cargo");
        cmd.arg("asm");
        if release {
            cmd.arg("--release");
        }
        cmd.arg("--intel");
        cmd.arg(function_path);

        let output = cmd.output()?;
        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    /// Check if a function is properly inlined by looking for call instructions
    ///
    /// Returns true if the function appears to be inlined (no call instructions found)
    pub fn verify_inlined(asm: &str) -> bool {
        !asm.contains("call") || asm.lines().filter(|l| l.contains("call")).count() < 2
    }

    /// Count the number of instructions in the assembly
    ///
    /// Useful for comparing optimization levels
    pub fn count_instructions(asm: &str) -> usize {
        asm.lines()
            .filter(|line| {
                let trimmed = line.trim();
                !trimmed.is_empty()
                    && !trimmed.starts_with(';')
                    && !trimmed.starts_with('#')
                    && !trimmed.starts_with('.')
                    && !trimmed.ends_with(':')
            })
            .count()
    }

    /// Generate a performance report comparing debug and release assembly
    pub fn compare_debug_release(function_path: &str) -> Result<String, std::io::Error> {
        let debug_asm = generate_asm(function_path, false)?;
        let release_asm = generate_asm(function_path, true)?;

        let debug_count = count_instructions(&debug_asm);
        let release_count = count_instructions(&release_asm);
        let debug_inlined = verify_inlined(&debug_asm);
        let release_inlined = verify_inlined(&release_asm);

        Ok(format!(
            "Assembly Comparison for {}\n\
             \n\
             Debug Build:\n\
             - Instructions: {}\n\
             - Inlined: {}\n\
             \n\
             Release Build:\n\
             - Instructions: {}\n\
             - Inlined: {}\n\
             \n\
             Optimization Ratio: {:.2}x fewer instructions in release\n",
            function_path,
            debug_count,
            debug_inlined,
            release_count,
            release_inlined,
            debug_count as f64 / release_count.max(1) as f64
        ))
    }
}

/// Workflow templates for common distributed computing patterns
///
/// This module provides pre-built workflow templates that implement common
/// distributed computing patterns, making it easy to apply best practices
/// without having to build workflows from scratch.
///
/// # Available Templates
///
/// - **ETL Pipeline**: Extract, Transform, Load pattern
/// - **Map-Reduce**: Parallel processing with aggregation
/// - **Scatter-Gather**: Distribute work and collect results
/// - **Fan-Out/Fan-In**: Parallel execution with synchronization
/// - **Sequential Pipeline**: Multi-stage processing
/// - **Batch Processing**: Process items in batches with retry
///
/// # Example
///
/// ```rust,ignore
/// use celers::workflow_templates::*;
/// use serde_json::json;
///
/// // Create an ETL pipeline
/// let pipeline = etl_pipeline(
///     "extract_data",
///     vec![json!({"source": "database"})],
///     "transform_data",
///     "load_data"
/// );
///
/// // Create a map-reduce workflow
/// let workflow = map_reduce_workflow(
///     "process_item",
///     vec![json!(1), json!(2), json!(3)],
///     "aggregate_results"
/// );
/// ```
pub mod workflow_templates {
    use crate::canvas::{Chain, Chord, Group};
    use crate::Signature;
    use serde_json::Value;

    /// Creates an ETL (Extract, Transform, Load) pipeline workflow
    ///
    /// This pattern is commonly used for data processing pipelines where data
    /// flows through multiple transformation stages.
    ///
    /// # Arguments
    ///
    /// * `extract_task` - Name of the task that extracts data
    /// * `extract_args` - Arguments for the extract task
    /// * `transform_task` - Name of the task that transforms data
    /// * `load_task` - Name of the task that loads processed data
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::workflow_templates::etl_pipeline;
    /// use serde_json::json;
    ///
    /// let pipeline = etl_pipeline(
    ///     "extract_from_api",
    ///     vec![json!({"url": "https://api.example.com"})],
    ///     "transform_data",
    ///     "load_to_database"
    /// );
    ///
    /// pipeline.apply_async(&broker).await?;
    /// ```
    pub fn etl_pipeline(
        extract_task: &str,
        extract_args: Vec<Value>,
        transform_task: &str,
        load_task: &str,
    ) -> Chain {
        Chain::new()
            .then(extract_task, extract_args)
            .then(transform_task, vec![])
            .then(load_task, vec![])
    }

    /// Creates a Map-Reduce workflow for parallel processing with aggregation
    ///
    /// This pattern processes items in parallel (map phase) and then aggregates
    /// the results (reduce phase).
    ///
    /// # Arguments
    ///
    /// * `map_task` - Name of the task to apply to each item
    /// * `items` - Collection of items to process
    /// * `reduce_task` - Name of the task that aggregates results
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::workflow_templates::map_reduce_workflow;
    /// use serde_json::json;
    ///
    /// let workflow = map_reduce_workflow(
    ///     "process_number",
    ///     vec![json!(1), json!(2), json!(3), json!(4)],
    ///     "sum_results"
    /// );
    /// ```
    pub fn map_reduce_workflow(map_task: &str, items: Vec<Value>, reduce_task: &str) -> Chord {
        let mut group = Group::new();
        for item in items {
            group = group.add(map_task, vec![item]);
        }

        let reduce_sig = Signature::new(reduce_task.to_string());

        Chord {
            header: group,
            body: reduce_sig,
        }
    }

    /// Creates a scatter-gather workflow for distributing work
    ///
    /// This pattern distributes different tasks to be executed in parallel
    /// and then gathers all results.
    ///
    /// # Arguments
    ///
    /// * `tasks` - List of (task_name, args) tuples to execute in parallel
    /// * `gather_task` - Name of the task that gathers all results
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::workflow_templates::scatter_gather;
    /// use serde_json::json;
    ///
    /// let tasks = vec![
    ///     ("fetch_user_data", vec![json!({"user_id": 1})]),
    ///     ("fetch_order_data", vec![json!({"user_id": 1})]),
    ///     ("fetch_preferences", vec![json!({"user_id": 1})]),
    /// ];
    ///
    /// let workflow = scatter_gather(tasks, "combine_user_profile");
    /// ```
    pub fn scatter_gather(tasks: Vec<(&str, Vec<Value>)>, gather_task: &str) -> Chord {
        let mut group = Group::new();
        for (task_name, args) in tasks {
            group = group.add(task_name, args);
        }

        let gather_sig = Signature::new(gather_task.to_string());

        Chord {
            header: group,
            body: gather_sig,
        }
    }

    /// Creates a batch processing workflow with automatic chunking
    ///
    /// This pattern processes large datasets by dividing them into batches,
    /// processing each batch in parallel, and then aggregating results.
    ///
    /// # Arguments
    ///
    /// * `process_task` - Name of the task that processes a batch
    /// * `items` - All items to process
    /// * `batch_size` - Number of items per batch
    /// * `aggregate_task` - Optional task to aggregate all batch results
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::workflow_templates::batch_processing;
    /// use serde_json::json;
    ///
    /// let items = (1..=100).map(|i| json!(i)).collect();
    /// let workflow = batch_processing(
    ///     "process_batch",
    ///     items,
    ///     10, // Process 10 items per batch
    ///     Some("combine_batch_results")
    /// );
    /// ```
    pub fn batch_processing(
        process_task: &str,
        items: Vec<Value>,
        batch_size: usize,
        aggregate_task: Option<&str>,
    ) -> Chord {
        let mut group = Group::new();

        // Split items into batches
        for chunk in items.chunks(batch_size) {
            let batch = Value::Array(chunk.to_vec());
            group = group.add(process_task, vec![batch]);
        }

        let body_sig = if let Some(agg_task) = aggregate_task {
            Signature::new(agg_task.to_string())
        } else {
            // Default no-op aggregation
            Signature::new("celers.noop".to_string())
        };

        Chord {
            header: group,
            body: body_sig,
        }
    }

    /// Creates a sequential pipeline workflow with error handling
    ///
    /// This pattern chains tasks sequentially with automatic retry and
    /// error recovery built in.
    ///
    /// # Arguments
    ///
    /// * `stages` - List of (task_name, args, max_retries) tuples
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::workflow_templates::sequential_pipeline;
    /// use serde_json::json;
    ///
    /// let stages = vec![
    ///     ("validate_input", vec![json!({"data": "test"})], 3),
    ///     ("process_data", vec![], 5),
    ///     ("save_results", vec![], 3),
    /// ];
    ///
    /// let pipeline = sequential_pipeline(stages);
    /// ```
    pub fn sequential_pipeline(stages: Vec<(&str, Vec<Value>, u32)>) -> Chain {
        let mut chain = Chain::new();

        for (task_name, args, max_retries) in stages {
            let mut sig = Signature::new(task_name.to_string()).with_args(args);
            sig.options.max_retries = Some(max_retries);

            chain.tasks.push(sig);
        }

        chain
    }

    /// Creates a priority-based workflow for handling urgent tasks first
    ///
    /// This pattern creates parallel tasks with different priorities,
    /// ensuring high-priority tasks are processed first.
    ///
    /// # Arguments
    ///
    /// * `tasks` - List of (task_name, args, priority) tuples
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::workflow_templates::priority_workflow;
    /// use serde_json::json;
    ///
    /// let tasks = vec![
    ///     ("critical_task", vec![json!(1)], 9),
    ///     ("normal_task", vec![json!(2)], 5),
    ///     ("low_priority_task", vec![json!(3)], 1),
    /// ];
    ///
    /// let workflow = priority_workflow(tasks);
    /// ```
    pub fn priority_workflow(tasks: Vec<(&str, Vec<Value>, u8)>) -> Group {
        let mut group = Group::new();

        for (task_name, args, priority) in tasks {
            let mut sig = Signature::new(task_name.to_string()).with_args(args);
            sig.options.priority = Some(priority);

            group.tasks.push(sig);
        }

        group
    }
}

/// Advanced task composition utilities
///
/// This module provides utilities for composing complex task workflows,
/// including conditional execution, dynamic task generation, and result
/// transformation.
///
/// # Example
///
/// ```rust,ignore
/// use celers::task_composition::*;
/// use serde_json::json;
///
/// // Create a conditional workflow
/// let workflow = conditional_chain(
///     "validate_data",
///     vec![json!({"data": "test"})],
///     vec![
///         ("process_valid_data", vec![]),
///         ("save_results", vec![]),
///     ],
///     Some(("handle_error", vec![]))
/// );
/// ```
pub mod task_composition {
    use crate::canvas::{Chain, Group};
    use crate::Signature;
    use serde_json::Value;

    /// Creates a conditional execution chain
    ///
    /// Executes a predicate task, and based on its result, executes either
    /// the success chain or the fallback chain.
    ///
    /// # Arguments
    ///
    /// * `predicate_task` - Task that returns a boolean condition
    /// * `predicate_args` - Arguments for the predicate task
    /// * `success_chain` - Tasks to execute if predicate is true
    /// * `fallback_chain` - Optional tasks to execute if predicate is false
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::task_composition::conditional_chain;
    /// use serde_json::json;
    ///
    /// let workflow = conditional_chain(
    ///     "check_balance",
    ///     vec![json!({"account_id": 123})],
    ///     vec![("process_payment", vec![]), ("send_receipt", vec![])],
    ///     Some(("send_insufficient_funds_email", vec![]))
    /// );
    /// ```
    #[allow(dead_code)]
    pub fn conditional_chain(
        predicate_task: &str,
        predicate_args: Vec<Value>,
        success_chain: Vec<(&str, Vec<Value>)>,
        _fallback_chain: Option<(&str, Vec<Value>)>,
    ) -> Chain {
        let mut chain = Chain::new();

        // Add predicate task
        chain = chain.then(predicate_task, predicate_args);

        // Add success chain tasks
        for (task_name, args) in success_chain {
            chain = chain.then(task_name, args);
        }

        // Note: Actual conditional logic would need to be implemented in the task itself
        // This is a template for the workflow structure

        chain
    }

    /// Creates a retry wrapper with exponential backoff
    ///
    /// Wraps a task with automatic retry logic using exponential backoff.
    ///
    /// # Arguments
    ///
    /// * `task_name` - Name of the task to wrap
    /// * `args` - Task arguments
    /// * `max_retries` - Maximum number of retry attempts
    /// * `initial_delay` - Initial delay in seconds (doubles each retry)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::task_composition::retry_wrapper;
    /// use serde_json::json;
    ///
    /// let sig = retry_wrapper(
    ///     "fetch_external_api",
    ///     vec![json!({"url": "https://api.example.com"})],
    ///     5,  // Retry up to 5 times
    ///     10  // Start with 10 second delay
    /// );
    /// ```
    pub fn retry_wrapper(
        task_name: &str,
        args: Vec<Value>,
        max_retries: u32,
        initial_delay: u64,
    ) -> Signature {
        let mut sig = Signature::new(task_name.to_string()).with_args(args);
        sig.options.max_retries = Some(max_retries);
        sig.options.countdown = Some(initial_delay);
        sig
    }

    /// Creates a timeout-protected task
    ///
    /// Wraps a task with a timeout, ensuring it doesn't run indefinitely.
    ///
    /// # Arguments
    ///
    /// * `task_name` - Name of the task to protect
    /// * `args` - Task arguments
    /// * `timeout_seconds` - Maximum execution time in seconds
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::task_composition::timeout_wrapper;
    /// use serde_json::json;
    ///
    /// let sig = timeout_wrapper(
    ///     "long_running_task",
    ///     vec![json!({"process": "large_dataset"})],
    ///     300  // 5 minute timeout
    /// );
    /// ```
    pub fn timeout_wrapper(task_name: &str, args: Vec<Value>, timeout_seconds: u64) -> Signature {
        let mut sig = Signature::new(task_name.to_string()).with_args(args);
        sig.options.time_limit = Some(timeout_seconds);
        sig
    }

    /// Creates a task group with circuit breaker pattern
    ///
    /// Groups tasks and adds circuit breaker semantics to prevent cascading
    /// failures.
    ///
    /// # Arguments
    ///
    /// * `tasks` - List of (task_name, args) tuples
    /// * `max_failures` - Maximum failures before circuit opens
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::task_composition::circuit_breaker_group;
    /// use serde_json::json;
    ///
    /// let tasks = vec![
    ///     ("call_service_a", vec![json!(1)]),
    ///     ("call_service_b", vec![json!(2)]),
    ///     ("call_service_c", vec![json!(3)]),
    /// ];
    ///
    /// let group = circuit_breaker_group(tasks, 2);
    /// ```
    pub fn circuit_breaker_group(tasks: Vec<(&str, Vec<Value>)>, max_failures: u32) -> Group {
        let mut group = Group::new();

        for (task_name, args) in tasks {
            let mut sig = Signature::new(task_name.to_string()).with_args(args);
            // Add retry logic for circuit breaker
            sig.options.max_retries = Some(max_failures);

            group.tasks.push(sig);
        }

        group
    }

    /// Creates a rate-limited workflow
    ///
    /// Spaces out task execution to respect rate limits.
    ///
    /// # Arguments
    ///
    /// * `task_name` - Name of the task
    /// * `items` - Items to process
    /// * `delay_between_tasks` - Delay in seconds between each task
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::task_composition::rate_limited_workflow;
    /// use serde_json::json;
    ///
    /// let items = vec![json!(1), json!(2), json!(3)];
    /// let workflow = rate_limited_workflow(
    ///     "call_rate_limited_api",
    ///     items,
    ///     5  // 5 seconds between each call
    /// );
    /// ```
    pub fn rate_limited_workflow(
        task_name: &str,
        items: Vec<Value>,
        delay_between_tasks: u64,
    ) -> Chain {
        let mut chain = Chain::new();

        for (i, item) in items.into_iter().enumerate() {
            let mut sig = Signature::new(task_name.to_string()).with_args(vec![item]);

            // Add countdown for all tasks except the first
            if i > 0 {
                sig.options.countdown = Some(delay_between_tasks * i as u64);
            }

            chain.tasks.push(sig);
        }

        chain
    }
}

/// Error recovery patterns for resilient task execution
///
/// This module provides patterns and utilities for handling errors gracefully
/// in distributed task systems, including fallback strategies, error aggregation,
/// and recovery mechanisms.
///
/// # Example
///
/// ```rust,ignore
/// use celers::error_recovery::*;
/// use serde_json::json;
///
/// // Create a task with fallback
/// let task_with_fallback = with_fallback(
///     "risky_operation",
///     vec![json!({"data": "test"})],
///     "safe_fallback_operation",
///     vec![json!({"data": "fallback"})]
/// );
/// ```
pub mod error_recovery {
    use crate::{Chain, Signature};
    use serde_json::Value;

    /// Creates a task chain with a fallback task in case of failure
    ///
    /// This pattern provides a fallback mechanism where if the primary task fails,
    /// a secondary fallback task is executed instead.
    ///
    /// # Arguments
    ///
    /// * `primary_task` - Name of the primary task to execute
    /// * `primary_args` - Arguments for the primary task
    /// * `fallback_task` - Name of the fallback task to execute on failure
    /// * `fallback_args` - Arguments for the fallback task
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::error_recovery::with_fallback;
    /// use serde_json::json;
    ///
    /// let task = with_fallback(
    ///     "fetch_from_primary_api",
    ///     vec![json!({"url": "https://api.example.com"})],
    ///     "fetch_from_backup_api",
    ///     vec![json!({"url": "https://backup.example.com"})]
    /// );
    /// ```
    ///
    /// # Note
    ///
    /// The actual fallback logic must be implemented in the task handlers.
    /// This function creates the workflow structure.
    pub fn with_fallback(
        primary_task: &str,
        primary_args: Vec<Value>,
        fallback_task: &str,
        fallback_args: Vec<Value>,
    ) -> Chain {
        Chain::new()
            .then(primary_task, primary_args)
            .then(fallback_task, fallback_args)
    }

    /// Creates a task signature with error suppression
    ///
    /// Configures a task to ignore errors and continue execution.
    /// Useful for non-critical tasks where failures shouldn't block the workflow.
    ///
    /// # Arguments
    ///
    /// * `task_name` - Name of the task
    /// * `args` - Task arguments
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::error_recovery::ignore_errors;
    /// use serde_json::json;
    ///
    /// let sig = ignore_errors(
    ///     "log_analytics",
    ///     vec![json!({"event": "user_action"})]
    /// );
    /// ```
    pub fn ignore_errors(task_name: &str, args: Vec<Value>) -> Signature {
        let mut sig = Signature::new(task_name.to_string()).with_args(args);
        sig.options.max_retries = Some(0); // No retries
                                           // Note: Actual error suppression logic would be in the task handler
        sig
    }

    /// Creates a task with graduated retry delays
    ///
    /// Implements exponential backoff retry strategy for tasks that may
    /// experience transient failures.
    ///
    /// # Arguments
    ///
    /// * `task_name` - Name of the task
    /// * `args` - Task arguments
    /// * `max_retries` - Maximum number of retry attempts
    /// * `base_delay` - Initial delay in seconds (doubles each retry)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::error_recovery::with_exponential_backoff;
    /// use serde_json::json;
    ///
    /// let sig = with_exponential_backoff(
    ///     "call_flaky_api",
    ///     vec![json!({"endpoint": "/data"})],
    ///     5,   // Retry up to 5 times
    ///     2    // Start with 2 second delay, then 4, 8, 16, 32
    /// );
    /// ```
    pub fn with_exponential_backoff(
        task_name: &str,
        args: Vec<Value>,
        max_retries: u32,
        base_delay: u64,
    ) -> Signature {
        let mut sig = Signature::new(task_name.to_string()).with_args(args);
        sig.options.max_retries = Some(max_retries);
        sig.options.countdown = Some(base_delay);
        // Note: Actual exponential backoff logic would be in the retry handler
        sig
    }

    /// Creates a task with a dead letter queue on failure
    ///
    /// Routes failed tasks to a designated error handling queue.
    ///
    /// # Arguments
    ///
    /// * `task_name` - Name of the task
    /// * `args` - Task arguments
    /// * `dlq_task` - Name of the dead letter queue handler task
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::error_recovery::with_dlq;
    /// use serde_json::json;
    ///
    /// let task = with_dlq(
    ///     "process_payment",
    ///     vec![json!({"amount": 100})],
    ///     "handle_failed_payment"
    /// );
    /// ```
    pub fn with_dlq(task_name: &str, args: Vec<Value>, dlq_task: &str) -> Chain {
        Chain::new().then(task_name, args).then(dlq_task, vec![])
    }
}

/// Workflow validation utilities
///
/// This module provides utilities for validating workflow configurations
/// before execution, helping catch configuration errors early.
///
/// # Example
///
/// ```rust,ignore
/// use celers::workflow_validation::*;
///
/// let chain = Chain::new()
///     .then("task1", vec![])
///     .then("task2", vec![]);
///
/// if let Err(errors) = validate_chain(&chain) {
///     for error in errors {
///         eprintln!("Validation error: {}", error);
///     }
/// }
/// ```
pub mod workflow_validation {
    use crate::{Chain, Chord, Group};

    /// Validation error type
    #[derive(Debug, Clone)]
    pub struct ValidationError {
        /// Error message
        pub message: String,
        /// Task name where error occurred (if applicable)
        pub task_name: Option<String>,
    }

    impl ValidationError {
        /// Creates a new validation error
        pub fn new(message: impl Into<String>) -> Self {
            Self {
                message: message.into(),
                task_name: None,
            }
        }

        /// Creates a validation error with task context
        pub fn with_task(message: impl Into<String>, task_name: impl Into<String>) -> Self {
            Self {
                message: message.into(),
                task_name: Some(task_name.into()),
            }
        }
    }

    impl std::fmt::Display for ValidationError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            if let Some(task) = &self.task_name {
                write!(f, "[{}] {}", task, self.message)
            } else {
                write!(f, "{}", self.message)
            }
        }
    }

    /// Validates a chain workflow
    ///
    /// Checks for common issues like empty chains, invalid task names, etc.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::workflow_validation::validate_chain;
    /// use celers::Chain;
    ///
    /// let chain = Chain::new()
    ///     .then("task1", vec![])
    ///     .then("task2", vec![]);
    ///
    /// match validate_chain(&chain) {
    ///     Ok(_) => println!("Chain is valid"),
    ///     Err(errors) => {
    ///         for err in errors {
    ///             eprintln!("Error: {}", err);
    ///         }
    ///     }
    /// }
    /// ```
    pub fn validate_chain(chain: &Chain) -> Result<(), Vec<ValidationError>> {
        let mut errors = Vec::new();

        if chain.tasks.is_empty() {
            errors.push(ValidationError::new("Chain must contain at least one task"));
        }

        for task in &chain.tasks {
            if task.task.is_empty() {
                errors.push(ValidationError::new("Task name cannot be empty"));
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Validates a group workflow
    ///
    /// Checks for common issues in parallel task groups.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::workflow_validation::validate_group;
    /// use celers::Group;
    ///
    /// let group = Group::new()
    ///     .add("task1", vec![])
    ///     .add("task2", vec![]);
    ///
    /// validate_group(&group)?;
    /// ```
    pub fn validate_group(group: &Group) -> Result<(), Vec<ValidationError>> {
        let mut errors = Vec::new();

        if group.tasks.is_empty() {
            errors.push(ValidationError::new("Group must contain at least one task"));
        }

        for task in &group.tasks {
            if task.task.is_empty() {
                errors.push(ValidationError::new("Task name cannot be empty"));
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Validates a chord workflow
    ///
    /// Checks that both header and body are properly configured.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::workflow_validation::validate_chord;
    /// use celers::{Chord, Group, Signature};
    ///
    /// let chord = Chord {
    ///     header: Group::new().add("task1", vec![]),
    ///     body: Signature::new("callback".to_string()),
    /// };
    ///
    /// validate_chord(&chord)?;
    /// ```
    pub fn validate_chord(chord: &Chord) -> Result<(), Vec<ValidationError>> {
        let mut errors = Vec::new();

        // Validate header group
        if let Err(mut group_errors) = validate_group(&chord.header) {
            errors.append(&mut group_errors);
        }

        // Validate body callback
        if chord.body.task.is_empty() {
            errors.push(ValidationError::with_task(
                "Callback task name cannot be empty",
                "body",
            ));
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Checks if a workflow is likely to cause performance issues
    ///
    /// Warns about potentially problematic configurations.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::workflow_validation::check_performance_concerns;
    /// use celers::Group;
    ///
    /// let large_group = Group::new();
    /// for i in 0..1000 {
    ///     large_group.add(&format!("task_{}", i), vec![]);
    /// }
    ///
    /// if let Some(warnings) = check_performance_concerns_group(&large_group) {
    ///     for warning in warnings {
    ///         println!("Warning: {}", warning);
    ///     }
    /// }
    /// ```
    pub fn check_performance_concerns_group(group: &Group) -> Option<Vec<String>> {
        let mut warnings = Vec::new();

        if group.tasks.len() > 100 {
            warnings.push(format!(
                "Group contains {} tasks, which may cause performance issues. Consider batching.",
                group.tasks.len()
            ));
        }

        if warnings.is_empty() {
            None
        } else {
            Some(warnings)
        }
    }

    /// Checks chain for performance concerns
    pub fn check_performance_concerns_chain(chain: &Chain) -> Option<Vec<String>> {
        let mut warnings = Vec::new();

        if chain.tasks.len() > 50 {
            warnings.push(format!(
                "Chain contains {} sequential tasks, which may cause long latency. Consider parallelizing.",
                chain.tasks.len()
            ));
        }

        if warnings.is_empty() {
            None
        } else {
            Some(warnings)
        }
    }
}

/// Result aggregation helpers for working with task results
///
/// This module provides utilities for collecting, transforming, and
/// aggregating results from multiple tasks.
///
/// # Example
///
/// ```rust,ignore
/// use celers::result_helpers::*;
///
/// // Helper for creating result collection tasks
/// let collector = create_result_collector("process_batch", 10);
/// ```
pub mod result_helpers {
    use crate::Signature;
    use serde_json::Value;

    /// Creates a signature for collecting results from multiple tasks
    ///
    /// Useful for aggregating results in map-reduce patterns.
    ///
    /// # Arguments
    ///
    /// * `collector_task` - Name of the task that collects results
    /// * `expected_count` - Expected number of results to collect
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::result_helpers::create_result_collector;
    ///
    /// let collector = create_result_collector("aggregate_results", 100);
    /// ```
    pub fn create_result_collector(collector_task: &str, expected_count: usize) -> Signature {
        let mut sig =
            Signature::new(collector_task.to_string()).with_args(vec![serde_json::json!({
                "expected_count": expected_count
            })]);
        sig.options.time_limit = Some(300); // 5 minute timeout for collection
        sig
    }

    /// Creates a task that filters results based on criteria
    ///
    /// # Arguments
    ///
    /// * `filter_task` - Name of the filtering task
    /// * `criteria` - Filtering criteria as JSON value
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::result_helpers::create_result_filter;
    /// use serde_json::json;
    ///
    /// let filter = create_result_filter(
    ///     "filter_successful",
    ///     json!({"status": "success"})
    /// );
    /// ```
    pub fn create_result_filter(filter_task: &str, criteria: Value) -> Signature {
        Signature::new(filter_task.to_string()).with_args(vec![criteria])
    }

    /// Creates a task for transforming result data
    ///
    /// # Arguments
    ///
    /// * `transform_task` - Name of the transformation task
    /// * `transformation_config` - Configuration for the transformation
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::result_helpers::create_result_transformer;
    /// use serde_json::json;
    ///
    /// let transformer = create_result_transformer(
    ///     "format_results",
    ///     json!({"format": "csv", "include_headers": true})
    /// );
    /// ```
    pub fn create_result_transformer(
        transform_task: &str,
        transformation_config: Value,
    ) -> Signature {
        Signature::new(transform_task.to_string()).with_args(vec![transformation_config])
    }

    /// Creates a task for reducing/aggregating multiple results
    ///
    /// # Arguments
    ///
    /// * `reduce_task` - Name of the reduce task
    /// * `operation` - Type of reduction operation (e.g., "sum", "average", "concat")
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::result_helpers::create_result_reducer;
    ///
    /// let reducer = create_result_reducer("sum_results", "sum");
    /// ```
    pub fn create_result_reducer(reduce_task: &str, operation: &str) -> Signature {
        Signature::new(reduce_task.to_string()).with_args(vec![serde_json::json!({
            "operation": operation
        })])
    }
}

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

    #[test]
    fn test_facade_exports() {
        // Verify main types are exported
        let _: Option<Box<dyn Broker>> = None;
    }

    #[test]
    fn test_config_validation() {
        use crate::config_validation::*;

        // Test worker config validation
        let result = validate_worker_config(Some(4), Some(10));
        assert!(result.is_ok());

        let result = validate_worker_config(Some(0), Some(10));
        assert!(result.is_err());

        let result = validate_worker_config(Some(4), Some(0));
        assert!(result.is_err());

        // Test broker URL validation
        let result = validate_broker_url("redis://localhost:6379");
        assert!(result.is_ok());

        let result = validate_broker_url("invalid");
        assert!(result.is_err());

        let result = validate_broker_url("");
        assert!(result.is_err());

        // Test feature compatibility
        let result = check_feature_compatibility(&["redis", "postgres"]);
        assert!(result.is_ok());
        assert!(!result.unwrap().is_empty()); // Should have warnings
    }

    #[test]
    #[cfg(feature = "redis")]
    fn test_redis_broker_export() {
        // Verify Redis broker is available when feature is enabled
        use crate::RedisBroker;
        let _: Option<RedisBroker> = None;
    }

    #[test]
    #[cfg(feature = "postgres")]
    fn test_postgres_broker_export() {
        // Verify PostgreSQL broker is available when feature is enabled
        use crate::PostgresBroker;
        let _: Option<PostgresBroker> = None;
    }

    #[test]
    #[cfg(feature = "mysql")]
    fn test_mysql_broker_export() {
        // Verify MySQL broker is available when feature is enabled
        use crate::MysqlBroker;
        let _: Option<MysqlBroker> = None;
    }

    #[test]
    #[cfg(feature = "amqp")]
    fn test_amqp_broker_export() {
        // Verify AMQP broker is available when feature is enabled
        use crate::AmqpBroker;
        let _: Option<AmqpBroker> = None;
    }

    #[test]
    #[cfg(feature = "sqs")]
    fn test_sqs_broker_export() {
        // Verify SQS broker is available when feature is enabled
        use crate::SqsBroker;
        let _: Option<SqsBroker> = None;
    }

    #[test]
    #[cfg(feature = "backend-redis")]
    fn test_redis_backend_export() {
        // Verify Redis backend is available when feature is enabled
        use crate::RedisResultBackend;
        let _: Option<RedisResultBackend> = None;
    }

    #[test]
    #[cfg(feature = "backend-db")]
    fn test_db_backend_export() {
        // Verify database backends are available when feature is enabled
        use crate::{MysqlResultBackend, PostgresResultBackend};
        let _: Option<PostgresResultBackend> = None;
        let _: Option<MysqlResultBackend> = None;
    }

    #[test]
    #[cfg(feature = "backend-rpc")]
    fn test_rpc_backend_export() {
        // Verify gRPC backend is available when feature is enabled
        use crate::GrpcResultBackend;
        let _: Option<GrpcResultBackend> = None;
    }

    #[test]
    #[cfg(feature = "beat")]
    fn test_beat_export() {
        // Verify beat scheduler is available when feature is enabled
        use crate::BeatScheduler;
        let _: Option<BeatScheduler> = None;
    }

    #[test]
    #[cfg(feature = "metrics")]
    #[allow(unused_imports)]
    fn test_metrics_export() {
        // Verify metrics functions are available when feature is enabled
        use crate::{gather_metrics, reset_metrics};
    }

    #[test]
    #[cfg(feature = "tracing")]
    #[allow(unused_imports)]
    fn test_tracing_export() {
        // Verify tracing functions are available when feature is enabled
        use crate::tracing::{init_tracing, task_span};
    }

    #[test]
    fn test_prelude_imports() {
        // Verify prelude imports work
        use crate::prelude::*;

        // Should be able to use common types
        let _: Option<Box<dyn Broker>> = None;
        let _: Option<SerializedTask> = None;
        let _: Option<TaskState> = None;
    }

    #[tokio::test]
    async fn test_mock_broker() {
        use crate::dev_utils::{create_test_task, MockBroker};
        use crate::Broker;

        let broker = MockBroker::new();
        assert_eq!(broker.queue_len(), 0);

        // Test enqueue
        let task = create_test_task("test.task");
        let task_id = broker.enqueue(task.clone()).await.unwrap();
        assert_eq!(task_id, task.metadata.id);

        assert_eq!(broker.queue_len(), 1);
        assert_eq!(broker.published_tasks().len(), 1);

        // Test dequeue
        let consumed = broker.dequeue().await.unwrap();
        assert!(consumed.is_some());

        let consumed_msg = consumed.unwrap();
        assert_eq!(consumed_msg.task.metadata.name, "test.task");

        assert_eq!(broker.queue_len(), 0);

        // Test clear
        broker.enqueue(task.clone()).await.unwrap();
        broker.clear();
        assert_eq!(broker.queue_len(), 0);
        assert_eq!(broker.published_tasks().len(), 0);
    }

    #[test]
    fn test_task_builder() {
        use crate::dev_utils::TaskBuilder;

        let task = TaskBuilder::new("my.task")
            .id("550e8400-e29b-41d4-a716-446655440000".to_string())
            .max_retries(3)
            .build();

        assert_eq!(task.metadata.name, "my.task");
        assert_eq!(
            task.metadata.id.to_string(),
            "550e8400-e29b-41d4-a716-446655440000"
        );
        assert_eq!(task.metadata.max_retries, 3);
    }

    #[test]
    fn test_compile_time_validation() {
        use crate::compile_time_validation::*;

        // Test that feature validation functions are callable
        assert!(has_broker_feature());
        assert!(has_serialization_feature());
        assert!(count_broker_features() > 0);

        // Test feature summary
        let summary = feature_summary();
        assert!(summary.contains("CeleRS Configuration:"));
        assert!(summary.contains("Brokers"));
        assert!(summary.contains("Backends"));
        assert!(summary.contains("Formats"));
    }

    // Integration tests for all broker types
    #[cfg(all(test, feature = "redis"))]
    mod redis_integration {
        use super::*;

        #[tokio::test]
        #[ignore = "requires Redis server"]
        async fn test_redis_broker_integration() {
            use crate::RedisBroker;

            // This test requires a running Redis server
            let broker_result = RedisBroker::new("redis://localhost:6379", "test_queue");

            if let Ok(broker) = broker_result {
                let task = crate::dev_utils::create_test_task("redis.test");
                let result = broker.enqueue(task).await;
                assert!(result.is_ok());
            }
        }
    }

    #[cfg(all(test, feature = "postgres"))]
    mod postgres_integration {
        use super::*;

        #[tokio::test]
        #[ignore = "requires PostgreSQL server"]
        async fn test_postgres_broker_integration() {
            use crate::PostgresBroker;

            // This test requires a running PostgreSQL server
            let broker_result =
                PostgresBroker::with_queue("postgres://localhost/test", "test_queue").await;

            if let Ok(broker) = broker_result {
                let task = crate::dev_utils::create_test_task("postgres.test");
                let result = broker.enqueue(task).await;
                assert!(result.is_ok());
            }
        }
    }

    #[cfg(all(test, feature = "mysql"))]
    mod mysql_integration {
        use super::*;

        #[tokio::test]
        #[ignore = "requires MySQL server"]
        async fn test_mysql_broker_integration() {
            use crate::MysqlBroker;

            // This test requires a running MySQL server
            let broker_result =
                MysqlBroker::with_queue("mysql://localhost/test", "test_queue").await;

            if let Ok(broker) = broker_result {
                let task = crate::dev_utils::create_test_task("mysql.test");
                let result = broker.enqueue(task).await;
                assert!(result.is_ok());
            }
        }
    }

    #[cfg(all(test, feature = "amqp"))]
    mod amqp_integration {
        #[allow(unused_imports)]
        use super::*;

        #[tokio::test]
        #[ignore = "requires RabbitMQ server"]
        async fn test_amqp_broker_integration() {
            use crate::AmqpBroker;

            // This test requires a running RabbitMQ server
            let broker_result = AmqpBroker::new("amqp://localhost:5672", "test_queue").await;

            // Just verify broker creation succeeds
            assert!(broker_result.is_ok());
        }
    }

    #[cfg(all(test, feature = "sqs"))]
    mod sqs_integration {
        #[allow(unused_imports)]
        use super::*;

        #[tokio::test]
        #[ignore = "requires AWS SQS"]
        async fn test_sqs_broker_integration() {
            use crate::SqsBroker;

            // This test requires AWS SQS access
            // SqsBroker::new takes only queue_name; AWS config comes from environment
            let broker_result = SqsBroker::new("test-queue").await;

            // Just verify broker creation succeeds
            assert!(broker_result.is_ok());
        }
    }

    // Backend integration tests
    #[cfg(all(test, feature = "backend-redis"))]
    mod backend_redis_integration {
        #[allow(unused_imports)]
        use super::*;

        #[tokio::test]
        #[ignore = "requires Redis server"]
        async fn test_redis_backend_integration() {
            use crate::RedisResultBackend;
            use celers_core::TaskResultValue;

            let backend_result = RedisResultBackend::new("redis://localhost:6379");

            if let Ok(backend) = backend_result {
                use crate::ResultStore;
                use uuid::Uuid;
                let task_id = Uuid::new_v4();
                let result = backend
                    .store_result(
                        task_id,
                        TaskResultValue::Success(serde_json::json!({"result": "success"})),
                    )
                    .await;
                assert!(result.is_ok());
            }
        }
    }

    #[cfg(all(test, feature = "backend-db"))]
    mod backend_db_integration {
        #[allow(unused_imports)]
        use super::*;

        #[tokio::test]
        #[ignore = "requires PostgreSQL server"]
        async fn test_postgres_backend_integration() {
            use crate::PostgresResultBackend;
            use celers_core::TaskResultValue;

            let backend_result = PostgresResultBackend::new("postgres://localhost/test").await;

            if let Ok(backend) = backend_result {
                use crate::ResultStore;
                use uuid::Uuid;
                let task_id = Uuid::new_v4();
                let result = backend
                    .store_result(
                        task_id,
                        TaskResultValue::Success(serde_json::json!({"result": "success"})),
                    )
                    .await;
                assert!(result.is_ok());
            }
        }

        #[tokio::test]
        #[ignore = "requires MySQL server"]
        async fn test_mysql_backend_integration() {
            use crate::MysqlResultBackend;
            use celers_core::TaskResultValue;

            let backend_result = MysqlResultBackend::new("mysql://localhost/test").await;

            if let Ok(backend) = backend_result {
                use crate::ResultStore;
                use uuid::Uuid;
                let task_id = Uuid::new_v4();
                let result = backend
                    .store_result(
                        task_id,
                        TaskResultValue::Success(serde_json::json!({"result": "success"})),
                    )
                    .await;
                assert!(result.is_ok());
            }
        }
    }

    #[cfg(all(test, feature = "beat"))]
    mod beat_integration {
        #[allow(unused_imports)]
        use super::*;

        #[tokio::test]
        #[ignore = "requires broker server"]
        async fn test_beat_scheduler_integration() {
            use crate::BeatScheduler;

            // Create a simple scheduler (no broker needed in constructor)
            let scheduler = BeatScheduler::new();

            // Verify scheduler was created by checking it has expected methods
            assert!(scheduler.list_tasks().is_empty());
        }
    }

    // Workflow integration tests
    #[test]
    fn test_workflow_chain() {
        use crate::canvas::Chain;

        let chain = Chain::new()
            .then("task1", vec![])
            .then("task2", vec![])
            .then("task3", vec![]);

        // Verify chain structure
        assert!(!chain.tasks.is_empty());
    }

    #[test]
    fn test_workflow_group() {
        use crate::canvas::Group;

        let group = Group::new()
            .add("task1", vec![])
            .add("task2", vec![])
            .add("task3", vec![]);

        // Verify group structure
        assert!(!group.tasks.is_empty());
    }

    #[test]
    fn test_workflow_chord() {
        use crate::canvas::{Chord, Group, Signature};

        let header = Group::new().add("task1", vec![]).add("task2", vec![]);

        let callback = Signature::new("callback".to_string());

        let chord = Chord::new(header, callback);

        // Verify chord structure
        assert!(!chord.header.tasks.is_empty());
    }

    // Performance and benchmarking tests
    #[test]
    fn test_task_creation_performance() {
        use crate::dev_utils::TaskBuilder;
        use std::time::Instant;

        let start = Instant::now();
        for i in 0..1000 {
            let _task = TaskBuilder::new(&format!("task.{}", i)).build();
        }
        let duration = start.elapsed();

        // Should be able to create 1000 tasks quickly (< 100ms)
        assert!(duration.as_millis() < 100);
    }

    #[test]
    fn test_broker_helper_functions() {
        use crate::broker_helper::BrokerConfigError;

        // Test error types
        let error = BrokerConfigError::MissingEnvVar("TEST".to_string());
        assert!(error.to_string().contains("TEST"));

        let error = BrokerConfigError::UnsupportedBrokerType {
            broker_type: "foo".to_string(),
            note: "bar".to_string(),
        };
        assert!(error.to_string().contains("foo"));

        let error = BrokerConfigError::FeatureNotEnabled {
            feature: "redis".to_string(),
        };
        assert!(error.to_string().contains("redis"));
    }

    // Configuration validation tests
    #[test]
    fn test_presets_exist() {
        use crate::presets::*;

        // Test that all presets are available
        let _config = production_config();
        let _config = high_throughput_config();
        let _config = low_latency_config();
        let _config = memory_constrained_config();
    }

    // Zero-cost abstractions verification tests
    #[test]
    fn test_zero_cost_task_creation() {
        use crate::dev_utils::TaskBuilder;
        use std::time::Instant;

        // Measure overhead of task creation
        let start = Instant::now();
        for _ in 0..10000 {
            let _task = TaskBuilder::new("test.task").build();
        }
        let duration = start.elapsed();

        // Should be fast - less than 50ms for 10k tasks (debug mode is slower)
        assert!(
            duration.as_millis() < 50,
            "Task creation overhead too high: {}ms",
            duration.as_millis()
        );
    }

    #[test]
    fn test_zero_cost_workflow_construction() {
        use crate::canvas::{Chain, Group};
        use std::time::Instant;

        // Measure overhead of workflow construction
        let start = Instant::now();
        for _ in 0..1000 {
            let _chain = Chain::new()
                .then("task1", vec![])
                .then("task2", vec![])
                .then("task3", vec![]);

            let _group = Group::new()
                .add("task1", vec![])
                .add("task2", vec![])
                .add("task3", vec![]);
        }
        let duration = start.elapsed();

        // Should be very fast - less than 50ms for 1k workflows in debug builds
        assert!(
            duration.as_millis() < 50,
            "Workflow construction overhead too high: {}ms",
            duration.as_millis()
        );
    }

    #[test]
    fn test_feature_validation_overhead() {
        use crate::compile_time_validation::*;
        use std::time::Instant;

        // Measure overhead of feature validation functions
        let start = Instant::now();
        for _ in 0..100000 {
            let _ = has_broker_feature();
            let _ = has_serialization_feature();
            let _ = count_broker_features();
            let _ = count_backend_features();
        }
        let duration = start.elapsed();

        // Const functions should have near-zero overhead
        assert!(
            duration.as_millis() < 10,
            "Feature validation overhead too high: {}ms",
            duration.as_millis()
        );
    }

    #[test]
    fn test_memory_efficiency() {
        use crate::dev_utils::TaskBuilder;

        // Measure memory footprint of tasks
        let tasks: Vec<_> = (0..1000)
            .map(|i| TaskBuilder::new(&format!("task{}", i)).build())
            .collect();

        // Verify tasks are created
        assert_eq!(tasks.len(), 1000);

        // Memory usage should be reasonable
        let estimated_size_per_task = std::mem::size_of_val(&tasks[0]);
        assert!(
            estimated_size_per_task < 1024,
            "Task size too large: {} bytes",
            estimated_size_per_task
        );
    }

    #[test]
    fn test_inline_optimization_candidates() {
        use crate::compile_time_validation::*;

        // Test that inline functions are small enough to be inlined
        assert!(has_broker_feature() || !has_broker_feature()); // Should be optimized to const
        assert!(has_serialization_feature() || !has_serialization_feature());
        // Should be optimized to const
    }

    // Performance regression tests with baseline tracking
    #[test]
    fn test_performance_regression_task_creation() {
        use crate::dev_utils::TaskBuilder;
        use std::time::Instant;

        // Baseline adjusted for debug builds (debug builds are ~10x slower than release)
        const BASELINE_MS: u128 = 100; // Baseline: 100ms for 10k tasks in debug
        const ITERATIONS: usize = 10000;

        let start = Instant::now();
        for i in 0..ITERATIONS {
            let _task = TaskBuilder::new(&format!("task.{}", i)).build();
        }
        let duration = start.elapsed();

        // Alert if performance regresses by more than 50%
        assert!(
            duration.as_millis() < BASELINE_MS * 3 / 2,
            "Performance regression detected: {}ms (baseline: {}ms) for {} tasks",
            duration.as_millis(),
            BASELINE_MS,
            ITERATIONS
        );
    }

    #[test]
    fn test_performance_regression_workflow_construction() {
        use crate::canvas::{Chain, Group};
        use std::time::Instant;

        const BASELINE_MS: u128 = 50; // Baseline: 50ms for 1k workflows (adjusted for debug builds)
        const ITERATIONS: usize = 1000;

        let start = Instant::now();
        for _ in 0..ITERATIONS {
            let _chain = Chain::new()
                .then("task1", vec![])
                .then("task2", vec![])
                .then("task3", vec![]);

            let _group = Group::new()
                .add("task1", vec![])
                .add("task2", vec![])
                .add("task3", vec![]);
        }
        let duration = start.elapsed();

        // Alert if performance regresses by more than 50%
        assert!(
            duration.as_millis() < BASELINE_MS * 3 / 2,
            "Performance regression detected: {}ms (baseline: {}ms) for {} workflows",
            duration.as_millis(),
            BASELINE_MS,
            ITERATIONS
        );
    }

    #[test]
    fn test_performance_regression_serialization() {
        use crate::dev_utils::TaskBuilder;
        use std::time::Instant;

        const BASELINE_MS: u128 = 50; // Baseline: 50ms for 1k serializations
        const ITERATIONS: usize = 1000;

        let tasks: Vec<_> = (0..ITERATIONS)
            .map(|i| TaskBuilder::new(&format!("task{}", i)).build())
            .collect();

        let start = Instant::now();
        for task in &tasks {
            let _serialized = serde_json::to_string(task).unwrap();
        }
        let duration = start.elapsed();

        // Alert if performance regresses by more than 50%
        assert!(
            duration.as_millis() < BASELINE_MS * 3 / 2,
            "Performance regression detected: {}ms (baseline: {}ms) for {} serializations",
            duration.as_millis(),
            BASELINE_MS,
            ITERATIONS
        );
    }

    #[test]
    fn test_performance_regression_config_validation() {
        use crate::config_validation::*;
        use std::time::Instant;

        const BASELINE_MS: u128 = 100; // Baseline: 100ms for 10k validations (adjusted for debug builds)
        const ITERATIONS: usize = 10000;

        let start = Instant::now();
        for _ in 0..ITERATIONS {
            let _ = validate_worker_config(Some(4), Some(10));
            let _ = validate_broker_url("redis://localhost:6379");
        }
        let duration = start.elapsed();

        // Alert if performance regresses by more than 50%
        assert!(
            duration.as_millis() < BASELINE_MS * 3 / 2,
            "Performance regression detected: {}ms (baseline: {}ms) for {} validations",
            duration.as_millis(),
            BASELINE_MS,
            ITERATIONS
        );
    }

    // Startup optimization tests
    #[test]
    fn test_lazy_init() {
        use crate::startup_optimization::LazyInit;

        static COUNTER: LazyInit<usize> = LazyInit::new();

        // First access initializes
        let value = COUNTER.get_or_init(|| 42);
        assert_eq!(*value, 42);

        // Second access returns the same value
        let value2 = COUNTER.get_or_init(|| 100);
        assert_eq!(*value2, 42); // Should still be 42, not 100
    }

    #[test]
    fn test_startup_metrics() {
        use crate::startup_optimization::StartupMetrics;

        let mut metrics = StartupMetrics::new();
        metrics.broker_init_ms = 100;
        metrics.config_load_ms = 50;
        metrics.backend_init_ms = 75;
        metrics.total_ms = 225;

        let report = metrics.report();
        assert!(report.contains("100ms"));
        assert!(report.contains("50ms"));
        assert!(report.contains("75ms"));
        assert!(report.contains("225ms"));
    }

    #[test]
    fn test_startup_metrics_default() {
        use crate::startup_optimization::StartupMetrics;

        let metrics = StartupMetrics::default();
        assert_eq!(metrics.broker_init_ms, 0);
        assert_eq!(metrics.config_load_ms, 0);
        assert_eq!(metrics.backend_init_ms, 0);
        assert_eq!(metrics.total_ms, 0);
    }

    #[tokio::test]
    async fn test_parallel_init() {
        use crate::startup_optimization::{parallel_init, AsyncInitTask};
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;

        let counter = Arc::new(AtomicUsize::new(0));

        type TestResult = std::result::Result<(), String>;
        let tasks: Vec<AsyncInitTask<(), String>> = vec![
            {
                let counter = counter.clone();
                Box::new(move || {
                    Box::pin(async move {
                        counter.fetch_add(1, Ordering::SeqCst);
                        Ok(())
                    })
                        as std::pin::Pin<Box<dyn std::future::Future<Output = TestResult> + Send>>
                })
            },
            {
                let counter = counter.clone();
                Box::new(move || {
                    Box::pin(async move {
                        counter.fetch_add(1, Ordering::SeqCst);
                        Ok(())
                    })
                        as std::pin::Pin<Box<dyn std::future::Future<Output = TestResult> + Send>>
                })
            },
            {
                let counter = counter.clone();
                Box::new(move || {
                    Box::pin(async move {
                        counter.fetch_add(1, Ordering::SeqCst);
                        Ok(())
                    })
                        as std::pin::Pin<Box<dyn std::future::Future<Output = TestResult> + Send>>
                })
            },
        ];

        let results = parallel_init(tasks).await;
        assert_eq!(results.len(), 3);
        assert_eq!(counter.load(Ordering::SeqCst), 3);
    }

    // IDE support tests
    #[test]
    fn test_ide_support_type_aliases() {
        use crate::ide_support::*;

        // Test BoxedResult compiles
        let _result: BoxedResult<i32> = Ok(42);

        // Test type aliases are accessible
        let _broker: Option<BoxedBroker> = None;
        let _task: Option<QueueTask> = None;
    }

    #[test]
    fn test_ide_support_defaults() {
        use crate::ide_support::defaults::*;

        // Verify default constants
        assert_eq!(DEFAULT_CONCURRENCY, 4);
        assert_eq!(DEFAULT_PREFETCH, 10);
        assert_eq!(DEFAULT_MAX_RETRIES, 3);
        assert_eq!(DEFAULT_RETRY_DELAY_SECS, 60);
        assert_eq!(DEFAULT_TASK_TIMEOUT_SECS, 3600);
        assert_eq!(DEFAULT_REDIS_PORT, 6379);
        assert_eq!(DEFAULT_POSTGRES_PORT, 5432);
        assert_eq!(DEFAULT_MYSQL_PORT, 3306);
        assert_eq!(DEFAULT_RABBITMQ_PORT, 5672);
        assert_eq!(DEFAULT_QUEUE_NAME, "celery");
    }

    #[test]
    fn test_ide_support_examples() {
        use crate::ide_support::examples::*;

        // Verify example constants are valid
        assert!(REDIS_URL_EXAMPLE.starts_with("redis://"));
        assert!(POSTGRES_URL_EXAMPLE.starts_with("postgres://"));
        assert!(MYSQL_URL_EXAMPLE.starts_with("mysql://"));
        assert!(RABBITMQ_URL_EXAMPLE.starts_with("amqp://"));
        assert!(SQS_URL_EXAMPLE.starts_with("https://sqs"));
    }

    #[test]
    fn test_ide_support_trait_bounds() {
        use crate::ide_support::{TaskArgs, TaskResult};

        // Test that common types implement the trait bounds
        fn assert_task_args<T: TaskArgs>() {}
        fn assert_task_result<T: TaskResult>() {}

        assert_task_args::<String>();
        assert_task_args::<i32>();
        assert_task_args::<Vec<u8>>();

        assert_task_result::<String>();
        assert_task_result::<i32>();
        assert_task_result::<Vec<u8>>();
    }

    #[tokio::test]
    async fn test_ide_support_boxed_future() {
        use crate::ide_support::{BoxedFuture, BoxedResult};

        fn create_future() -> BoxedFuture<String> {
            Box::pin(async { Ok("test".to_string()) })
        }

        let result: BoxedResult<String> = create_future().await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "test");
    }

    #[test]
    #[cfg(feature = "dev-utils")]
    fn test_assembly_inspection_count_instructions() {
        use crate::assembly_inspection::count_instructions;

        let sample_asm = r#"
            ; Function prologue
            push   rbp
            mov    rbp, rsp
            ; Actual code
            add    rdi, rsi
            mov    rax, rdi
            ; Function epilogue
            pop    rbp
            ret
        "#;

        let count = count_instructions(sample_asm);
        assert_eq!(count, 6); // Should count 6 actual instructions (push, mov, add, mov, pop, ret)
    }

    #[test]
    #[cfg(feature = "dev-utils")]
    fn test_assembly_inspection_verify_inlined() {
        use crate::assembly_inspection::verify_inlined;

        // Well-inlined function (no calls)
        let inlined_asm = r#"
            add    rdi, rsi
            mov    rax, rdi
            ret
        "#;
        assert!(verify_inlined(inlined_asm));

        // Not inlined (has call instruction)
        let not_inlined_asm = r#"
            push   rbp
            call   some_function
            call   another_function
            pop    rbp
            ret
        "#;
        assert!(!verify_inlined(not_inlined_asm));
    }

    // Convenience functions tests
    #[test]
    fn test_convenience_chunks() {
        use crate::convenience::chunks;
        use serde_json::json;

        let items = vec![json!(1), json!(2), json!(3), json!(4), json!(5)];
        let workflow = chunks("process_item", items, 2);

        assert_eq!(workflow.task.task, "process_item");
        assert_eq!(workflow.items.len(), 5);
        assert_eq!(workflow.chunk_size, 2);
    }

    #[test]
    fn test_convenience_map() {
        use crate::convenience::map;
        use serde_json::json;

        let items = vec![json!(1), json!(2), json!(3)];
        let workflow = map("square", items);

        assert_eq!(workflow.task.task, "square");
        assert_eq!(workflow.argsets.len(), 3);
    }

    #[test]
    fn test_convenience_starmap() {
        use crate::convenience::starmap;
        use serde_json::json;

        let args = vec![vec![json!(1), json!(2)], vec![json!(3), json!(4)]];
        let workflow = starmap("add", args);

        assert_eq!(workflow.task.task, "add");
        assert_eq!(workflow.argsets.len(), 2);
        assert_eq!(workflow.argsets[0].len(), 2);
    }

    #[test]
    fn test_convenience_options() {
        use crate::convenience::options;

        let opts = options();
        // Just verify it creates TaskOptions successfully
        assert!(opts.max_retries.is_none());
    }

    #[test]
    fn test_convenience_with_retry() {
        use crate::convenience::with_retry;

        let opts = with_retry(5, 60);
        assert_eq!(opts.max_retries, Some(5));
        assert_eq!(opts.countdown, Some(60));
    }

    #[test]
    fn test_convenience_with_timeout() {
        use crate::convenience::with_timeout;

        let opts = with_timeout(300);
        assert_eq!(opts.time_limit, Some(300));
    }

    #[test]
    fn test_convenience_with_priority() {
        use crate::convenience::with_priority;

        let opts = with_priority(9);
        assert_eq!(opts.priority, Some(9));
    }

    #[test]
    fn test_convenience_with_countdown() {
        use crate::convenience::with_countdown;

        let opts = with_countdown(60);
        assert_eq!(opts.countdown, Some(60));
    }

    #[test]
    fn test_convenience_with_expires() {
        use crate::convenience::with_expires;

        let opts = with_expires(7200);
        assert_eq!(opts.expires, Some(7200));
    }

    #[test]
    fn test_convenience_batch() {
        use crate::convenience::batch;
        use serde_json::json;

        let args_list = vec![
            vec![json!(1), json!(2)],
            vec![json!(3), json!(4)],
            vec![json!(5), json!(6)],
        ];
        let tasks = batch("add", args_list);

        assert_eq!(tasks.len(), 3);
        assert_eq!(tasks[0].task, "add");
        assert_eq!(tasks[1].task, "add");
        assert_eq!(tasks[2].task, "add");
    }

    #[test]
    #[cfg(feature = "redis")]
    fn test_quick_start_redis_broker() {
        use crate::quick_start::redis_broker;

        // Test that the function creates a broker with proper URL handling
        let result = redis_broker("localhost:6379", "test_queue");
        assert!(result.is_ok() || result.is_err()); // Will fail to connect but should parse
    }

    #[test]
    #[cfg(feature = "mysql")]
    fn test_quick_start_mysql_broker_function_exists() {
        // Just verify the function compiles and is available
        // Actual connection test would require a running MySQL server
        use crate::quick_start::mysql_broker;
        // mysql_broker is an async function, just verify it exists
        let _ = mysql_broker;
    }

    #[test]
    #[cfg(feature = "amqp")]
    fn test_quick_start_amqp_broker_function_exists() {
        // Just verify the function compiles and is available
        use crate::quick_start::amqp_broker;
        // amqp_broker is an async function, just verify it exists
        let _ = amqp_broker;
    }

    #[test]
    #[cfg(feature = "sqs")]
    fn test_quick_start_sqs_broker_function_exists() {
        // Just verify the function compiles and is available
        use crate::quick_start::sqs_broker;
        // sqs_broker is an async function that takes only queue name, just verify it exists
        let _ = sqs_broker;
    }

    #[test]
    fn test_ide_support_additional_type_aliases() {
        use crate::ide_support::{TaskId, WorkerStats};

        // Verify type aliases are usable
        let _task_id: TaskId = uuid::Uuid::new_v4();

        // Test that WorkerStats type alias works
        fn accepts_worker_stats(_stats: &WorkerStats) {}
        let stats = WorkerStats {
            total_tasks: 0,
            active_tasks: 0,
            succeeded: 0,
            failed: 0,
            retried: 0,
            uptime: 0.0,
            loadavg: None,
            memory_usage: None,
            pool: None,
            broker: None,
            clock: None,
        };
        accepts_worker_stats(&stats);
    }

    // Tests for new convenience functions
    #[test]
    fn test_convenience_delay() {
        use crate::convenience::delay;
        use serde_json::json;

        let sig = delay("send_email", vec![json!("user@example.com")], 60);
        assert_eq!(sig.task, "send_email");
        assert_eq!(sig.options.countdown, Some(60));
        assert_eq!(sig.args.len(), 1);
    }

    #[test]
    fn test_convenience_expire_in() {
        use crate::convenience::expire_in;
        use serde_json::json;

        let sig = expire_in("process_data", vec![json!({"id": 123})], 7200);
        assert_eq!(sig.task, "process_data");
        assert_eq!(sig.options.expires, Some(7200));
        assert_eq!(sig.args.len(), 1);
    }

    #[test]
    fn test_convenience_high_priority() {
        use crate::convenience::high_priority;
        use serde_json::json;

        let sig = high_priority("urgent_task", vec![json!({"alert": true})]);
        assert_eq!(sig.task, "urgent_task");
        assert_eq!(sig.options.priority, Some(9));
    }

    #[test]
    fn test_convenience_low_priority() {
        use crate::convenience::low_priority;
        use serde_json::json;

        let sig = low_priority("background_cleanup", vec![json!({})]);
        assert_eq!(sig.task, "background_cleanup");
        assert_eq!(sig.options.priority, Some(1));
    }

    #[test]
    fn test_convenience_parallel() {
        use crate::convenience::parallel;
        use serde_json::json;

        let workflow = parallel()
            .add("task1", vec![json!(1)])
            .add("task2", vec![json!(2)])
            .add("task3", vec![json!(3)]);

        assert_eq!(workflow.tasks.len(), 3);
    }

    // Tests for new worker presets
    #[test]
    fn test_presets_cpu_bound_config() {
        use crate::presets::cpu_bound_config;

        let config = cpu_bound_config();
        assert!(config.is_ok());
        let config = config.unwrap();
        assert_eq!(config.concurrency, num_cpus::get());
    }

    #[test]
    fn test_presets_io_bound_config() {
        use crate::presets::io_bound_config;

        let config = io_bound_config();
        assert!(config.is_ok());
        let config = config.unwrap();
        assert_eq!(config.concurrency, num_cpus::get() * 4);
    }

    #[test]
    fn test_presets_balanced_config() {
        use crate::presets::balanced_config;

        let config = balanced_config();
        assert!(config.is_ok());
        let config = config.unwrap();
        assert_eq!(config.concurrency, num_cpus::get() * 2);
    }

    #[test]
    fn test_presets_development_config() {
        use crate::presets::development_config;

        let config = development_config();
        assert!(config.is_ok());
        let config = config.unwrap();
        assert_eq!(config.concurrency, 2);
    }

    // Tests for new type aliases
    #[test]
    fn test_ide_support_new_type_aliases() {
        use crate::ide_support::{
            BrokerUrl, ConcurrencyLevel, PrefetchCount, PriorityLevel, QueueName, RetryCount,
            TaskName, TimeoutSeconds,
        };

        // Verify type aliases compile and work correctly
        let _queue: QueueName = "celery".to_string();
        let _url: BrokerUrl = "redis://localhost:6379".to_string();
        let _retries: RetryCount = 3;
        let _priority: PriorityLevel = 9;
        let _timeout: TimeoutSeconds = 300;
        let _task_name: TaskName = "my_task".to_string();
        let _concurrency: ConcurrencyLevel = 4;
        let _prefetch: PrefetchCount = 10;
    }

    // Tests for advanced convenience functions
    #[test]
    fn test_convenience_critical() {
        use crate::convenience::critical;
        use serde_json::json;

        let sig = critical("process_payment", vec![json!({"amount": 100})]);
        assert_eq!(sig.task, "process_payment");
        assert_eq!(sig.options.priority, Some(9));
        assert_eq!(sig.options.max_retries, Some(5));
    }

    #[test]
    fn test_convenience_best_effort() {
        use crate::convenience::best_effort;
        use serde_json::json;

        let sig = best_effort("update_cache", vec![json!({"key": "value"})]);
        assert_eq!(sig.task, "update_cache");
        assert_eq!(sig.options.priority, Some(1));
        assert_eq!(sig.options.max_retries, Some(0));
    }

    #[test]
    fn test_convenience_transient() {
        use crate::convenience::transient;
        use serde_json::json;

        let sig = transient("temp_notification", vec![json!({"msg": "hi"})], 300);
        assert_eq!(sig.task, "temp_notification");
        assert_eq!(sig.options.expires, Some(300));
    }

    #[test]
    fn test_convenience_retry_with_backoff() {
        use crate::convenience::retry_with_backoff;

        let opts = retry_with_backoff(5, 60);
        assert_eq!(opts.max_retries, Some(5));
        assert_eq!(opts.countdown, Some(60));
    }

    #[test]
    fn test_convenience_pipeline() {
        use crate::convenience::pipeline;
        use serde_json::json;

        let workflow = pipeline()
            .then("fetch_data", vec![json!(1)])
            .then("process_data", vec![json!(2)])
            .then("save_results", vec![json!(3)]);

        assert_eq!(workflow.tasks.len(), 3);
    }

    #[test]
    fn test_convenience_fan_out() {
        use crate::convenience::fan_out;
        use serde_json::json;

        let items = vec![json!(1), json!(2), json!(3)];
        let workflow = fan_out("process_item", items);

        assert_eq!(workflow.task.task, "process_item");
        assert_eq!(workflow.argsets.len(), 3);
    }

    #[test]
    fn test_convenience_fan_in() {
        use crate::convenience::{fan_in, parallel, task};
        use serde_json::json;

        let tasks = parallel()
            .add("task1", vec![json!(1)])
            .add("task2", vec![json!(2)]);

        let callback = task("aggregate_results");
        let workflow = fan_in(tasks, callback);

        assert_eq!(workflow.header.tasks.len(), 2);
        assert_eq!(workflow.body.task, "aggregate_results");
    }

    // Tests for workflow templates
    #[test]
    fn test_workflow_template_etl_pipeline() {
        use crate::workflow_templates::etl_pipeline;
        use serde_json::json;

        let pipeline = etl_pipeline(
            "extract",
            vec![json!({"source": "db"})],
            "transform",
            "load",
        );

        assert_eq!(pipeline.tasks.len(), 3);
        assert_eq!(pipeline.tasks[0].task, "extract");
        assert_eq!(pipeline.tasks[1].task, "transform");
        assert_eq!(pipeline.tasks[2].task, "load");
    }

    #[test]
    fn test_workflow_template_map_reduce() {
        use crate::workflow_templates::map_reduce_workflow;
        use serde_json::json;

        let workflow =
            map_reduce_workflow("process", vec![json!(1), json!(2), json!(3)], "aggregate");

        assert_eq!(workflow.header.tasks.len(), 3);
        assert_eq!(workflow.body.task, "aggregate");
    }

    #[test]
    fn test_workflow_template_scatter_gather() {
        use crate::workflow_templates::scatter_gather;
        use serde_json::json;

        let tasks = vec![
            ("task1", vec![json!(1)]),
            ("task2", vec![json!(2)]),
            ("task3", vec![json!(3)]),
        ];

        let workflow = scatter_gather(tasks, "gather");

        assert_eq!(workflow.header.tasks.len(), 3);
        assert_eq!(workflow.body.task, "gather");
    }

    #[test]
    fn test_workflow_template_batch_processing() {
        use crate::workflow_templates::batch_processing;
        use serde_json::json;

        let items: Vec<_> = (1..=25).map(|i| json!(i)).collect();
        let workflow = batch_processing("process_batch", items, 10, Some("aggregate"));

        // 25 items with batch_size 10 = 3 batches (10 + 10 + 5)
        assert_eq!(workflow.header.tasks.len(), 3);
        assert_eq!(workflow.body.task, "aggregate");
    }

    #[test]
    fn test_workflow_template_sequential_pipeline() {
        use crate::workflow_templates::sequential_pipeline;
        use serde_json::json;

        let stages = vec![
            ("stage1", vec![json!(1)], 3),
            ("stage2", vec![json!(2)], 5),
            ("stage3", vec![json!(3)], 2),
        ];

        let pipeline = sequential_pipeline(stages);

        assert_eq!(pipeline.tasks.len(), 3);
        assert_eq!(pipeline.tasks[0].options.max_retries, Some(3));
        assert_eq!(pipeline.tasks[1].options.max_retries, Some(5));
        assert_eq!(pipeline.tasks[2].options.max_retries, Some(2));
    }

    #[test]
    fn test_workflow_template_priority_workflow() {
        use crate::workflow_templates::priority_workflow;
        use serde_json::json;

        let tasks = vec![
            ("critical", vec![json!(1)], 9),
            ("normal", vec![json!(2)], 5),
            ("low", vec![json!(3)], 1),
        ];

        let workflow = priority_workflow(tasks);

        assert_eq!(workflow.tasks.len(), 3);
        assert_eq!(workflow.tasks[0].options.priority, Some(9));
        assert_eq!(workflow.tasks[1].options.priority, Some(5));
        assert_eq!(workflow.tasks[2].options.priority, Some(1));
    }

    // Tests for task composition
    #[test]
    fn test_task_composition_retry_wrapper() {
        use crate::task_composition::retry_wrapper;
        use serde_json::json;

        let sig = retry_wrapper("my_task", vec![json!(1)], 5, 10);

        assert_eq!(sig.task, "my_task");
        assert_eq!(sig.options.max_retries, Some(5));
        assert_eq!(sig.options.countdown, Some(10));
    }

    #[test]
    fn test_task_composition_timeout_wrapper() {
        use crate::task_composition::timeout_wrapper;
        use serde_json::json;

        let sig = timeout_wrapper("long_task", vec![json!(1)], 300);

        assert_eq!(sig.task, "long_task");
        assert_eq!(sig.options.time_limit, Some(300));
    }

    #[test]
    fn test_task_composition_circuit_breaker() {
        use crate::task_composition::circuit_breaker_group;
        use serde_json::json;

        let tasks = vec![("service_a", vec![json!(1)]), ("service_b", vec![json!(2)])];

        let group = circuit_breaker_group(tasks, 3);

        assert_eq!(group.tasks.len(), 2);
        assert_eq!(group.tasks[0].options.max_retries, Some(3));
        assert_eq!(group.tasks[1].options.max_retries, Some(3));
    }

    #[test]
    fn test_task_composition_rate_limited() {
        use crate::task_composition::rate_limited_workflow;
        use serde_json::json;

        let items = vec![json!(1), json!(2), json!(3)];
        let workflow = rate_limited_workflow("api_call", items, 5);

        assert_eq!(workflow.tasks.len(), 3);
        assert_eq!(workflow.tasks[0].options.countdown, None); // First task has no delay
        assert_eq!(workflow.tasks[1].options.countdown, Some(5)); // 5 seconds delay
        assert_eq!(workflow.tasks[2].options.countdown, Some(10)); // 10 seconds delay
    }

    // Tests for prelude exports of new modules
    #[test]
    fn test_prelude_workflow_templates() {
        use crate::prelude::*;
        use serde_json::json;

        // Test that workflow template functions are available from prelude
        let _pipeline = etl_pipeline("extract", vec![json!(1)], "transform", "load");
        let _map_reduce = map_reduce_workflow("map", vec![json!(1)], "reduce");
        let _scatter = scatter_gather(vec![("t1", vec![json!(1)])], "gather");
        let _batch = batch_processing("process", vec![json!(1)], 5, None);
        let _seq = sequential_pipeline(vec![("s1", vec![json!(1)], 3)]);
        let _priority = priority_workflow(vec![("t1", vec![json!(1)], 9)]);
    }

    #[test]
    fn test_prelude_task_composition() {
        use crate::prelude::*;
        use serde_json::json;

        // Test that task composition functions are available from prelude
        let _retry = retry_wrapper("task", vec![json!(1)], 5, 10);
        let _timeout = timeout_wrapper("task", vec![json!(1)], 300);
        let _circuit = circuit_breaker_group(vec![("t1", vec![json!(1)])], 3);
        let _rate = rate_limited_workflow("task", vec![json!(1)], 5);
    }

    // Tests for error recovery patterns
    #[test]
    fn test_error_recovery_with_fallback() {
        use crate::error_recovery::with_fallback;
        use serde_json::json;

        let chain = with_fallback(
            "primary_task",
            vec![json!(1)],
            "fallback_task",
            vec![json!(2)],
        );

        assert_eq!(chain.tasks.len(), 2);
        assert_eq!(chain.tasks[0].task, "primary_task");
        assert_eq!(chain.tasks[1].task, "fallback_task");
    }

    #[test]
    fn test_error_recovery_ignore_errors() {
        use crate::error_recovery::ignore_errors;
        use serde_json::json;

        let sig = ignore_errors("non_critical_task", vec![json!(1)]);

        assert_eq!(sig.task, "non_critical_task");
        assert_eq!(sig.options.max_retries, Some(0));
        // Error suppression logic would be implemented in task handler
    }

    #[test]
    fn test_error_recovery_exponential_backoff() {
        use crate::error_recovery::with_exponential_backoff;
        use serde_json::json;

        let sig = with_exponential_backoff("flaky_task", vec![json!(1)], 5, 2);

        assert_eq!(sig.task, "flaky_task");
        assert_eq!(sig.options.max_retries, Some(5));
        assert_eq!(sig.options.countdown, Some(2));
    }

    #[test]
    fn test_error_recovery_with_dlq() {
        use crate::error_recovery::with_dlq;
        use serde_json::json;

        let chain = with_dlq("risky_task", vec![json!(1)], "dlq_handler");

        assert_eq!(chain.tasks.len(), 2);
        assert_eq!(chain.tasks[0].task, "risky_task");
        assert_eq!(chain.tasks[1].task, "dlq_handler");
    }

    // Tests for workflow validation
    #[test]
    fn test_workflow_validation_chain_valid() {
        use crate::workflow_validation::validate_chain;
        use crate::Chain;

        let chain = Chain::new().then("task1", vec![]).then("task2", vec![]);

        assert!(validate_chain(&chain).is_ok());
    }

    #[test]
    fn test_workflow_validation_chain_empty() {
        use crate::workflow_validation::validate_chain;
        use crate::Chain;

        let chain = Chain::new();

        assert!(validate_chain(&chain).is_err());
    }

    #[test]
    fn test_workflow_validation_group_valid() {
        use crate::workflow_validation::validate_group;
        use crate::Group;

        let group = Group::new().add("task1", vec![]).add("task2", vec![]);

        assert!(validate_group(&group).is_ok());
    }

    #[test]
    fn test_workflow_validation_group_empty() {
        use crate::workflow_validation::validate_group;
        use crate::Group;

        let group = Group::new();

        assert!(validate_group(&group).is_err());
    }

    #[test]
    fn test_workflow_validation_chord_valid() {
        use crate::workflow_validation::validate_chord;
        use crate::{Chord, Group, Signature};

        let chord = Chord {
            header: Group::new().add("task1", vec![]),
            body: Signature::new("callback".to_string()),
        };

        assert!(validate_chord(&chord).is_ok());
    }

    #[test]
    fn test_workflow_validation_performance_concerns() {
        use crate::workflow_validation::check_performance_concerns_group;
        use crate::Group;

        let mut large_group = Group::new();
        for i in 0..150 {
            large_group = large_group.add(&format!("task_{}", i), vec![]);
        }

        let warnings = check_performance_concerns_group(&large_group);
        assert!(warnings.is_some());
    }

    // Tests for result helpers
    #[test]
    fn test_result_helpers_collector() {
        use crate::result_helpers::create_result_collector;

        let collector = create_result_collector("aggregate", 100);

        assert_eq!(collector.task, "aggregate");
        assert_eq!(collector.options.time_limit, Some(300));
    }

    #[test]
    fn test_result_helpers_filter() {
        use crate::result_helpers::create_result_filter;
        use serde_json::json;

        let filter = create_result_filter("filter_task", json!({"status": "success"}));

        assert_eq!(filter.task, "filter_task");
        assert_eq!(filter.args.len(), 1);
    }

    #[test]
    fn test_result_helpers_transformer() {
        use crate::result_helpers::create_result_transformer;
        use serde_json::json;

        let transformer = create_result_transformer("transform", json!({"format": "csv"}));

        assert_eq!(transformer.task, "transform");
        assert_eq!(transformer.args.len(), 1);
    }

    #[test]
    fn test_result_helpers_reducer() {
        use crate::result_helpers::create_result_reducer;

        let reducer = create_result_reducer("reduce_task", "sum");

        assert_eq!(reducer.task, "reduce_task");
        assert_eq!(reducer.args.len(), 1);
    }

    // Tests for prelude exports of new modules
    #[test]
    fn test_prelude_error_recovery() {
        use crate::prelude::*;
        use serde_json::json;

        let _fallback = with_fallback("t1", vec![json!(1)], "t2", vec![json!(2)]);
        let _ignore = ignore_errors("t", vec![json!(1)]);
        let _backoff = with_exponential_backoff("t", vec![json!(1)], 5, 2);
        let _dlq = with_dlq("t", vec![json!(1)], "dlq");
    }

    #[test]
    fn test_prelude_workflow_validation() {
        use crate::prelude::*;

        let chain = Chain::new().then("task", vec![]);
        let group = Group::new().add("task", vec![]);

        let _ = validate_chain(&chain);
        let _ = validate_group(&group);
        let _ = check_performance_concerns_chain(&chain);
        let _ = check_performance_concerns_group(&group);

        // Test WorkflowValidationError is available from prelude (aliased)
        let _error = WorkflowValidationError::new("test error");
    }

    #[test]
    fn test_prelude_result_helpers() {
        use crate::prelude::*;
        use serde_json::json;

        let _collector = create_result_collector("collect", 10);
        let _filter = create_result_filter("filter", json!({}));
        let _transformer = create_result_transformer("transform", json!({}));
        let _reducer = create_result_reducer("reduce", "sum");
    }

    // Tests for advanced workflow patterns
    #[test]
    fn test_advanced_patterns_module_available() {
        // Verify advanced patterns module is accessible
        use crate::advanced_patterns::*;

        // Test conditional workflow helper
        let workflow =
            create_conditional_workflow("check", vec![], "success", vec![], "failure", vec![]);
        assert!(!workflow.tasks.is_empty());
    }

    #[test]
    fn test_monitoring_helpers_available() {
        use crate::monitoring_helpers::*;

        let monitor = TaskMonitor::new();
        assert_eq!(monitor.total_tasks(), 0);

        monitor.record_success(100);
        assert_eq!(monitor.total_tasks(), 1);
        assert_eq!(monitor.successful_tasks(), 1);

        monitor.record_failure(200);
        assert_eq!(monitor.total_tasks(), 2);
        assert_eq!(monitor.failed_tasks(), 1);
    }

    #[test]
    fn test_batch_helpers_available() {
        use crate::batch_helpers::*;
        use serde_json::json;

        let items = vec![json!(1), json!(2), json!(3), json!(4), json!(5)];
        let batches = create_dynamic_batches("process", items, 2);
        assert_eq!(batches.header.tasks.len(), 3); // 5 items / 2 = 3 batches
    }

    #[test]
    fn test_advanced_patterns_dynamic_workflow() {
        use crate::advanced_patterns::create_dynamic_workflow;
        use serde_json::json;

        let workflow =
            create_dynamic_workflow("generator", vec![json!({"config": "test"})], "executor");
        assert_eq!(workflow.tasks.len(), 2);
    }

    #[test]
    fn test_advanced_patterns_saga_workflow() {
        use crate::advanced_patterns::create_saga_workflow;
        use serde_json::json;

        let steps = vec![
            ("step1", vec![json!(1)], "compensate1", vec![json!(1)]),
            ("step2", vec![json!(2)], "compensate2", vec![json!(2)]),
        ];

        let workflow = create_saga_workflow(steps);
        assert_eq!(workflow.tasks.len(), 2);
    }

    #[test]
    fn test_monitoring_average_time() {
        use crate::monitoring_helpers::TaskMonitor;

        let monitor = TaskMonitor::new();
        monitor.record_success(100);
        monitor.record_success(200);
        monitor.record_success(300);

        assert_eq!(monitor.average_execution_time_ms(), 200);
    }

    #[test]
    fn test_monitoring_success_rate() {
        use crate::monitoring_helpers::TaskMonitor;

        let monitor = TaskMonitor::new();
        monitor.record_success(100);
        monitor.record_success(100);
        monitor.record_failure(100);

        assert!((monitor.success_rate() - 66.67).abs() < 0.1);
    }

    #[test]
    fn test_batch_adaptive_batches() {
        use crate::batch_helpers::create_adaptive_batches;
        use serde_json::json;

        let items: Vec<_> = (1..=100).map(|i| json!(i)).collect();
        let workflow = create_adaptive_batches("process", items, 5, 20);

        // Should create batches with adaptive sizing
        assert!(!workflow.header.tasks.is_empty());
    }

    #[test]
    fn test_batch_prioritized_batches() {
        use crate::batch_helpers::create_prioritized_batches;
        use serde_json::json;

        let high = vec![json!(1), json!(2)];
        let medium = vec![json!(3), json!(4)];
        let low = vec![json!(5), json!(6)];

        let group = create_prioritized_batches("process", (high, medium, low), 1);

        // Should have tasks with different priorities
        assert_eq!(group.tasks.len(), 6);
        assert_eq!(group.tasks[0].options.priority, Some(9));
        assert_eq!(group.tasks[2].options.priority, Some(5));
        assert_eq!(group.tasks[4].options.priority, Some(1));
    }

    // Health check utilities tests
    #[test]
    fn test_health_check_worker_health_checker() {
        use crate::health_check::{HealthStatus, WorkerHealthChecker};

        let checker = WorkerHealthChecker::default();

        // Should be healthy initially
        let result = checker.check_health();
        assert_eq!(result.status, HealthStatus::Healthy);
        assert!(checker.is_ready());
        assert!(checker.is_alive());

        // Record heartbeat and task processing
        checker.heartbeat();
        checker.task_processed();

        // Should still be healthy
        let result = checker.check_health();
        assert_eq!(result.status, HealthStatus::Healthy);
    }

    #[test]
    fn test_health_check_dependency_checker() {
        use crate::health_check::{DependencyChecker, HealthCheckResult, HealthStatus};

        let checker = DependencyChecker::new("database", || {
            HealthCheckResult::healthy("Database is operational")
        });

        assert_eq!(checker.name(), "database");
        let result = checker.check();
        assert_eq!(result.status, HealthStatus::Healthy);
    }

    #[test]
    fn test_health_check_result_builder() {
        use crate::health_check::{HealthCheckResult, HealthStatus};

        let result = HealthCheckResult::healthy("All systems operational")
            .with_metadata("uptime", "3600")
            .with_metadata("requests", "1000");

        assert_eq!(result.status, HealthStatus::Healthy);
        assert_eq!(result.message, "All systems operational");
        assert_eq!(result.metadata.len(), 2);
    }

    // Resource management tests
    #[test]
    fn test_resource_management_limits() {
        use crate::resource_management::ResourceLimits;

        let limits = ResourceLimits::unlimited();
        assert!(limits.max_memory_bytes.is_none());
        assert!(limits.max_cpu_seconds.is_none());

        let limits = ResourceLimits::memory_constrained(512);
        assert_eq!(limits.max_memory_bytes, Some(512 * 1024 * 1024));

        let limits = ResourceLimits::cpu_intensive(60);
        assert_eq!(limits.max_cpu_seconds, Some(60));

        let limits = ResourceLimits::io_intensive(300);
        assert_eq!(limits.max_wall_time_seconds, Some(300));
    }

    #[test]
    fn test_resource_management_tracker() {
        use crate::resource_management::{ResourceLimits, ResourceTracker};
        use std::thread;
        use std::time::Duration;

        let limits = ResourceLimits::memory_constrained(100);
        let tracker = ResourceTracker::new(limits);

        tracker.start();
        thread::sleep(Duration::from_millis(10));

        tracker.record_memory_usage(50 * 1024 * 1024); // 50 MB
        assert_eq!(tracker.peak_memory_bytes(), 50 * 1024 * 1024);

        // Should be within limits
        assert!(tracker.check_limits().is_ok());

        // Recording more memory
        tracker.record_memory_usage(75 * 1024 * 1024); // 75 MB
        assert_eq!(tracker.peak_memory_bytes(), 75 * 1024 * 1024);
    }

    #[test]
    fn test_resource_management_pool() {
        use crate::resource_management::ResourcePool;

        let pool: ResourcePool<String> = ResourcePool::new(3);
        assert!(pool.is_empty());
        assert_eq!(pool.max_size(), 3);

        // Add resources
        pool.release("resource1".to_string()).unwrap();
        pool.release("resource2".to_string()).unwrap();
        assert_eq!(pool.available(), 2);

        // Acquire resources
        let r1 = pool.acquire();
        assert!(r1.is_some());
        assert_eq!(pool.available(), 1);

        let r2 = pool.acquire();
        assert!(r2.is_some());
        assert_eq!(pool.available(), 0);
        assert!(pool.is_empty());
    }

    // Task hooks tests
    #[test]
    fn test_task_hooks_hook_registry() {
        use crate::task_hooks::{HookRegistry, LoggingHook};

        let mut registry = HookRegistry::new();
        assert_eq!(registry.pre_hook_count(), 0);
        assert_eq!(registry.post_hook_count(), 0);

        registry.register_pre_hook(LoggingHook::new(false, false));
        registry.register_post_hook(LoggingHook::new(false, false));

        assert_eq!(registry.pre_hook_count(), 1);
        assert_eq!(registry.post_hook_count(), 1);
    }

    #[test]
    fn test_task_hooks_logging_hook() {
        use crate::task_hooks::{LoggingHook, PostExecutionHook, PreExecutionHook};
        use serde_json::json;

        let hook = LoggingHook::new(false, false);
        let mut args = vec![json!({"x": 1})];

        // Test pre-execution hook
        let result = hook.before_execute("test_task", "task-123", &mut args);
        assert!(result.is_ok());

        // Test post-execution hook
        let task_result: std::result::Result<serde_json::Value, String> = Ok(json!({"result": 42}));
        let result = hook.after_execute("test_task", "task-123", &task_result, 100);
        assert!(result.is_ok());

        // Test with error result
        let task_result: std::result::Result<serde_json::Value, String> =
            Err("Task failed".to_string());
        let result = hook.after_execute("test_task", "task-123", &task_result, 100);
        assert!(result.is_ok());
    }

    #[test]
    fn test_task_hooks_validation_hook() {
        use crate::task_hooks::{PreExecutionHook, ValidationHook};
        use serde_json::json;

        let hook = ValidationHook::new(|task_name: &str, args: &Vec<serde_json::Value>| {
            if args.is_empty() {
                return Err("Arguments cannot be empty".into());
            }
            if task_name == "forbidden" {
                return Err("Task is forbidden".into());
            }
            Ok(())
        });

        let mut args = vec![json!({"x": 1})];
        let result = hook.before_execute("allowed_task", "task-123", &mut args);
        assert!(result.is_ok());

        let result = hook.before_execute("forbidden", "task-123", &mut args);
        assert!(result.is_err());

        let mut empty_args = vec![];
        let result = hook.before_execute("allowed_task", "task-123", &mut empty_args);
        assert!(result.is_err());
    }

    #[test]
    fn test_task_hooks_run_hooks() {
        use crate::task_hooks::{HookRegistry, LoggingHook};
        use serde_json::json;

        let mut registry = HookRegistry::new();
        registry.register_pre_hook(LoggingHook::new(false, false));
        registry.register_post_hook(LoggingHook::new(false, false));

        let mut args = vec![json!({"x": 1})];
        let result = registry.run_pre_hooks("test_task", "task-123", &mut args);
        assert!(result.is_ok());

        let task_result: std::result::Result<serde_json::Value, String> = Ok(json!({"result": 42}));
        let result = registry.run_post_hooks("test_task", "task-123", &task_result, 100);
        assert!(result.is_ok());
    }

    // Metrics aggregation tests
    #[test]
    fn test_metrics_aggregation_histogram() {
        use crate::metrics_aggregation::Histogram;

        let mut histogram = Histogram::new();
        assert_eq!(histogram.count(), 0);
        assert_eq!(histogram.mean(), 0.0);

        histogram.record(100.0);
        histogram.record(200.0);
        histogram.record(150.0);

        assert_eq!(histogram.count(), 3);
        assert_eq!(histogram.sum(), 450.0);
        assert_eq!(histogram.mean(), 150.0);

        let p50 = histogram.percentile(50.0);
        assert!(p50 > 0.0);
    }

    #[test]
    fn test_metrics_aggregation_aggregator() {
        use crate::metrics_aggregation::MetricsAggregator;
        use std::time::Duration;

        let aggregator = MetricsAggregator::new();

        // Record some task executions
        aggregator.record_duration("task1", Duration::from_millis(100));
        aggregator.record_duration("task1", Duration::from_millis(200));
        aggregator.record_duration("task2", Duration::from_millis(50));

        assert_eq!(aggregator.task_count("task1"), 2);
        assert_eq!(aggregator.task_count("task2"), 1);
        assert_eq!(aggregator.task_count("task3"), 0);

        let mean = aggregator.mean_duration("task1");
        assert!(mean > 100.0 && mean < 200.0);

        let p50 = aggregator.percentile_duration("task1", 50.0);
        assert!(p50 > 0.0);

        let throughput = aggregator.throughput("task1");
        assert!(throughput > 0.0);
    }

    #[test]
    fn test_metrics_aggregation_error_tracking() {
        use crate::metrics_aggregation::MetricsAggregator;
        use std::time::Duration;

        let aggregator = MetricsAggregator::new();

        aggregator.record_duration("task1", Duration::from_millis(100));
        aggregator.record_duration("task1", Duration::from_millis(150));
        aggregator.record_error("task1");

        assert_eq!(aggregator.task_count("task1"), 2);
        assert_eq!(aggregator.error_count("task1"), 1);

        let success_rate = aggregator.success_rate("task1");
        assert!((success_rate - 50.0).abs() < 0.1);

        // Task with no errors should have 100% success rate
        aggregator.record_duration("task2", Duration::from_millis(100));
        let success_rate = aggregator.success_rate("task2");
        assert_eq!(success_rate, 100.0);
    }

    #[test]
    fn test_metrics_aggregation_summary() {
        use crate::metrics_aggregation::MetricsAggregator;
        use std::time::Duration;

        let aggregator = MetricsAggregator::new();

        aggregator.record_duration("task1", Duration::from_millis(100));
        aggregator.record_duration("task1", Duration::from_millis(200));
        aggregator.record_error("task1");

        let summary = aggregator.summary("task1");
        assert!(summary.contains("task1"));
        assert!(summary.contains("Total Executions"));
        assert!(summary.contains("Mean Duration"));
        assert!(summary.contains("Throughput"));
    }

    #[test]
    fn test_metrics_aggregation_task_names() {
        use crate::metrics_aggregation::MetricsAggregator;
        use std::time::Duration;

        let aggregator = MetricsAggregator::new();

        aggregator.record_duration("task1", Duration::from_millis(100));
        aggregator.record_duration("task2", Duration::from_millis(200));
        aggregator.record_duration("task3", Duration::from_millis(300));

        let names = aggregator.task_names();
        assert_eq!(names.len(), 3);
        assert!(names.contains(&"task1".to_string()));
        assert!(names.contains(&"task2".to_string()));
        assert!(names.contains(&"task3".to_string()));
    }

    #[test]
    fn test_prelude_exports_new_modules() {
        // Test that all new module types are exported in prelude
        use crate::prelude::*;

        // Health check types
        let _: Option<WorkerHealthChecker> = None;
        let _: Option<DependencyChecker> = None;
        let _: Option<HealthCheckResult> = None;

        // Resource management types
        let _: Option<ResourceLimits> = None;
        let _: Option<ResourceTracker> = None;
        let _: Option<ResourcePool<String>> = None;

        // Task hooks types
        let _: Option<HookRegistry> = None;
        let _: Option<LoggingHook> = None;

        // Metrics aggregation types
        let _: Option<MetricsAggregator> = None;
        let _: Option<Histogram> = None;
    }

    // Task cancellation tests
    #[test]
    fn test_task_cancellation_token() {
        use crate::task_cancellation::CancellationToken;

        let token = CancellationToken::new();
        assert!(!token.is_cancelled());
        assert!(token.check_cancelled().is_ok());

        token.cancel(Some("User requested cancellation".to_string()));
        assert!(token.is_cancelled());
        assert!(token.check_cancelled().is_err());
        assert_eq!(
            token.cancellation_reason(),
            Some("User requested cancellation".to_string())
        );
    }

    #[test]
    fn test_task_cancellation_timeout_manager() {
        use crate::task_cancellation::TimeoutManager;
        use std::thread;
        use std::time::Duration;

        let manager = TimeoutManager::new(Duration::from_millis(100));
        assert!(!manager.is_timed_out());
        assert!(manager.check_timeout().is_ok());

        thread::sleep(Duration::from_millis(150));
        assert!(manager.is_timed_out());
        assert!(manager.check_timeout().is_err());
    }

    #[test]
    fn test_task_cancellation_execution_guard() {
        use crate::task_cancellation::{CancellationToken, ExecutionGuard};
        use std::time::Duration;

        let token = CancellationToken::new();
        let guard = ExecutionGuard::new(token.clone(), Some(Duration::from_secs(10)));

        assert!(guard.should_continue().is_ok());

        token.cancel(None);
        assert!(guard.should_continue().is_err());
    }

    // Retry strategies tests
    #[test]
    fn test_retry_strategies_exponential_backoff() {
        use crate::retry_strategies::RetryStrategy;
        use std::time::Duration;

        let strategy = RetryStrategy::exponential_backoff(3, Duration::from_secs(1));
        assert_eq!(strategy.max_retries, 3);

        let delay0 = strategy.calculate_delay(0);
        assert_eq!(delay0, Duration::from_secs(0));

        let delay1 = strategy.calculate_delay(1);
        assert!(delay1.as_millis() >= 750 && delay1.as_millis() <= 1250); // With jitter

        let delay2 = strategy.calculate_delay(2);
        assert!(delay2.as_millis() >= 1500); // At least 1.5s base with jitter
    }

    #[test]
    fn test_retry_strategies_fixed_delay() {
        use crate::retry_strategies::RetryStrategy;
        use std::time::Duration;

        let strategy = RetryStrategy::fixed_delay(5, Duration::from_millis(500));
        assert_eq!(strategy.max_retries, 5);

        let delay = strategy.calculate_delay(1);
        assert_eq!(delay, Duration::from_millis(500));

        let delay = strategy.calculate_delay(3);
        assert_eq!(delay, Duration::from_millis(500));
    }

    #[test]
    fn test_retry_strategies_default_policy() {
        use crate::retry_strategies::{DefaultRetryPolicy, RetryPolicy};

        let policy = DefaultRetryPolicy::new(3);
        assert!(policy.should_retry("any error", 0));
        assert!(policy.should_retry("any error", 2));
        assert!(!policy.should_retry("any error", 3));
    }

    #[test]
    fn test_retry_strategies_error_pattern_policy() {
        use crate::retry_strategies::{ErrorPatternRetryPolicy, RetryPolicy};

        let policy =
            ErrorPatternRetryPolicy::new(3, vec!["timeout".to_string(), "connection".to_string()]);

        assert!(policy.should_retry("connection error", 0));
        assert!(policy.should_retry("timeout occurred", 1));
        assert!(!policy.should_retry("invalid input", 0));
        assert!(!policy.should_retry("timeout", 3)); // Max retries reached
    }

    // Task dependencies tests
    #[test]
    fn test_task_dependencies_graph() {
        use crate::task_dependencies::DependencyGraph;

        let mut graph = DependencyGraph::new();
        graph.add_task("task1");
        graph.add_task("task2");
        graph.add_task("task3");

        graph.add_dependency("task2", "task1"); // task2 depends on task1
        graph.add_dependency("task3", "task2"); // task3 depends on task2

        assert_eq!(graph.get_dependencies("task1"), Vec::<String>::new());
        assert_eq!(graph.get_dependencies("task2"), vec!["task1"]);
        assert_eq!(graph.get_dependencies("task3"), vec!["task2"]);

        assert_eq!(graph.get_dependents("task1"), vec!["task2"]);
        assert_eq!(graph.get_dependents("task2"), vec!["task3"]);
    }

    #[test]
    fn test_task_dependencies_circular_detection() {
        use crate::task_dependencies::DependencyGraph;

        let mut graph = DependencyGraph::new();
        graph.add_task("task1");
        graph.add_task("task2");
        graph.add_task("task3");

        graph.add_dependency("task2", "task1");
        graph.add_dependency("task3", "task2");
        graph.add_dependency("task1", "task3"); // Creates cycle

        assert!(graph.has_circular_dependencies());
    }

    #[test]
    fn test_task_dependencies_topological_sort() {
        use crate::task_dependencies::DependencyGraph;

        let mut graph = DependencyGraph::new();
        graph.add_task("task1");
        graph.add_task("task2");
        graph.add_task("task3");

        graph.add_dependency("task2", "task1");
        graph.add_dependency("task3", "task2");

        let sorted = graph.topological_sort().unwrap();
        assert_eq!(sorted, vec!["task1", "task2", "task3"]);
    }

    #[test]
    fn test_task_dependencies_ready_tasks() {
        use crate::task_dependencies::DependencyGraph;
        use std::collections::HashSet;

        let mut graph = DependencyGraph::new();
        graph.add_task("task1");
        graph.add_task("task2");
        graph.add_task("task3");

        graph.add_dependency("task2", "task1");
        graph.add_dependency("task3", "task2");

        let completed: HashSet<String> = HashSet::new();
        let ready = graph.get_ready_tasks(&completed);
        assert_eq!(ready, vec!["task1"]); // Only task1 has no dependencies

        let mut completed = HashSet::new();
        completed.insert("task1".to_string());
        let ready = graph.get_ready_tasks(&completed);
        assert_eq!(ready, vec!["task2"]); // task2 becomes ready
    }

    // Performance profiling tests
    #[test]
    fn test_performance_profiling_profiler() {
        use crate::performance_profiling::PerformanceProfiler;
        use std::thread;
        use std::time::Duration;

        let profiler = PerformanceProfiler::new();

        profiler.start_span("operation1");
        thread::sleep(Duration::from_millis(10));
        profiler.end_span();

        profiler.start_span("operation2");
        thread::sleep(Duration::from_millis(20));
        profiler.end_span();

        let profile1 = profiler.get_profile("operation1").unwrap();
        assert_eq!(profile1.name, "operation1");
        assert_eq!(profile1.invocation_count, 1);
        assert!(profile1.total_duration.as_millis() >= 10);

        let profile2 = profiler.get_profile("operation2").unwrap();
        assert_eq!(profile2.invocation_count, 1);
        assert!(profile2.total_duration.as_millis() >= 20);
    }

    #[test]
    fn test_performance_profiling_multiple_invocations() {
        use crate::performance_profiling::PerformanceProfiler;
        use std::thread;
        use std::time::Duration;

        let profiler = PerformanceProfiler::new();

        for _ in 0..3 {
            profiler.start_span("repeated_op");
            thread::sleep(Duration::from_millis(5));
            profiler.end_span();
        }

        let profile = profiler.get_profile("repeated_op").unwrap();
        assert_eq!(profile.invocation_count, 3);
        assert!(profile.total_duration.as_millis() >= 15);
    }

    #[test]
    fn test_performance_profiling_slowest_operations() {
        use crate::performance_profiling::PerformanceProfiler;
        use std::thread;
        use std::time::Duration;

        let profiler = PerformanceProfiler::new();

        // Use larger time gaps to avoid flakiness under system load
        profiler.start_span("fast_op");
        thread::sleep(Duration::from_millis(10));
        profiler.end_span();

        profiler.start_span("slow_op");
        thread::sleep(Duration::from_millis(150));
        profiler.end_span();

        profiler.start_span("medium_op");
        thread::sleep(Duration::from_millis(50));
        profiler.end_span();

        let slowest = profiler.get_slowest_operations(2);
        assert_eq!(slowest.len(), 2);
        assert_eq!(slowest[0].name, "slow_op");
        assert_eq!(slowest[1].name, "medium_op");
    }

    #[test]
    fn test_performance_profiling_report_generation() {
        use crate::performance_profiling::PerformanceProfiler;
        use std::thread;
        use std::time::Duration;

        let profiler = PerformanceProfiler::new();

        profiler.start_span("test_operation");
        thread::sleep(Duration::from_millis(10));
        profiler.end_span();

        let report = profiler.generate_report();
        assert!(report.contains("Performance Profile Report"));
        assert!(report.contains("test_operation"));
        assert!(report.contains("Count"));
        assert!(report.contains("Total"));
    }

    #[test]
    fn test_prelude_exports_additional_modules() {
        // Test that all additional module types are exported in prelude
        use crate::prelude::*;

        // Task cancellation types
        let _: Option<CancellationToken> = None;
        let _: Option<TimeoutManager> = None;
        let _: Option<ExecutionGuard> = None;

        // Retry strategy types
        let _: Option<RetryStrategy> = None;
        let _: Option<DefaultRetryPolicy> = None;
        let _: Option<ErrorPatternRetryPolicy> = None;

        // Task dependency types
        let _: Option<DependencyGraph> = None;

        // Performance profiling types
        // Note: PerformanceProfiler is not exported in prelude to avoid conflict with dev_utils
        let _: Option<PerformanceProfile> = None;
        let _: Option<ProfileSpan<'_>> = None;

        // Access PerformanceProfiler directly from module
        let _: Option<crate::performance_profiling::PerformanceProfiler> = None;
    }
}

/// Advanced workflow patterns for complex use cases
///
/// This module provides advanced workflow patterns including conditional execution,
/// dynamic task generation, and complex orchestration patterns.
pub mod advanced_patterns {
    use crate::{Chain, Group, Signature};
    use serde_json::Value;

    /// Creates a conditional workflow with success and failure branches
    ///
    /// This creates a chain that includes both success and failure paths.
    /// The actual branching logic must be implemented in the condition task.
    ///
    /// # Arguments
    ///
    /// * `condition_task` - Task that evaluates the condition
    /// * `condition_args` - Arguments for the condition task
    /// * `success_task` - Task to execute on success
    /// * `success_args` - Arguments for success task
    /// * `failure_task` - Task to execute on failure
    /// * `failure_args` - Arguments for failure task
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::advanced_patterns::create_conditional_workflow;
    /// use serde_json::json;
    ///
    /// let workflow = create_conditional_workflow(
    ///     "check_balance",
    ///     vec![json!({"account_id": 123})],
    ///     "process_payment",
    ///     vec![json!({"amount": 100})],
    ///     "send_insufficient_funds_notice",
    ///     vec![json!({"account_id": 123})]
    /// );
    /// ```
    pub fn create_conditional_workflow(
        condition_task: &str,
        condition_args: Vec<Value>,
        success_task: &str,
        success_args: Vec<Value>,
        failure_task: &str,
        failure_args: Vec<Value>,
    ) -> Chain {
        // Create a chain with condition task
        // The condition task should route to success or failure based on its result
        let mut chain = Chain::new();
        chain = chain.then(condition_task, condition_args);
        chain = chain.then(success_task, success_args);
        // Note: Failure path would be implemented via task routing/error handling
        // This is a template for the workflow structure
        let _ = failure_task;
        let _ = failure_args;
        chain
    }

    /// Creates a dynamic workflow where tasks are generated at runtime
    ///
    /// This pattern allows for workflows where the number and type of tasks
    /// are determined dynamically based on input data.
    ///
    /// # Arguments
    ///
    /// * `generator_task` - Task that generates the list of tasks to execute
    /// * `generator_args` - Arguments for the generator task
    /// * `executor_task` - Task that executes the generated tasks
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::advanced_patterns::create_dynamic_workflow;
    /// use serde_json::json;
    ///
    /// let workflow = create_dynamic_workflow(
    ///     "generate_tasks",
    ///     vec![json!({"rules": "config.json"})],
    ///     "execute_task"
    /// );
    /// ```
    pub fn create_dynamic_workflow(
        generator_task: &str,
        generator_args: Vec<Value>,
        executor_task: &str,
    ) -> Chain {
        Chain::new()
            .then(generator_task, generator_args)
            .then(executor_task, vec![])
    }

    /// Creates a workflow with parallel sub-chains
    ///
    /// This pattern executes multiple chains in parallel, useful for
    /// independent workflows that should run concurrently.
    ///
    /// # Arguments
    ///
    /// * `chains` - List of (chain_name, tasks) tuples
    /// * `aggregate_task` - Optional task to aggregate results from all chains
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::advanced_patterns::create_parallel_chains;
    /// use serde_json::json;
    ///
    /// let chains = vec![
    ///     ("process_images", vec![("resize", vec![]), ("optimize", vec![])]),
    ///     ("process_videos", vec![("transcode", vec![]), ("thumbnail", vec![])]),
    /// ];
    ///
    /// let workflow = create_parallel_chains(chains, Some("finalize"));
    /// ```
    #[allow(clippy::type_complexity)]
    pub fn create_parallel_chains(
        chains: Vec<(&str, Vec<(&str, Vec<Value>)>)>,
        aggregate_task: Option<&str>,
    ) -> Group {
        let mut group = Group::new();

        for (_chain_name, tasks) in chains {
            // Create a signature for the first task in each chain
            if let Some((first_task, first_args)) = tasks.first() {
                let sig = Signature::new(first_task.to_string()).with_args(first_args.clone());
                group.tasks.push(sig);
            }
        }

        // Note: Aggregate task would be added as a chord if provided
        let _ = aggregate_task;

        group
    }

    /// Creates a saga pattern workflow for distributed transactions
    ///
    /// Implements the saga pattern with compensating transactions for each step.
    ///
    /// # Arguments
    ///
    /// * `steps` - List of (forward_task, forward_args, compensate_task, compensate_args) tuples
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::advanced_patterns::create_saga_workflow;
    /// use serde_json::json;
    ///
    /// let steps = vec![
    ///     ("reserve_inventory", vec![json!(1)], "release_inventory", vec![json!(1)]),
    ///     ("charge_payment", vec![json!(2)], "refund_payment", vec![json!(2)]),
    ///     ("ship_order", vec![json!(3)], "cancel_shipment", vec![json!(3)]),
    /// ];
    ///
    /// let workflow = create_saga_workflow(steps);
    /// ```
    pub fn create_saga_workflow(steps: Vec<(&str, Vec<Value>, &str, Vec<Value>)>) -> Chain {
        let mut chain = Chain::new();

        // Add forward tasks
        for (forward_task, forward_args, _compensate_task, _compensate_args) in steps {
            chain = chain.then(forward_task, forward_args);
            // Note: Compensation tasks would be invoked on failure
            // This requires error handling logic in the task implementation
        }

        chain
    }
}

/// Monitoring and observability helpers
///
/// This module provides utilities for monitoring task execution, tracking metrics,
/// and observing workflow behavior in production.
pub mod monitoring_helpers {
    use std::sync::{Arc, Mutex};
    use std::time::{SystemTime, UNIX_EPOCH};

    /// Task execution monitor
    ///
    /// Tracks task execution statistics and provides insights into task performance.
    #[derive(Clone)]
    pub struct TaskMonitor {
        metrics: Arc<Mutex<MonitorMetrics>>,
    }

    #[derive(Debug, Clone)]
    struct MonitorMetrics {
        total_tasks: usize,
        successful_tasks: usize,
        failed_tasks: usize,
        total_execution_time_ms: u128,
        start_time: u64,
    }

    impl TaskMonitor {
        /// Creates a new task monitor
        pub fn new() -> Self {
            Self {
                metrics: Arc::new(Mutex::new(MonitorMetrics {
                    total_tasks: 0,
                    successful_tasks: 0,
                    failed_tasks: 0,
                    total_execution_time_ms: 0,
                    start_time: SystemTime::now()
                        .duration_since(UNIX_EPOCH)
                        .unwrap()
                        .as_secs(),
                })),
            }
        }

        /// Records a successful task execution
        pub fn record_success(&self, execution_time_ms: u128) {
            let mut metrics = self.metrics.lock().expect("lock should not be poisoned");
            metrics.total_tasks += 1;
            metrics.successful_tasks += 1;
            metrics.total_execution_time_ms += execution_time_ms;
        }

        /// Records a failed task execution
        pub fn record_failure(&self, execution_time_ms: u128) {
            let mut metrics = self.metrics.lock().expect("lock should not be poisoned");
            metrics.total_tasks += 1;
            metrics.failed_tasks += 1;
            metrics.total_execution_time_ms += execution_time_ms;
        }

        /// Gets the total number of tasks processed
        pub fn total_tasks(&self) -> usize {
            self.metrics
                .lock()
                .expect("lock should not be poisoned")
                .total_tasks
        }

        /// Gets the number of successful tasks
        pub fn successful_tasks(&self) -> usize {
            self.metrics
                .lock()
                .expect("lock should not be poisoned")
                .successful_tasks
        }

        /// Gets the number of failed tasks
        pub fn failed_tasks(&self) -> usize {
            self.metrics
                .lock()
                .expect("lock should not be poisoned")
                .failed_tasks
        }

        /// Gets the average execution time in milliseconds
        pub fn average_execution_time_ms(&self) -> u128 {
            let metrics = self.metrics.lock().expect("lock should not be poisoned");
            if metrics.total_tasks == 0 {
                0
            } else {
                metrics.total_execution_time_ms / metrics.total_tasks as u128
            }
        }

        /// Gets the success rate as a percentage
        pub fn success_rate(&self) -> f64 {
            let metrics = self.metrics.lock().expect("lock should not be poisoned");
            if metrics.total_tasks == 0 {
                0.0
            } else {
                (metrics.successful_tasks as f64 / metrics.total_tasks as f64) * 100.0
            }
        }

        /// Resets all metrics
        pub fn reset(&self) {
            let mut metrics = self.metrics.lock().expect("lock should not be poisoned");
            metrics.total_tasks = 0;
            metrics.successful_tasks = 0;
            metrics.failed_tasks = 0;
            metrics.total_execution_time_ms = 0;
            metrics.start_time = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs();
        }

        /// Generates a summary report
        pub fn summary(&self) -> String {
            let metrics = self.metrics.lock().expect("lock should not be poisoned");
            format!(
                "Task Monitor Summary:\n\
                 - Total Tasks: {}\n\
                 - Successful: {} ({:.2}%)\n\
                 - Failed: {} ({:.2}%)\n\
                 - Avg Execution Time: {}ms\n\
                 - Uptime: {}s",
                metrics.total_tasks,
                metrics.successful_tasks,
                if metrics.total_tasks > 0 {
                    (metrics.successful_tasks as f64 / metrics.total_tasks as f64) * 100.0
                } else {
                    0.0
                },
                metrics.failed_tasks,
                if metrics.total_tasks > 0 {
                    (metrics.failed_tasks as f64 / metrics.total_tasks as f64) * 100.0
                } else {
                    0.0
                },
                if metrics.total_tasks > 0 {
                    metrics.total_execution_time_ms / metrics.total_tasks as u128
                } else {
                    0
                },
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs()
                    - metrics.start_time
            )
        }
    }

    impl Default for TaskMonitor {
        fn default() -> Self {
            Self::new()
        }
    }
}

/// Batch processing helpers for efficient data processing
///
/// This module provides utilities for processing large datasets in batches,
/// including dynamic batch sizing and parallel batch processing.
pub mod batch_helpers {
    use crate::{Chord, Group, Signature};
    use serde_json::Value;

    /// Creates batches with dynamic sizing based on item count
    ///
    /// Automatically determines optimal batch size for efficient processing.
    ///
    /// # Arguments
    ///
    /// * `task_name` - Name of the task to process each batch
    /// * `items` - Items to process
    /// * `target_batch_size` - Target size for each batch
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::batch_helpers::create_dynamic_batches;
    /// use serde_json::json;
    ///
    /// let items = (1..=100).map(|i| json!(i)).collect();
    /// let workflow = create_dynamic_batches("process_batch", items, 10);
    /// ```
    pub fn create_dynamic_batches(
        task_name: &str,
        items: Vec<Value>,
        target_batch_size: usize,
    ) -> Chord {
        let mut group = Group::new();
        let batch_size = if target_batch_size == 0 {
            1
        } else {
            target_batch_size
        };

        for chunk in items.chunks(batch_size) {
            let batch = Value::Array(chunk.to_vec());
            group = group.add(task_name, vec![batch]);
        }

        Chord {
            header: group,
            body: Signature::new("batch_complete".to_string()),
        }
    }

    /// Creates adaptive batches that adjust size based on processing characteristics
    ///
    /// # Arguments
    ///
    /// * `task_name` - Name of the task to process each batch
    /// * `items` - Items to process
    /// * `min_batch_size` - Minimum batch size
    /// * `max_batch_size` - Maximum batch size
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::batch_helpers::create_adaptive_batches;
    /// use serde_json::json;
    ///
    /// let items = (1..=1000).map(|i| json!(i)).collect();
    /// let workflow = create_adaptive_batches("process", items, 10, 100);
    /// ```
    pub fn create_adaptive_batches(
        task_name: &str,
        items: Vec<Value>,
        min_batch_size: usize,
        max_batch_size: usize,
    ) -> Chord {
        let mut group = Group::new();

        // Calculate adaptive batch size based on total items
        let batch_size = if items.len() < min_batch_size {
            items.len()
        } else if items.len() > max_batch_size * 10 {
            max_batch_size
        } else {
            // Use a size between min and max based on item count
            let calculated = (items.len() as f64).sqrt() as usize;
            calculated.clamp(min_batch_size, max_batch_size)
        };

        for chunk in items.chunks(batch_size.max(1)) {
            let batch = Value::Array(chunk.to_vec());
            group = group.add(task_name, vec![batch]);
        }

        Chord {
            header: group,
            body: Signature::new("batch_complete".to_string()),
        }
    }

    /// Creates prioritized batches with different priority levels
    ///
    /// # Arguments
    ///
    /// * `task_name` - Name of the task to process each batch
    /// * `priority_items` - Items grouped by priority (high, medium, low)
    /// * `batch_size` - Size of each batch
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use celers::batch_helpers::create_prioritized_batches;
    /// use serde_json::json;
    ///
    /// let high = vec![json!(1), json!(2)];
    /// let medium = vec![json!(3), json!(4)];
    /// let low = vec![json!(5), json!(6)];
    ///
    /// let workflow = create_prioritized_batches("process", (high, medium, low), 2);
    /// ```
    pub fn create_prioritized_batches(
        task_name: &str,
        priority_items: (Vec<Value>, Vec<Value>, Vec<Value>),
        batch_size: usize,
    ) -> Group {
        let (high_priority, medium_priority, low_priority) = priority_items;
        let mut group = Group::new();

        // Process high priority items first
        for chunk in high_priority.chunks(batch_size.max(1)) {
            let batch = Value::Array(chunk.to_vec());
            let mut sig = Signature::new(task_name.to_string()).with_args(vec![batch]);
            sig.options.priority = Some(9);
            group.tasks.push(sig);
        }

        // Then medium priority
        for chunk in medium_priority.chunks(batch_size.max(1)) {
            let batch = Value::Array(chunk.to_vec());
            let mut sig = Signature::new(task_name.to_string()).with_args(vec![batch]);
            sig.options.priority = Some(5);
            group.tasks.push(sig);
        }

        // Finally low priority
        for chunk in low_priority.chunks(batch_size.max(1)) {
            let batch = Value::Array(chunk.to_vec());
            let mut sig = Signature::new(task_name.to_string()).with_args(vec![batch]);
            sig.options.priority = Some(1);
            group.tasks.push(sig);
        }

        group
    }
}

/// Health check utilities for monitoring worker and task health
///
/// This module provides utilities for implementing health checks in workers,
/// including readiness, liveness, and dependency checks.
pub mod health_check {
    use std::sync::{Arc, Mutex};
    use std::time::{Duration, Instant};

    /// Health status of a component
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub enum HealthStatus {
        /// Component is healthy and operational
        Healthy,
        /// Component is degraded but still operational
        Degraded,
        /// Component is unhealthy and not operational
        Unhealthy,
    }

    /// Health check result
    #[derive(Debug, Clone)]
    pub struct HealthCheckResult {
        /// Status of the health check
        pub status: HealthStatus,
        /// Human-readable message
        pub message: String,
        /// Timestamp of the check
        pub timestamp: Instant,
        /// Additional metadata
        pub metadata: Vec<(String, String)>,
    }

    impl HealthCheckResult {
        /// Creates a new healthy result
        pub fn healthy(message: impl Into<String>) -> Self {
            Self {
                status: HealthStatus::Healthy,
                message: message.into(),
                timestamp: Instant::now(),
                metadata: Vec::new(),
            }
        }

        /// Creates a new degraded result
        pub fn degraded(message: impl Into<String>) -> Self {
            Self {
                status: HealthStatus::Degraded,
                message: message.into(),
                timestamp: Instant::now(),
                metadata: Vec::new(),
            }
        }

        /// Creates a new unhealthy result
        pub fn unhealthy(message: impl Into<String>) -> Self {
            Self {
                status: HealthStatus::Unhealthy,
                message: message.into(),
                timestamp: Instant::now(),
                metadata: Vec::new(),
            }
        }

        /// Adds metadata to the health check result
        pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
            self.metadata.push((key.into(), value.into()));
            self
        }
    }

    /// Worker health checker
    ///
    /// Monitors worker health including heartbeat, task processing, and dependencies.
    #[derive(Clone)]
    pub struct WorkerHealthChecker {
        last_heartbeat: Arc<Mutex<Instant>>,
        last_task_processed: Arc<Mutex<Option<Instant>>>,
        heartbeat_timeout: Duration,
        task_timeout: Duration,
    }

    impl WorkerHealthChecker {
        /// Creates a new worker health checker
        ///
        /// # Arguments
        ///
        /// * `heartbeat_timeout` - Maximum time between heartbeats before unhealthy
        /// * `task_timeout` - Maximum time since last task processed before degraded
        pub fn new(heartbeat_timeout: Duration, task_timeout: Duration) -> Self {
            Self {
                last_heartbeat: Arc::new(Mutex::new(Instant::now())),
                last_task_processed: Arc::new(Mutex::new(None)),
                heartbeat_timeout,
                task_timeout,
            }
        }

        /// Records a heartbeat
        pub fn heartbeat(&self) {
            *self
                .last_heartbeat
                .lock()
                .expect("lock should not be poisoned") = Instant::now();
        }

        /// Records task processing
        pub fn task_processed(&self) {
            *self
                .last_task_processed
                .lock()
                .expect("lock should not be poisoned") = Some(Instant::now());
        }

        /// Checks worker health status
        pub fn check_health(&self) -> HealthCheckResult {
            let now = Instant::now();
            let last_heartbeat = *self
                .last_heartbeat
                .lock()
                .expect("lock should not be poisoned");
            let last_task = *self
                .last_task_processed
                .lock()
                .expect("lock should not be poisoned");

            // Check heartbeat
            if now.duration_since(last_heartbeat) > self.heartbeat_timeout {
                return HealthCheckResult::unhealthy("Worker heartbeat timeout").with_metadata(
                    "last_heartbeat_seconds_ago",
                    format!("{}", now.duration_since(last_heartbeat).as_secs()),
                );
            }

            // Check task processing
            if let Some(last_task_time) = last_task {
                if now.duration_since(last_task_time) > self.task_timeout {
                    return HealthCheckResult::degraded("No tasks processed recently")
                        .with_metadata(
                            "last_task_seconds_ago",
                            format!("{}", now.duration_since(last_task_time).as_secs()),
                        );
                }
            }

            HealthCheckResult::healthy("Worker is operational").with_metadata(
                "uptime_seconds",
                format!("{}", now.duration_since(last_heartbeat).as_secs()),
            )
        }

        /// Checks if worker is ready to accept tasks
        pub fn is_ready(&self) -> bool {
            matches!(
                self.check_health().status,
                HealthStatus::Healthy | HealthStatus::Degraded
            )
        }

        /// Checks if worker is alive
        pub fn is_alive(&self) -> bool {
            let now = Instant::now();
            let last_heartbeat = *self
                .last_heartbeat
                .lock()
                .expect("lock should not be poisoned");
            now.duration_since(last_heartbeat) <= self.heartbeat_timeout
        }
    }

    impl Default for WorkerHealthChecker {
        fn default() -> Self {
            Self::new(Duration::from_secs(30), Duration::from_secs(300))
        }
    }

    /// Dependency health checker
    ///
    /// Monitors health of external dependencies (database, cache, etc.)
    pub struct DependencyChecker {
        name: String,
        check_fn: Box<dyn Fn() -> HealthCheckResult + Send + Sync>,
    }

    impl DependencyChecker {
        /// Creates a new dependency checker
        ///
        /// # Arguments
        ///
        /// * `name` - Name of the dependency
        /// * `check_fn` - Function to check dependency health
        pub fn new<F>(name: impl Into<String>, check_fn: F) -> Self
        where
            F: Fn() -> HealthCheckResult + Send + Sync + 'static,
        {
            Self {
                name: name.into(),
                check_fn: Box::new(check_fn),
            }
        }

        /// Checks the dependency health
        pub fn check(&self) -> HealthCheckResult {
            (self.check_fn)()
        }

        /// Gets the dependency name
        pub fn name(&self) -> &str {
            &self.name
        }
    }
}

/// Resource management utilities for controlling task resource usage
///
/// This module provides utilities for managing and limiting resource consumption
/// by tasks, including memory, CPU, and execution time limits.
pub mod resource_management {
    use std::sync::{Arc, Mutex};
    use std::time::{Duration, Instant};

    /// Resource limits for a task
    #[derive(Debug, Clone)]
    pub struct ResourceLimits {
        /// Maximum memory usage in bytes
        pub max_memory_bytes: Option<usize>,
        /// Maximum CPU time in seconds
        pub max_cpu_seconds: Option<u64>,
        /// Maximum wall-clock time in seconds
        pub max_wall_time_seconds: Option<u64>,
        /// Maximum number of file descriptors
        pub max_file_descriptors: Option<usize>,
    }

    impl ResourceLimits {
        /// Creates new resource limits with no restrictions
        pub fn unlimited() -> Self {
            Self {
                max_memory_bytes: None,
                max_cpu_seconds: None,
                max_wall_time_seconds: None,
                max_file_descriptors: None,
            }
        }

        /// Creates resource limits for memory-constrained tasks
        pub fn memory_constrained(max_memory_mb: usize) -> Self {
            Self {
                max_memory_bytes: Some(max_memory_mb * 1024 * 1024),
                max_cpu_seconds: None,
                max_wall_time_seconds: Some(300), // 5 minutes
                max_file_descriptors: Some(100),
            }
        }

        /// Creates resource limits for CPU-intensive tasks
        pub fn cpu_intensive(max_cpu_seconds: u64) -> Self {
            Self {
                max_memory_bytes: None,
                max_cpu_seconds: Some(max_cpu_seconds),
                max_wall_time_seconds: Some(max_cpu_seconds + 60),
                max_file_descriptors: Some(50),
            }
        }

        /// Creates resource limits for I/O-intensive tasks
        pub fn io_intensive(max_wall_time_seconds: u64) -> Self {
            Self {
                max_memory_bytes: Some(512 * 1024 * 1024), // 512 MB
                max_cpu_seconds: None,
                max_wall_time_seconds: Some(max_wall_time_seconds),
                max_file_descriptors: Some(1000),
            }
        }

        /// Sets maximum memory limit
        pub fn with_max_memory_mb(mut self, mb: usize) -> Self {
            self.max_memory_bytes = Some(mb * 1024 * 1024);
            self
        }

        /// Sets maximum CPU time limit
        pub fn with_max_cpu_seconds(mut self, seconds: u64) -> Self {
            self.max_cpu_seconds = Some(seconds);
            self
        }

        /// Sets maximum wall-clock time limit
        pub fn with_max_wall_time_seconds(mut self, seconds: u64) -> Self {
            self.max_wall_time_seconds = Some(seconds);
            self
        }
    }

    /// Resource usage tracker
    #[derive(Clone)]
    pub struct ResourceTracker {
        start_time: Arc<Mutex<Instant>>,
        peak_memory_bytes: Arc<Mutex<usize>>,
        limits: ResourceLimits,
    }

    impl ResourceTracker {
        /// Creates a new resource tracker with specified limits
        pub fn new(limits: ResourceLimits) -> Self {
            Self {
                start_time: Arc::new(Mutex::new(Instant::now())),
                peak_memory_bytes: Arc::new(Mutex::new(0)),
                limits,
            }
        }

        /// Starts tracking resources
        pub fn start(&self) {
            *self.start_time.lock().expect("lock should not be poisoned") = Instant::now();
        }

        /// Records memory usage
        pub fn record_memory_usage(&self, bytes: usize) {
            let mut peak = self
                .peak_memory_bytes
                .lock()
                .expect("lock should not be poisoned");
            if bytes > *peak {
                *peak = bytes;
            }
        }

        /// Checks if resource limits are exceeded
        pub fn check_limits(&self) -> Result<(), String> {
            let elapsed = self
                .start_time
                .lock()
                .expect("lock should not be poisoned")
                .elapsed();

            // Check wall-clock time
            if let Some(max_wall_time) = self.limits.max_wall_time_seconds {
                if elapsed > Duration::from_secs(max_wall_time) {
                    return Err(format!(
                        "Wall-clock time limit exceeded: {}s > {}s",
                        elapsed.as_secs(),
                        max_wall_time
                    ));
                }
            }

            // Check memory
            if let Some(max_memory) = self.limits.max_memory_bytes {
                let peak_memory = *self
                    .peak_memory_bytes
                    .lock()
                    .expect("lock should not be poisoned");
                if peak_memory > max_memory {
                    return Err(format!(
                        "Memory limit exceeded: {} bytes > {} bytes",
                        peak_memory, max_memory
                    ));
                }
            }

            Ok(())
        }

        /// Gets elapsed time
        pub fn elapsed(&self) -> Duration {
            self.start_time
                .lock()
                .expect("lock should not be poisoned")
                .elapsed()
        }

        /// Gets peak memory usage
        pub fn peak_memory_bytes(&self) -> usize {
            *self
                .peak_memory_bytes
                .lock()
                .expect("lock should not be poisoned")
        }

        /// Gets resource limits
        pub fn limits(&self) -> &ResourceLimits {
            &self.limits
        }
    }

    /// Resource pool for managing shared resources
    pub struct ResourcePool<T> {
        resources: Arc<Mutex<Vec<T>>>,
        max_size: usize,
    }

    impl<T> ResourcePool<T> {
        /// Creates a new resource pool
        pub fn new(max_size: usize) -> Self {
            Self {
                resources: Arc::new(Mutex::new(Vec::with_capacity(max_size))),
                max_size,
            }
        }

        /// Acquires a resource from the pool
        pub fn acquire(&self) -> Option<T> {
            self.resources
                .lock()
                .expect("lock should not be poisoned")
                .pop()
        }

        /// Returns a resource to the pool
        pub fn release(&self, resource: T) -> Result<(), String> {
            let mut resources = self.resources.lock().expect("lock should not be poisoned");
            if resources.len() >= self.max_size {
                return Err("Resource pool is full".to_string());
            }
            resources.push(resource);
            Ok(())
        }

        /// Gets the number of available resources
        pub fn available(&self) -> usize {
            self.resources
                .lock()
                .expect("lock should not be poisoned")
                .len()
        }

        /// Gets the maximum pool size
        pub fn max_size(&self) -> usize {
            self.max_size
        }

        /// Checks if the pool is empty
        pub fn is_empty(&self) -> bool {
            self.resources
                .lock()
                .expect("lock should not be poisoned")
                .is_empty()
        }
    }

    impl<T> Clone for ResourcePool<T> {
        fn clone(&self) -> Self {
            Self {
                resources: Arc::clone(&self.resources),
                max_size: self.max_size,
            }
        }
    }
}

/// Task lifecycle hooks for pre/post execution events
///
/// This module provides utilities for implementing hooks that run before/after
/// task execution, useful for logging, metrics, validation, and cleanup.
pub mod task_hooks {
    use serde_json::Value;
    use std::sync::Arc;

    /// Hook execution result
    pub type HookResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;

    /// Pre-execution hook
    ///
    /// Runs before task execution. Can modify task arguments or abort execution.
    pub trait PreExecutionHook: Send + Sync {
        /// Executes before task runs
        ///
        /// # Arguments
        ///
        /// * `task_name` - Name of the task
        /// * `task_id` - Unique identifier for the task instance
        /// * `args` - Task arguments (can be modified)
        ///
        /// # Returns
        ///
        /// * `Ok(())` - Continue with task execution
        /// * `Err(e)` - Abort task execution with error
        fn before_execute(
            &self,
            task_name: &str,
            task_id: &str,
            args: &mut Vec<Value>,
        ) -> HookResult;
    }

    /// Post-execution hook
    ///
    /// Runs after task execution (both success and failure).
    pub trait PostExecutionHook: Send + Sync {
        /// Executes after task completes
        ///
        /// # Arguments
        ///
        /// * `task_name` - Name of the task
        /// * `task_id` - Unique identifier for the task instance
        /// * `result` - Task execution result
        /// * `duration_ms` - Execution duration in milliseconds
        fn after_execute(
            &self,
            task_name: &str,
            task_id: &str,
            result: &Result<Value, String>,
            duration_ms: u128,
        ) -> HookResult;
    }

    /// Hook registry for managing task lifecycle hooks
    pub struct HookRegistry {
        pre_hooks: Vec<Arc<dyn PreExecutionHook>>,
        post_hooks: Vec<Arc<dyn PostExecutionHook>>,
    }

    impl HookRegistry {
        /// Creates a new hook registry
        pub fn new() -> Self {
            Self {
                pre_hooks: Vec::new(),
                post_hooks: Vec::new(),
            }
        }

        /// Registers a pre-execution hook
        pub fn register_pre_hook<H>(&mut self, hook: H)
        where
            H: PreExecutionHook + 'static,
        {
            self.pre_hooks.push(Arc::new(hook));
        }

        /// Registers a post-execution hook
        pub fn register_post_hook<H>(&mut self, hook: H)
        where
            H: PostExecutionHook + 'static,
        {
            self.post_hooks.push(Arc::new(hook));
        }

        /// Runs all pre-execution hooks
        pub fn run_pre_hooks(
            &self,
            task_name: &str,
            task_id: &str,
            args: &mut Vec<Value>,
        ) -> HookResult {
            for hook in &self.pre_hooks {
                hook.before_execute(task_name, task_id, args)?;
            }
            Ok(())
        }

        /// Runs all post-execution hooks
        pub fn run_post_hooks(
            &self,
            task_name: &str,
            task_id: &str,
            result: &Result<Value, String>,
            duration_ms: u128,
        ) -> HookResult {
            for hook in &self.post_hooks {
                hook.after_execute(task_name, task_id, result, duration_ms)?;
            }
            Ok(())
        }

        /// Gets the number of registered pre-execution hooks
        pub fn pre_hook_count(&self) -> usize {
            self.pre_hooks.len()
        }

        /// Gets the number of registered post-execution hooks
        pub fn post_hook_count(&self) -> usize {
            self.post_hooks.len()
        }
    }

    impl Default for HookRegistry {
        fn default() -> Self {
            Self::new()
        }
    }

    /// Logging hook for task execution
    pub struct LoggingHook {
        log_args: bool,
        log_results: bool,
    }

    impl LoggingHook {
        /// Creates a new logging hook
        pub fn new(log_args: bool, log_results: bool) -> Self {
            Self {
                log_args,
                log_results,
            }
        }
    }

    impl PreExecutionHook for LoggingHook {
        fn before_execute(
            &self,
            task_name: &str,
            task_id: &str,
            args: &mut Vec<Value>,
        ) -> HookResult {
            if self.log_args {
                println!("[TASK] Starting {} ({}): {:?}", task_name, task_id, args);
            } else {
                println!("[TASK] Starting {} ({})", task_name, task_id);
            }
            Ok(())
        }
    }

    impl PostExecutionHook for LoggingHook {
        fn after_execute(
            &self,
            task_name: &str,
            task_id: &str,
            result: &Result<Value, String>,
            duration_ms: u128,
        ) -> HookResult {
            match result {
                Ok(value) => {
                    if self.log_results {
                        println!(
                            "[TASK] Completed {} ({}) in {}ms: {:?}",
                            task_name, task_id, duration_ms, value
                        );
                    } else {
                        println!(
                            "[TASK] Completed {} ({}) in {}ms",
                            task_name, task_id, duration_ms
                        );
                    }
                }
                Err(e) => {
                    println!(
                        "[TASK] Failed {} ({}) in {}ms: {}",
                        task_name, task_id, duration_ms, e
                    );
                }
            }
            Ok(())
        }
    }

    /// Validation hook for checking task arguments
    pub struct ValidationHook<F>
    where
        F: Fn(&str, &Vec<Value>) -> HookResult + Send + Sync,
    {
        validator: F,
    }

    impl<F> ValidationHook<F>
    where
        F: Fn(&str, &Vec<Value>) -> HookResult + Send + Sync,
    {
        /// Creates a new validation hook
        pub fn new(validator: F) -> Self {
            Self { validator }
        }
    }

    impl<F> PreExecutionHook for ValidationHook<F>
    where
        F: Fn(&str, &Vec<Value>) -> HookResult + Send + Sync,
    {
        fn before_execute(
            &self,
            task_name: &str,
            _task_id: &str,
            args: &mut Vec<Value>,
        ) -> HookResult {
            (self.validator)(task_name, args)
        }
    }
}

/// Metrics aggregation utilities for collecting and analyzing task metrics
///
/// This module provides utilities for aggregating and analyzing metrics from
/// task execution, including histograms, percentiles, and time-series data.
pub mod metrics_aggregation {
    use std::collections::HashMap;
    use std::sync::{Arc, Mutex};
    use std::time::{Duration, Instant};

    /// Time-series data point
    #[derive(Debug, Clone)]
    pub struct DataPoint {
        /// Timestamp of the data point
        pub timestamp: Instant,
        /// Value of the metric
        pub value: f64,
    }

    /// Histogram for tracking value distributions
    pub struct Histogram {
        buckets: Vec<(f64, usize)>, // (upper_bound, count)
        total_count: usize,
        sum: f64,
    }

    impl Histogram {
        /// Creates a new histogram with default buckets
        pub fn new() -> Self {
            Self::with_buckets(vec![
                10.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 2500.0, 5000.0, 10000.0,
            ])
        }

        /// Creates a histogram with custom buckets
        pub fn with_buckets(bucket_bounds: Vec<f64>) -> Self {
            let buckets = bucket_bounds.into_iter().map(|b| (b, 0)).collect();
            Self {
                buckets,
                total_count: 0,
                sum: 0.0,
            }
        }

        /// Records a value
        pub fn record(&mut self, value: f64) {
            self.total_count += 1;
            self.sum += value;

            for (bound, count) in &mut self.buckets {
                if value <= *bound {
                    *count += 1;
                    break;
                }
            }
        }

        /// Gets the total count of recorded values
        pub fn count(&self) -> usize {
            self.total_count
        }

        /// Gets the sum of all recorded values
        pub fn sum(&self) -> f64 {
            self.sum
        }

        /// Gets the mean value
        pub fn mean(&self) -> f64 {
            if self.total_count == 0 {
                0.0
            } else {
                self.sum / self.total_count as f64
            }
        }

        /// Gets the percentile value (approximate)
        pub fn percentile(&self, p: f64) -> f64 {
            if self.total_count == 0 {
                return 0.0;
            }

            let target_count = (self.total_count as f64 * p / 100.0) as usize;
            let mut cumulative = 0;

            for (bound, count) in &self.buckets {
                cumulative += count;
                if cumulative >= target_count {
                    return *bound;
                }
            }

            // Return the last bucket bound if we didn't find it
            self.buckets.last().map(|(b, _)| *b).unwrap_or(0.0)
        }

        /// Resets the histogram
        pub fn reset(&mut self) {
            for (_, count) in &mut self.buckets {
                *count = 0;
            }
            self.total_count = 0;
            self.sum = 0.0;
        }
    }

    impl Default for Histogram {
        fn default() -> Self {
            Self::new()
        }
    }

    /// Metrics aggregator for task execution metrics
    pub struct MetricsAggregator {
        task_durations: Arc<Mutex<HashMap<String, Histogram>>>,
        task_counts: Arc<Mutex<HashMap<String, usize>>>,
        task_errors: Arc<Mutex<HashMap<String, usize>>>,
        time_series: Arc<Mutex<HashMap<String, Vec<DataPoint>>>>,
        start_time: Instant,
    }

    impl MetricsAggregator {
        /// Creates a new metrics aggregator
        pub fn new() -> Self {
            Self {
                task_durations: Arc::new(Mutex::new(HashMap::new())),
                task_counts: Arc::new(Mutex::new(HashMap::new())),
                task_errors: Arc::new(Mutex::new(HashMap::new())),
                time_series: Arc::new(Mutex::new(HashMap::new())),
                start_time: Instant::now(),
            }
        }

        /// Records task execution duration
        pub fn record_duration(&self, task_name: &str, duration: Duration) {
            let duration_ms = duration.as_secs_f64() * 1000.0;

            // Update histogram
            let mut durations = self
                .task_durations
                .lock()
                .expect("lock should not be poisoned");
            durations
                .entry(task_name.to_string())
                .or_default()
                .record(duration_ms);

            // Update count
            let mut counts = self
                .task_counts
                .lock()
                .expect("lock should not be poisoned");
            *counts.entry(task_name.to_string()).or_insert(0) += 1;

            // Update time series
            let mut series = self
                .time_series
                .lock()
                .expect("lock should not be poisoned");
            series
                .entry(task_name.to_string())
                .or_default()
                .push(DataPoint {
                    timestamp: Instant::now(),
                    value: duration_ms,
                });
        }

        /// Records task error
        pub fn record_error(&self, task_name: &str) {
            let mut errors = self
                .task_errors
                .lock()
                .expect("lock should not be poisoned");
            *errors.entry(task_name.to_string()).or_insert(0) += 1;
        }

        /// Gets task execution count
        pub fn task_count(&self, task_name: &str) -> usize {
            self.task_counts
                .lock()
                .unwrap()
                .get(task_name)
                .copied()
                .unwrap_or(0)
        }

        /// Gets task error count
        pub fn error_count(&self, task_name: &str) -> usize {
            self.task_errors
                .lock()
                .unwrap()
                .get(task_name)
                .copied()
                .unwrap_or(0)
        }

        /// Gets task success rate
        pub fn success_rate(&self, task_name: &str) -> f64 {
            let total = self.task_count(task_name);
            if total == 0 {
                return 100.0;
            }
            let errors = self.error_count(task_name);
            ((total - errors) as f64 / total as f64) * 100.0
        }

        /// Gets mean duration for a task
        pub fn mean_duration(&self, task_name: &str) -> f64 {
            self.task_durations
                .lock()
                .unwrap()
                .get(task_name)
                .map(|h| h.mean())
                .unwrap_or(0.0)
        }

        /// Gets percentile duration for a task
        pub fn percentile_duration(&self, task_name: &str, percentile: f64) -> f64 {
            self.task_durations
                .lock()
                .unwrap()
                .get(task_name)
                .map(|h| h.percentile(percentile))
                .unwrap_or(0.0)
        }

        /// Gets throughput (tasks per second) for a task
        pub fn throughput(&self, task_name: &str) -> f64 {
            let elapsed = self.start_time.elapsed().as_secs_f64();
            if elapsed == 0.0 {
                return 0.0;
            }
            self.task_count(task_name) as f64 / elapsed
        }

        /// Gets all task names
        pub fn task_names(&self) -> Vec<String> {
            self.task_counts
                .lock()
                .expect("lock should not be poisoned")
                .keys()
                .cloned()
                .collect()
        }

        /// Generates a summary report
        pub fn summary(&self, task_name: &str) -> String {
            let count = self.task_count(task_name);
            let errors = self.error_count(task_name);
            let success_rate = self.success_rate(task_name);
            let mean = self.mean_duration(task_name);
            let p50 = self.percentile_duration(task_name, 50.0);
            let p95 = self.percentile_duration(task_name, 95.0);
            let p99 = self.percentile_duration(task_name, 99.0);
            let throughput = self.throughput(task_name);

            format!(
                "Task Metrics: {}\n\
                 - Total Executions: {}\n\
                 - Errors: {} ({:.2}% success rate)\n\
                 - Mean Duration: {:.2}ms\n\
                 - P50 Duration: {:.2}ms\n\
                 - P95 Duration: {:.2}ms\n\
                 - P99 Duration: {:.2}ms\n\
                 - Throughput: {:.2} tasks/sec",
                task_name, count, errors, success_rate, mean, p50, p95, p99, throughput
            )
        }

        /// Resets all metrics
        pub fn reset(&self) {
            self.task_durations
                .lock()
                .expect("lock should not be poisoned")
                .clear();
            self.task_counts
                .lock()
                .expect("lock should not be poisoned")
                .clear();
            self.task_errors
                .lock()
                .expect("lock should not be poisoned")
                .clear();
            self.time_series
                .lock()
                .expect("lock should not be poisoned")
                .clear();
        }
    }

    impl Default for MetricsAggregator {
        fn default() -> Self {
            Self::new()
        }
    }

    impl Clone for MetricsAggregator {
        fn clone(&self) -> Self {
            Self {
                task_durations: Arc::clone(&self.task_durations),
                task_counts: Arc::clone(&self.task_counts),
                task_errors: Arc::clone(&self.task_errors),
                time_series: Arc::clone(&self.time_series),
                start_time: self.start_time,
            }
        }
    }
}

/// Task cancellation utilities for managing task lifecycle
///
/// This module provides utilities for cancelling tasks, implementing timeouts,
/// and managing task execution boundaries.
pub mod task_cancellation {
    use std::sync::{Arc, Mutex};
    use std::time::{Duration, Instant};

    /// Cancellation token for task control
    #[derive(Clone)]
    pub struct CancellationToken {
        cancelled: Arc<Mutex<bool>>,
        cancellation_reason: Arc<Mutex<Option<String>>>,
    }

    impl CancellationToken {
        /// Creates a new cancellation token
        pub fn new() -> Self {
            Self {
                cancelled: Arc::new(Mutex::new(false)),
                cancellation_reason: Arc::new(Mutex::new(None)),
            }
        }

        /// Cancels the token with an optional reason
        pub fn cancel(&self, reason: Option<String>) {
            *self.cancelled.lock().expect("lock should not be poisoned") = true;
            *self
                .cancellation_reason
                .lock()
                .expect("lock should not be poisoned") = reason;
        }

        /// Checks if the token is cancelled
        pub fn is_cancelled(&self) -> bool {
            *self.cancelled.lock().expect("lock should not be poisoned")
        }

        /// Gets the cancellation reason if available
        pub fn cancellation_reason(&self) -> Option<String> {
            self.cancellation_reason
                .lock()
                .expect("lock should not be poisoned")
                .clone()
        }

        /// Throws an error if the token is cancelled
        pub fn check_cancelled(&self) -> Result<(), String> {
            if self.is_cancelled() {
                Err(self
                    .cancellation_reason()
                    .unwrap_or_else(|| "Task was cancelled".to_string()))
            } else {
                Ok(())
            }
        }
    }

    impl Default for CancellationToken {
        fn default() -> Self {
            Self::new()
        }
    }

    /// Timeout manager for task execution
    pub struct TimeoutManager {
        timeout: Duration,
        start_time: Instant,
    }

    impl TimeoutManager {
        /// Creates a new timeout manager
        pub fn new(timeout: Duration) -> Self {
            Self {
                timeout,
                start_time: Instant::now(),
            }
        }

        /// Checks if the timeout has been exceeded
        pub fn is_timed_out(&self) -> bool {
            self.start_time.elapsed() > self.timeout
        }

        /// Gets the remaining time
        pub fn remaining(&self) -> Duration {
            let elapsed = self.start_time.elapsed();
            if elapsed >= self.timeout {
                Duration::from_secs(0)
            } else {
                self.timeout - elapsed
            }
        }

        /// Gets the elapsed time
        pub fn elapsed(&self) -> Duration {
            self.start_time.elapsed()
        }

        /// Checks timeout and returns error if exceeded
        pub fn check_timeout(&self) -> Result<(), String> {
            if self.is_timed_out() {
                Err(format!(
                    "Task timeout exceeded: {}s",
                    self.timeout.as_secs()
                ))
            } else {
                Ok(())
            }
        }
    }

    /// Task execution guard combining cancellation and timeout
    pub struct ExecutionGuard {
        cancellation_token: CancellationToken,
        timeout_manager: Option<TimeoutManager>,
    }

    impl ExecutionGuard {
        /// Creates a new execution guard
        pub fn new(cancellation_token: CancellationToken, timeout: Option<Duration>) -> Self {
            Self {
                cancellation_token,
                timeout_manager: timeout.map(TimeoutManager::new),
            }
        }

        /// Checks if execution should continue
        pub fn should_continue(&self) -> Result<(), String> {
            self.cancellation_token.check_cancelled()?;
            if let Some(timeout_mgr) = &self.timeout_manager {
                timeout_mgr.check_timeout()?;
            }
            Ok(())
        }

        /// Gets the cancellation token
        pub fn cancellation_token(&self) -> &CancellationToken {
            &self.cancellation_token
        }

        /// Gets remaining timeout if configured
        pub fn remaining_timeout(&self) -> Option<Duration> {
            self.timeout_manager.as_ref().map(|t| t.remaining())
        }
    }
}

/// Advanced retry strategies for fault-tolerant task execution
///
/// This module provides sophisticated retry strategies including exponential backoff,
/// jitter, circuit breaker integration, and custom retry policies.
pub mod retry_strategies {
    use std::time::Duration;

    /// Retry strategy configuration
    #[derive(Debug, Clone)]
    pub struct RetryStrategy {
        /// Maximum number of retry attempts
        pub max_retries: u32,
        /// Initial delay between retries
        pub initial_delay: Duration,
        /// Maximum delay between retries
        pub max_delay: Duration,
        /// Backoff multiplier
        pub backoff_multiplier: f64,
        /// Whether to add jitter
        pub use_jitter: bool,
    }

    impl RetryStrategy {
        /// Creates a new retry strategy with exponential backoff
        pub fn exponential_backoff(max_retries: u32, initial_delay: Duration) -> Self {
            Self {
                max_retries,
                initial_delay,
                max_delay: Duration::from_secs(300), // 5 minutes
                backoff_multiplier: 2.0,
                use_jitter: true,
            }
        }

        /// Creates a linear backoff strategy
        pub fn linear_backoff(max_retries: u32, delay: Duration) -> Self {
            Self {
                max_retries,
                initial_delay: delay,
                max_delay: delay,
                backoff_multiplier: 1.0,
                use_jitter: false,
            }
        }

        /// Creates a fixed delay strategy
        pub fn fixed_delay(max_retries: u32, delay: Duration) -> Self {
            Self {
                max_retries,
                initial_delay: delay,
                max_delay: delay,
                backoff_multiplier: 1.0,
                use_jitter: false,
            }
        }

        /// Creates a fibonacci backoff strategy
        pub fn fibonacci_backoff(max_retries: u32, base_delay: Duration) -> Self {
            Self {
                max_retries,
                initial_delay: base_delay,
                max_delay: Duration::from_secs(600), // 10 minutes
                backoff_multiplier: 1.618,           // Golden ratio
                use_jitter: true,
            }
        }

        /// Calculates the delay for a specific retry attempt
        pub fn calculate_delay(&self, attempt: u32) -> Duration {
            if attempt == 0 {
                return Duration::from_secs(0);
            }

            let base_delay = if self.backoff_multiplier == 1.0 {
                self.initial_delay
            } else {
                let multiplier = self.backoff_multiplier.powi(attempt as i32 - 1);
                let delay_ms = self.initial_delay.as_millis() as f64 * multiplier;
                Duration::from_millis(delay_ms.min(self.max_delay.as_millis() as f64) as u64)
            };

            if self.use_jitter {
                // Add ±25% jitter
                let jitter_factor = 0.75 + (rand::random::<f64>() * 0.5);
                let delay_ms = (base_delay.as_millis() as f64 * jitter_factor) as u64;
                Duration::from_millis(delay_ms)
            } else {
                base_delay
            }
        }

        /// Sets maximum delay
        pub fn with_max_delay(mut self, max_delay: Duration) -> Self {
            self.max_delay = max_delay;
            self
        }

        /// Sets whether to use jitter
        pub fn with_jitter(mut self, use_jitter: bool) -> Self {
            self.use_jitter = use_jitter;
            self
        }

        /// Sets backoff multiplier
        pub fn with_multiplier(mut self, multiplier: f64) -> Self {
            self.backoff_multiplier = multiplier;
            self
        }
    }

    impl Default for RetryStrategy {
        fn default() -> Self {
            Self::exponential_backoff(3, Duration::from_secs(1))
        }
    }

    /// Retry decision based on error type
    pub trait RetryPolicy: Send + Sync {
        /// Determines if a retry should be attempted for the given error
        fn should_retry(&self, error: &str, attempt: u32) -> bool;
    }

    /// Default retry policy that retries on all errors
    pub struct DefaultRetryPolicy {
        max_retries: u32,
    }

    impl DefaultRetryPolicy {
        /// Creates a new default retry policy
        pub fn new(max_retries: u32) -> Self {
            Self { max_retries }
        }
    }

    impl RetryPolicy for DefaultRetryPolicy {
        fn should_retry(&self, _error: &str, attempt: u32) -> bool {
            attempt < self.max_retries
        }
    }

    /// Retry policy that only retries on specific error patterns
    pub struct ErrorPatternRetryPolicy {
        max_retries: u32,
        retryable_patterns: Vec<String>,
    }

    impl ErrorPatternRetryPolicy {
        /// Creates a new error pattern retry policy
        pub fn new(max_retries: u32, retryable_patterns: Vec<String>) -> Self {
            Self {
                max_retries,
                retryable_patterns,
            }
        }
    }

    impl RetryPolicy for ErrorPatternRetryPolicy {
        fn should_retry(&self, error: &str, attempt: u32) -> bool {
            if attempt >= self.max_retries {
                return false;
            }
            self.retryable_patterns
                .iter()
                .any(|pattern| error.contains(pattern))
        }
    }
}

/// Task dependency management for workflow orchestration
///
/// This module provides utilities for managing task dependencies,
/// building dependency graphs, and ensuring proper execution order.
pub mod task_dependencies {
    use std::collections::{HashMap, HashSet};

    /// Task dependency graph
    pub struct DependencyGraph {
        /// Dependencies: task_id -> set of task_ids it depends on
        dependencies: HashMap<String, HashSet<String>>,
        /// Reverse dependencies: task_id -> set of task_ids that depend on it
        dependents: HashMap<String, HashSet<String>>,
    }

    impl DependencyGraph {
        /// Creates a new dependency graph
        pub fn new() -> Self {
            Self {
                dependencies: HashMap::new(),
                dependents: HashMap::new(),
            }
        }

        /// Adds a task to the graph
        pub fn add_task(&mut self, task_id: impl Into<String>) {
            let task_id = task_id.into();
            self.dependencies.entry(task_id.clone()).or_default();
            self.dependents.entry(task_id).or_default();
        }

        /// Adds a dependency: task depends on dependency
        pub fn add_dependency(
            &mut self,
            task_id: impl Into<String>,
            dependency_id: impl Into<String>,
        ) {
            let task_id = task_id.into();
            let dependency_id = dependency_id.into();

            self.dependencies
                .entry(task_id.clone())
                .or_default()
                .insert(dependency_id.clone());

            self.dependents
                .entry(dependency_id)
                .or_default()
                .insert(task_id);
        }

        /// Gets direct dependencies of a task
        pub fn get_dependencies(&self, task_id: &str) -> Vec<String> {
            self.dependencies
                .get(task_id)
                .map(|deps| deps.iter().cloned().collect())
                .unwrap_or_default()
        }

        /// Gets all tasks that depend on this task
        pub fn get_dependents(&self, task_id: &str) -> Vec<String> {
            self.dependents
                .get(task_id)
                .map(|deps| deps.iter().cloned().collect())
                .unwrap_or_default()
        }

        /// Checks if there are circular dependencies
        pub fn has_circular_dependencies(&self) -> bool {
            let mut visited = HashSet::new();
            let mut rec_stack = HashSet::new();

            for task_id in self.dependencies.keys() {
                if self.has_cycle(task_id, &mut visited, &mut rec_stack) {
                    return true;
                }
            }
            false
        }

        fn has_cycle(
            &self,
            task_id: &str,
            visited: &mut HashSet<String>,
            rec_stack: &mut HashSet<String>,
        ) -> bool {
            if rec_stack.contains(task_id) {
                return true;
            }
            if visited.contains(task_id) {
                return false;
            }

            visited.insert(task_id.to_string());
            rec_stack.insert(task_id.to_string());

            if let Some(deps) = self.dependencies.get(task_id) {
                for dep in deps {
                    if self.has_cycle(dep, visited, rec_stack) {
                        return true;
                    }
                }
            }

            rec_stack.remove(task_id);
            false
        }

        /// Gets tasks in topological order (tasks with no dependencies first)
        pub fn topological_sort(&self) -> Result<Vec<String>, String> {
            if self.has_circular_dependencies() {
                return Err("Circular dependencies detected".to_string());
            }

            let mut result = Vec::new();
            let mut visited = HashSet::new();
            let mut temp_mark = HashSet::new();

            for task_id in self.dependencies.keys() {
                if !visited.contains(task_id) {
                    self.visit(task_id, &mut visited, &mut temp_mark, &mut result)?;
                }
            }

            Ok(result)
        }

        fn visit(
            &self,
            task_id: &str,
            visited: &mut HashSet<String>,
            temp_mark: &mut HashSet<String>,
            result: &mut Vec<String>,
        ) -> Result<(), String> {
            if temp_mark.contains(task_id) {
                return Err("Circular dependency detected".to_string());
            }
            if visited.contains(task_id) {
                return Ok(());
            }

            temp_mark.insert(task_id.to_string());

            if let Some(deps) = self.dependencies.get(task_id) {
                for dep in deps {
                    self.visit(dep, visited, temp_mark, result)?;
                }
            }

            temp_mark.remove(task_id);
            visited.insert(task_id.to_string());
            result.push(task_id.to_string());

            Ok(())
        }

        /// Gets tasks that are ready to execute (all dependencies satisfied)
        pub fn get_ready_tasks(&self, completed_tasks: &HashSet<String>) -> Vec<String> {
            self.dependencies
                .iter()
                .filter(|(task_id, deps)| {
                    !completed_tasks.contains(*task_id)
                        && deps.iter().all(|dep| completed_tasks.contains(dep))
                })
                .map(|(task_id, _)| task_id.clone())
                .collect()
        }
    }

    impl Default for DependencyGraph {
        fn default() -> Self {
            Self::new()
        }
    }
}

/// Performance profiling utilities for task execution analysis
///
/// This module provides utilities for profiling task execution,
/// identifying bottlenecks, and optimizing performance.
pub mod performance_profiling {
    use std::collections::HashMap;
    use std::sync::{Arc, Mutex};
    use std::time::{Duration, Instant};

    /// Performance profile for a task or operation
    #[derive(Debug, Clone)]
    pub struct PerformanceProfile {
        /// Name of the profiled operation
        pub name: String,
        /// Total execution time
        pub total_duration: Duration,
        /// Time spent in child operations
        pub children_duration: Duration,
        /// Self time (total - children)
        pub self_duration: Duration,
        /// Number of invocations
        pub invocation_count: usize,
    }

    impl PerformanceProfile {
        /// Gets average duration per invocation
        pub fn avg_duration(&self) -> Duration {
            if self.invocation_count == 0 {
                Duration::from_secs(0)
            } else {
                self.total_duration / self.invocation_count as u32
            }
        }

        /// Gets percentage of time spent in self vs children
        pub fn self_time_percentage(&self) -> f64 {
            if self.total_duration.as_millis() == 0 {
                0.0
            } else {
                (self.self_duration.as_millis() as f64 / self.total_duration.as_millis() as f64)
                    * 100.0
            }
        }
    }

    /// Performance profiler for tracking execution time
    pub struct PerformanceProfiler {
        profiles: Arc<Mutex<HashMap<String, PerformanceProfile>>>,
        active_spans: Arc<Mutex<Vec<(String, Instant)>>>,
    }

    impl PerformanceProfiler {
        /// Creates a new performance profiler
        pub fn new() -> Self {
            Self {
                profiles: Arc::new(Mutex::new(HashMap::new())),
                active_spans: Arc::new(Mutex::new(Vec::new())),
            }
        }

        /// Starts profiling an operation
        pub fn start_span(&self, name: impl Into<String>) {
            let name = name.into();
            self.active_spans
                .lock()
                .unwrap()
                .push((name, Instant::now()));
        }

        /// Ends the current profiling span
        pub fn end_span(&self) {
            let span_data = self
                .active_spans
                .lock()
                .expect("lock should not be poisoned")
                .pop();
            if let Some((name, start_time)) = span_data {
                let duration = start_time.elapsed();
                let mut profiles = self.profiles.lock().expect("lock should not be poisoned");

                let profile = profiles
                    .entry(name.clone())
                    .or_insert_with(|| PerformanceProfile {
                        name: name.clone(),
                        total_duration: Duration::from_secs(0),
                        children_duration: Duration::from_secs(0),
                        self_duration: Duration::from_secs(0),
                        invocation_count: 0,
                    });

                profile.total_duration += duration;
                profile.invocation_count += 1;
                profile.self_duration = profile.total_duration - profile.children_duration;
            }
        }

        /// Gets the profile for a specific operation
        pub fn get_profile(&self, name: &str) -> Option<PerformanceProfile> {
            self.profiles
                .lock()
                .expect("lock should not be poisoned")
                .get(name)
                .cloned()
        }

        /// Gets all profiles
        pub fn get_all_profiles(&self) -> Vec<PerformanceProfile> {
            self.profiles
                .lock()
                .expect("lock should not be poisoned")
                .values()
                .cloned()
                .collect()
        }

        /// Gets profiles sorted by total duration (slowest first)
        pub fn get_slowest_operations(&self, limit: usize) -> Vec<PerformanceProfile> {
            let mut profiles = self.get_all_profiles();
            profiles.sort_by(|a, b| b.total_duration.cmp(&a.total_duration));
            profiles.truncate(limit);
            profiles
        }

        /// Generates a performance report
        pub fn generate_report(&self) -> String {
            let profiles = self.get_all_profiles();
            if profiles.is_empty() {
                return "No profiling data available".to_string();
            }

            let mut report = String::from("Performance Profile Report\n");
            report.push_str(&format!("{}\n", "=".repeat(80)));

            for profile in profiles {
                report.push_str(&format!(
                    "{:<30} | Count: {:>6} | Total: {:>8.2}ms | Avg: {:>8.2}ms | Self: {:>6.1}%\n",
                    profile.name,
                    profile.invocation_count,
                    profile.total_duration.as_secs_f64() * 1000.0,
                    profile.avg_duration().as_secs_f64() * 1000.0,
                    profile.self_time_percentage()
                ));
            }

            report
        }

        /// Resets all profiling data
        pub fn reset(&self) {
            self.profiles
                .lock()
                .expect("lock should not be poisoned")
                .clear();
            self.active_spans
                .lock()
                .expect("lock should not be poisoned")
                .clear();
        }
    }

    impl Default for PerformanceProfiler {
        fn default() -> Self {
            Self::new()
        }
    }

    impl Clone for PerformanceProfiler {
        fn clone(&self) -> Self {
            Self {
                profiles: Arc::clone(&self.profiles),
                active_spans: Arc::clone(&self.active_spans),
            }
        }
    }

    /// RAII guard for automatic span tracking
    pub struct ProfileSpan<'a> {
        profiler: &'a PerformanceProfiler,
    }

    impl<'a> ProfileSpan<'a> {
        /// Creates a new profile span
        pub fn new(profiler: &'a PerformanceProfiler, name: impl Into<String>) -> Self {
            profiler.start_span(name);
            Self { profiler }
        }
    }

    impl<'a> Drop for ProfileSpan<'a> {
        fn drop(&mut self) {
            self.profiler.end_span();
        }
    }
}