camel-component-container 0.8.1

Docker/Container component for rust-camel — run, manage and listen to container events via the Camel routing engine
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
//! Camel Container Component
//!
//! This component provides integration with Docker containers, allowing Camel routes
//! to manage container lifecycle (create, start, stop, remove) and consume container events.

pub mod bundle;

pub use bundle::ContainerBundle;

use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};

use async_trait::async_trait;
use bollard::Docker;
use bollard::models::{
    ContainerCreateBody, NetworkConnectRequest, NetworkCreateRequest, NetworkDisconnectRequest,
};
use bollard::query_parameters::{
    CreateContainerOptions, CreateImageOptions, EventsOptions, ListContainersOptions,
    ListImagesOptions, ListNetworksOptions, LogsOptions, RemoveContainerOptions,
    StartContainerOptions,
};
use bollard::service::{HostConfig, PortBinding};
use camel_component_api::parse_uri;
use camel_component_api::{Body, BoxProcessor, CamelError, Exchange, Message};
use camel_component_api::{Component, Consumer, ConsumerContext, Endpoint, ProducerContext};
use tower::Service;

/// Global tracker for containers created by this component.
/// Used for cleanup on shutdown (especially important for hot-reload scenarios).
static CONTAINER_TRACKER: once_cell::sync::Lazy<Arc<Mutex<HashSet<String>>>> =
    once_cell::sync::Lazy::new(|| Arc::new(Mutex::new(HashSet::new())));

/// Registers a container ID for tracking (will be cleaned up on shutdown).
fn track_container(id: String) {
    if let Ok(mut tracker) = CONTAINER_TRACKER.lock() {
        tracker.insert(id);
    }
}

/// Removes a container ID from tracking (when it's been removed naturally).
fn untrack_container(id: &str) {
    if let Ok(mut tracker) = CONTAINER_TRACKER.lock() {
        tracker.remove(id);
    }
}

/// Cleans up all tracked containers. Call this on application shutdown.
pub async fn cleanup_tracked_containers() {
    let ids: Vec<String> = {
        match CONTAINER_TRACKER.lock() {
            Ok(tracker) => tracker.iter().cloned().collect(),
            Err(_) => return,
        }
    };

    if ids.is_empty() {
        return;
    }

    tracing::info!("Cleaning up {} tracked container(s)", ids.len());

    let docker = match Docker::connect_with_local_defaults() {
        Ok(d) => d,
        Err(e) => {
            tracing::error!("Failed to connect to Docker for cleanup: {}", e);
            return;
        }
    };

    for id in ids {
        match docker
            .remove_container(
                &id,
                Some(RemoveContainerOptions {
                    force: true,
                    ..Default::default()
                }),
            )
            .await
        {
            Ok(_) => {
                tracing::debug!("Cleaned up container {}", id);
                untrack_container(&id);
            }
            Err(e) => {
                tracing::warn!("Failed to cleanup container {}: {}", id, e);
            }
        }
    }
}

// Header constants for container operations

/// Timeout (seconds) for connecting to the Docker daemon.
const DOCKER_CONNECT_TIMEOUT_SECS: u64 = 120;

/// Header key for specifying the container action (e.g., "list", "run", "start", "stop", "remove").
pub const HEADER_ACTION: &str = "CamelContainerAction";

/// Header key for specifying the container image to use for "run" operations.
pub const HEADER_IMAGE: &str = "CamelContainerImage";

/// Header key for specifying or receiving the container ID.
pub const HEADER_CONTAINER_ID: &str = "CamelContainerId";

/// Header key for the log stream type (stdout or stderr).
pub const HEADER_LOG_STREAM: &str = "CamelContainerLogStream";

/// Header key for the log timestamp.
pub const HEADER_LOG_TIMESTAMP: &str = "CamelContainerLogTimestamp";

/// Header key for specifying the container name for "run" operations.
pub const HEADER_CONTAINER_NAME: &str = "CamelContainerName";

/// Header key for the result status of a container operation (e.g., "success").
pub const HEADER_ACTION_RESULT: &str = "CamelContainerActionResult";

/// Header key for specifying the command to execute in a container.
pub const HEADER_CMD: &str = "CamelContainerCmd";

/// Header key for specifying the network name for network operations.
pub const HEADER_NETWORK: &str = "CamelContainerNetwork";

/// Header key for the exit code of an exec operation.
pub const HEADER_EXIT_CODE: &str = "CamelContainerExitCode";

/// Header key for specifying volume mounts.
pub const HEADER_VOLUMES: &str = "CamelContainerVolumes";

/// Header key for the exec instance ID.
pub const HEADER_EXEC_ID: &str = "CamelContainerExecId";

// ---------------------------------------------------------------------------
// ContainerGlobalConfig
// ---------------------------------------------------------------------------

/// Global configuration for Container component.
/// Supports serde deserialization with defaults and builder methods.
/// These are the fallback defaults when URI params are not set.
#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
#[serde(default)]
pub struct ContainerGlobalConfig {
    /// The Docker host URL (default: "unix:///var/run/docker.sock").
    pub docker_host: String,
}

impl Default for ContainerGlobalConfig {
    fn default() -> Self {
        Self {
            docker_host: "unix:///var/run/docker.sock".to_string(),
        }
    }
}

impl ContainerGlobalConfig {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_docker_host(mut self, v: impl Into<String>) -> Self {
        self.docker_host = v.into();
        self
    }
}

// ---------------------------------------------------------------------------
// ContainerConfig (endpoint configuration)
// ---------------------------------------------------------------------------

/// Configuration for the container component endpoint.
///
/// This struct holds the parsed URI configuration including the operation type,
/// optional container image, and Docker host connection details.
#[derive(Debug, Clone)]
pub struct ContainerConfig {
    /// The operation to perform (e.g., "list", "run", "start", "stop", "remove", "events").
    pub operation: String,
    /// The container image to use for "run" operations (can be overridden via header).
    pub image: Option<String>,
    /// The container name to use for "run" operations (can be overridden via header).
    pub name: Option<String>,
    /// The Docker host URL (defaults to "unix:///var/run/docker.sock").
    pub host: Option<String>,
    /// Command to run in the container (e.g., "sleep 30").
    pub cmd: Option<String>,
    /// Port mappings in format "hostPort:containerPort" (e.g., "8080:80,8443:443").
    pub ports: Option<String>,
    /// Environment variables in format "KEY=value,KEY2=value2".
    pub env: Option<String>,
    /// Network mode (e.g., "bridge", "host", "none"). Default: "bridge".
    pub network: Option<String>,
    /// Container ID or name for logs consumer.
    pub container_id: Option<String>,
    /// Follow log output (default: true for consumer).
    pub follow: bool,
    /// Include timestamps in logs (default: false).
    pub timestamps: bool,
    /// Number of lines to show from the end of logs (default: all).
    pub tail: Option<String>,
    /// Automatically pull the image if not present (default: true).
    pub auto_pull: bool,
    /// Automatically remove the container when it exits (default: true).
    pub auto_remove: bool,
    /// Volume mounts in format "host:container:ro" (e.g., "./html:/usr/share/nginx/html:ro").
    pub volumes: Option<String>,
    /// User to run the container or exec command as (e.g., "root").
    pub user: Option<String>,
    /// Working directory inside the container.
    pub workdir: Option<String>,
    /// Whether to detach from the exec process (default: false).
    pub detach: bool,
    /// Network driver for network-create (e.g., "bridge", "overlay").
    pub driver: Option<String>,
    /// Whether to force the operation (default: false).
    pub force: bool,
}

impl ContainerConfig {
    /// Parses a container URI into a `ContainerConfig`.
    ///
    /// # Arguments
    /// * `uri` - The URI to parse (e.g., "container:run?image=alpine")
    ///
    /// # Errors
    /// Returns an error if the URI scheme is not "container".
    pub fn from_uri(uri: &str) -> Result<Self, CamelError> {
        let parts = parse_uri(uri)?;
        if parts.scheme != "container" {
            return Err(CamelError::InvalidUri(format!(
                "expected scheme 'container', got '{}'",
                parts.scheme
            )));
        }

        let image = parts.params.get("image").cloned();
        let name = parts.params.get("name").cloned();
        let cmd = parts.params.get("cmd").cloned();
        let ports = parts.params.get("ports").cloned();
        let env = parts.params.get("env").cloned();
        let network = parts.params.get("network").cloned();
        let container_id = parts.params.get("containerId").cloned();
        let follow = parts
            .params
            .get("follow")
            .map(|v| v.eq_ignore_ascii_case("true"))
            .unwrap_or(true);
        let timestamps = parts
            .params
            .get("timestamps")
            .map(|v| v.eq_ignore_ascii_case("true"))
            .unwrap_or(false);
        let tail = parts.params.get("tail").cloned();
        let auto_pull = parts
            .params
            .get("autoPull")
            .map(|v| v.eq_ignore_ascii_case("true"))
            .unwrap_or(true);
        let auto_remove = parts
            .params
            .get("autoRemove")
            .map(|v| v.eq_ignore_ascii_case("true"))
            .unwrap_or(true);
        // host is only set from URI param; global config defaults are applied later
        let host = parts.params.get("host").cloned();
        let volumes = parts.params.get("volumes").cloned();
        let user = parts.params.get("user").cloned();
        let workdir = parts.params.get("workdir").cloned();
        let detach = parts
            .params
            .get("detach")
            .map(|v| v.eq_ignore_ascii_case("true"))
            .unwrap_or(false);
        let driver = parts.params.get("driver").cloned();
        let force = parts
            .params
            .get("force")
            .map(|v| v.eq_ignore_ascii_case("true"))
            .unwrap_or(false);

        Ok(Self {
            operation: parts.path,
            image,
            name,
            host,
            cmd,
            ports,
            env,
            network,
            container_id,
            follow,
            timestamps,
            tail,
            auto_pull,
            auto_remove,
            volumes,
            user,
            workdir,
            detach,
            driver,
            force,
        })
    }

    /// Apply global config defaults to this endpoint config.
    /// Only sets values that are currently `None`.
    fn apply_global_defaults(&mut self, global: &ContainerGlobalConfig) {
        if self.host.is_none() {
            self.host = Some(global.docker_host.clone());
        }
    }

    fn docker_socket_path(&self) -> Result<&str, CamelError> {
        let host = self.host.as_deref().unwrap_or(if cfg!(windows) {
            "npipe:////./pipe/docker_engine"
        } else {
            "unix:///var/run/docker.sock"
        });

        if host.starts_with("unix://") || host.starts_with("npipe://") {
            return Ok(host);
        }

        if host.contains("://") {
            return Err(CamelError::ProcessorError(format!(
                "Unsupported Docker host scheme: {} (only unix:// and npipe:// are supported)",
                host
            )));
        }

        Ok(host)
    }

    pub fn connect_docker_client(&self) -> Result<Docker, CamelError> {
        let socket_path = self.docker_socket_path()?;
        Docker::connect_with_socket(
            socket_path,
            DOCKER_CONNECT_TIMEOUT_SECS,
            bollard::API_DEFAULT_VERSION,
        )
        .map_err(|e| {
            CamelError::ProcessorError(format!("Failed to connect to docker daemon: {}", e))
        })
    }

    /// Connects to the Docker daemon using the configured host.
    ///
    /// This method establishes a Unix socket connection to Docker and verifies
    /// the connection by sending a ping request.
    ///
    /// # Errors
    /// Returns an error if the connection fails or the ping request fails.
    pub async fn connect_docker(&self) -> Result<Docker, CamelError> {
        let docker = self.connect_docker_client()?;
        docker
            .ping()
            .await
            .map_err(|e| CamelError::ProcessorError(format!("Docker ping failed: {}", e)))?;
        Ok(docker)
    }

    #[allow(clippy::type_complexity)]
    fn parse_ports(&self) -> Option<(Vec<String>, HashMap<String, Option<Vec<PortBinding>>>)> {
        let ports_str = self.ports.as_ref()?;

        let mut exposed_ports: Vec<String> = Vec::new();
        let mut port_bindings: HashMap<String, Option<Vec<PortBinding>>> = HashMap::new();

        for mapping in ports_str.split(',') {
            let mapping = mapping.trim();
            if mapping.is_empty() {
                continue;
            }

            let (host_port, container_spec) = mapping.split_once(':')?;

            let (container_port, protocol) = if container_spec.contains('/') {
                let parts: Vec<&str> = container_spec.split('/').collect();
                (parts[0], parts[1])
            } else {
                (container_spec, "tcp")
            };

            let container_key = format!("{}/{}", container_port, protocol);

            exposed_ports.push(container_key.clone());

            port_bindings.insert(
                container_key,
                Some(vec![PortBinding {
                    host_ip: None,
                    host_port: Some(host_port.to_string()),
                }]),
            );
        }

        if exposed_ports.is_empty() {
            None
        } else {
            Some((exposed_ports, port_bindings))
        }
    }

    fn parse_env(&self) -> Option<Vec<String>> {
        let env_str = self.env.as_ref()?;

        let env_vars: Vec<String> = env_str
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();

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

    #[cfg(test)]
    #[allow(clippy::type_complexity)]
    fn parse_volumes(&self) -> Option<(Vec<String>, Vec<String>)> {
        self.volumes.as_deref().and_then(parse_volume_str)
    }
}

/// Parses a volume specification string into bind mounts and anonymous volumes.
///
/// Format: `host:container:ro|rw` for bind mounts, `path` for anonymous volumes,
/// `path:ro|rw` for anonymous volumes with mode, or `name:container` for named volumes.
#[allow(clippy::type_complexity)]
fn parse_volume_str(volumes_str: &str) -> Option<(Vec<String>, Vec<String>)> {
    let mut binds: Vec<String> = Vec::new();
    let mut anonymous_volumes: Vec<String> = Vec::new();

    for entry in volumes_str.split(',') {
        let entry = entry.trim();
        if entry.is_empty() {
            continue;
        }

        let segments: Vec<&str> = entry.split(':').collect();

        match segments.len() {
            3 => {
                let source = segments[0];
                let target = segments[1];
                let mode = segments[2];
                if mode != "ro" && mode != "rw" {
                    continue;
                }
                binds.push(format!("{}:{}:{}", source, target, mode));
            }
            2 => {
                let a = segments[0];
                let b = segments[1];
                if b == "ro" || b == "rw" {
                    anonymous_volumes.push(a.to_string());
                } else {
                    binds.push(format!("{}:{}", a, b));
                }
            }
            1 => {
                anonymous_volumes.push(segments[0].to_string());
            }
            _ => continue,
        }
    }

    if binds.is_empty() && anonymous_volumes.is_empty() {
        None
    } else {
        Some((binds, anonymous_volumes))
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProducerOperation {
    List,
    Run,
    Start,
    Stop,
    Remove,
    Exec,
    NetworkCreate,
    NetworkConnect,
    NetworkDisconnect,
    NetworkRemove,
    NetworkList,
}

fn parse_producer_operation(operation: &str) -> Result<ProducerOperation, CamelError> {
    match operation {
        "list" => Ok(ProducerOperation::List),
        "run" => Ok(ProducerOperation::Run),
        "start" => Ok(ProducerOperation::Start),
        "stop" => Ok(ProducerOperation::Stop),
        "remove" => Ok(ProducerOperation::Remove),
        "exec" => Ok(ProducerOperation::Exec),
        "network-create" => Ok(ProducerOperation::NetworkCreate),
        "network-connect" => Ok(ProducerOperation::NetworkConnect),
        "network-disconnect" => Ok(ProducerOperation::NetworkDisconnect),
        "network-remove" => Ok(ProducerOperation::NetworkRemove),
        "network-list" => Ok(ProducerOperation::NetworkList),
        _ => Err(CamelError::ProcessorError(format!(
            "Unknown container operation: {}",
            operation
        ))),
    }
}

fn resolve_container_name(exchange: &Exchange, config: &ContainerConfig) -> Option<String> {
    exchange
        .input
        .header(HEADER_CONTAINER_NAME)
        .and_then(|v| v.as_str().map(|s| s.to_string()))
        .or_else(|| config.name.clone())
}

async fn image_exists_locally(docker: &Docker, image: &str) -> Result<bool, CamelError> {
    let images = docker
        .list_images(None::<ListImagesOptions>)
        .await
        .map_err(|e| CamelError::ProcessorError(format!("Failed to list images: {}", e)))?;

    Ok(images.iter().any(|img| {
        img.repo_tags
            .iter()
            .any(|tag| tag == image || tag.starts_with(&format!("{}:", image)))
    }))
}

async fn pull_image_with_progress(
    docker: &Docker,
    image: &str,
    timeout_secs: u64,
) -> Result<(), CamelError> {
    use futures::StreamExt;

    tracing::info!("Pulling image: {}", image);

    let mut stream = docker.create_image(
        Some(CreateImageOptions {
            from_image: Some(image.to_string()),
            ..Default::default()
        }),
        None,
        None,
    );

    let start = std::time::Instant::now();
    let mut last_progress = std::time::Instant::now();

    while let Some(item) = stream.next().await {
        if start.elapsed().as_secs() > timeout_secs {
            return Err(CamelError::ProcessorError(format!(
                "Image pull timeout after {}s. Try manually: docker pull {}",
                timeout_secs, image
            )));
        }

        match item {
            Ok(update) => {
                // Log progress every 2 seconds
                if last_progress.elapsed().as_secs() >= 2 {
                    if let Some(status) = update.status {
                        tracing::debug!("Pull progress: {}", status);
                    }
                    last_progress = std::time::Instant::now();
                }
            }
            Err(e) => {
                let err_str = e.to_string().to_lowercase();
                if err_str.contains("unauthorized") || err_str.contains("401") {
                    return Err(CamelError::ProcessorError(format!(
                        "Authentication required for image '{}'. Configure Docker credentials: docker login",
                        image
                    )));
                }
                if err_str.contains("not found") || err_str.contains("404") {
                    return Err(CamelError::ProcessorError(format!(
                        "Image '{}' not found in registry. Check the image name and tag",
                        image
                    )));
                }
                return Err(CamelError::ProcessorError(format!(
                    "Failed to pull image '{}': {}",
                    image, e
                )));
            }
        }
    }

    tracing::info!("Successfully pulled image: {}", image);
    Ok(())
}

async fn ensure_image_available(
    docker: &Docker,
    image: &str,
    auto_pull: bool,
    timeout_secs: u64,
) -> Result<(), CamelError> {
    if image_exists_locally(docker, image).await? {
        tracing::debug!("Image '{}' already available locally", image);
        return Ok(());
    }

    if !auto_pull {
        return Err(CamelError::ProcessorError(format!(
            "Image '{}' not found locally. Set autoPull=true to pull automatically, or run: docker pull {}",
            image, image
        )));
    }

    pull_image_with_progress(docker, image, timeout_secs).await
}

fn format_docker_event(event: &bollard::models::EventMessage) -> String {
    let action = event.action.as_deref().unwrap_or("unknown");
    let actor = event.actor.as_ref();

    let container_name = actor
        .and_then(|a| a.attributes.as_ref())
        .and_then(|attrs| attrs.get("name"))
        .map(|s| s.as_str())
        .unwrap_or("unknown");

    let image = actor
        .and_then(|a| a.attributes.as_ref())
        .and_then(|attrs| attrs.get("image"))
        .map(|s| s.as_str())
        .unwrap_or("");

    let exit_code = actor
        .and_then(|a| a.attributes.as_ref())
        .and_then(|attrs| attrs.get("exitCode"))
        .map(|s| s.as_str());

    match action {
        "create" => {
            if image.is_empty() {
                format!("[CREATE] Container {}", container_name)
            } else {
                format!("[CREATE] Container {} ({})", container_name, image)
            }
        }
        "start" => format!("[START]  Container {}", container_name),
        "die" => {
            if let Some(code) = exit_code {
                format!("[DIE]    Container {} (exit: {})", container_name, code)
            } else {
                format!("[DIE]    Container {}", container_name)
            }
        }
        "destroy" => format!("[DESTROY] Container {}", container_name),
        "stop" => format!("[STOP]   Container {}", container_name),
        "pause" => format!("[PAUSE]  Container {}", container_name),
        "unpause" => format!("[UNPAUSE] Container {}", container_name),
        "restart" => format!("[RESTART] Container {}", container_name),
        _ => format!("[{}] Container {}", action.to_uppercase(), container_name),
    }
}

async fn run_container_with_cleanup<CreateFn, CreateFut, StartFn, StartFut, RemoveFn, RemoveFut>(
    create: CreateFn,
    start: StartFn,
    remove: RemoveFn,
) -> Result<String, CamelError>
where
    CreateFn: FnOnce() -> CreateFut,
    CreateFut: Future<Output = Result<String, CamelError>>,
    StartFn: FnOnce(String) -> StartFut,
    StartFut: Future<Output = Result<(), CamelError>>,
    RemoveFn: FnOnce(String) -> RemoveFut,
    RemoveFut: Future<Output = Result<(), CamelError>>,
{
    let container_id = create().await?;
    if let Err(start_err) = start(container_id.clone()).await {
        if let Err(remove_err) = remove(container_id.clone()).await {
            return Err(CamelError::ProcessorError(format!(
                "Failed to start container: {}. Cleanup failed: {}",
                start_err, remove_err
            )));
        }
        return Err(start_err);
    }

    Ok(container_id)
}

async fn handle_list(
    docker: Docker,
    _config: ContainerConfig,
    exchange: &mut Exchange,
) -> Result<(), CamelError> {
    let containers = docker
        .list_containers(None::<ListContainersOptions>)
        .await
        .map_err(|e| CamelError::ProcessorError(format!("Failed to list containers: {}", e)))?;

    let json_value = serde_json::to_value(&containers).map_err(|e| {
        CamelError::ProcessorError(format!("Failed to serialize containers: {}", e))
    })?;

    exchange.input.body = Body::Json(json_value);
    exchange.input.set_header(
        HEADER_ACTION_RESULT,
        serde_json::Value::String("success".to_string()),
    );
    Ok(())
}

async fn handle_run(
    docker: Docker,
    config: ContainerConfig,
    exchange: &mut Exchange,
) -> Result<(), CamelError> {
    let image = exchange
        .input
        .header(HEADER_IMAGE)
        .and_then(|v| v.as_str().map(|s| s.to_string()))
        .or(config.image.clone())
        .ok_or_else(|| {
            CamelError::ProcessorError(
                "missing image for run operation. Specify in URI (image=alpine) or header (CamelContainerImage)".to_string(),
            )
        })?;

    let image = if !image.contains(':') && !image.contains('@') {
        format!("{}:latest", image)
    } else {
        image
    };

    let pull_timeout = 300;
    ensure_image_available(&docker, &image, config.auto_pull, pull_timeout)
        .await
        .map_err(|e| {
            CamelError::ProcessorError(format!("Image '{}' not available: {}", image, e))
        })?;

    let container_name = resolve_container_name(exchange, &config);
    let container_name_ref = container_name.as_deref().unwrap_or("");
    let cmd_parts: Option<Vec<String>> = config
        .cmd
        .as_ref()
        .map(|c| c.split_whitespace().map(|s| s.to_string()).collect());
    let auto_remove = config.auto_remove;
    let (exposed_ports, port_bindings) = config.parse_ports().unwrap_or_default();
    let env_vars = config.parse_env();
    let network_mode = config.network.clone();

    let volumes_str = exchange
        .input
        .header(HEADER_VOLUMES)
        .and_then(|v| v.as_str().map(|s| s.to_string()))
        .or(config.volumes.clone());
    let (binds, anon_volumes) = volumes_str
        .as_deref()
        .and_then(parse_volume_str)
        .unwrap_or_default();

    let docker_create = docker.clone();
    let docker_start = docker.clone();
    let docker_remove = docker.clone();

    let container_id = run_container_with_cleanup(
        move || async move {
            let create_options = CreateContainerOptions {
                name: Some(container_name_ref.to_string()),
                ..Default::default()
            };
            let container_config = ContainerCreateBody {
                image: Some(image.clone()),
                cmd: cmd_parts,
                env: env_vars,
                exposed_ports: if exposed_ports.is_empty() { None } else { Some(exposed_ports) },
                volumes: if anon_volumes.is_empty() { None } else { Some(anon_volumes) },
                host_config: Some(HostConfig {
                    auto_remove: Some(auto_remove),
                    port_bindings: if port_bindings.is_empty() { None } else { Some(port_bindings) },
                    network_mode,
                    binds: if binds.is_empty() { None } else { Some(binds) },
                    ..Default::default()
                }),
                ..Default::default()
            };

            let create_response = docker_create
                .create_container(Some(create_options), container_config)
                .await
                .map_err(|e| {
                    let err_str = e.to_string().to_lowercase();
                    if err_str.contains("409") || err_str.contains("conflict") {
                        CamelError::ProcessorError(format!(
                            "Container name '{}' already exists. Use a unique name or remove the existing container first",
                            container_name_ref
                        ))
                    } else {
                        CamelError::ProcessorError(format!(
                            "Failed to create container: {}",
                            e
                        ))
                    }
                })?;

            Ok(create_response.id)
        },
        move |container_id| async move {
            docker_start
                .start_container(&container_id, None::<StartContainerOptions>)
                .await
                .map_err(|e| {
                    CamelError::ProcessorError(format!(
                        "Failed to start container: {}",
                        e
                    ))
                })
        },
        move |container_id| async move {
            docker_remove
                .remove_container(&container_id, None)
                .await
                .map_err(|e| {
                    CamelError::ProcessorError(format!(
                        "Failed to remove container after start failure: {}",
                        e
                    ))
                })
        },
    )
    .await?;

    track_container(container_id.clone());

    exchange
        .input
        .set_header(HEADER_CONTAINER_ID, serde_json::Value::String(container_id));
    exchange.input.set_header(
        HEADER_ACTION_RESULT,
        serde_json::Value::String("success".to_string()),
    );
    Ok(())
}

async fn handle_lifecycle(
    docker: Docker,
    _config: ContainerConfig,
    exchange: &mut Exchange,
    operation: ProducerOperation,
    operation_name: &str,
) -> Result<(), CamelError> {
    let container_id = exchange
        .input
        .header(HEADER_CONTAINER_ID)
        .and_then(|v| v.as_str().map(|s| s.to_string()))
        .ok_or_else(|| {
            CamelError::ProcessorError(format!(
                "{} header is required for {} operation",
                HEADER_CONTAINER_ID, operation_name
            ))
        })?;

    match operation {
        ProducerOperation::Start => {
            docker
                .start_container(&container_id, None::<StartContainerOptions>)
                .await
                .map_err(|e| {
                    CamelError::ProcessorError(format!("Failed to start container: {}", e))
                })?;
        }
        ProducerOperation::Stop => {
            docker
                .stop_container(&container_id, None)
                .await
                .map_err(|e| {
                    CamelError::ProcessorError(format!("Failed to stop container: {}", e))
                })?;
        }
        ProducerOperation::Remove => {
            docker
                .remove_container(&container_id, None)
                .await
                .map_err(|e| {
                    CamelError::ProcessorError(format!("Failed to remove container: {}", e))
                })?;
            untrack_container(&container_id);
        }
        _ => {}
    }

    exchange.input.set_header(
        HEADER_ACTION_RESULT,
        serde_json::Value::String("success".to_string()),
    );
    Ok(())
}

async fn handle_exec(
    docker: Docker,
    config: ContainerConfig,
    exchange: &mut Exchange,
) -> Result<(), CamelError> {
    let container_id = exchange
        .input
        .header(HEADER_CONTAINER_ID)
        .and_then(|v| v.as_str().map(|s| s.to_string()))
        .or(config.container_id.clone())
        .ok_or_else(|| {
            CamelError::ProcessorError(format!(
                "{} header or containerId param is required for exec operation",
                HEADER_CONTAINER_ID
            ))
        })?;

    let cmd = exchange
        .input
        .header(HEADER_CMD)
        .and_then(|v| v.as_str().map(|s| s.to_string()))
        .or(config.cmd.clone())
        .ok_or_else(|| {
            CamelError::ProcessorError(
                "CamelContainerCmd header or cmd param is required for exec operation".to_string(),
            )
        })?;

    let cmd_parts: Vec<String> = cmd.split_whitespace().map(|s| s.to_string()).collect();
    let env_vars = config.parse_env();

    let exec_config = bollard::exec::CreateExecOptions {
        cmd: Some(cmd_parts),
        env: env_vars,
        user: config.user.clone(),
        working_dir: config.workdir.clone(),
        attach_stdout: Some(true),
        attach_stderr: Some(true),
        ..Default::default()
    };

    let create_result = docker
        .create_exec(&container_id, exec_config)
        .await
        .map_err(|e| {
            let err_str = e.to_string().to_lowercase();
            if err_str.contains("404") || err_str.contains("no such") {
                CamelError::ProcessorError(format!(
                    "Container '{}' not found for exec",
                    container_id
                ))
            } else {
                CamelError::ProcessorError(format!("Failed to create exec: {}", e))
            }
        })?;

    let exec_id = create_result.id;

    if config.detach {
        docker
            .start_exec(
                &exec_id,
                Some(bollard::exec::StartExecOptions {
                    detach: true,
                    ..Default::default()
                }),
            )
            .await
            .map_err(|e| {
                CamelError::ProcessorError(format!("Failed to start exec (detached): {}", e))
            })?;

        exchange
            .input
            .set_header(HEADER_EXEC_ID, serde_json::Value::String(exec_id));
        exchange
            .input
            .set_header(HEADER_CONTAINER_ID, serde_json::Value::String(container_id));
    } else {
        let start_result = docker
            .start_exec(&exec_id, None)
            .await
            .map_err(|e| CamelError::ProcessorError(format!("Failed to start exec: {}", e)))?;

        let mut output = String::new();

        match start_result {
            bollard::exec::StartExecResults::Attached {
                output: mut stream, ..
            } => {
                use futures::StreamExt;
                while let Some(msg) = stream.next().await {
                    match msg {
                        Ok(bollard::container::LogOutput::StdOut { message }) => {
                            output.push_str(&String::from_utf8_lossy(&message));
                        }
                        Ok(bollard::container::LogOutput::StdErr { message }) => {
                            output.push_str(&String::from_utf8_lossy(&message));
                        }
                        Ok(_) => {}
                        Err(e) => {
                            output.push_str(&format!("[error reading stream: {}]", e));
                        }
                    }
                }
            }
            bollard::exec::StartExecResults::Detached => {}
        }

        let inspect = docker
            .inspect_exec(&exec_id)
            .await
            .map_err(|e| CamelError::ProcessorError(format!("Failed to inspect exec: {}", e)))?;

        let exit_code: i64 = inspect.exit_code.unwrap_or(0);

        let output = output.trim_end().to_string();
        exchange.input.body = Body::Text(output);
        exchange.input.set_header(
            HEADER_EXIT_CODE,
            serde_json::Value::Number(exit_code.into()),
        );
        exchange
            .input
            .set_header(HEADER_CONTAINER_ID, serde_json::Value::String(container_id));
    }

    exchange.input.set_header(
        HEADER_ACTION_RESULT,
        serde_json::Value::String("success".to_string()),
    );
    Ok(())
}

async fn handle_network_create(
    docker: Docker,
    config: ContainerConfig,
    exchange: &mut Exchange,
) -> Result<(), CamelError> {
    let network_name = exchange
        .input
        .header(HEADER_CONTAINER_NAME)
        .and_then(|v| v.as_str().map(|s| s.to_string()))
        .or(config.name.clone())
        .ok_or_else(|| {
            CamelError::ProcessorError(
                "CamelContainerName header or name param is required for network-create"
                    .to_string(),
            )
        })?;

    let driver = config.driver.as_deref().unwrap_or("bridge");

    let options = NetworkCreateRequest {
        name: network_name.clone(),
        driver: Some(driver.to_string()),
        ..Default::default()
    };

    let result = docker.create_network(options).await.map_err(|e| {
        let err_str = e.to_string().to_lowercase();
        if err_str.contains("409") || err_str.contains("already exists") {
            CamelError::ProcessorError(format!("Network '{}' already exists", network_name))
        } else {
            CamelError::ProcessorError(format!("Failed to create network: {}", e))
        }
    })?;

    let network_id = result.id.clone();
    let json_value = serde_json::to_value(&result).map_err(|e| {
        CamelError::ProcessorError(format!("Failed to serialize network response: {}", e))
    })?;

    exchange.input.body = Body::Json(json_value);
    exchange
        .input
        .set_header(HEADER_NETWORK, serde_json::Value::String(network_id));
    exchange.input.set_header(
        HEADER_ACTION_RESULT,
        serde_json::Value::String("success".to_string()),
    );
    Ok(())
}

async fn handle_network_connect(
    docker: Docker,
    config: ContainerConfig,
    exchange: &mut Exchange,
) -> Result<(), CamelError> {
    let network = exchange
        .input
        .header(HEADER_NETWORK)
        .and_then(|v| v.as_str().map(|s| s.to_string()))
        .or(config.network.clone())
        .ok_or_else(|| {
            CamelError::ProcessorError(
                "CamelContainerNetwork header or network param is required for network-connect"
                    .to_string(),
            )
        })?;

    let container = exchange
        .input
        .header(HEADER_CONTAINER_ID)
        .and_then(|v| v.as_str().map(|s| s.to_string()))
        .or(config.container_id.clone())
        .ok_or_else(|| {
            CamelError::ProcessorError(
                "CamelContainerId header or container param is required for network-connect"
                    .to_string(),
            )
        })?;

    docker
        .connect_network(
            &network,
            NetworkConnectRequest {
                container,
                ..Default::default()
            },
        )
        .await
        .map_err(|e| {
            let err_str = e.to_string().to_lowercase();
            if err_str.contains("404") || err_str.contains("not found") {
                CamelError::ProcessorError(format!("Network '{}' or container not found", network))
            } else {
                CamelError::ProcessorError(format!("Failed to connect to network: {}", e))
            }
        })?;

    exchange.input.set_header(
        HEADER_ACTION_RESULT,
        serde_json::Value::String("success".to_string()),
    );
    Ok(())
}

async fn handle_network_disconnect(
    docker: Docker,
    config: ContainerConfig,
    exchange: &mut Exchange,
) -> Result<(), CamelError> {
    let network = exchange
        .input
        .header(HEADER_NETWORK)
        .and_then(|v| v.as_str().map(|s| s.to_string()))
        .or(config.network.clone())
        .ok_or_else(|| {
            CamelError::ProcessorError(
                "CamelContainerNetwork header or network param is required for network-disconnect"
                    .to_string(),
            )
        })?;

    let container = exchange
        .input
        .header(HEADER_CONTAINER_ID)
        .and_then(|v| v.as_str().map(|s| s.to_string()))
        .or(config.container_id.clone())
        .ok_or_else(|| {
            CamelError::ProcessorError(
                "CamelContainerId header or container param is required for network-disconnect"
                    .to_string(),
            )
        })?;

    docker
        .disconnect_network(
            &network,
            NetworkDisconnectRequest {
                container,
                force: Some(config.force),
            },
        )
        .await
        .map_err(|e| {
            let err_str = e.to_string().to_lowercase();
            if err_str.contains("404") || err_str.contains("not found") {
                CamelError::ProcessorError(format!("Network '{}' or container not found", network))
            } else {
                CamelError::ProcessorError(format!("Failed to disconnect from network: {}", e))
            }
        })?;

    exchange.input.set_header(
        HEADER_ACTION_RESULT,
        serde_json::Value::String("success".to_string()),
    );
    Ok(())
}

async fn handle_network_remove(
    docker: Docker,
    config: ContainerConfig,
    exchange: &mut Exchange,
) -> Result<(), CamelError> {
    let network = exchange
        .input
        .header(HEADER_NETWORK)
        .and_then(|v| v.as_str().map(|s| s.to_string()))
        .or(config.network.clone())
        .ok_or_else(|| {
            CamelError::ProcessorError(
                "CamelContainerNetwork header or network param is required for network-remove"
                    .to_string(),
            )
        })?;

    docker.remove_network(&network).await.map_err(|e| {
        let err_str = e.to_string().to_lowercase();
        if err_str.contains("404") || err_str.contains("not found") {
            CamelError::ProcessorError(format!("Network '{}' not found", network))
        } else if err_str.contains("409") || err_str.contains("in use") {
            CamelError::ProcessorError(format!(
                "Network '{}' is in use and cannot be removed",
                network
            ))
        } else {
            CamelError::ProcessorError(format!("Failed to remove network: {}", e))
        }
    })?;

    exchange.input.set_header(
        HEADER_ACTION_RESULT,
        serde_json::Value::String("success".to_string()),
    );
    Ok(())
}

async fn handle_network_list(
    docker: Docker,
    _config: ContainerConfig,
    exchange: &mut Exchange,
) -> Result<(), CamelError> {
    let networks = docker
        .list_networks(None::<ListNetworksOptions>)
        .await
        .map_err(|e| CamelError::ProcessorError(format!("Failed to list networks: {}", e)))?;

    let json_value = serde_json::to_value(&networks)
        .map_err(|e| CamelError::ProcessorError(format!("Failed to serialize networks: {}", e)))?;

    exchange.input.body = Body::Json(json_value);
    exchange.input.set_header(
        HEADER_ACTION_RESULT,
        serde_json::Value::String("success".to_string()),
    );
    Ok(())
}

/// Producer for executing container operations.
///
/// This producer handles synchronous container operations like listing,
/// creating, starting, stopping, and removing containers.
#[derive(Clone)]
pub struct ContainerProducer {
    config: ContainerConfig,
    docker: Docker,
}

impl Service<Exchange> for ContainerProducer {
    type Response = Exchange;
    type Error = CamelError;
    type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, mut exchange: Exchange) -> Self::Future {
        let config = self.config.clone();
        let docker = self.docker.clone();
        Box::pin(async move {
            let operation_name = exchange
                .input
                .header(HEADER_ACTION)
                .and_then(|v| v.as_str().map(|s| s.to_string()))
                .unwrap_or_else(|| config.operation.clone());

            let operation = parse_producer_operation(&operation_name)?;

            match operation {
                ProducerOperation::List => {
                    handle_list(docker, config, &mut exchange).await?;
                }
                ProducerOperation::Run => {
                    handle_run(docker, config, &mut exchange).await?;
                }
                ProducerOperation::Start => {
                    handle_lifecycle(docker, config, &mut exchange, operation, &operation_name)
                        .await?;
                }
                ProducerOperation::Stop => {
                    handle_lifecycle(docker, config, &mut exchange, operation, &operation_name)
                        .await?;
                }
                ProducerOperation::Remove => {
                    handle_lifecycle(docker, config, &mut exchange, operation, &operation_name)
                        .await?;
                }
                ProducerOperation::Exec => {
                    handle_exec(docker, config, &mut exchange).await?;
                }
                ProducerOperation::NetworkCreate => {
                    handle_network_create(docker, config, &mut exchange).await?;
                }
                ProducerOperation::NetworkConnect => {
                    handle_network_connect(docker, config, &mut exchange).await?;
                }
                ProducerOperation::NetworkDisconnect => {
                    handle_network_disconnect(docker, config, &mut exchange).await?;
                }
                ProducerOperation::NetworkRemove => {
                    handle_network_remove(docker, config, &mut exchange).await?;
                }
                ProducerOperation::NetworkList => {
                    handle_network_list(docker, config, &mut exchange).await?;
                }
            }

            Ok(exchange)
        })
    }
}

/// Consumer for receiving Docker container events or logs.
///
/// This consumer subscribes to Docker events or container logs and forwards them
/// to the route as exchanges. It implements automatic reconnection on connection failures.
pub struct ContainerConsumer {
    config: ContainerConfig,
}

#[async_trait]
impl Consumer for ContainerConsumer {
    async fn start(&mut self, context: ConsumerContext) -> Result<(), CamelError> {
        match self.config.operation.as_str() {
            "events" => self.start_events_consumer(context).await,
            "logs" => self.start_logs_consumer(context).await,
            _ => Err(CamelError::EndpointCreationFailed(format!(
                "Consumer only supports 'events' or 'logs' operations, got '{}'",
                self.config.operation
            ))),
        }
    }

    async fn stop(&mut self) -> Result<(), CamelError> {
        Ok(())
    }

    fn concurrency_model(&self) -> camel_component_api::ConcurrencyModel {
        camel_component_api::ConcurrencyModel::Concurrent { max: None }
    }
}

impl ContainerConsumer {
    async fn start_events_consumer(&mut self, context: ConsumerContext) -> Result<(), CamelError> {
        use futures::StreamExt;

        loop {
            if context.is_cancelled() {
                tracing::info!("Container events consumer shutting down");
                return Ok(());
            }

            let docker = match self.config.connect_docker().await {
                Ok(d) => d,
                Err(e) => {
                    tracing::error!(
                        "Consumer failed to connect to docker: {}. Retrying in 5s...",
                        e
                    );
                    tokio::select! {
                        _ = context.cancelled() => {
                            tracing::info!("Container events consumer shutting down");
                            return Ok(());
                        }
                        _ = tokio::time::sleep(std::time::Duration::from_secs(5)) => {}
                    }
                    continue;
                }
            };

            let mut event_stream = docker.events(None::<EventsOptions>);

            loop {
                tokio::select! {
                    _ = context.cancelled() => {
                        tracing::info!("Container events consumer shutting down");
                        return Ok(());
                    }

                    msg = event_stream.next() => {
                        match msg {
                            Some(Ok(event)) => {
                                let formatted = format_docker_event(&event);
                                let message = Message::new(Body::Text(formatted));
                                let exchange = Exchange::new(message);

                                if let Err(e) = context.send(exchange).await {
                                    tracing::error!("Failed to send exchange: {:?}", e);
                                    break;
                                }
                            }
                            Some(Err(e)) => {
                                tracing::error!("Docker event stream error: {}. Reconnecting...", e);
                                break;
                            }
                            None => {
                                tracing::info!("Docker event stream ended. Reconnecting...");
                                break;
                            }
                        }
                    }
                }
            }

            tokio::select! {
                _ = context.cancelled() => {
                    tracing::info!("Container events consumer shutting down");
                    return Ok(());
                }
                _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {}
            }
        }
    }

    async fn start_logs_consumer(&mut self, context: ConsumerContext) -> Result<(), CamelError> {
        use futures::StreamExt;

        let container_id = self.config.container_id.clone().ok_or_else(|| {
            CamelError::EndpointCreationFailed(
                "containerId is required for logs consumer. Use container:logs?containerId=xxx"
                    .to_string(),
            )
        })?;

        loop {
            if context.is_cancelled() {
                tracing::info!("Container logs consumer shutting down");
                return Ok(());
            }

            let docker = match self.config.connect_docker().await {
                Ok(d) => d,
                Err(e) => {
                    tracing::error!(
                        "Logs consumer failed to connect to docker: {}. Retrying in 5s...",
                        e
                    );
                    tokio::select! {
                        _ = context.cancelled() => {
                            tracing::info!("Container logs consumer shutting down");
                            return Ok(());
                        }
                        _ = tokio::time::sleep(std::time::Duration::from_secs(5)) => {}
                    }
                    continue;
                }
            };

            let tail = self
                .config
                .tail
                .clone()
                .unwrap_or_else(|| "all".to_string());

            let options = LogsOptions {
                follow: self.config.follow,
                stdout: true,
                stderr: true,
                timestamps: self.config.timestamps,
                tail,
                ..Default::default()
            };

            let mut log_stream = docker.logs(&container_id, Some(options));
            let container_id_header = container_id.clone();

            loop {
                tokio::select! {
                    _ = context.cancelled() => {
                        tracing::info!("Container logs consumer shutting down");
                        return Ok(());
                    }

                    msg = log_stream.next() => {
                        match msg {
                            Some(Ok(log_output)) => {
                                let (stream_type, content) = match log_output {
                                    bollard::container::LogOutput::StdOut { message } => {
                                        ("stdout", String::from_utf8_lossy(&message).into_owned())
                                    }
                                    bollard::container::LogOutput::StdErr { message } => {
                                        ("stderr", String::from_utf8_lossy(&message).into_owned())
                                    }
                                    bollard::container::LogOutput::Console { message } => {
                                        ("console", String::from_utf8_lossy(&message).into_owned())
                                    }
                                    bollard::container::LogOutput::StdIn { message } => {
                                        ("stdin", String::from_utf8_lossy(&message).into_owned())
                                    }
                                };

                                let content = content.trim_end();
                                if content.is_empty() {
                                    continue;
                                }

                                let mut message = Message::new(Body::Text(content.to_string()));
                                message.set_header(
                                    HEADER_CONTAINER_ID,
                                    serde_json::Value::String(container_id_header.clone()),
                                );
                                message.set_header(
                                    HEADER_LOG_STREAM,
                                    serde_json::Value::String(stream_type.to_string()),
                                );

                                if self.config.timestamps
                                    && let Some(ts) = extract_timestamp(content) {
                                        message.set_header(
                                            HEADER_LOG_TIMESTAMP,
                                            serde_json::Value::String(ts),
                                        );
                                    }

                                let exchange = Exchange::new(message);

                                if let Err(e) = context.send(exchange).await {
                                    tracing::error!("Failed to send log exchange: {:?}", e);
                                    break;
                                }
                            }
                            Some(Err(e)) => {
                                tracing::error!("Docker log stream error: {}. Reconnecting...", e);
                                break;
                            }
                            None => {
                                if self.config.follow {
                                    tracing::info!("Docker log stream ended. Reconnecting...");
                                    break;
                                } else {
                                    tracing::info!("Container logs consumer finished (follow=false)");
                                    return Ok(());
                                }
                            }
                        }
                    }
                }
            }

            tokio::select! {
                _ = context.cancelled() => {
                    tracing::info!("Container logs consumer shutting down");
                    return Ok(());
                }
                _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {}
            }
        }
    }
}

fn extract_timestamp(log_line: &str) -> Option<String> {
    let parts: Vec<&str> = log_line.splitn(2, ' ').collect();
    if parts.len() > 1 && parts[0].contains('T') {
        Some(parts[0].to_string())
    } else {
        None
    }
}

/// Component for creating container endpoints.
///
/// This component handles URIs with the "container" scheme and creates
/// appropriate producer and consumer endpoints for Docker operations.
///
/// Containers created via `run` operation are tracked globally and can be
/// cleaned up on shutdown by calling `cleanup_tracked_containers()`.
pub struct ContainerComponent {
    config: Option<ContainerGlobalConfig>,
}

impl ContainerComponent {
    /// Creates a new container component instance without global config.
    pub fn new() -> Self {
        Self { config: None }
    }

    /// Creates a container component with the given global config.
    pub fn with_config(config: ContainerGlobalConfig) -> Self {
        Self {
            config: Some(config),
        }
    }

    /// Creates a container component with optional global config.
    pub fn with_optional_config(config: Option<ContainerGlobalConfig>) -> Self {
        Self { config }
    }
}

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

impl Component for ContainerComponent {
    fn scheme(&self) -> &str {
        "container"
    }

    fn create_endpoint(
        &self,
        uri: &str,
        _ctx: &dyn camel_component_api::ComponentContext,
    ) -> Result<Box<dyn Endpoint>, CamelError> {
        let mut config = ContainerConfig::from_uri(uri)?;
        // Apply global defaults if present and URI didn't set them
        if let Some(ref global) = self.config {
            config.apply_global_defaults(global);
        }
        Ok(Box::new(ContainerEndpoint {
            uri: uri.to_string(),
            config,
        }))
    }
}

/// Endpoint for container operations.
///
/// This endpoint creates producers for executing container operations
/// and consumers for receiving container events.
pub struct ContainerEndpoint {
    uri: String,
    config: ContainerConfig,
}

impl ContainerEndpoint {
    /// Returns the Docker host configured for this endpoint.
    /// Returns `None` if not set (for testing purposes).
    pub fn docker_host(&self) -> Option<&str> {
        self.config.host.as_deref()
    }
}

impl Endpoint for ContainerEndpoint {
    fn uri(&self) -> &str {
        &self.uri
    }

    fn create_consumer(&self) -> Result<Box<dyn Consumer>, CamelError> {
        Ok(Box::new(ContainerConsumer {
            config: self.config.clone(),
        }))
    }

    fn create_producer(&self, _ctx: &ProducerContext) -> Result<BoxProcessor, CamelError> {
        let docker = self.config.connect_docker_client()?;
        Ok(BoxProcessor::new(ContainerProducer {
            config: self.config.clone(),
            docker,
        }))
    }
}

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

    #[test]
    fn test_container_config() {
        let config = ContainerConfig::from_uri("container:run?image=alpine").unwrap();
        assert_eq!(config.operation, "run");
        assert_eq!(config.image.as_deref(), Some("alpine"));
        // host is None by default; global config applies it later
        assert!(config.host.is_none());
    }

    #[test]
    fn test_global_config_applied_to_endpoint() {
        // When global config is set and URI doesn't specify host,
        // apply_global_defaults should set host from global config.
        let global =
            ContainerGlobalConfig::default().with_docker_host("unix:///custom/docker.sock");
        let mut config = ContainerConfig::from_uri("container:run?image=alpine").unwrap();
        assert!(
            config.host.is_none(),
            "URI without ?host= should leave host as None"
        );
        config.apply_global_defaults(&global);
        assert_eq!(
            config.host.as_deref(),
            Some("unix:///custom/docker.sock"),
            "global docker_host must be applied when URI did not set host"
        );
    }

    #[test]
    fn test_uri_param_wins_over_global_config() {
        // When URI explicitly sets host param, apply_global_defaults must NOT override it.
        let global =
            ContainerGlobalConfig::default().with_docker_host("unix:///custom/docker.sock");
        let mut config =
            ContainerConfig::from_uri("container:run?image=alpine&host=unix:///override.sock")
                .unwrap();
        assert_eq!(
            config.host.as_deref(),
            Some("unix:///override.sock"),
            "URI-set host should be parsed correctly"
        );
        config.apply_global_defaults(&global);
        assert_eq!(
            config.host.as_deref(),
            Some("unix:///override.sock"),
            "global config must NOT override a host already set by URI"
        );
    }

    #[test]
    fn test_container_config_parses_name() {
        let config = ContainerConfig::from_uri("container:run?name=my-container").unwrap();
        assert_eq!(config.name.as_deref(), Some("my-container"));
    }

    #[test]
    fn test_parse_producer_operation_known() {
        assert_eq!(
            parse_producer_operation("list").unwrap(),
            ProducerOperation::List
        );
        assert_eq!(
            parse_producer_operation("run").unwrap(),
            ProducerOperation::Run
        );
        assert_eq!(
            parse_producer_operation("start").unwrap(),
            ProducerOperation::Start
        );
        assert_eq!(
            parse_producer_operation("stop").unwrap(),
            ProducerOperation::Stop
        );
        assert_eq!(
            parse_producer_operation("remove").unwrap(),
            ProducerOperation::Remove
        );
    }

    #[test]
    fn test_parse_producer_operation_unknown() {
        let err = parse_producer_operation("destruir_mundo").unwrap_err();
        match err {
            CamelError::ProcessorError(msg) => {
                assert!(
                    msg.contains("Unknown container operation"),
                    "Unexpected error message: {}",
                    msg
                );
            }
            _ => panic!("Expected ProcessorError for unknown operation"),
        }
    }

    #[test]
    fn test_parse_producer_operation_new_variants() {
        assert_eq!(
            parse_producer_operation("exec").unwrap(),
            ProducerOperation::Exec
        );
        assert_eq!(
            parse_producer_operation("network-create").unwrap(),
            ProducerOperation::NetworkCreate
        );
        assert_eq!(
            parse_producer_operation("network-connect").unwrap(),
            ProducerOperation::NetworkConnect
        );
        assert_eq!(
            parse_producer_operation("network-disconnect").unwrap(),
            ProducerOperation::NetworkDisconnect
        );
        assert_eq!(
            parse_producer_operation("network-remove").unwrap(),
            ProducerOperation::NetworkRemove
        );
        assert_eq!(
            parse_producer_operation("network-list").unwrap(),
            ProducerOperation::NetworkList
        );
    }

    #[test]
    fn test_resolve_container_name_header_overrides_config() {
        let config = ContainerConfig::from_uri("container:run?name=config-name").unwrap();
        let mut exchange = Exchange::new(Message::new(""));
        exchange.input.set_header(
            HEADER_CONTAINER_NAME,
            serde_json::Value::String("header-name".to_string()),
        );

        let resolved = resolve_container_name(&exchange, &config);
        assert_eq!(resolved.as_deref(), Some("header-name"));
    }

    #[test]
    fn test_container_config_rejects_tcp_host() {
        let config = ContainerConfig::from_uri("container:list?host=tcp://localhost:2375").unwrap();
        let err = config.connect_docker_client().unwrap_err();
        match err {
            CamelError::ProcessorError(msg) => {
                assert!(
                    msg.to_lowercase().contains("tcp"),
                    "Expected TCP scheme error, got: {}",
                    msg
                );
            }
            _ => panic!("Expected ProcessorError for unsupported tcp host"),
        }
    }

    #[tokio::test]
    async fn test_run_container_with_cleanup_removes_on_start_failure() {
        let remove_called = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let remove_called_clone = remove_called.clone();

        let result = run_container_with_cleanup(
            || async { Ok("container-123".to_string()) },
            |_id| async move {
                Err(CamelError::ProcessorError(
                    "Failed to start container".to_string(),
                ))
            },
            move |_id| {
                let remove_called_inner = remove_called_clone.clone();
                async move {
                    remove_called_inner.store(true, std::sync::atomic::Ordering::SeqCst);
                    Ok(())
                }
            },
        )
        .await;

        assert!(result.is_err(), "Expected start failure to bubble up");
        assert!(
            remove_called.load(std::sync::atomic::Ordering::SeqCst),
            "Expected cleanup to remove container"
        );
    }

    #[test]
    fn test_container_component_creates_endpoint() {
        let component = ContainerComponent::new();
        assert_eq!(component.scheme(), "container");
        let ctx = NoOpComponentContext;
        let endpoint = component
            .create_endpoint("container:run?image=alpine", &ctx)
            .unwrap();
        assert_eq!(endpoint.uri(), "container:run?image=alpine");
    }

    #[test]
    fn test_container_config_parses_ports() {
        let config =
            ContainerConfig::from_uri("container:run?image=nginx&ports=8080:80,8443:443").unwrap();
        assert_eq!(config.ports.as_deref(), Some("8080:80,8443:443"));
    }

    #[test]
    fn test_container_config_parses_env() {
        let config =
            ContainerConfig::from_uri("container:run?image=nginx&env=FOO=bar,BAZ=qux").unwrap();
        assert_eq!(config.env.as_deref(), Some("FOO=bar,BAZ=qux"));
    }

    #[test]
    fn test_container_config_parses_logs_options() {
        let config = ContainerConfig::from_uri(
            "container:logs?containerId=my-app&follow=true&timestamps=true&tail=100",
        )
        .unwrap();
        assert_eq!(config.operation, "logs");
        assert_eq!(config.container_id.as_deref(), Some("my-app"));
        assert!(config.follow);
        assert!(config.timestamps);
        assert_eq!(config.tail.as_deref(), Some("100"));
    }

    #[test]
    fn test_container_config_logs_defaults() {
        let config = ContainerConfig::from_uri("container:logs?containerId=test").unwrap();
        assert!(config.follow); // default: true
        assert!(!config.timestamps); // default: false
        assert!(config.tail.is_none()); // default: None (all)
    }

    #[test]
    fn test_parse_ports_single() {
        let config = ContainerConfig::from_uri("container:run?image=nginx&ports=8080:80").unwrap();
        let (exposed, bindings) = config.parse_ports().unwrap();

        assert!(exposed.contains(&"80/tcp".to_string()));
        assert!(bindings.contains_key("80/tcp"));

        let binding = bindings.get("80/tcp").unwrap().as_ref().unwrap();
        assert_eq!(binding.len(), 1);
        assert_eq!(binding[0].host_port, Some("8080".to_string()));
    }

    #[test]
    fn test_parse_ports_multiple() {
        let config =
            ContainerConfig::from_uri("container:run?image=nginx&ports=8080:80,8443:443").unwrap();
        let (exposed, bindings) = config.parse_ports().unwrap();

        assert!(exposed.contains(&"80/tcp".to_string()));
        assert!(exposed.contains(&"443/tcp".to_string()));
        assert_eq!(bindings.len(), 2);
    }

    #[test]
    fn test_parse_ports_with_protocol() {
        let config =
            ContainerConfig::from_uri("container:run?image=nginx&ports=8080:80/tcp,5353:53/udp")
                .unwrap();
        let (exposed, _bindings) = config.parse_ports().unwrap();

        assert!(exposed.contains(&"80/tcp".to_string()));
        assert!(exposed.contains(&"53/udp".to_string()));
    }

    #[test]
    fn test_parse_ports_none() {
        let config = ContainerConfig::from_uri("container:run?image=nginx").unwrap();
        assert!(config.parse_ports().is_none());
    }

    #[test]
    fn test_parse_env_single() {
        let config = ContainerConfig::from_uri("container:run?image=nginx&env=FOO=bar").unwrap();
        let env = config.parse_env().unwrap();

        assert_eq!(env.len(), 1);
        assert_eq!(env[0], "FOO=bar");
    }

    #[test]
    fn test_parse_env_multiple() {
        let config =
            ContainerConfig::from_uri("container:run?image=nginx&env=FOO=bar,BAZ=qux,NUM=123")
                .unwrap();
        let env = config.parse_env().unwrap();

        assert_eq!(env.len(), 3);
        assert!(env.contains(&"FOO=bar".to_string()));
        assert!(env.contains(&"BAZ=qux".to_string()));
        assert!(env.contains(&"NUM=123".to_string()));
    }

    #[test]
    fn test_parse_env_none() {
        let config = ContainerConfig::from_uri("container:run?image=nginx").unwrap();
        assert!(config.parse_env().is_none());
    }

    use camel_component_api::Message;
    use std::sync::Arc;

    #[tokio::test]
    async fn test_container_producer_resolves_operation_from_header() {
        // Try to connect to Docker - if fails, return early
        let docker = match Docker::connect_with_local_defaults() {
            Ok(d) => d,
            Err(_) => {
                eprintln!("Skipping test: Could not connect to Docker daemon");
                return;
            }
        };

        if docker.ping().await.is_err() {
            eprintln!("Skipping test: Docker daemon not responding to ping");
            return;
        }

        let component = ContainerComponent::new();
        let ctx = NoOpComponentContext;
        let endpoint = component.create_endpoint("container:run", &ctx).unwrap();

        let ctx = ProducerContext::new();
        let mut producer = endpoint.create_producer(&ctx).unwrap();

        let mut exchange = Exchange::new(Message::new(""));
        exchange
            .input
            .set_header(HEADER_ACTION, serde_json::Value::String("list".into()));

        use tower::ServiceExt;
        let result = producer
            .ready()
            .await
            .unwrap()
            .call(exchange)
            .await
            .unwrap();

        // For list operation, the result header should be on the input message
        assert_eq!(
            result
                .input
                .header(HEADER_ACTION_RESULT)
                .map(|v| v.as_str().unwrap()),
            Some("success")
        );
    }

    #[tokio::test]
    async fn test_container_producer_connection_error_on_invalid_host() {
        // Test that an invalid host (nonexistent socket) results in a connection error
        let component = ContainerComponent::new();
        let ctx = NoOpComponentContext;
        let endpoint = component
            .create_endpoint("container:list?host=unix:///nonexistent/docker.sock", &ctx)
            .unwrap();

        let ctx = ProducerContext::new();
        let result = endpoint.create_producer(&ctx);

        // The producer should return an error because it cannot connect to the invalid socket
        assert!(
            result.is_err(),
            "Expected error when connecting to invalid host"
        );
        let err = result.unwrap_err();
        match &err {
            CamelError::ProcessorError(msg) => {
                assert!(
                    msg.to_lowercase().contains("connection")
                        || msg.to_lowercase().contains("connect")
                        || msg.to_lowercase().contains("socket")
                        || msg.contains("docker"),
                    "Error message should indicate connection failure, got: {}",
                    msg
                );
            }
            _ => panic!("Expected ProcessorError, got: {:?}", err),
        }
    }

    /// Test that start, stop, remove operations return an error when CamelContainerId header is missing.
    #[tokio::test]
    async fn test_container_producer_lifecycle_operations_missing_id() {
        // Try to connect to Docker - if fails, return early
        let docker = match Docker::connect_with_local_defaults() {
            Ok(d) => d,
            Err(_) => {
                eprintln!("Skipping test: Could not connect to Docker daemon");
                return;
            }
        };

        if docker.ping().await.is_err() {
            eprintln!("Skipping test: Docker daemon not responding to ping");
            return;
        }

        let component = ContainerComponent::new();
        let ctx = NoOpComponentContext;
        let endpoint = component.create_endpoint("container:start", &ctx).unwrap();
        let ctx = ProducerContext::new();
        let mut producer = endpoint.create_producer(&ctx).unwrap();

        // Test each lifecycle operation without CamelContainerId header
        for operation in ["start", "stop", "remove"] {
            let mut exchange = Exchange::new(Message::new(""));
            exchange.input.set_header(
                HEADER_ACTION,
                serde_json::Value::String(operation.to_string()),
            );
            // Deliberately NOT setting CamelContainerId header

            use tower::ServiceExt;
            let result = producer.ready().await.unwrap().call(exchange).await;

            assert!(
                result.is_err(),
                "Expected error for {} operation without CamelContainerId",
                operation
            );
            let err = result.unwrap_err();
            match &err {
                CamelError::ProcessorError(msg) => {
                    assert!(
                        msg.contains(HEADER_CONTAINER_ID),
                        "Error message should mention {}, got: {}",
                        HEADER_CONTAINER_ID,
                        msg
                    );
                }
                _ => panic!("Expected ProcessorError for {}, got: {:?}", operation, err),
            }
        }
    }

    /// Test that stop operation returns an error for a nonexistent container.
    #[tokio::test]
    async fn test_container_producer_stop_nonexistent() {
        // Try to connect to Docker - if fails, return early
        let docker = match Docker::connect_with_local_defaults() {
            Ok(d) => d,
            Err(_) => {
                eprintln!("Skipping test: Could not connect to Docker daemon");
                return;
            }
        };

        if docker.ping().await.is_err() {
            eprintln!("Skipping test: Docker daemon not responding to ping");
            return;
        }

        let component = ContainerComponent::new();
        let ctx = NoOpComponentContext;
        let endpoint = component.create_endpoint("container:stop", &ctx).unwrap();
        let ctx = ProducerContext::new();
        let mut producer = endpoint.create_producer(&ctx).unwrap();

        let mut exchange = Exchange::new(Message::new(""));
        exchange
            .input
            .set_header(HEADER_ACTION, serde_json::Value::String("stop".into()));
        exchange.input.set_header(
            HEADER_CONTAINER_ID,
            serde_json::Value::String("nonexistent-container-123".into()),
        );

        use tower::ServiceExt;
        let result = producer.ready().await.unwrap().call(exchange).await;

        assert!(
            result.is_err(),
            "Expected error when stopping nonexistent container"
        );
        let err = result.unwrap_err();
        match &err {
            CamelError::ProcessorError(msg) => {
                // Docker API returns 404 with "No such container" message
                assert!(
                    msg.to_lowercase().contains("no such container")
                        || msg.to_lowercase().contains("not found")
                        || msg.contains("404"),
                    "Error message should indicate container not found, got: {}",
                    msg
                );
            }
            _ => panic!("Expected ProcessorError, got: {:?}", err),
        }
    }

    /// Test that run operation returns an error when no image is provided.
    #[tokio::test]
    async fn test_container_producer_run_missing_image() {
        // Try to connect to Docker - if fails, return early
        let docker = match Docker::connect_with_local_defaults() {
            Ok(d) => d,
            Err(_) => {
                eprintln!("Skipping test: Could not connect to Docker daemon");
                return;
            }
        };

        if docker.ping().await.is_err() {
            eprintln!("Skipping test: Docker daemon not responding to ping");
            return;
        }

        // Create producer without an image in the URI
        let component = ContainerComponent::new();
        let ctx = NoOpComponentContext;
        let endpoint = component.create_endpoint("container:run", &ctx).unwrap();
        let ctx = ProducerContext::new();
        let mut producer = endpoint.create_producer(&ctx).unwrap();

        let mut exchange = Exchange::new(Message::new(""));
        exchange
            .input
            .set_header(HEADER_ACTION, serde_json::Value::String("run".into()));
        // Deliberately NOT setting CamelContainerImage header

        use tower::ServiceExt;
        let result = producer.ready().await.unwrap().call(exchange).await;

        assert!(
            result.is_err(),
            "Expected error for run operation without image"
        );
        let err = result.unwrap_err();
        match &err {
            CamelError::ProcessorError(msg) => {
                assert!(
                    msg.to_lowercase().contains("image"),
                    "Error message should mention 'image', got: {}",
                    msg
                );
            }
            _ => panic!("Expected ProcessorError, got: {:?}", err),
        }
    }

    /// Test that run operation uses image from header.
    #[tokio::test]
    async fn test_container_producer_run_image_from_header() {
        // Try to connect to Docker - if fails, return early
        let docker = match Docker::connect_with_local_defaults() {
            Ok(d) => d,
            Err(_) => {
                eprintln!("Skipping test: Could not connect to Docker daemon");
                return;
            }
        };

        if docker.ping().await.is_err() {
            eprintln!("Skipping test: Docker daemon not responding to ping");
            return;
        }

        // Create producer without an image in the URI
        let component = ContainerComponent::new();
        let ctx = NoOpComponentContext;
        let endpoint = component.create_endpoint("container:run", &ctx).unwrap();
        let ctx = ProducerContext::new();
        let mut producer = endpoint.create_producer(&ctx).unwrap();

        let mut exchange = Exchange::new(Message::new(""));
        exchange
            .input
            .set_header(HEADER_ACTION, serde_json::Value::String("run".into()));
        // Set a non-existent image to test that the run operation attempts to use it
        exchange.input.set_header(
            HEADER_IMAGE,
            serde_json::Value::String("nonexistent-image-xyz-12345:latest".into()),
        );

        use tower::ServiceExt;
        let result = producer.ready().await.unwrap().call(exchange).await;

        // The operation should fail because the image doesn't exist
        assert!(
            result.is_err(),
            "Expected error when running container with nonexistent image"
        );
        let err = result.unwrap_err();
        match &err {
            CamelError::ProcessorError(msg) => {
                // Docker API returns an error about the missing image
                assert!(
                    msg.to_lowercase().contains("no such image")
                        || msg.to_lowercase().contains("not found")
                        || msg.to_lowercase().contains("image")
                        || msg.to_lowercase().contains("pull")
                        || msg.contains("404"),
                    "Error message should indicate image issue, got: {}",
                    msg
                );
            }
            _ => panic!("Expected ProcessorError, got: {:?}", err),
        }
    }

    /// Integration test: Actually run a container with alpine:latest.
    /// This test verifies the full flow: create → start → set headers.
    #[tokio::test]
    async fn test_container_producer_run_alpine_container() {
        let docker = match Docker::connect_with_local_defaults() {
            Ok(d) => d,
            Err(_) => {
                eprintln!("Skipping test: Could not connect to Docker daemon");
                return;
            }
        };

        if docker.ping().await.is_err() {
            eprintln!("Skipping test: Docker daemon not responding to ping");
            return;
        }

        // Pull alpine:latest if not present
        let images = docker.list_images(None::<ListImagesOptions>).await.unwrap();
        let has_alpine = images
            .iter()
            .any(|img| img.repo_tags.iter().any(|t| t.starts_with("alpine")));

        if !has_alpine {
            eprintln!("Pulling alpine:latest image...");
            let mut stream = docker.create_image(
                Some(CreateImageOptions {
                    from_image: Some("alpine:latest".to_string()),
                    ..Default::default()
                }),
                None,
                None,
            );

            use futures::StreamExt;
            while let Some(_item) = stream.next().await {
                // Wait for pull to complete
            }
            eprintln!("Image pulled successfully");
        }

        // Create producer
        let component = ContainerComponent::new();
        let ctx = NoOpComponentContext;
        let endpoint = component.create_endpoint("container:run", &ctx).unwrap();
        let ctx = ProducerContext::new();
        let mut producer = endpoint.create_producer(&ctx).unwrap();

        // Run container with unique name
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_millis();
        let container_name = format!("test-rust-camel-{}", timestamp);
        let mut exchange = Exchange::new(Message::new(""));
        exchange.input.set_header(
            HEADER_IMAGE,
            serde_json::Value::String("alpine:latest".into()),
        );
        exchange.input.set_header(
            HEADER_CONTAINER_NAME,
            serde_json::Value::String(container_name.clone()),
        );

        use tower::ServiceExt;
        let result = producer
            .ready()
            .await
            .unwrap()
            .call(exchange)
            .await
            .expect("Container run should succeed");

        // Verify container ID was set
        let container_id = result
            .input
            .header(HEADER_CONTAINER_ID)
            .and_then(|v| v.as_str().map(|s| s.to_string()))
            .expect("Expected container ID header");
        assert!(!container_id.is_empty(), "Container ID should not be empty");

        // Verify success header
        assert_eq!(
            result
                .input
                .header(HEADER_ACTION_RESULT)
                .and_then(|v| v.as_str()),
            Some("success")
        );

        // Verify container exists in Docker
        let inspect = docker
            .inspect_container(&container_id, None)
            .await
            .expect("Container should exist");
        assert_eq!(inspect.id.as_deref(), Some(container_id.as_str()));

        // Cleanup: remove container
        docker
            .remove_container(
                &container_id,
                Some(RemoveContainerOptions {
                    force: true,
                    ..Default::default()
                }),
            )
            .await
            .ok();

        eprintln!("✅ Container {} created and cleaned up", container_id);
    }

    /// Test that consumer returns an error for unsupported operations.
    #[tokio::test]
    async fn test_container_consumer_unsupported_operation() {
        use tokio::sync::mpsc;

        let component = ContainerComponent::new();
        let ctx = NoOpComponentContext;
        let endpoint = component.create_endpoint("container:run", &ctx).unwrap();
        let mut consumer = endpoint.create_consumer().unwrap();

        // Create a minimal ConsumerContext
        let (tx, _rx) = mpsc::channel(16);
        let cancel_token = tokio_util::sync::CancellationToken::new();
        let context = ConsumerContext::new(tx, cancel_token);

        let result = consumer.start(context).await;

        // Should return error because "run" is not a supported consumer operation
        assert!(
            result.is_err(),
            "Expected error for unsupported consumer operation"
        );
        let err = result.unwrap_err();
        match &err {
            CamelError::EndpointCreationFailed(msg) => {
                assert!(
                    msg.contains("Consumer only supports 'events' or 'logs'"),
                    "Error message should mention events or logs support, got: {}",
                    msg
                );
            }
            _ => panic!("Expected EndpointCreationFailed error, got: {:?}", err),
        }
    }

    #[test]
    fn test_container_consumer_concurrency_model_is_concurrent() {
        let consumer = ContainerConsumer {
            config: ContainerConfig::from_uri("container:events").unwrap(),
        };

        assert_eq!(
            consumer.concurrency_model(),
            camel_component_api::ConcurrencyModel::Concurrent { max: None }
        );
    }

    /// Test that consumer gracefully shuts down when cancellation is requested.
    /// This test requires a running Docker daemon. If Docker is not available, the test
    /// will be ignored.
    #[tokio::test]
    async fn test_container_consumer_cancellation() {
        use std::sync::atomic::{AtomicBool, Ordering};
        use tokio::sync::mpsc;

        // Try to connect to Docker - if fails, return early
        let docker = match Docker::connect_with_local_defaults() {
            Ok(d) => d,
            Err(_) => {
                eprintln!("Skipping test: Could not connect to Docker daemon");
                return;
            }
        };

        if docker.ping().await.is_err() {
            eprintln!("Skipping test: Docker daemon not responding to ping");
            return;
        }

        let component = ContainerComponent::new();
        let ctx = NoOpComponentContext;
        let endpoint = component.create_endpoint("container:events", &ctx).unwrap();
        let mut consumer = endpoint.create_consumer().unwrap();

        // Create a ConsumerContext
        let (tx, _rx) = mpsc::channel(16);
        let cancel_token = tokio_util::sync::CancellationToken::new();
        let context = ConsumerContext::new(tx, cancel_token.clone());

        // Track if the consumer task has completed
        let completed = Arc::new(AtomicBool::new(false));
        let completed_clone = completed.clone();

        // Spawn consumer in background
        let handle = tokio::spawn(async move {
            let result = consumer.start(context).await;
            // Mark as completed when done
            completed_clone.store(true, Ordering::SeqCst);
            result
        });

        // Wait a bit for the consumer to start
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

        // Consumer should still be running (not completed)
        assert!(
            !completed.load(Ordering::SeqCst),
            "Consumer should still be running before cancellation"
        );

        // Request cancellation
        cancel_token.cancel();

        // Wait for the task to complete (with timeout)
        let result = tokio::time::timeout(tokio::time::Duration::from_millis(500), handle).await;

        // Task should have completed (not timed out)
        assert!(
            result.is_ok(),
            "Consumer should gracefully shut down after cancellation"
        );

        // Verify the consumer completed
        assert!(
            completed.load(Ordering::SeqCst),
            "Consumer should have completed after cancellation"
        );
    }

    /// Integration test for listing containers.
    /// This test requires a running Docker daemon. If Docker is not available, the test
    /// will return early and be effectively ignored.
    #[tokio::test]
    async fn test_container_producer_list_containers() {
        // Try to connect to Docker using default config
        // If ping fails, return early (effectively ignoring this test)
        let docker = match Docker::connect_with_local_defaults() {
            Ok(d) => d,
            Err(_) => {
                eprintln!("Skipping test: Could not connect to Docker daemon");
                return;
            }
        };

        if docker.ping().await.is_err() {
            eprintln!("Skipping test: Docker daemon not responding to ping");
            return;
        }

        // Create producer with list operation
        let component = ContainerComponent::new();
        let ctx = NoOpComponentContext;
        let endpoint = component.create_endpoint("container:list", &ctx).unwrap();

        let ctx = ProducerContext::new();
        let mut producer = endpoint.create_producer(&ctx).unwrap();

        // Create exchange with list operation in header
        let mut exchange = Exchange::new(Message::new(""));
        exchange
            .input
            .set_header(HEADER_ACTION, serde_json::Value::String("list".into()));

        // Call the producer
        use tower::ServiceExt;
        let result = producer
            .ready()
            .await
            .unwrap()
            .call(exchange)
            .await
            .expect("Producer should succeed when Docker is available");

        // Assert that the input exchange body is a JSON array
        // (because list_containers should put the JSON result in the body)
        match &result.input.body {
            camel_component_api::Body::Json(json_value) => {
                assert!(
                    json_value.is_array(),
                    "Expected input body to be a JSON array, got: {:?}",
                    json_value
                );
            }
            other => panic!("Expected Body::Json with array, got: {:?}", other),
        }
    }

    #[test]
    fn test_container_config_parses_volumes() {
        let config = ContainerConfig::from_uri(
            "container:run?image=nginx&volumes=./html:/usr/share/nginx/html:ro",
        )
        .unwrap();
        assert_eq!(
            config.volumes.as_deref(),
            Some("./html:/usr/share/nginx/html:ro")
        );
    }

    #[test]
    fn test_container_config_parses_exec_params() {
        let config = ContainerConfig::from_uri(
            "container:exec?containerId=my-app&cmd=ls /app&user=root&workdir=/tmp&detach=true",
        )
        .unwrap();
        assert_eq!(config.operation, "exec");
        assert_eq!(config.container_id.as_deref(), Some("my-app"));
        assert_eq!(config.cmd.as_deref(), Some("ls /app"));
        assert_eq!(config.user.as_deref(), Some("root"));
        assert_eq!(config.workdir.as_deref(), Some("/tmp"));
        assert!(config.detach);
    }

    #[test]
    fn test_container_config_parses_network_create_params() {
        let config =
            ContainerConfig::from_uri("container:network-create?name=my-net&driver=bridge")
                .unwrap();
        assert_eq!(config.operation, "network-create");
        assert_eq!(config.name.as_deref(), Some("my-net"));
        assert_eq!(config.driver.as_deref(), Some("bridge"));
    }

    #[test]
    fn test_container_config_defaults_new_fields() {
        let config = ContainerConfig::from_uri("container:list").unwrap();
        assert!(config.volumes.is_none());
        assert!(config.user.is_none());
        assert!(config.workdir.is_none());
        assert!(!config.detach);
        assert!(config.driver.is_none());
        assert!(!config.force);
    }

    #[test]
    fn test_parse_volumes_bind_mount() {
        let config = ContainerConfig::from_uri(
            "container:run?image=nginx&volumes=./html:/usr/share/nginx/html:ro",
        )
        .unwrap();
        let (binds, anon) = config.parse_volumes().unwrap();
        assert_eq!(binds, vec!["./html:/usr/share/nginx/html:ro"]);
        assert!(anon.is_empty());
    }

    #[test]
    fn test_parse_volumes_named_volume() {
        let config =
            ContainerConfig::from_uri("container:run?image=postgres&volumes=data:/var/lib/data")
                .unwrap();
        let (binds, anon) = config.parse_volumes().unwrap();
        assert_eq!(binds, vec!["data:/var/lib/data"]);
        assert!(anon.is_empty());
    }

    #[test]
    fn test_parse_volumes_anonymous() {
        let config =
            ContainerConfig::from_uri("container:run?image=alpine&volumes=/tmp/app-data").unwrap();
        let (binds, anon) = config.parse_volumes().unwrap();
        assert!(binds.is_empty());
        assert!(anon.contains(&"/tmp/app-data".to_string()));
    }

    #[test]
    fn test_parse_volumes_anonymous_with_mode() {
        let config =
            ContainerConfig::from_uri("container:run?image=alpine&volumes=/tmp/app-data:ro")
                .unwrap();
        let (binds, anon) = config.parse_volumes().unwrap();
        assert!(binds.is_empty());
        assert!(anon.contains(&"/tmp/app-data".to_string()));
    }

    #[test]
    fn test_parse_volumes_multiple() {
        let config = ContainerConfig::from_uri(
            "container:run?image=nginx&volumes=./html:/usr/share/nginx/html:ro,data:/var/log/app",
        )
        .unwrap();
        let (binds, anon) = config.parse_volumes().unwrap();
        assert_eq!(binds.len(), 2);
        assert!(binds.contains(&"./html:/usr/share/nginx/html:ro".to_string()));
        assert!(binds.contains(&"data:/var/log/app".to_string()));
        assert!(anon.is_empty());
    }

    #[test]
    fn test_parse_volumes_mixed() {
        let config = ContainerConfig::from_uri(
            "container:run?image=nginx&volumes=./html:/usr/share/nginx/html:ro,/tmp/cache",
        )
        .unwrap();
        let (binds, anon) = config.parse_volumes().unwrap();
        assert_eq!(binds.len(), 1);
        assert!(anon.contains(&"/tmp/cache".to_string()));
    }

    #[test]
    fn test_parse_volumes_none() {
        let config = ContainerConfig::from_uri("container:run?image=nginx").unwrap();
        assert!(config.parse_volumes().is_none());
    }

    #[test]
    fn test_parse_volumes_empty_entry_skipped() {
        let config = ContainerConfig::from_uri("container:run?image=nginx&volumes=,,").unwrap();
        assert!(config.parse_volumes().is_none());
    }

    #[test]
    fn test_parse_volumes_rw_mode() {
        let config =
            ContainerConfig::from_uri("container:run?image=nginx&volumes=./data:/app/data:rw")
                .unwrap();
        let (binds, _) = config.parse_volumes().unwrap();
        assert_eq!(binds, vec!["./data:/app/data:rw"]);
    }

    #[tokio::test]
    async fn test_container_producer_network_lifecycle() {
        let docker = match Docker::connect_with_local_defaults() {
            Ok(d) => d,
            Err(_) => {
                eprintln!("Skipping test: Could not connect to Docker daemon");
                return;
            }
        };
        if docker.ping().await.is_err() {
            eprintln!("Skipping test: Docker daemon not responding to ping");
            return;
        }

        let network_name = format!("camel-test-{}", std::process::id());

        let component = ContainerComponent::new();
        let component_ctx = NoOpComponentContext;

        // Create network
        let endpoint = component
            .create_endpoint(
                &format!("container:network-create?name={}", network_name),
                &component_ctx,
            )
            .unwrap();
        let ctx = ProducerContext::new();
        let mut producer = endpoint.create_producer(&ctx).unwrap();

        let mut exchange = Exchange::new(Message::new(""));
        exchange.input.set_header(
            HEADER_ACTION,
            serde_json::Value::String("network-create".into()),
        );

        use tower::ServiceExt;
        let result = producer
            .ready()
            .await
            .unwrap()
            .call(exchange)
            .await
            .expect("Network create should succeed");

        let network_id = result
            .input
            .header(HEADER_NETWORK)
            .and_then(|v| v.as_str().map(|s| s.to_string()))
            .expect("Should have network ID");

        assert!(!network_id.is_empty());

        // List networks
        let endpoint = component
            .create_endpoint("container:network-list", &component_ctx)
            .unwrap();
        let mut producer = endpoint.create_producer(&ctx).unwrap();

        let mut exchange = Exchange::new(Message::new(""));
        exchange.input.set_header(
            HEADER_ACTION,
            serde_json::Value::String("network-list".into()),
        );

        let list_result = producer
            .ready()
            .await
            .unwrap()
            .call(exchange)
            .await
            .expect("Network list should succeed");

        match &list_result.input.body {
            Body::Json(json_value) => {
                assert!(json_value.is_array(), "Expected JSON array");
            }
            other => panic!("Expected Body::Json, got: {:?}", other),
        }

        // Remove network
        let endpoint = component
            .create_endpoint(
                &format!("container:network-remove?network={}", network_name),
                &component_ctx,
            )
            .unwrap();
        let mut producer = endpoint.create_producer(&ctx).unwrap();

        let mut exchange = Exchange::new(Message::new(""));
        exchange.input.set_header(
            HEADER_ACTION,
            serde_json::Value::String("network-remove".into()),
        );

        let remove_result = producer
            .ready()
            .await
            .unwrap()
            .call(exchange)
            .await
            .expect("Network remove should succeed");

        let action_result = remove_result
            .input
            .header(HEADER_ACTION_RESULT)
            .and_then(|v| v.as_str());
        assert_eq!(action_result, Some("success"));
    }
}