bambu-rs 0.1.0

AI-agent-friendly Bambu Lab 3D printer CLI & library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
//! The `bambu` command-line interface (behind the `cli` feature).
//!
//! Thin layer over the library: parse args, resolve a connection target, call
//! the client, format output. Agent contract: human-readable output by default,
//! machine-readable JSON to stdout with `--json` (no TTY auto-detection — output
//! format depends only on the flag); a semantic exit-code scheme; the access
//! code is never printed.

use std::process::ExitCode;
use std::time::Duration;

use clap::{Parser, Subcommand};
use serde::Serialize;

use crate::camera::{CameraClient, CameraError};
use crate::client::{
    ClientError, CommandOutcome, LanMqttClient, StatusSource, VerifyStage, WatchStep,
};
use crate::config::{self, Config, ConfigError, Overrides, Profile, ResolvedTarget};
use crate::core::capability::{self, ControlAssessment, ControlRefusal};
use crate::core::command::{
    AmsControl, AmsFilamentSetting, Command as ProtoCommand, LedNode, SpeedLevel, TimelapseControl,
};
use crate::core::park::ParkTuning;
use crate::core::project::{self, PlateInspection};
use crate::core::report::ReportState;
use crate::core::safety::{self, GcodeVerdict, TempLimits};
use crate::core::stage::Stage;
use crate::core::start::{self, PrintStartParams};
use crate::core::status::{GcodeState, PrinterStatus};
use crate::core::timelapse::{ActivityAction, CaptureAction, CaptureSession, PrintActivitySession};
use crate::core::version::Module;
use crate::ftp::{FtpError, FtpsClient};
use crate::park::{DECODE_H, DECODE_W, ParkCapture, ParkEvent, run_park_camera};

/// Exit codes (a subset of the documented scheme).
mod exit {
    pub const GENERAL: u8 = 1;
    pub const VALIDATION: u8 = 3;
    pub const CONFIRM_REQUIRED: u8 = 4;
    pub const PRINTER_BUSY: u8 = 5;
    pub const VERIFY_TIMEOUT: u8 = 6;
    pub const TRANSPORT: u8 = 7;
    pub const DEVICE_REJECTED: u8 = 8;
}

#[derive(Parser)]
#[command(
    name = "bambu",
    version,
    about = "Monitor and drive Bambu Lab printers over the LAN"
)]
struct Cli {
    /// Printer profile to use (defaults to the configured default).
    #[arg(long, global = true)]
    printer: Option<String>,
    /// Override the printer IP address.
    #[arg(long, global = true)]
    ip: Option<String>,
    /// Override the serial number.
    #[arg(long, global = true)]
    serial: Option<String>,
    /// Override the LAN access code.
    #[arg(long, global = true)]
    access_code: Option<String>,
    /// Override the model (e.g. a1mini).
    #[arg(long, global = true)]
    model: Option<String>,
    /// Emit machine-readable JSON (default output is human-readable).
    #[arg(long, global = true)]
    json: bool,
    /// Read through a running `bambu serve`'s HTTP API instead of opening a
    /// direct MQTT connection — lower latency, since serve already holds a live
    /// delta-merged snapshot (a cold connect+pushall costs seconds). Only the
    /// open reads honor it (`status`, `status --watch`); writes still go direct.
    /// e.g. `http://127.0.0.1:8088`. (Needs no access code — reads are open.)
    #[cfg(feature = "server")]
    #[arg(long, global = true, env = "BAMBU_SERVE_URL", value_name = "URL")]
    via_serve: Option<String>,
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Manage saved printer profiles.
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },
    /// Print a status snapshot; with --watch, monitor continuously.
    Status {
        /// Continuously monitor: print live updates and do NOT stop at job
        /// completion (runs until --timeout or Ctrl-C). To watch a print *to
        /// completion*, use `job start --watch`.
        #[arg(long)]
        watch: bool,
        /// With --watch, poll every N seconds (sends `pushall`) for a higher
        /// data rate, like Bambu Studio. Default: passive (printer's ~2s push).
        #[arg(long)]
        interval: Option<u64>,
        /// With --watch, give up only after NO report for this many seconds
        /// (resets while the printer responds; drops auto-reconnect). Default 2m.
        #[arg(long, default_value_t = 120)]
        timeout: u64,
    },
    /// Show the printer's firmware/module inventory and resolved capabilities.
    Info,
    /// Decode the active HMS (Health Management System) alerts.
    Hms,
    /// Start, pause, resume, stop, or dismiss the error of a print job.
    Job {
        #[command(subcommand)]
        action: JobAction,
    },
    /// Transfer files to/from the printer over FTPS.
    File {
        #[command(subcommand)]
        action: FileAction,
    },
    /// Camera operations (A1/P1 chamber-image stream).
    Camera {
        #[command(subcommand)]
        action: CameraAction,
    },
    /// Timelapse: toggle printer-side recording, fetch videos, or drive an
    /// external camera from the print's own layer events.
    Timelapse {
        #[command(subcommand)]
        action: TimelapseAction,
    },
    /// Turn a light on or off (control test; low-risk).
    Light {
        /// "on" or "off".
        #[arg(value_parser = ["on", "off"])]
        state: String,
        /// Which light: chamber (default) or work. `work` is [spec] — not every
        /// model has one (this A1 mini only reports `chamber_light`).
        #[arg(long, default_value = "chamber", value_parser = ["chamber", "work"])]
        node: String,
        /// Watch the report for this many seconds after sending.
        #[arg(long, default_value_t = 8)]
        timeout: u64,
    },
    /// Set the print-speed profile (can be sent mid-print; reversible).
    Speed {
        /// Speed level.
        #[arg(value_parser = ["silent", "standard", "sport", "ludicrous"])]
        level: String,
        /// Watch the report for this many seconds to confirm spd_lvl changed.
        #[arg(long, default_value_t = 8)]
        timeout: u64,
    },
    /// AMS operations (control, filament change, tray settings). [spec] —
    /// derived from OpenBambuAPI, not yet confirmed on this unit's AMS Lite.
    Ams {
        #[command(subcommand)]
        action: AmsAction,
    },
    /// Run printer calibration. With no routine flags it runs them ALL (the default);
    /// pass any of --bed-level/--vibration/--motor-noise to run just those.
    Calibrate {
        #[command(flatten)]
        args: CalibrateArgs,
    },
    /// Send a raw G-code line and watch the report (control; needs --confirm).
    Gcode {
        /// The G-code line, e.g. "G28" (home all axes).
        line: String,
        /// Required to actually send a control command.
        #[arg(long)]
        confirm: bool,
        /// Override the static safety check (over-limit temps, cold extrusion).
        #[arg(long)]
        force: bool,
        /// Watch the report for this many seconds after sending.
        #[arg(long, default_value_t = 30)]
        timeout: u64,
    },
    /// Reboot the printer (disruptive; needs --confirm). The printer drops the
    /// connection and restarts (~1–2 min) and may rejoin DHCP on a new IP.
    Reboot {
        /// Required — the printer will disconnect and restart.
        #[arg(long)]
        confirm: bool,
    },
    /// Serve the monitoring + control HTTP API (and the web dashboard SPA when
    /// built with the `dashboard` feature).
    #[cfg(feature = "server")]
    #[command(alias = "dashboard")]
    Serve {
        /// Bind host. Default 127.0.0.1; a non-loopback host serves over the
        /// network (without --password, control is open — a warning is printed).
        #[arg(long, default_value = "127.0.0.1")]
        host: String,
        /// Bind port.
        #[arg(long, default_value_t = 8088)]
        port: u16,
        /// Password gating control (write) requests. Reads are always open; if
        /// omitted, control is open too. May also be set via $BAMBU_SERVE_PASSWORD.
        #[arg(long, env = "BAMBU_SERVE_PASSWORD")]
        password: Option<String>,
        /// Serve deterministic fake data (no printer needed; for demos/E2E).
        #[arg(long)]
        fake: bool,
        /// Poll the printer every N seconds for live updates (default: passive).
        #[arg(long)]
        interval: Option<u64>,
        /// External IP-camera snapshot URL(s) the dashboard proxies (single JPEG
        /// per GET, e.g. an ATOM Cam `http://HOST/cgi-bin/get_jpeg.cgi`). Repeat the
        /// flag for multiple cameras, optionally labelling each as `label=url`. The
        /// dashboard shows them as tabs and can add/remove more at runtime. May also
        /// be set via $BAMBU_CAMERA_URL (comma-separated).
        #[arg(long, env = "BAMBU_CAMERA_URL", value_delimiter = ',')]
        camera_url: Vec<String>,
        /// Seed external cameras from a JSON file — a list of
        /// `{ "label"?, "url", "stream_url"?, "park_tuning"? }`, the same shape as
        /// `/api/camera/config`. Unlike `--camera-url` this can carry a stream URL and
        /// per-camera park tuning (so a camera is live-park-capable from launch). Seeded
        /// after any `--camera-url`; all remain editable at runtime.
        #[arg(long, value_name = "PATH")]
        cameras_config: Option<std::path::PathBuf>,
    },
}

#[derive(Subcommand)]
enum ConfigAction {
    /// Add or update a profile (named by --printer).
    Add {
        #[arg(long)]
        ip: String,
        #[arg(long)]
        serial: String,
        #[arg(long)]
        access_code: String,
        #[arg(long)]
        model: String,
        /// Make this the default profile.
        #[arg(long)]
        set_default: bool,
    },
    /// List saved profiles.
    List,
    /// Show a profile (access code redacted).
    Show,
}

#[derive(Subcommand)]
enum JobAction {
    /// Start a print of a file already on the printer (.gcode or .gcode.3mf).
    /// With --upload, FILE is instead a LOCAL path that's uploaded first.
    Start {
        /// On-printer path (e.g. /foo.gcode.3mf), or — with --upload — a LOCAL
        /// file to upload then print.
        file: String,
        /// Upload FILE (a local path) to the printer, then print it. The remote
        /// path defaults to /<basename> (override with --dest).
        #[arg(long)]
        upload: bool,
        /// With --upload, the on-printer destination path (default /<basename>).
        #[arg(long)]
        dest: Option<String>,
        /// With --upload, replace the destination if it already exists (default:
        /// refuse, to avoid clobbering a file mid-print).
        #[arg(long)]
        overwrite: bool,
        /// Plate number (for .3mf project files).
        #[arg(long, default_value_t = 1)]
        plate: u32,
        /// Use the AMS with this mapping: comma-separated tray indices per
        /// filament, -1 = external spool (e.g. "0,-1").
        #[arg(long)]
        ams_map: Option<String>,
        /// Build-plate type.
        #[arg(long, default_value = "auto")]
        bed_type: String,
        /// Record a printer-side timelapse for this print (sets the
        /// project_file `timelapse` flag). Needs a working built-in camera.
        #[arg(long)]
        timelapse: bool,
        /// Show the resolved command JSON without sending it (safe).
        #[arg(long)]
        dry_run: bool,
        /// Required to actually start a print.
        #[arg(long)]
        confirm: bool,
        /// Guard: refuse unless the on-printer file's plate-gcode md5 matches
        /// this (case-insensitive). Get it from `--dry-run`. (.3mf only.)
        #[arg(long)]
        expect_md5: Option<String>,
        /// Guard: refuse unless --plate equals this. (.3mf only.)
        #[arg(long)]
        expect_plate: Option<u32>,
        /// After starting, watch the job to completion and detect anomalies
        /// (a device error or a FAILED state exits non-zero).
        #[arg(long)]
        watch: bool,
        /// With --watch, give up watching after this many seconds (default 6h).
        #[arg(long, default_value_t = 21600)]
        watch_timeout: u64,
        /// With --watch, poll every N seconds (sends `pushall`) for a higher
        /// data rate, like Bambu Studio. Default: passive.
        #[arg(long)]
        interval: Option<u64>,
    },
    /// Pause the current print (needs --confirm).
    Pause {
        #[arg(long)]
        confirm: bool,
    },
    /// Resume a paused print (needs --confirm).
    Resume {
        #[arg(long)]
        confirm: bool,
    },
    /// Stop (cancel) the current print — irreversible (needs --confirm).
    Stop {
        #[arg(long)]
        confirm: bool,
    },
    /// Dismiss a print error (`clean_print_error`) — the way Bambu Studio clears
    /// an error popup so the printer can leave FAILED without a reboot. Narrow:
    /// it only acknowledges the error, it does not stop/resume/clear the job or
    /// the bed. Needs --confirm.
    ClearError {
        #[arg(long)]
        confirm: bool,
    },
}

/// `calibrate` flags: which routines to run, plus the shared run/verify knobs. Mirrors the
/// dashboard's picker — selecting none runs them all (the common "full calibration").
#[derive(clap::Args)]
struct CalibrateArgs {
    /// Auto-level the heated bed.
    #[arg(long)]
    bed_level: bool,
    /// Vibration / resonance compensation.
    #[arg(long)]
    vibration: bool,
    /// Motor-noise (current) calibration.
    #[arg(long)]
    motor_noise: bool,
    /// Show what would run, without sending it (safe).
    #[arg(long)]
    dry_run: bool,
    /// Required to actually run calibration (it moves the hardware).
    #[arg(long)]
    confirm: bool,
    /// After starting, watch the printer report until calibration finishes.
    #[arg(long)]
    watch: bool,
    /// With --watch, give up watching after this many seconds (default 1h).
    #[arg(long, default_value_t = 3600)]
    watch_timeout: u64,
    /// With --watch, poll every N seconds (sends `pushall`) for a higher data
    /// rate. Default: passive (wait for the printer's own pushes).
    #[arg(long)]
    interval: Option<u64>,
}

#[derive(Subcommand)]
enum TimelapseAction {
    /// Enable printer-side timelapse recording (camera.ipcam_timelapse).
    Enable {
        /// Watch the report for this many seconds to confirm the setting.
        #[arg(long, default_value_t = 8)]
        timeout: u64,
    },
    /// Disable printer-side timelapse recording (camera.ipcam_timelapse).
    Disable {
        #[arg(long, default_value_t = 8)]
        timeout: u64,
    },
    /// List recorded timelapse files on the printer (FTPS /timelapse).
    List,
    /// Download a recorded timelapse file from the printer.
    Get {
        /// File name under /timelapse (or a full on-printer path).
        name: String,
        /// Local output path (default: the file's basename in the CWD).
        #[arg(long)]
        out: Option<std::path::PathBuf>,
    },
    /// Drive an EXTERNAL camera: watch the active print and run a capture
    /// command on each new layer (works even with no/!broken built-in camera).
    ///
    /// The capture command goes after `--` and runs as argv (no shell), so its
    /// own flags are fine. Tokens {frame} (the numbered output path), {layer} and
    /// {outdir} are substituted. E.g. an ATOM Cam / IP camera:
    ///   bambu timelapse capture --out-dir ./tl -- \
    ///     curl -s -m 15 -o {frame} http://$ATOMCAM_HOST/cgi-bin/get_jpeg.cgi
    Capture {
        /// Directory for captured frames (created if missing).
        #[arg(long, default_value = "./timelapse")]
        out_dir: std::path::PathBuf,
        /// Capture every Nth layer (1 = every layer).
        #[arg(long, default_value_t = 1)]
        every: u64,
        /// Frame file extension used for {frame} paths.
        #[arg(long, default_value = "jpg")]
        ext: String,
        /// Poll the printer every N seconds (sends `pushall`) for a higher layer
        /// detection rate. Default: passive (printer's ~2s push).
        #[arg(long)]
        interval: Option<u64>,
        /// Give up watching after this many seconds (default 6h).
        #[arg(long, default_value_t = 21600)]
        timeout: u64,
        /// Wait for a print to start instead of requiring one already running:
        /// sit through idle/finished states (and a stale error from the last
        /// print) and begin capturing once the print becomes active. Lets you
        /// launch this BEFORE starting the print. Bounded by --timeout.
        #[arg(long)]
        wait: bool,
        /// The capture command (after `--`), as argv: program then args, with
        /// {frame}/{layer}/{outdir} tokens. Run directly, never via a shell.
        #[arg(trailing_var_arg = true, allow_hyphen_values = true, num_args = 1.., value_name = "CMD")]
        on_layer_cmd: Vec<String>,
    },
    /// Live "parked frame per layer" preview from a camera's MJPEG /stream — the
    /// in-process miner, no MQTT/printer connection needed (it reads the camera, not
    /// the printer). Updates <out>/latest_park.jpg each layer in near-real-time (point an
    /// auto-reloading viewer at it, e.g. `feh --reload 1 <out>/latest_park.jpg`) and
    /// accumulates park_*.jpg + parks.jsonl. Ctrl-C stops cleanly. Needs ffmpeg.
    ///
    ///   bambu timelapse park http://<host>/stream --config tuning.json --out ./live \
    ///     --serve http://<serve-host>:8088 --assemble timelapse.mp4
    Park {
        /// The camera's MJPEG stream URL, e.g. http://<host>/stream.
        stream_url: String,
        /// Per-camera detection tuning JSON (copy the skill's tuning.example.json and
        /// calibrate). There are deliberately NO defaults — a missing knob is an error,
        /// because the right values depend on where the camera and printer sit.
        #[arg(long)]
        config: std::path::PathBuf,
        /// Output dir for latest_park.jpg + park_*.jpg + parks.jsonl (created if missing).
        #[arg(long, default_value = "./park")]
        out: std::path::PathBuf,
        /// On stop, assemble the accumulated park_*.jpg into this mp4 (needs ffmpeg).
        #[arg(long)]
        assemble: Option<std::path::PathBuf>,
        /// Playback frame rate for --assemble.
        #[arg(long, default_value_t = 12)]
        out_fps: u32,
        /// Auto-stop when the print ends: poll a running `bambu serve`'s /api/status for
        /// the print lifecycle (no MQTT from here, so it never conflicts with serve or the
        /// printer's connection). Without it the run ends on --max-seconds / Ctrl-C.
        #[arg(long, value_name = "SERVE_URL")]
        serve: Option<String>,
        /// Auto-stop when the print ends by watching the printer DIRECTLY over MQTT (uses
        /// the selected profile / BAMBU_* env). Alternative to --serve when no serve is
        /// running — the A1 accepts a second MQTT connection, so it won't disrupt one.
        #[arg(long, conflicts_with = "serve")]
        watch_printer: bool,
        /// Detection decode width (tiny grayscale; rarely changed).
        #[arg(long, default_value_t = DECODE_W as u32)]
        width: u32,
        /// Detection decode height.
        #[arg(long, default_value_t = DECODE_H as u32)]
        height: u32,
        /// Stop cleanly after N seconds (default: run until --serve's print-end / Ctrl-C).
        #[arg(long)]
        max_seconds: Option<u64>,
    },
    /// Encode a captured timelapse to mp4 with ffmpeg (must be on PATH). INPUT is
    /// either a directory of frame_*.jpg (the smooth per-layer or plain sampled
    /// frames → an image-sequence timelapse) or a .mjpeg stream file (the plain
    /// stream recording → real video). Output defaults to the input + `.mp4`.
    Encode {
        /// A directory of frame_*.jpg, or a .mjpeg stream file.
        input: std::path::PathBuf,
        /// Output mp4 path (default: the input path with a .mp4 suffix).
        #[arg(long)]
        out: Option<std::path::PathBuf>,
        /// Playback frame rate (frames/sec).
        #[arg(long, default_value_t = 30)]
        fps: u32,
        /// Keep only every Nth frame to speed it up (1 = keep all).
        #[arg(long, default_value_t = 1)]
        speed: u32,
    },
}

#[derive(Subcommand)]
enum AmsAction {
    /// Resume the AMS after a pause/error (ams_control resume).
    Resume {
        #[arg(long)]
        confirm: bool,
    },
    /// Reset the AMS state (ams_control reset).
    Reset {
        #[arg(long)]
        confirm: bool,
    },
    /// Pause the AMS (ams_control pause).
    Pause {
        #[arg(long)]
        confirm: bool,
    },
    /// Change the loaded filament via the AMS — physically moves filament.
    Change {
        /// Target tray id.
        #[arg(long)]
        tray: u32,
        /// New nozzle temperature (°C) for the target filament.
        #[arg(long)]
        tar_temp: i64,
        /// Current nozzle temperature (°C); defaults to the new temp.
        #[arg(long)]
        curr_temp: Option<i64>,
        #[arg(long)]
        dry_run: bool,
        #[arg(long)]
        confirm: bool,
    },
    /// Set a tray's filament profile (material/colour/temps).
    SetFilament {
        #[arg(long, default_value_t = 0)]
        ams: u32,
        #[arg(long)]
        tray: u32,
        /// Material, e.g. PLA, PETG.
        #[arg(long = "type")]
        material: String,
        /// Colour as hex RRGGBBAA (alpha usually FF).
        #[arg(long, default_value = "000000FF")]
        color: String,
        /// Min/max nozzle temperature (°C).
        #[arg(long)]
        min: i64,
        #[arg(long)]
        max: i64,
        /// Filament profile id (e.g. GFA00); optional.
        #[arg(long, default_value = "")]
        info_idx: String,
        #[arg(long)]
        dry_run: bool,
        #[arg(long)]
        confirm: bool,
    },
    /// Set AMS RFID-read options (ams_user_setting).
    Settings {
        #[arg(long, default_value_t = 0)]
        ams: u32,
        /// Read RFID on startup.
        #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
        startup_read: bool,
        /// Read RFID on tray insertion.
        #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
        tray_read: bool,
        #[arg(long)]
        confirm: bool,
    },
}

#[derive(Subcommand)]
enum CameraAction {
    /// Grab one JPEG frame and write it to a file.
    Snapshot {
        /// Output file path.
        #[arg(long, default_value = "snapshot.jpg")]
        out: std::path::PathBuf,
        /// Give up after this many seconds.
        #[arg(long, default_value_t = 10)]
        timeout: u64,
    },
}

#[derive(Subcommand)]
enum FileAction {
    /// List file names in a directory on the printer.
    Ls {
        #[arg(default_value = "/")]
        dir: String,
    },
    /// Upload a local file to the printer.
    Upload {
        /// Local file to upload.
        local: std::path::PathBuf,
        /// Destination directory on the printer (root by default — the A1 mini
        /// prints from `/`; a file under `/cache` fails the print with 0x0500C010).
        #[arg(long, default_value = "/")]
        dest: String,
    },
    /// Download a file from the printer (e.g. a timelapse video).
    Download {
        /// On-printer path, e.g. /timelapse/video.mp4.
        remote: String,
        /// Local output path (default: the remote file's basename in the CWD).
        #[arg(long)]
        out: Option<std::path::PathBuf>,
    },
    /// Delete a file on the printer — irreversible (needs --confirm).
    Rm {
        /// On-printer path to delete.
        remote: String,
        #[arg(long)]
        confirm: bool,
    },
}

/// A CLI error carrying the exit code to return.
#[derive(Debug)]
struct CliError {
    code: u8,
    message: String,
}

impl CliError {
    fn new(code: u8, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }
}

impl From<ConfigError> for CliError {
    fn from(e: ConfigError) -> Self {
        let code = match e {
            ConfigError::MissingField(_) | ConfigError::UnknownProfile(_) => exit::VALIDATION,
            _ => exit::GENERAL,
        };
        CliError::new(code, e.to_string())
    }
}

impl From<ClientError> for CliError {
    fn from(e: ClientError) -> Self {
        let code = match e {
            ClientError::Timeout(_) => exit::VERIFY_TIMEOUT,
            _ => exit::TRANSPORT,
        };
        CliError::new(code, e.to_string())
    }
}

impl From<FtpError> for CliError {
    fn from(e: FtpError) -> Self {
        CliError::new(exit::TRANSPORT, e.to_string())
    }
}

impl From<CameraError> for CliError {
    fn from(e: CameraError) -> Self {
        CliError::new(exit::TRANSPORT, e.to_string())
    }
}

/// Entry point. Parses args, dispatches, and maps errors to exit codes.
pub fn run() -> ExitCode {
    // Pull BAMBU_* from a local .env (without overriding real env vars) so an
    // interactive user need not export them every time.
    config::load_dotenv();
    // With the `license-notice` feature (release builds), add a `--license-notice`
    // flag that prints the embedded third-party notices; otherwise a plain parse.
    #[cfg(feature = "license-notice")]
    let cli = {
        use notalawyer_clap::{ParseExt, include_notice};
        Cli::parse_with_license_notice(include_notice!())
    };
    #[cfg(not(feature = "license-notice"))]
    let cli = Cli::parse();
    match dispatch(&cli) {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("error: {}", e.message);
            ExitCode::from(e.code)
        }
    }
}

fn dispatch(cli: &Cli) -> Result<(), CliError> {
    match &cli.command {
        Command::Config { action } => run_config(cli, action),
        Command::Status {
            watch,
            interval,
            timeout,
        } => run_status(cli, *watch, *interval, *timeout),
        Command::Info => run_info(cli),
        Command::Hms => run_hms(cli),
        Command::Job { action } => run_job(cli, action),
        Command::File { action } => run_file(cli, action),
        Command::Camera { action } => run_camera(cli, action),
        Command::Timelapse { action } => run_timelapse(cli, action),
        Command::Ams { action } => run_ams(cli, action),
        Command::Light {
            state,
            node,
            timeout,
        } => run_light(cli, state == "on", node, *timeout),
        Command::Speed { level, timeout } => run_speed(cli, level, *timeout),
        Command::Calibrate { args } => run_calibrate(cli, args),
        Command::Gcode {
            line,
            confirm,
            force,
            timeout,
        } => run_gcode(cli, line, *confirm, *force, *timeout),
        Command::Reboot { confirm } => run_reboot(cli, *confirm),
        #[cfg(feature = "server")]
        Command::Serve {
            host,
            port,
            password,
            fake,
            interval,
            camera_url,
            cameras_config,
        } => run_serve(
            cli,
            host,
            *port,
            password.clone(),
            *fake,
            *interval,
            camera_url.clone(),
            cameras_config.clone(),
        ),
    }
}

fn config_path() -> Result<std::path::PathBuf, CliError> {
    config::default_config_path()
        .ok_or_else(|| CliError::new(exit::GENERAL, "cannot determine config path (no HOME)"))
}

fn run_config(cli: &Cli, action: &ConfigAction) -> Result<(), CliError> {
    let path = config_path()?;
    let mut cfg = Config::load_or_default(&path)?;
    match action {
        ConfigAction::Add {
            ip,
            serial,
            access_code,
            model,
            set_default,
        } => {
            let name = cli.printer.clone().ok_or_else(|| {
                CliError::new(exit::VALIDATION, "config add needs --printer <name>")
            })?;
            let profile = Profile {
                ip: ip.clone(),
                serial: serial.clone(),
                model: model.clone(),
                mode: "lan".to_string(),
                access_code: access_code.clone(),
            };
            cfg.printers.insert(name.clone(), profile);
            if *set_default || cfg.default_printer.is_none() {
                cfg.default_printer = Some(name.clone());
            }
            cfg.save(&path)?;
            eprintln!("saved profile '{name}' to {}", path.display());
            Ok(())
        }
        ConfigAction::List => {
            if want_json(cli) {
                let names: Vec<&String> = cfg.printers.keys().collect();
                print_json(&serde_json::json!({
                    "default": cfg.default_printer,
                    "printers": names,
                }));
            } else if cfg.printers.is_empty() {
                eprintln!("no profiles configured");
            } else {
                for name in cfg.printers.keys() {
                    let marker = if cfg.default_printer.as_deref() == Some(name) {
                        " (default)"
                    } else {
                        ""
                    };
                    println!("{name}{marker}");
                }
            }
            Ok(())
        }
        ConfigAction::Show => {
            let name = selected_profile_name(cli, &cfg)?.ok_or_else(|| {
                CliError::new(
                    exit::VALIDATION,
                    "no printer selected: pass --printer or set a default",
                )
            })?;
            let profile = cfg
                .profile(&name)
                .ok_or_else(|| CliError::from(ConfigError::UnknownProfile(name.clone())))?;
            let view = RedactedProfile::from(&name, profile);
            if want_json(cli) {
                print_json(&view);
            } else {
                println!("{view}");
            }
            Ok(())
        }
    }
}

fn run_status(
    cli: &Cli,
    watch: bool,
    interval_secs: Option<u64>,
    timeout_secs: u64,
) -> Result<(), CliError> {
    // `--via-serve`: read the snapshot off a running serve's HTTP API instead of
    // a direct MQTT connect. Branch BEFORE config::resolve — the serve path needs
    // no ip/serial/access_code, only the (optional) display identity.
    #[cfg(feature = "server")]
    if let Some(base) = cli.via_serve.clone() {
        return run_status_via_serve(cli, &base, watch, interval_secs);
    }
    let cfg = Config::load_or_default(&config_path()?)?;
    let profile_name = selected_profile_name(cli, &cfg)?;
    let profile = profile_name.as_deref().and_then(|n| cfg.profile(n));
    let overrides = flag_overrides(cli).over(Overrides::from_env());
    let target = config::resolve(profile, &overrides)?;
    let model = target.model.to_string();

    if watch {
        // Continuous monitor: live updates that do NOT stop at job completion
        // (runs until --timeout or Ctrl-C). Output goes to stdout.
        let client = LanMqttClient::new(target).with_timeout(Duration::from_secs(timeout_secs));
        let interval = interval_secs.map(Duration::from_secs);
        return watch_to_terminal(&client, cli, model, profile_name, false, interval, true);
    }

    let state = LanMqttClient::new(target).fetch_snapshot()?;
    let status = PrinterStatus::from_state(state.get());
    let output = StatusOutput {
        printer: profile_name,
        model,
        status,
    };
    if want_json(cli) {
        print_json(&output);
    } else {
        print_status_human(&output);
    }
    Ok(())
}

/// `bambu status --via-serve <url>`: fetch the snapshot from a running serve and
/// render it through the same `StatusOutput` paths as the MQTT version, so the
/// output is byte-for-byte the same shape. Reads are open, so no credentials are
/// touched — only the display identity (printer name + model) is resolved, and
/// even that is best-effort (it may not match the serve's actual target).
#[cfg(feature = "server")]
fn run_status_via_serve(
    cli: &Cli,
    base: &str,
    watch: bool,
    interval_secs: Option<u64>,
) -> Result<(), CliError> {
    if watch {
        return watch_via_serve(cli, base, interval_secs);
    }
    let (printer, model) = serve_display_identity(cli);
    let status = fetch_serve_status(base)?;
    let output = StatusOutput {
        printer,
        model,
        status,
    };
    if want_json(cli) {
        print_json(&output);
    } else {
        print_status_human(&output);
    }
    Ok(())
}

/// `status --watch --via-serve`: poll the serve's snapshot on an interval and
/// print a line on every change (same renderer as the MQTT monitor). Continuous —
/// runs until Ctrl-C; a failed poll is a hard transport error (exit 7) rather than
/// silently repainting a stale snapshot. Default cadence 2s (serve's own update
/// rate); `--interval` overrides.
#[cfg(feature = "server")]
fn watch_via_serve(cli: &Cli, base: &str, interval_secs: Option<u64>) -> Result<(), CliError> {
    let interval = Duration::from_secs(interval_secs.unwrap_or(2).max(1));
    let mut last: Option<WatchKey> = None;
    loop {
        let status = fetch_serve_status(base)?;
        emit_watch_change(&status, &mut last, cli, true);
        std::thread::sleep(interval);
    }
}

/// Join a serve base URL with the status path. Trailing slashes on the base are
/// trimmed so `http://h:8088` and `http://h:8088/` both work.
#[cfg(feature = "server")]
fn serve_status_url(base: &str) -> String {
    format!("{}/api/status", base.trim_end_matches('/'))
}

/// GET the serve's `/api/status` and deserialize it into [`PrinterStatus`]. A
/// short timeout keeps this on the "instant read" path; any failure is a
/// transport error (exit 7) — never a silent fall-through to direct MQTT.
#[cfg(feature = "server")]
fn fetch_serve_status(base: &str) -> Result<PrinterStatus, CliError> {
    let url = serve_status_url(base);
    let resp = ureq::AgentBuilder::new()
        .timeout(Duration::from_secs(5))
        .build()
        .get(&url)
        .call()
        .map_err(|e| {
            CliError::new(
                exit::TRANSPORT,
                format!("couldn't reach serve at {url}: {e}"),
            )
        })?;
    // ureq is built without its `json` feature (no `into_json`), so read the body
    // and parse with serde_json directly.
    let body = resp.into_string().map_err(|e| {
        CliError::new(
            exit::TRANSPORT,
            format!("couldn't read response from {url}: {e}"),
        )
    })?;
    serde_json::from_str::<PrinterStatus>(&body).map_err(|e| {
        CliError::new(
            exit::TRANSPORT,
            format!("unexpected status response from {url}: {e}"),
        )
    })
}

/// Resolve the printer name + model for display only (no credentials). This must
/// NEVER block the serve read: `--via-serve` exists precisely so a caller without
/// local config can read an open API, so a missing/corrupt config, no `HOME`, or a
/// stale `default_printer` all degrade to best-effort (`None` / `"unknown"`)
/// rather than erroring. The label may not match the serve's actual target — that
/// is accepted, since the serve is the source of truth here.
#[cfg(feature = "server")]
fn serve_display_identity(cli: &Cli) -> (Option<String>, String) {
    let cfg = config_path()
        .ok()
        .map(|p| Config::load_or_default(&p))
        .and_then(Result::ok);
    // The label is just what the caller asked for (or the configured default) — we
    // do NOT require it to exist as a profile, so a stale name can't block the read.
    let printer = cli
        .printer
        .clone()
        .or_else(|| cfg.as_ref().and_then(|c| c.default_printer.clone()));
    let profile = printer
        .as_deref()
        .zip(cfg.as_ref())
        .and_then(|(n, c)| c.profile(n));
    let overrides = flag_overrides(cli).over(Overrides::from_env());
    let model = overrides
        .model
        .or_else(|| profile.map(|p| p.model.clone()))
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "unknown".to_string());
    (printer, model)
}

/// One decoded HMS alert, for output.
#[derive(Serialize)]
struct HmsView {
    code: String,
    code_hyphen: String,
    severity: u16,
    is_lidar: bool,
    wiki: String,
}

fn run_hms(cli: &Cli) -> Result<(), CliError> {
    let state = connect_client(cli, 10)?.fetch_snapshot()?;
    let entries = crate::core::hms::decode_report_hms(state.get());
    let views: Vec<HmsView> = entries
        .iter()
        .map(|e| HmsView {
            code: e.code_string(),
            code_hyphen: e.code_hyphen(),
            severity: e.severity_raw(),
            is_lidar: e.is_lidar(),
            wiki: e.wiki_url(),
        })
        .collect();

    if want_json(cli) {
        print_json(&views);
    } else if views.is_empty() {
        println!("no active HMS alerts");
    } else {
        for v in &views {
            println!("{}  (severity {})  {}", v.code, v.severity, v.wiki);
        }
    }
    Ok(())
}

/// Agent-facing view of the control assessment (degrade-not-wall).
#[derive(Serialize)]
struct ControlView {
    /// `allowed` | `requires_developer_mode` | `newer_firmware_untested` | `refused`.
    status: &'static str,
    /// Whether control is *expected* to work (true for the first three).
    expected_ok: bool,
    /// Human-readable reason, present for warnings/refusals.
    reason: Option<String>,
}

impl ControlView {
    fn from(assessment: ControlAssessment) -> Self {
        let refusal = |r: ControlRefusal| match r {
            ControlRefusal::UnknownModel => "model not in the capability registry",
            ControlRefusal::FirmwareNewerThanKnown => "firmware newer than the registry knows",
            ControlRefusal::DeveloperModeUnavailable => {
                "Developer Mode unavailable on this firmware"
            }
            ControlRefusal::UnknownControlBoundary => {
                "no confirmed control boundary for this model"
            }
        };
        match assessment {
            ControlAssessment::Allowed => ControlView {
                status: "allowed",
                expected_ok: true,
                reason: None,
            },
            ControlAssessment::RequiresDeveloperMode => ControlView {
                status: "requires_developer_mode",
                expected_ok: true,
                reason: Some("control needs LAN-only + Developer Mode enabled".into()),
            },
            ControlAssessment::NewerFirmwareUntested => ControlView {
                status: "newer_firmware_untested",
                expected_ok: true,
                reason: Some(
                    "firmware is newer than the tested range; control is very likely fine but \
                     unverified against this version"
                        .into(),
                ),
            },
            ControlAssessment::Refused(r) => ControlView {
                status: "refused",
                expected_ok: false,
                reason: Some(refusal(r).into()),
            },
        }
    }
}

/// Output of `bambu info`: identity + firmware + resolved capabilities.
#[derive(Serialize)]
struct InfoOutput {
    printer: Option<String>,
    model: String,
    firmware: Option<String>,
    registry_status: &'static str,
    push_mode: Option<&'static str>,
    camera_transport: Option<&'static str>,
    developer_mode: Option<&'static str>,
    control: ControlView,
    modules: Vec<Module>,
}

fn run_info(cli: &Cli) -> Result<(), CliError> {
    let cfg = Config::load_or_default(&config_path()?)?;
    let profile_name = selected_profile_name(cli, &cfg)?;
    let profile = profile_name.as_deref().and_then(|n| cfg.profile(n));
    let overrides = flag_overrides(cli).over(Overrides::from_env());
    let target = config::resolve(profile, &overrides)?;
    let model = target.model.clone();

    let version = connect_client(cli, 10)?.fetch_version()?;

    // Resolve capabilities only when the firmware is known; without it we can
    // still report descriptive facts via a model-only lookup is not possible
    // (resolve needs a firmware), so we fall back to reporting "unknown firmware".
    let registry = capability::default_registry();
    let output = match &version.firmware {
        Some(fw) => {
            let caps = capability::resolve(&registry, &model, fw);
            InfoOutput {
                printer: profile_name,
                model: model.to_string(),
                firmware: Some(fw.to_string()),
                registry_status: registry_status_str(caps.registry_status),
                push_mode: caps.push_mode.map(push_mode_str),
                camera_transport: caps.camera_transport.map(camera_transport_str),
                developer_mode: caps.developer_mode.map(developer_mode_str),
                control: ControlView::from(caps.control_assessment()),
                modules: version.modules.clone(),
            }
        }
        None => InfoOutput {
            printer: profile_name,
            model: model.to_string(),
            firmware: None,
            registry_status: "unknown_firmware",
            push_mode: None,
            camera_transport: None,
            developer_mode: None,
            control: ControlView {
                status: "unknown",
                expected_ok: false,
                reason: Some("could not read the firmware version (no `ota` module)".into()),
            },
            modules: version.modules.clone(),
        },
    };

    if want_json(cli) {
        print_json(&output);
    } else {
        print_info_human(&output);
    }
    Ok(())
}

fn registry_status_str(s: capability::RegistryStatus) -> &'static str {
    use capability::RegistryStatus::*;
    match s {
        Supported => "supported",
        FirmwareNewerThanKnown => "firmware_newer_than_known",
        UnknownModel => "unknown_model",
    }
}

fn push_mode_str(m: capability::PushMode) -> &'static str {
    match m {
        capability::PushMode::Full => "full",
        capability::PushMode::DeltaOnly => "delta_only",
    }
}

fn camera_transport_str(t: capability::CameraTransport) -> &'static str {
    use capability::CameraTransport::*;
    match t {
        Rtsp322 => "rtsp_322",
        JpegTcp6000 => "jpeg_tcp_6000",
        None => "none",
    }
}

fn developer_mode_str(d: capability::DeveloperMode) -> &'static str {
    match d {
        capability::DeveloperMode::Available => "available",
        capability::DeveloperMode::Unavailable => "unavailable",
    }
}

fn print_info_human(o: &InfoOutput) {
    println!(
        "printer: {} ({})",
        o.printer.as_deref().unwrap_or("-"),
        o.model
    );
    println!("firmware: {}", o.firmware.as_deref().unwrap_or("?"));
    println!("registry: {}", o.registry_status);
    if let Some(p) = o.push_mode {
        println!("push:     {p}");
    }
    if let Some(c) = o.camera_transport {
        println!("camera:   {c}");
    }
    match &o.control.reason {
        Some(r) => println!("control:  {}{r}", o.control.status),
        None => println!("control:  {}", o.control.status),
    }
    if !o.modules.is_empty() {
        println!("modules:");
        for m in &o.modules {
            let hw = m.hw_ver.as_deref().unwrap_or("-");
            let sw = m.sw_ver.as_deref().unwrap_or("-");
            let prod = m
                .product_name
                .as_deref()
                .map(|p| format!("  {p}"))
                .unwrap_or_default();
            println!("  {:<10} hw {:<9} sw {}{prod}", m.name, hw, sw);
        }
    }
}

/// The report fields whose change triggers a new `watch` progress line.
/// Temperatures are rounded to whole °C so heating/cooling is visible (each 1 °C
/// step prints a line) without spamming on sub-degree jitter.
#[derive(PartialEq)]
struct WatchKey {
    gcode_state: Option<String>,
    stg_cur: Option<i64>,
    mc_percent: Option<i64>,
    layer_num: Option<i64>,
    nozzle: Option<i64>,
    bed: Option<i64>,
    error: Option<i64>,
}

/// The change-trigger fields for `st`. Temperatures round to whole °C so each 1 °C
/// step prints (visible heating/cooling) without sub-degree spam.
fn watch_key(st: &PrinterStatus) -> WatchKey {
    WatchKey {
        gcode_state: st.gcode_state.clone(),
        stg_cur: st.stg_cur,
        mc_percent: st.mc_percent,
        layer_num: st.layer_num,
        nozzle: st.nozzle_temper.map(|v| v.round() as i64),
        bed: st.bed_temper.map(|v| v.round() as i64),
        error: st.error.as_ref().map(|e| e.code),
    }
}

/// One human progress line: `STATE  pct%  layer a/b  N…/… B…/…  ETA…  [stage]  ⚠err`.
fn format_watch_line(st: &PrinterStatus) -> String {
    let stage = match (st.stg_cur, st.stage.as_deref()) {
        (Some(id), Some(name)) if !Stage(id).is_no_stage() => format!("  [{name}]"),
        _ => String::new(),
    };
    let err = match &st.error {
        Some(e) => format!("{}", e.hex),
        None => String::new(),
    };
    // Nozzle/bed as current°→target° (target omitted when off/unset).
    let temp = |cur: Option<f64>, tgt: Option<f64>| match cur {
        Some(c) => match tgt.filter(|t| *t > 0.0) {
            Some(t) => format!("{c:.0}/{t:.0}"),
            None => format!("{c:.0}"),
        },
        None => "-".to_string(),
    };
    let eta = match st.remaining_time_min.filter(|m| *m > 0) {
        Some(m) => format!("  ETA {}", fmt_eta(m)),
        None => String::new(),
    };
    format!(
        "{:<8} {:>3}%  layer {}/{}  N{} B{}{eta}{stage}{err}",
        st.gcode_state.as_deref().unwrap_or("?"),
        st.mc_percent.unwrap_or(0),
        st.layer_num.unwrap_or(0),
        st.total_layer_num.unwrap_or(0),
        temp(st.nozzle_temper, st.nozzle_target),
        temp(st.bed_temper, st.bed_target),
    )
}

/// Print a progress line for `st` IFF it changed from `last` (and update `last`).
/// Shared by the MQTT monitor and the serve-polling watch. A continuous monitor's
/// lines ARE its output → stdout (NDJSON under `--json`); a watch-to-completion
/// keeps stdout for its final snapshot, so its progress goes to stderr.
fn emit_watch_change(st: &PrinterStatus, last: &mut Option<WatchKey>, cli: &Cli, continuous: bool) {
    let key = watch_key(st);
    if last.as_ref() == Some(&key) {
        return;
    }
    *last = Some(key);
    if continuous {
        if want_json(cli) {
            if let Ok(j) = serde_json::to_string(st) {
                println!("{j}");
            }
        } else {
            println!("{}", format_watch_line(st));
        }
    } else {
        eprintln!("{}", format_watch_line(st));
    }
}

/// Watch the printer to a terminal state, **or until a device error appears**,
/// printing a progress line (to stderr) on every change. Used by `watch` and by
/// `job start --watch`. A `print_error` mid-job is treated as an anomaly: stop,
/// surface it, and exit non-zero regardless of `exit_status`. `exit_status`
/// additionally makes a FAILED end-state exit non-zero (gh-run-watch style).
fn watch_to_terminal(
    client: &LanMqttClient,
    cli: &Cli,
    model: String,
    profile_name: Option<String>,
    exit_status: bool,
    interval: Option<Duration>,
    continuous: bool,
) -> Result<(), CliError> {
    let mut last: Option<WatchKey> = None;
    let mut on_update = |state: &ReportState| -> WatchStep {
        let st = PrinterStatus::from_state(state.get());
        emit_watch_change(&st, &mut last, cli, continuous);
        // A continuous monitor never stops on its own (runs until timeout / Ctrl-C).
        if continuous {
            return WatchStep::Continue;
        }
        // A device fault is an anomaly worth stopping for, even mid-RUNNING.
        if st.error.is_some() {
            return WatchStep::Stop;
        }
        match st.state() {
            Some(s) if is_watch_terminal(s) => WatchStep::Stop,
            _ => WatchStep::Continue,
        }
    };

    // status --watch monitors (reconnects, stall timeout); job start --watch
    // watches a job to completion (fail-fast).
    let result = if continuous {
        client.monitor(interval, &mut on_update)
    } else {
        client.watch(interval, &mut on_update)
    };
    let final_state = result?;
    // The monitor's per-change lines were the output; it ends only via its
    // stall window (or Ctrl-C) — nothing more to print, no exit codes.
    if continuous {
        return Ok(());
    }

    let status = PrinterStatus::from_state(final_state.get());
    let error = status.error.clone();
    let failed = status.state() == Some(GcodeState::Failed);
    let output = StatusOutput {
        printer: profile_name,
        model,
        status,
    };
    if want_json(cli) {
        print_json(&output);
    } else {
        print_status_human(&output);
    }
    if let Some(e) = error {
        return Err(CliError::new(
            exit::DEVICE_REJECTED,
            format!(
                "a device error appeared during the job: {} ({})",
                e.hex, e.code
            ),
        ));
    }
    if exit_status && failed {
        return Err(CliError::new(
            exit::GENERAL,
            "print ended in a FAILED state",
        ));
    }
    Ok(())
}

/// Resolve `(model string, profile name)` for status/watch output headers,
/// using the same precedence as a connection.
fn watch_identity(cli: &Cli) -> Result<(String, Option<String>), CliError> {
    let cfg = Config::load_or_default(&config_path()?)?;
    let profile_name = selected_profile_name(cli, &cfg)?;
    let profile = profile_name.as_deref().and_then(|n| cfg.profile(n));
    let overrides = flag_overrides(cli).over(Overrides::from_env());
    let target = config::resolve(profile, &overrides)?;
    Ok((target.model.to_string(), profile_name))
}

fn run_light(cli: &Cli, on: bool, node: &str, timeout_secs: u64) -> Result<(), CliError> {
    let node = match node {
        "chamber" => LedNode::ChamberLight,
        "work" => LedNode::WorkLight,
        other => {
            return Err(CliError::new(
                exit::VALIDATION,
                format!("unknown light {other:?}"),
            ));
        }
    };
    let client = connect_client(cli, timeout_secs)?;
    eprintln!(
        "setting {} {}",
        node.as_str(),
        if on { "on" } else { "off" }
    );
    report_command_outcome(
        cli,
        client.send_and_verify(&ProtoCommand::Led { node, on })?,
    )
}

fn run_speed(cli: &Cli, level: &str, timeout_secs: u64) -> Result<(), CliError> {
    let level = match level {
        "silent" => SpeedLevel::Silent,
        "standard" => SpeedLevel::Standard,
        "sport" => SpeedLevel::Sport,
        "ludicrous" => SpeedLevel::Ludicrous,
        other => {
            return Err(CliError::new(
                exit::VALIDATION,
                format!("unknown speed {other:?}"),
            ));
        }
    };
    let client = connect_client(cli, timeout_secs)?;
    eprintln!(
        "setting print speed to {} (level {}) …",
        level.as_str(),
        level.level()
    );
    report_command_outcome(
        cli,
        client.send_and_verify(&ProtoCommand::PrintSpeed(level))?,
    )
}

fn run_reboot(cli: &Cli, confirm: bool) -> Result<(), CliError> {
    if !confirm {
        return Err(CliError::new(
            exit::CONFIRM_REQUIRED,
            "refusing to reboot without --confirm (the printer will disconnect and restart)",
        ));
    }
    let client = connect_client(cli, 10)?;
    eprintln!("sending reboot …");
    // Reboot tears down the connection, so there is no ACK — fire-and-forget.
    client.send_fire(&ProtoCommand::Reboot)?;
    eprintln!(
        "reboot sent — the printer will disconnect and restart (~1–2 min). \
         No ACK is expected; it may rejoin DHCP on a different IP."
    );
    Ok(())
}

#[cfg(feature = "server")]
#[allow(clippy::too_many_arguments)]
fn run_serve(
    cli: &Cli,
    host: &str,
    port: u16,
    password: Option<String>,
    fake: bool,
    interval: Option<u64>,
    camera_url: Vec<String>,
    cameras_config: Option<std::path::PathBuf>,
) -> Result<(), CliError> {
    // Live mode needs a connection target; fake mode doesn't touch the printer.
    let target = if fake {
        None
    } else {
        Some(resolve_target(cli)?)
    };
    // Parse each `--camera-url` entry (`label=url` or a bare `url`), then any from
    // `--cameras-config` (which can also carry a stream URL + park tuning). The running
    // index gives stable sequential auto-labels (external 1, external 2, …) across both.
    let mut external_cameras: Vec<crate::server::ExternalCamera> = Vec::new();
    for e in camera_url
        .iter()
        .map(|e| e.trim())
        .filter(|e| !e.is_empty())
    {
        if let Some(c) = crate::server::ExternalCamera::parse(e, external_cameras.len()) {
            external_cameras.push(c);
        }
    }
    if let Some(path) = &cameras_config {
        for seed in load_seed_cameras(path)? {
            let i = external_cameras.len();
            // Parse the one tuning object two ways: ParkTuning strictly (a partial tuning is
            // a loud validation error, as before), SelectTuning best-effort (its select knobs
            // may be absent in a park-only config → no clean smooth assemble for this camera).
            let (park, select) = match &seed.park_tuning {
                None => (None, None),
                Some(v) => {
                    let park: ParkTuning = serde_json::from_value(v.clone()).map_err(|e| {
                        CliError::new(
                            exit::VALIDATION,
                            format!("invalid park_tuning in --cameras-config: {e}"),
                        )
                    })?;
                    let select = serde_json::from_value(v.clone()).ok();
                    (Some(park), select)
                }
            };
            external_cameras.push(
                crate::server::ExternalCamera::new(seed.label, seed.url, seed.stream_url, i)
                    .with_park_tuning(park)
                    .with_select_tuning(select),
            );
        }
    }
    let opts = crate::server::ServeOpts {
        host: host.to_string(),
        port,
        password,
        fake,
        interval: interval.map(Duration::from_secs),
        external_cameras,
    };
    crate::server::serve(target, opts).map_err(|e| CliError::new(exit::GENERAL, e.to_string()))
}

/// One entry of a `--cameras-config` JSON file — the same shape as `/api/camera/config`,
/// plus an optional `park_tuning` (validated by serde: no baked defaults).
#[cfg(feature = "server")]
#[derive(serde::Deserialize)]
struct SeedCamera {
    #[serde(default)]
    label: Option<String>,
    url: String,
    #[serde(default)]
    stream_url: Option<String>,
    /// Raw tuning object; parsed below into ParkTuning (strict) AND SelectTuning
    /// (best-effort — its extra select knobs may be absent in a park-only config).
    #[serde(default)]
    park_tuning: Option<serde_json::Value>,
}

/// Read `--cameras-config`: a JSON array of [`SeedCamera`]. A read/parse failure (incl. a
/// partial park_tuning) is a clean validation error rather than a silent skip.
#[cfg(feature = "server")]
fn load_seed_cameras(path: &std::path::Path) -> Result<Vec<SeedCamera>, CliError> {
    let raw = std::fs::read_to_string(path)
        .map_err(|e| CliError::new(exit::VALIDATION, format!("reading {}: {e}", path.display())))?;
    serde_json::from_str(&raw).map_err(|e| {
        CliError::new(
            exit::VALIDATION,
            format!("invalid --cameras-config {}: {e}", path.display()),
        )
    })
}

fn run_gcode(
    cli: &Cli,
    line: &str,
    confirm: bool,
    force: bool,
    timeout_secs: u64,
) -> Result<(), CliError> {
    if !confirm {
        return Err(CliError::new(
            exit::CONFIRM_REQUIRED,
            "refusing to send a control command without --confirm",
        ));
    }
    // Static safety guard: block recognised-dangerous lines (over-limit temps,
    // cold extrusion) unless explicitly overridden with --force.
    if !force && let GcodeVerdict::Block(reason) = safety::check_gcode(line, &TempLimits::default())
    {
        return Err(CliError::new(
            exit::VALIDATION,
            format!("refusing unsafe G-code: {reason}"),
        ));
    }
    let client = connect_client(cli, timeout_secs)?;
    eprintln!("sending gcode_line {line:?}");
    report_command_outcome(
        cli,
        client.send_and_verify(&ProtoCommand::GcodeLine(line.to_string()))?,
    )
}

fn run_file(cli: &Cli, action: &FileAction) -> Result<(), CliError> {
    let ftps = FtpsClient::new(resolve_target(cli)?);
    match action {
        FileAction::Ls { dir } => {
            let names = ftps.list(dir)?;
            if want_json(cli) {
                print_json(&names);
            } else {
                for name in &names {
                    println!("{name}");
                }
            }
            Ok(())
        }
        FileAction::Upload { local, dest } => {
            let filename = local
                .file_name()
                .and_then(|s| s.to_str())
                .ok_or_else(|| CliError::new(exit::VALIDATION, "invalid local file name"))?;
            let remote = format!("{}/{filename}", dest.trim_end_matches('/'));
            let n = ftps.upload(local, &remote)?;
            eprintln!("uploaded {n} bytes to {remote}");
            Ok(())
        }
        FileAction::Download { remote, out } => {
            let local = match out {
                Some(p) => p.clone(),
                None => std::path::Path::new(remote)
                    .file_name()
                    .map(std::path::PathBuf::from)
                    .ok_or_else(|| {
                        CliError::new(
                            exit::VALIDATION,
                            format!("cannot derive an output name from {remote:?}; pass --out"),
                        )
                    })?,
            };
            let n = ftps.download(remote, &local)?;
            eprintln!("downloaded {n} bytes to {}", local.display());
            if want_json(cli) {
                print_json(&serde_json::json!({
                    "path": local.to_string_lossy(),
                    "bytes": n,
                }));
            } else {
                // The file path is the result (never the file's bytes).
                println!("{}", local.display());
            }
            Ok(())
        }
        FileAction::Rm { remote, confirm } => {
            if !*confirm {
                return Err(CliError::new(
                    exit::CONFIRM_REQUIRED,
                    "refusing to delete a file without --confirm",
                ));
            }
            ftps.delete(remote)?;
            eprintln!("deleted {remote}");
            if want_json(cli) {
                print_json(&serde_json::json!({ "deleted": true, "remote": remote }));
            }
            Ok(())
        }
    }
}

fn run_job(cli: &Cli, action: &JobAction) -> Result<(), CliError> {
    match action {
        JobAction::Start {
            file,
            upload,
            dest,
            overwrite,
            plate,
            ams_map,
            bed_type,
            timelapse,
            dry_run,
            confirm,
            expect_md5,
            expect_plate,
            watch,
            watch_timeout,
            interval,
        } => {
            // --upload (FILE is a local path → upload then start) is a distinct
            // enough flow to live on its own; the shared core::start builder keeps
            // the command logic from duplicating.
            if *upload {
                if expect_md5.is_some() || expect_plate.is_some() {
                    return Err(CliError::new(
                        exit::VALIDATION,
                        "--expect-md5 / --expect-plate don't apply with --upload \
                         (you're providing the local file; its md5 is used directly)",
                    ));
                }
                return run_job_start_upload(
                    cli,
                    file,
                    *plate,
                    dest.as_deref(),
                    *overwrite,
                    ams_map.as_deref(),
                    bed_type,
                    *timelapse,
                    *dry_run,
                    *confirm,
                    *watch,
                    *watch_timeout,
                    *interval,
                );
            }
            let is_3mf = file.to_ascii_lowercase().ends_with(".3mf");
            // The expect-guards are 3mf-only (raw .gcode has no plate/md5 metadata):
            // reject them on a .gcode rather than silently ignore.
            if !is_3mf && (expect_md5.is_some() || expect_plate.is_some()) {
                return Err(CliError::new(
                    exit::VALIDATION,
                    "--expect-md5 / --expect-plate only apply to .3mf files",
                ));
            }
            let cmd = build_start_command(file, *plate, ams_map.as_deref(), bed_type, *timelapse)?;

            // The AMS mapping (if any), for validation + dry-run preview.
            let ams_mapping: Option<Vec<i32>> = match &cmd {
                ProtoCommand::ProjectFile(pf) if pf.use_ams => Some(pf.ams_mapping.clone()),
                _ => None,
            };
            // Tray-range is cheap and needs no inspection — fail fast on EVERY
            // path (even a plain confirm or an unreachable printer). The
            // filament-count match needs the 3mf, so it runs below once inspected.
            if let Some(m) = &ams_mapping {
                validate_ams_map(m, None)?;
            }

            // When an expect-guard is given, inspecting the on-printer file is
            // MANDATORY (the caller asked us to verify) and a mismatch is fatal.
            // A bare --dry-run inspects BEST-EFFORT (enrich the plan if the
            // printer is reachable, else show the payload alone). A plain start
            // doesn't inspect at all — that path stays fast and unchanged.
            let has_expect = expect_md5.is_some() || expect_plate.is_some();
            let mut inspection: Option<PlateInspection> = None;
            // For a best-effort dry-run, remember why inspection failed so the
            // plan can say so explicitly (never a silent/ambiguous null).
            let mut inspect_error: Option<String> = None;
            if is_3mf && (has_expect || ams_mapping.is_some() || *dry_run) {
                let mandatory = has_expect || ams_mapping.is_some();
                match inspect_remote_plate(cli, file, *plate) {
                    Ok(insp) => {
                        project::verify_expectations(
                            &insp,
                            *plate,
                            expect_md5.as_deref(),
                            *expect_plate,
                        )
                        .map_err(|e| CliError::new(exit::VALIDATION, e.to_string()))?;
                        // Filament-count check now that we know the plate's
                        // filaments. On a real start a mismatch is fatal (exit 3);
                        // on --dry-run it's downgraded to a warning so the plan
                        // (which also flags it) still prints for the agent to fix.
                        if let Some(m) = &ams_mapping {
                            match validate_ams_map(m, Some(insp.filament_colors.len())) {
                                Ok(warns) => {
                                    for w in warns {
                                        eprintln!("warning: {w}");
                                    }
                                }
                                Err(e) if *dry_run => eprintln!("warning: {}", e.message),
                                Err(e) => return Err(e),
                            }
                        }
                        inspection = Some(insp);
                    }
                    // Inspection is mandatory when an expect-guard or an AMS
                    // mapping needs the filament count; only best-effort for a
                    // bare dry-run.
                    Err(e) if mandatory => return Err(e),
                    Err(e) => {
                        eprintln!(
                            "note: could not inspect the on-printer file ({}); \
                             showing the payload only",
                            e.message
                        );
                        inspect_error = Some(e.message);
                    }
                }
            }

            if *dry_run {
                // Real plan: the resolved payload + what the on-printer file holds.
                print_json(&start_plan_json(
                    &cmd,
                    file,
                    inspection.as_ref(),
                    inspect_error.as_deref(),
                    ams_mapping.as_deref(),
                    *timelapse,
                ));
                return Ok(());
            }
            if !*confirm {
                return Err(CliError::new(
                    exit::CONFIRM_REQUIRED,
                    "refusing to start a print without --confirm (try --dry-run first)",
                ));
            }
            ensure_idle(cli)?;
            let client = connect_client(cli, 30)?;
            eprintln!("starting print: {file}");
            let outcome = client.send_and_verify(&cmd)?;
            // Only keep watching if the print actually started; otherwise the
            // verdict (rejected/unverified) is the result.
            if *watch && outcome == CommandOutcome::Verified {
                eprintln!("print started; watching for completion / anomalies …");
                let (model, profile_name) = watch_identity(cli)?;
                let watcher = connect_client(cli, *watch_timeout)?;
                let watch_interval = interval.map(Duration::from_secs);
                watch_to_terminal(
                    &watcher,
                    cli,
                    model,
                    profile_name,
                    true,
                    watch_interval,
                    false,
                )
            } else {
                report_command_outcome(cli, outcome)
            }
        }
        JobAction::Pause { confirm } => job_control(cli, ProtoCommand::Pause, *confirm),
        JobAction::Resume { confirm } => job_control(cli, ProtoCommand::Resume, *confirm),
        JobAction::Stop { confirm } => job_control(cli, ProtoCommand::Stop, *confirm),
        JobAction::ClearError { confirm } => {
            job_control(cli, ProtoCommand::CleanPrintError, *confirm)
        }
    }
}

/// `bambu job start --upload <local>`: FTPS-upload a local file, then start the
/// print from its on-printer path. The command — including the plate-gcode md5,
/// read from the LOCAL bytes so the printer verifies what we just sent — is built
/// by the shared `core::start` builder (the same one the serve uses).
#[allow(clippy::too_many_arguments)]
fn run_job_start_upload(
    cli: &Cli,
    local: &str,
    plate: u32,
    dest: Option<&str>,
    overwrite: bool,
    ams_map: Option<&str>,
    bed_type: &str,
    timelapse: bool,
    dry_run: bool,
    confirm: bool,
    watch: bool,
    watch_timeout: u64,
    interval: Option<u64>,
) -> Result<(), CliError> {
    let local_path = std::path::Path::new(local);
    let basename = local_path
        .file_name()
        .and_then(|s| s.to_str())
        .ok_or_else(|| CliError::new(exit::VALIDATION, format!("invalid local file: {local:?}")))?;
    let is_3mf = basename.to_ascii_lowercase().ends_with(".3mf");
    // Default to the printer root: the A1 mini prints from `/`; an uploaded file
    // under `/cache` fails the print start with 0x0500C010 (verified on-device).
    let remote = match dest {
        Some(d) => d.to_string(),
        None => format!("/{basename}"),
    };
    // The command type (project_file vs gcode_file) is derived from the REMOTE
    // path, but inspection/md5 come from the LOCAL file — a --dest that flips the
    // .3mf-ness would start the wrong command type for the bytes we uploaded.
    if remote.to_ascii_lowercase().ends_with(".3mf") != is_3mf {
        return Err(CliError::new(
            exit::VALIDATION,
            format!(
                "--dest {remote:?} must keep {basename:?}'s type (both .3mf, or both raw .gcode)"
            ),
        ));
    }

    // Parse + range-check the AMS map up front (no I/O — fail fast).
    let parsed_ams: Option<Vec<i32>> = match (is_3mf, ams_map) {
        (true, Some(m)) => Some(parse_ams_map(m)?),
        _ => None,
    };
    if let Some(m) = &parsed_ams {
        validate_ams_map(m, None)?;
    }

    // Inspect the LOCAL bytes (the file we're about to upload) for the md5 the
    // printer will verify, plus the filament count for the AMS-map check.
    let inspection: Option<PlateInspection> = if is_3mf {
        let bytes = std::fs::read(local_path)
            .map_err(|e| CliError::new(exit::VALIDATION, format!("reading {local}: {e}")))?;
        let insp = project::inspect_plate(&bytes, plate)
            .map_err(|e| CliError::new(exit::VALIDATION, format!("3mf inspection: {e}")))?;
        if let Some(m) = &parsed_ams {
            for w in validate_ams_map(m, Some(insp.filament_colors.len()))? {
                eprintln!("warning: {w}");
            }
        }
        Some(insp)
    } else {
        None
    };

    // Build the wire command for the REMOTE path, stamping in the local md5.
    let params = PrintStartParams {
        file: remote.clone(),
        plate,
        use_ams: parsed_ams.is_some(),
        ams_map: parsed_ams.clone().unwrap_or_default(),
        bed_type: bed_type.to_string(),
        timelapse,
    };
    let cmd = start::build_command(&params, inspection.as_ref());

    if dry_run {
        // Plan: the resolved command + what would be uploaded where (nothing is sent).
        let mut plan = start_plan_json(
            &cmd,
            &remote,
            inspection.as_ref(),
            None,
            parsed_ams.as_deref(),
            timelapse,
        );
        plan["upload"] =
            serde_json::json!({ "local": local, "remote": remote, "overwrite": overwrite });
        print_json(&plan);
        return Ok(());
    }
    if !confirm {
        return Err(CliError::new(
            exit::CONFIRM_REQUIRED,
            "refusing to upload + start without --confirm (try --dry-run first)",
        ));
    }
    ensure_idle(cli)?;

    // Upload (guarding an accidental clobber), then start from the remote path.
    let ftps = FtpsClient::new(resolve_target(cli)?);
    if !overwrite && remote_file_exists(&ftps, &remote) {
        return Err(CliError::new(
            exit::VALIDATION,
            format!("{remote} already exists on the printer (pass --overwrite to replace it)"),
        ));
    }
    let n = ftps.upload(local_path, &remote)?;
    eprintln!("uploaded {n} bytes to {remote}");

    let client = connect_client(cli, 30)?;
    eprintln!("starting print: {remote}");
    let outcome = client.send_and_verify(&cmd)?;
    if watch && outcome == CommandOutcome::Verified {
        eprintln!("print started; watching for completion / anomalies …");
        let (model, profile_name) = watch_identity(cli)?;
        let watcher = connect_client(cli, watch_timeout)?;
        watch_to_terminal(
            &watcher,
            cli,
            model,
            profile_name,
            true,
            interval.map(Duration::from_secs),
            false,
        )
    } else {
        report_command_outcome(cli, outcome)
    }
}

/// Best-effort "does `remote` already exist?" (list its parent dir, match the
/// basename). A listing failure (dir absent, transport blip) is treated as "no":
/// a flaky stat shouldn't block an upload, and the upload itself surfaces real
/// transport errors.
fn remote_file_exists(ftps: &FtpsClient, remote: &str) -> bool {
    let (dir, name) = match remote.rsplit_once('/') {
        Some((d, n)) => (if d.is_empty() { "/" } else { d }, n),
        None => ("/", remote),
    };
    ftps.list(dir)
        .map(|names| names.iter().any(|e| e.rsplit('/').next() == Some(name)))
        .unwrap_or(false)
}

/// Build the start command, choosing project_file (.3mf) or gcode_file (.gcode).
fn build_start_command(
    file: &str,
    plate: u32,
    ams_map: Option<&str>,
    bed_type: &str,
    timelapse: bool,
) -> Result<ProtoCommand, CliError> {
    // AMS mapping only applies to a .3mf; parse it (the one CLI-fallible bit) and
    // hand the resolved params to the shared core builder. md5 is left unset here
    // (we have no inspection at this point — `job start --upload` supplies one).
    let is_3mf = file.to_ascii_lowercase().ends_with(".3mf");
    let (use_ams, parsed_map) = match (is_3mf, ams_map) {
        (true, Some(map)) => (true, parse_ams_map(map)?),
        _ => (false, Vec::new()),
    };
    let params = PrintStartParams {
        file: file.to_string(),
        plate,
        use_ams,
        ams_map: parsed_map,
        bed_type: bed_type.to_string(),
        timelapse,
    };
    Ok(start::build_command(&params, None))
}

fn parse_ams_map(map: &str) -> Result<Vec<i32>, CliError> {
    map.split(',')
        .map(|s| s.trim().parse::<i32>())
        .collect::<Result<Vec<_>, _>>()
        .map_err(|_| CliError::new(exit::VALIDATION, format!("invalid --ams-map: {map:?}")))
}

/// Validate a parsed `--ams-map`. Tray range is **always** checked (needs only
/// the mapping); the filament-count match is checked only when `filament_count`
/// is known (we have to inspect the on-printer 3mf for that). A wrong mapping is
/// the AMS footgun the plan calls out — refuse (exit 3) rather than mis-print.
/// Returns warnings (non-fatal advisories) for the caller to surface.
fn validate_ams_map(
    mapping: &[i32],
    filament_count: Option<usize>,
) -> Result<Vec<String>, CliError> {
    // Range: A1 AMS Lite has trays 0..=3; -1 = external spool.
    for (i, &v) in mapping.iter().enumerate() {
        if !(-1..=3).contains(&v) {
            return Err(CliError::new(
                exit::VALIDATION,
                format!(
                    "--ams-map[{i}]={v} is out of range (AMS trays are 0..3, or -1 for the \
                     external spool)"
                ),
            ));
        }
    }
    if let Some(n) = filament_count
        && mapping.len() != n
    {
        return Err(CliError::new(
            exit::VALIDATION,
            format!(
                "--ams-map has {} entr{} but the plate has {n} filament(s) — one tray per \
                 filament, in order",
                mapping.len(),
                if mapping.len() == 1 { "y" } else { "ies" },
            ),
        ));
    }
    let mut warnings = Vec::new();
    if mapping.iter().filter(|&&v| v == -1).count() > 1 {
        warnings.push(
            "more than one filament is mapped to the external spool (-1); only one filament can \
             physically feed from it — verify this is intended"
                .to_string(),
        );
    }
    Ok(warnings)
}

/// Build the dry-run `ams_mapping_preview`: one entry per plate filament, pairing
/// its colour (the device-confirmed count source) with the tray it's mapped to.
fn ams_mapping_preview(colors: &[String], mapping: &[i32]) -> serde_json::Value {
    let entries: Vec<serde_json::Value> = mapping
        .iter()
        .enumerate()
        .map(|(i, &tray)| {
            let source = if tray == -1 {
                "external spool".to_string()
            } else {
                format!("AMS tray {tray}")
            };
            serde_json::json!({
                "filament": i,
                "color": colors.get(i),
                "tray": tray,
                "source": source,
            })
        })
        .collect();
    serde_json::Value::Array(entries)
}

/// Download the on-printer `.3mf` to a temp file and inspect the given plate.
/// The temp file is always removed (success or error). A download failure maps
/// to exit 7 (transport), a parse/missing-plate to exit 3 (validation).
fn inspect_remote_plate(
    cli: &Cli,
    on_printer_path: &str,
    plate: u32,
) -> Result<PlateInspection, CliError> {
    let ftps = FtpsClient::new(resolve_target(cli)?);
    // Download into a freshly-created, randomly-named temp DIR (O_EXCL): an
    // attacker can't pre-create/symlink a path they can't predict, and the dir
    // (with the downloaded file and its `.part`) is RAII-removed on every exit
    // path — normal, `?`-error, or panic. Avoids the classic /tmp symlink/TOCTOU.
    let dir = tempfile::Builder::new()
        .prefix("bambu-inspect-")
        .tempdir()
        .map_err(|e| CliError::new(exit::GENERAL, format!("creating temp dir: {e}")))?;
    let tmp = dir.path().join("inspect.3mf");
    ftps.download(on_printer_path, &tmp)?; // FtpError -> exit 7
    let bytes = std::fs::read(&tmp)
        .map_err(|e| CliError::new(exit::GENERAL, format!("reading downloaded 3mf: {e}")))?;
    project::inspect_plate(&bytes, plate)
        .map_err(|e| CliError::new(exit::VALIDATION, format!("3mf inspection: {e}")))
    // `dir` drops here (or at any `?` above) -> the temp dir is removed.
}

/// Build the `--dry-run` plan: the exact command payload plus what the
/// on-printer file actually contains (so an agent can read the md5/plate and
/// pass them back as `--expect-md5`/`--expect-plate`).
fn start_plan_json(
    cmd: &ProtoCommand,
    file: &str,
    inspection: Option<&PlateInspection>,
    inspect_error: Option<&str>,
    ams_mapping: Option<&[i32]>,
    timelapse_armed: bool,
) -> serde_json::Value {
    let inspection_json = match (inspection, inspect_error) {
        // Inspected the on-printer file successfully.
        (Some(i), _) => {
            let mut warnings: Vec<String> = Vec::new();
            if !i.sidecar_matches {
                warnings.push(
                    "the file's own .gcode.md5 sidecar disagrees with the computed md5; \
                     using the computed value"
                        .to_string(),
                );
            }
            // Arming timelapse on a plate WITHOUT the per-layer park blocks won't park the
            // head — no clean/object-only timelapse. Call it out before --confirm.
            if timelapse_armed && !i.has_timelapse_blocks {
                warnings.push(
                    "--timelapse is set, but this plate has no per-layer park moves; \
                     the head won't park (no clean object-only timelapse)"
                        .to_string(),
                );
            }
            // Pair each filament with the tray it'll draw from, so the mapping can
            // be eyeballed before --confirm (the plan's mandatory AMS preview).
            let ams_preview = ams_mapping.map(|m| ams_mapping_preview(&i.filament_colors, m));
            if let Some(m) = ams_mapping
                && m.len() != i.filament_colors.len()
            {
                warnings.push(format!(
                    "--ams-map has {} entries but the plate has {} filament(s)",
                    m.len(),
                    i.filament_colors.len()
                ));
            }
            serde_json::json!({
                "inspected": true,
                "file": file,
                "plate": i.plate,
                "gcode_md5": i.gcode_md5,
                "sidecar_md5": i.sidecar_md5,
                "sidecar_matches": i.sidecar_matches,
                "bed_type": i.bed_type,
                "filament_colors": i.filament_colors,
                // Whether the sliced gcode injects the per-layer timelapse park (the
                // precondition for a clean/object-only timelapse — it still only runs if
                // timelapse is armed at print start with --timelapse).
                "has_timelapse_blocks": i.has_timelapse_blocks,
                "ams_mapping_preview": ams_preview,
                "source": "on-printer file (downloaded for inspection)",
                "warnings": warnings,
            })
        }
        // Best-effort inspection was attempted but failed — say so explicitly,
        // so an agent reading stdout never mistakes "couldn't check" for "fine".
        (None, Some(err)) => serde_json::json!({
            "inspected": false,
            "error": err,
        }),
        // No inspection applies (raw .gcode has no plate/md5 metadata).
        (None, None) => serde_json::Value::Null,
    };
    serde_json::json!({
        "command": cmd.to_payload("1"),
        "inspection": inspection_json,
    })
}

/// Refuse to start a print unless the printer is idle (a key safety guard).
fn ensure_idle(cli: &Cli) -> Result<(), CliError> {
    let state = connect_client(cli, 10)?.fetch_snapshot()?;
    match PrinterStatus::from_state(state.get()).state() {
        None | Some(GcodeState::Idle) | Some(GcodeState::Finish) | Some(GcodeState::Failed) => {
            Ok(())
        }
        Some(busy) => Err(CliError::new(
            exit::PRINTER_BUSY,
            format!("printer is busy ({busy:?}); refusing to start a print"),
        )),
    }
}

fn run_ams(cli: &Cli, action: &AmsAction) -> Result<(), CliError> {
    // Helper: a plain control command gated on --confirm (ACK-verified).
    let control =
        |cli: &Cli, cmd: ProtoCommand, confirm: bool, what: &str| -> Result<(), CliError> {
            if !confirm {
                return Err(CliError::new(
                    exit::CONFIRM_REQUIRED,
                    format!("{what} needs --confirm"),
                ));
            }
            let client = connect_client(cli, 15)?;
            eprintln!("{what} … (AMS commands are [spec]; the ACK confirms acceptance)");
            report_command_outcome(cli, client.send_and_verify(&cmd)?)
        };
    match action {
        AmsAction::Resume { confirm } => control(
            cli,
            ProtoCommand::AmsControl(AmsControl::Resume),
            *confirm,
            "ams resume",
        ),
        AmsAction::Reset { confirm } => control(
            cli,
            ProtoCommand::AmsControl(AmsControl::Reset),
            *confirm,
            "ams reset",
        ),
        AmsAction::Pause { confirm } => control(
            cli,
            ProtoCommand::AmsControl(AmsControl::Pause),
            *confirm,
            "ams pause",
        ),
        AmsAction::Change {
            tray,
            tar_temp,
            curr_temp,
            dry_run,
            confirm,
        } => {
            // Guard the nozzle temps the same way the raw-gcode guard does, so an
            // AMS change can't command an unsafe temperature.
            let max = TempLimits::default().max_nozzle as i64;
            let curr = curr_temp.unwrap_or(*tar_temp);
            for (label, t) in [("--tar-temp", *tar_temp), ("--curr-temp", curr)] {
                if t < 0 || t > max {
                    return Err(CliError::new(
                        exit::VALIDATION,
                        format!("{label} {t}°C is out of range (0..={max})"),
                    ));
                }
            }
            let cmd = ProtoCommand::AmsChangeFilament {
                target: *tray,
                curr_temp: curr,
                tar_temp: *tar_temp,
            };
            if *dry_run {
                print_json(&cmd.to_payload("1"));
                return Ok(());
            }
            if !*confirm {
                return Err(CliError::new(
                    exit::CONFIRM_REQUIRED,
                    "ams change physically moves filament; needs --confirm (try --dry-run first)",
                ));
            }
            // A filament change is a physical operation — only when idle.
            ensure_idle(cli)?;
            let client = connect_client(cli, 30)?;
            eprintln!(
                "changing filament to tray {tray} … [spec, untested on this unit] — \
                 the ACK confirms acceptance; watch `bambu status` for the physical change"
            );
            report_command_outcome(cli, client.send_and_verify(&cmd)?)
        }
        AmsAction::SetFilament {
            ams,
            tray,
            material,
            color,
            min,
            max,
            info_idx,
            dry_run,
            confirm,
        } => {
            // Validate the user input before building the command.
            if min > max {
                return Err(CliError::new(
                    exit::VALIDATION,
                    format!("--min {min} must be <= --max {max}"),
                ));
            }
            let limit = TempLimits::default().max_nozzle as i64;
            if *min < 0 || *max > limit {
                return Err(CliError::new(
                    exit::VALIDATION,
                    format!("nozzle temps must be within 0..={limit}°C"),
                ));
            }
            if color.len() != 8 || !color.chars().all(|c| c.is_ascii_hexdigit()) {
                return Err(CliError::new(
                    exit::VALIDATION,
                    format!("--color must be 8 hex digits RRGGBBAA (got {color:?})"),
                ));
            }
            let cmd = ProtoCommand::AmsFilamentSetting(Box::new(AmsFilamentSetting {
                ams_id: *ams,
                tray_id: *tray,
                tray_info_idx: info_idx.clone(),
                tray_color: color.clone(),
                nozzle_temp_min: *min,
                nozzle_temp_max: *max,
                tray_type: material.clone(),
            }));
            if *dry_run {
                print_json(&cmd.to_payload("1"));
                return Ok(());
            }
            control(cli, cmd, *confirm, "ams set-filament")
        }
        AmsAction::Settings {
            ams,
            startup_read,
            tray_read,
            confirm,
        } => control(
            cli,
            ProtoCommand::AmsUserSetting {
                ams_id: *ams,
                startup_read: *startup_read,
                tray_read: *tray_read,
            },
            *confirm,
            "ams settings",
        ),
    }
}

fn run_calibrate(cli: &Cli, args: &CalibrateArgs) -> Result<(), CliError> {
    // No routine flag → run them all (the default), matching the dashboard picker.
    let none_picked = !(args.bed_level || args.vibration || args.motor_noise);
    let bed_level = args.bed_level || none_picked;
    let vibration = args.vibration || none_picked;
    let motor_noise = args.motor_noise || none_picked;
    let cmd = ProtoCommand::Calibration {
        bed_level,
        vibration,
        motor_noise,
    };
    let what = describe_calibration(bed_level, vibration, motor_noise);

    if args.dry_run {
        // Human-readable by default; JSON only with --json (matches the contract).
        if want_json(cli) {
            print_json(&serde_json::json!({
                "plan": {
                    "bed_level": bed_level,
                    "vibration": vibration,
                    "motor_noise": motor_noise,
                    "what": what,
                },
                "payload": cmd.to_payload("1"),
            }));
        } else {
            eprintln!("dry run — would run calibration: {what}");
            eprintln!("(nothing sent; re-run with --confirm to start)");
        }
        return Ok(());
    }
    if !args.confirm {
        return Err(CliError::new(
            exit::CONFIRM_REQUIRED,
            "calibration moves the hardware; needs --confirm (try --dry-run first)",
        ));
    }
    ensure_idle(cli)?;
    let client = connect_client(cli, 20)?;
    eprintln!("starting calibration: {what}");
    let outcome = client.send_and_verify(&cmd)?;
    // With --watch, follow the report to completion (like `job start --watch`);
    // otherwise the accept/verify verdict is the result.
    if args.watch && outcome == CommandOutcome::Verified {
        eprintln!("calibration started; watching until it finishes …");
        let (model, profile_name) = watch_identity(cli)?;
        let watcher = connect_client(cli, args.watch_timeout)?;
        let watch_interval = args.interval.map(Duration::from_secs);
        watch_to_terminal(
            &watcher,
            cli,
            model,
            profile_name,
            false,
            watch_interval,
            false,
        )
    } else {
        report_command_outcome(cli, outcome)
    }
}

/// A human label for the calibration steps that are enabled.
fn describe_calibration(bed_level: bool, vibration: bool, motor_noise: bool) -> String {
    let mut parts = Vec::new();
    if bed_level {
        parts.push("bed level");
    }
    if vibration {
        parts.push("vibration");
    }
    if motor_noise {
        parts.push("motor noise");
    }
    if parts.is_empty() {
        "nothing".to_string()
    } else {
        parts.join(" + ")
    }
}

fn job_control(cli: &Cli, cmd: ProtoCommand, confirm: bool) -> Result<(), CliError> {
    if !confirm {
        return Err(CliError::new(
            exit::CONFIRM_REQUIRED,
            "this control command needs --confirm",
        ));
    }
    let client = connect_client(cli, 15)?;
    report_command_outcome(cli, client.send_and_verify(&cmd)?)
}

fn run_camera(cli: &Cli, action: &CameraAction) -> Result<(), CliError> {
    match action {
        CameraAction::Snapshot { out, timeout } => {
            let camera =
                CameraClient::new(resolve_target(cli)?).with_timeout(Duration::from_secs(*timeout));
            let jpeg = camera.snapshot()?;
            std::fs::write(out, &jpeg).map_err(|e| {
                CliError::new(exit::GENERAL, format!("write {}: {e}", out.display()))
            })?;
            eprintln!("wrote {} bytes", jpeg.len());
            if want_json(cli) {
                print_json(&serde_json::json!({
                    "path": out.to_string_lossy(),
                    "bytes": jpeg.len(),
                }));
            } else {
                // The file path is the result (never inline image bytes).
                println!("{}", out.display());
            }
            Ok(())
        }
    }
}

fn run_timelapse(cli: &Cli, action: &TimelapseAction) -> Result<(), CliError> {
    match action {
        TimelapseAction::Enable { timeout } => {
            timelapse_set(cli, TimelapseControl::Enable, *timeout)
        }
        TimelapseAction::Disable { timeout } => {
            timelapse_set(cli, TimelapseControl::Disable, *timeout)
        }
        TimelapseAction::List => {
            let names = FtpsClient::new(resolve_target(cli)?).list("/timelapse")?;
            if want_json(cli) {
                print_json(&names);
            } else if names.is_empty() {
                println!("no timelapse files on the printer");
            } else {
                for n in &names {
                    println!("{n}");
                }
            }
            Ok(())
        }
        TimelapseAction::Get { name, out } => {
            // Accept either a bare file name or a full on-printer path.
            let remote = if name.starts_with('/') {
                name.clone()
            } else {
                format!("/timelapse/{name}")
            };
            let local = match out {
                Some(p) => p.clone(),
                None => std::path::Path::new(&remote)
                    .file_name()
                    .map(std::path::PathBuf::from)
                    .ok_or_else(|| {
                        CliError::new(exit::VALIDATION, "cannot derive an output name; pass --out")
                    })?,
            };
            let n = FtpsClient::new(resolve_target(cli)?).download(&remote, &local)?;
            eprintln!("downloaded {n} bytes to {}", local.display());
            if want_json(cli) {
                print_json(&serde_json::json!({
                    "path": local.to_string_lossy(),
                    "bytes": n,
                }));
            } else {
                println!("{}", local.display());
            }
            Ok(())
        }
        TimelapseAction::Capture {
            on_layer_cmd,
            out_dir,
            every,
            ext,
            interval,
            timeout,
            wait,
        } => run_timelapse_capture(
            cli,
            on_layer_cmd,
            out_dir,
            *every,
            ext,
            interval.map(Duration::from_secs),
            *timeout,
            *wait,
        ),
        TimelapseAction::Encode {
            input,
            out,
            fps,
            speed,
        } => run_encode(input, out.as_deref(), *fps, *speed),
        TimelapseAction::Park {
            stream_url,
            config,
            out,
            assemble,
            out_fps,
            serve,
            watch_printer,
            width,
            height,
            max_seconds,
        } => run_timelapse_park(ParkArgs {
            stream_url,
            config,
            out,
            assemble: assemble.as_deref(),
            out_fps: *out_fps,
            serve: serve.as_deref(),
            watch_printer: *watch_printer,
            width: *width,
            height: *height,
            max_seconds: *max_seconds,
            cli,
        }),
    }
}

/// Inputs for [`run_timelapse_park`] — bundled to keep the call readable as options grow.
struct ParkArgs<'a> {
    stream_url: &'a str,
    config: &'a std::path::Path,
    out: &'a std::path::Path,
    assemble: Option<&'a std::path::Path>,
    out_fps: u32,
    serve: Option<&'a str>,
    watch_printer: bool,
    width: u32,
    height: u32,
    max_seconds: Option<u64>,
    cli: &'a Cli,
}

/// `bambu timelapse park`: drive the live park miner over a camera's MJPEG stream. No
/// printer/MQTT connection — the park signal comes from the camera, so this just needs
/// the stream URL + a calibrated tuning. Blocks until the stream ends, `--max-seconds`
/// elapses, or the process is interrupted; reports each park to stderr and a final
/// summary (JSON with `--json`).
fn run_timelapse_park(args: ParkArgs) -> Result<(), CliError> {
    let ParkArgs {
        stream_url,
        config,
        out,
        assemble,
        out_fps,
        serve,
        watch_printer,
        width,
        height,
        max_seconds,
        cli,
    } = args;
    // No baked defaults: a missing knob is a hard error, not a silent stale value.
    let raw = std::fs::read_to_string(config).map_err(|e| {
        CliError::new(
            exit::VALIDATION,
            format!("reading tuning config {}: {e}", config.display()),
        )
    })?;
    let tuning: ParkTuning = serde_json::from_str(&raw).map_err(|e| {
        CliError::new(
            exit::VALIDATION,
            format!(
                "invalid tuning config {} (no defaults): {e}",
                config.display()
            ),
        )
    })?;
    std::fs::create_dir_all(out)
        .map_err(|e| CliError::new(exit::GENERAL, format!("creating {}: {e}", out.display())))?;

    let cap = ParkCapture {
        id: "park".to_string(),
        stream_url: stream_url.to_string(),
        tuning,
    };
    // Every stop source — Ctrl-C, --max-seconds, and --serve's print-end — converges on
    // this one flag, which run_park_camera's watchdog turns into an ffmpeg kill + clean
    // unwind (final summary + --assemble).
    let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    {
        let cancel = cancel.clone();
        // A second Ctrl-C is left to the OS default (hard kill) in case cleanup hangs.
        let _ =
            ctrlc::set_handler(move || cancel.store(true, std::sync::atomic::Ordering::Relaxed));
    }
    if let Some(secs) = max_seconds {
        let cancel = cancel.clone();
        std::thread::spawn(move || {
            std::thread::sleep(Duration::from_secs(secs));
            cancel.store(true, std::sync::atomic::Ordering::Relaxed);
        });
    }
    if let Some(base) = serve {
        spawn_serve_autostop(base, &cancel)?;
    } else if watch_printer {
        spawn_printer_autostop(cli, &cancel)?;
    }

    eprintln!("watching {stream_url} -> {}", out.display());
    eprintln!(
        "  live preview: open {}/latest_park.jpg in an auto-reloading viewer \
         (e.g. feh --reload 1 {}/latest_park.jpg)",
        out.display(),
        out.display()
    );
    let auto_stop = if serve.is_some() {
        "print end (via serve), "
    } else if watch_printer {
        "print end (via printer), "
    } else {
        ""
    };
    eprintln!(
        "  stops on: {}{}Ctrl-C",
        auto_stop,
        max_seconds.map_or(String::new(), |s| format!("{s}s, ")),
    );

    let mut parks = 0u64;
    let mut on_park = |ev| match ev {
        ParkEvent::Written => {
            eprintln!("park #{parks}");
            parks += 1;
        }
        // A replace refines the last park (stronger frame, same layer) — not a new one.
        ParkEvent::Replaced => {
            eprintln!("park #{} updated (stronger frame)", parks.saturating_sub(1))
        }
        ParkEvent::Dropped => eprintln!("warning: a park frame was dropped (ring JPEG missing)"),
    };
    let stats = run_park_camera(
        &cap,
        out,
        width as usize,
        height as usize,
        &cancel,
        &mut on_park,
    )
    .map_err(|e| CliError::new(exit::GENERAL, e))?;

    if stats.frames == 0 {
        return Err(CliError::new(
            exit::TRANSPORT,
            format!("read 0 frames from {stream_url} — check the URL and that ffmpeg can open it"),
        ));
    }
    eprintln!(
        "done: {} parks ({} frames, {} replaced, {} dropped) -> {}",
        stats.parks,
        stats.frames,
        stats.replaced,
        stats.dropped,
        out.display()
    );

    let assembled = match assemble {
        Some(mp4) if stats.parks > 0 => {
            assemble_park_mp4(out, mp4, out_fps)?;
            eprintln!("assembled {}", mp4.display());
            Some(mp4.to_string_lossy().to_string())
        }
        Some(_) => {
            eprintln!("nothing to assemble (no parks captured)");
            None
        }
        None => None,
    };

    if want_json(cli) {
        print_json(&serde_json::json!({
            "out": out.to_string_lossy(),
            "frames": stats.frames,
            "parks": stats.parks,
            "replaced": stats.replaced,
            "dropped": stats.dropped,
            "assembled": assembled,
        }));
    }
    Ok(())
}

/// Assemble the accumulated `park_%06d.jpg` sequence in `out_dir` into `mp4` at `fps`.
fn assemble_park_mp4(
    out_dir: &std::path::Path,
    mp4: &std::path::Path,
    fps: u32,
) -> Result<(), CliError> {
    // Shared with the serve's download endpoint — one ffmpeg assembly in the library.
    crate::captures::assemble_mp4(out_dir, crate::captures::CaptureKind::Park, mp4, fps).map_err(
        |e| {
            let code = if e.contains("ffmpeg not found") {
                exit::VALIDATION
            } else {
                exit::GENERAL
            };
            CliError::new(code, e)
        },
    )
}

/// Spawn the `--serve` auto-stop poller: read a running serve's `/api/status` on an
/// interval, feed it through the pure print-lifecycle state machine, and flip `cancel`
/// once the print ends (after having been active). No MQTT from here — serve owns the
/// single printer connection — so it never conflicts. Transient poll failures are skipped
/// (the run still stops on Ctrl-C / --max-seconds).
#[cfg(feature = "server")]
fn spawn_serve_autostop(
    base: &str,
    cancel: &std::sync::Arc<std::sync::atomic::AtomicBool>,
) -> Result<(), CliError> {
    // Fail fast if serve isn't reachable, rather than silently never auto-stopping.
    fetch_serve_status(base)?;
    let base = base.to_string();
    let cancel = cancel.clone();
    std::thread::spawn(move || {
        let mut activity = PrintActivitySession::new(true);
        while !cancel.load(std::sync::atomic::Ordering::Relaxed) {
            if let Ok(status) = fetch_serve_status(&base)
                && activity.observe(&status) == ActivityAction::Stop
            {
                cancel.store(true, std::sync::atomic::Ordering::Relaxed);
                return;
            }
            std::thread::sleep(Duration::from_secs(2));
        }
    });
    Ok(())
}

#[cfg(not(feature = "server"))]
fn spawn_serve_autostop(
    _base: &str,
    _cancel: &std::sync::Arc<std::sync::atomic::AtomicBool>,
) -> Result<(), CliError> {
    Err(CliError::new(
        exit::VALIDATION,
        "--serve needs the `server` feature (not compiled into this build)",
    ))
}

/// Spawn the `--watch-printer` auto-stop poller: open a DIRECT MQTT connection to the
/// configured printer (profile / BAMBU_* env) and watch its print lifecycle through the
/// pure [`PrintActivitySession`], flipping `cancel` once the print ends. The A1 accepts a
/// second MQTT connection (device-verified), so this runs fine alongside a `bambu serve`.
///
/// Uses [`monitor`](LanMqttClient::monitor) (auto-reconnecting; the timeout is a *stall*
/// window reset on every report) with a periodic pushall, so it watches INDEFINITELY
/// across a long print — or while armed before it starts — and only gives up if the
/// printer is unreachable for the whole stall window. The target is resolved up front
/// (fail-fast on a missing config); a later disappearance is a non-fatal warning, since
/// --max-seconds / Ctrl-C still stop the run.
fn spawn_printer_autostop(
    cli: &Cli,
    cancel: &std::sync::Arc<std::sync::atomic::AtomicBool>,
) -> Result<(), CliError> {
    let target = resolve_target(cli)?;
    let cancel = cancel.clone();
    std::thread::spawn(move || {
        use std::sync::atomic::Ordering::Relaxed;
        // Stall window: monitor only returns after no report for this long. The 30s
        // pushall keeps reports flowing (idle or printing), so it watches indefinitely
        // while the printer responds, auto-reconnecting through transient drops.
        let client = LanMqttClient::new(target).with_timeout(Duration::from_secs(120));
        let mut activity = PrintActivitySession::new(true);
        // Retry loop: monitor returns when WE stop it (print end / cancel) or after a
        // sustained outage (a stall returns Ok, a hard error returns Err). If we didn't
        // stop it, auto-stop is momentarily unarmed — say so (never exit silently) and
        // re-enter, so it RESUMES once the printer responds again. --max-seconds / Ctrl-C
        // stay as backstops throughout.
        while !cancel.load(Relaxed) {
            let mut on_update = |state: &ReportState| -> WatchStep {
                if cancel.load(Relaxed) {
                    return WatchStep::Stop; // another stop source fired
                }
                let st = PrinterStatus::from_state(state.get());
                if activity.observe(&st) == ActivityAction::Stop {
                    cancel.store(true, Relaxed);
                    WatchStep::Stop
                } else {
                    WatchStep::Continue
                }
            };
            let result = client.monitor(Some(Duration::from_secs(30)), &mut on_update);
            if cancel.load(Relaxed) {
                break; // we (or another stop source) ended the run
            }
            match result {
                Err(e) if !matches!(e, ClientError::Timeout(_)) => {
                    eprintln!("warning: printer auto-stop watch error: {e}; retrying…")
                }
                _ => eprintln!(
                    "warning: printer unreachable — print-end auto-stop paused, retrying…"
                ),
            }
            std::thread::sleep(Duration::from_secs(5));
        }
    });
    Ok(())
}

/// Default mp4 path for an `encode` input: the input path with a `.mp4` suffix
/// (a `frames/` dir → `frames.mp4`; `plain.mjpeg` → `plain.mp4`).
fn default_mp4_out(input: &std::path::Path) -> std::path::PathBuf {
    input.with_extension("mp4")
}

/// Whether `input` is a `.mjpeg` stream file (vs an image-sequence directory).
fn is_mjpeg(input: &std::path::Path) -> bool {
    input
        .extension()
        .and_then(|e| e.to_str())
        .is_some_and(|e| e.eq_ignore_ascii_case("mjpeg"))
}

/// Build the ffmpeg argument vector to encode `input` → `out`. A directory is an
/// image sequence (`frame_*.jpg`, the smooth/sampled frames); a `.mjpeg` file is a
/// multipart stream (the plain recording). Pure, so the command shape is tested
/// without running ffmpeg.
fn build_ffmpeg_args(
    input: &std::path::Path,
    out: &std::path::Path,
    fps: u32,
    speed: u32,
) -> Result<Vec<String>, CliError> {
    let fps = fps.max(1);
    let speed = speed.max(1);
    let mut args: Vec<String> = vec!["-y".into()];
    if input.is_dir() {
        // Image sequence: the input framerate sets the timelapse speed.
        args.extend(["-framerate".into(), fps.to_string()]);
        args.extend(["-pattern_type".into(), "glob".into()]);
        args.extend(["-i".into(), format!("{}/frame_*.jpg", input.display())]);
        if speed > 1 {
            // framestep drops frames; setpts re-times the survivors to `fps` so it
            // actually plays faster (not the original spacing with gaps).
            args.extend([
                "-vf".into(),
                format!("framestep={speed},setpts=N/{fps}/TB"),
                "-r".into(),
                fps.to_string(),
            ]);
        }
    } else if is_mjpeg(input) {
        // Multipart MJPEG stream: re-time the frames to `fps` (keeping every
        // `speed`-th to fast-forward).
        args.extend(["-f".into(), "mpjpeg".into()]);
        args.extend(["-i".into(), input.display().to_string()]);
        let vf = if speed > 1 {
            format!("framestep={speed},setpts=N/{fps}/TB")
        } else {
            format!("setpts=N/{fps}/TB")
        };
        args.extend(["-vf".into(), vf, "-r".into(), fps.to_string(), "-an".into()]);
    } else {
        return Err(CliError::new(
            exit::VALIDATION,
            format!(
                "{}: encode input must be a directory of frame_*.jpg or a .mjpeg file",
                input.display()
            ),
        ));
    }
    args.extend(
        [
            "-c:v",
            "libx264",
            "-pix_fmt",
            "yuv420p",
            "-movflags",
            "+faststart",
        ]
        .map(String::from),
    );
    args.push(out.display().to_string());
    Ok(args)
}

/// `bambu timelapse encode`: run ffmpeg (if present) to turn a recording into mp4.
fn run_encode(
    input: &std::path::Path,
    out: Option<&std::path::Path>,
    fps: u32,
    speed: u32,
) -> Result<(), CliError> {
    if !input.exists() {
        return Err(CliError::new(
            exit::VALIDATION,
            format!("{}: no such file or directory", input.display()),
        ));
    }
    let out = out
        .map(std::path::Path::to_path_buf)
        .unwrap_or_else(|| default_mp4_out(input));
    let args = build_ffmpeg_args(input, &out, fps, speed)?;

    // ffmpeg is an optional, runtime dependency — fail clearly if it's missing.
    let status = std::process::Command::new("ffmpeg")
        .args(&args)
        .status()
        .map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                CliError::new(
                    exit::VALIDATION,
                    "ffmpeg not found on PATH — install ffmpeg to encode mp4",
                )
            } else {
                CliError::new(exit::GENERAL, format!("running ffmpeg: {e}"))
            }
        })?;
    if !status.success() {
        return Err(CliError::new(
            exit::GENERAL,
            format!("ffmpeg exited with {status}"),
        ));
    }
    eprintln!("encoded {}", out.display());
    println!("{}", out.display());
    Ok(())
}

fn timelapse_set(cli: &Cli, control: TimelapseControl, timeout_secs: u64) -> Result<(), CliError> {
    let client = connect_client(cli, timeout_secs)?;
    eprintln!("setting timelapse {}", control.as_str());
    report_command_outcome(
        cli,
        client.send_and_verify(&ProtoCommand::IpcamTimelapse(control))?,
    )
}

/// Drive an external camera: watch the active print and run a capture command on
/// each new layer. This is the workaround for a missing/broken built-in camera —
/// the printer's own `layer_num` is the trigger; the user supplies any capture
/// tool. Capture runs as argv (no shell) with `{frame}`/`{layer}`/`{outdir}`
/// substituted; a failed grab is logged and skipped so it never aborts the watch.
// A CLI handler fanning out one flag per parameter — grouping them into a struct
// would add indirection without making the call site (a single match arm) clearer.
#[allow(clippy::too_many_arguments)]
fn run_timelapse_capture(
    cli: &Cli,
    on_layer_cmd: &[String],
    out_dir: &std::path::Path,
    every: u64,
    ext: &str,
    interval: Option<Duration>,
    timeout_secs: u64,
    wait: bool,
) -> Result<(), CliError> {
    if every == 0 {
        return Err(CliError::new(exit::VALIDATION, "--every must be >= 1"));
    }
    if ext.is_empty() || ext.len() > 12 || !ext.chars().all(|c| c.is_ascii_alphanumeric()) {
        return Err(CliError::new(
            exit::VALIDATION,
            "--ext must be 1-12 alphanumeric characters (e.g. jpg, png)",
        ));
    }
    std::fs::create_dir_all(out_dir)
        .map_err(|e| CliError::new(exit::GENERAL, format!("create {}: {e}", out_dir.display())))?;
    let client = connect_client(cli, timeout_secs)?;

    if wait {
        eprintln!(
            "waiting for a print to start, then capturing every {} layer(s) to {}",
            every,
            out_dir.display()
        );
    } else {
        eprintln!(
            "watching the active print; capturing every {} layer(s) to {}",
            every,
            out_dir.display()
        );
    }

    // Run captures on a dedicated worker thread fed by a channel, so a slow
    // capture command never blocks the MQTT event loop (which would miss layer
    // updates and risk tripping the keepalive). The watch callback only enqueues.
    let (tx, rx) = std::sync::mpsc::channel::<(std::path::PathBuf, i64)>();
    let worker = {
        let argv = on_layer_cmd.to_vec();
        let dir = out_dir.to_path_buf();
        std::thread::spawn(move || {
            let (mut captured, mut failures) = (0u64, 0u64);
            for (frame, layer) in rx {
                match run_capture_cmd(&argv, &frame, layer, &dir) {
                    Ok(()) => {
                        captured += 1;
                        eprintln!("captured frame (layer {layer}) -> {}", frame.display());
                    }
                    Err(e) => {
                        failures += 1;
                        eprintln!("capture failed at layer {layer}: {e} (continuing)");
                    }
                }
            }
            (captured, failures)
        })
    };

    // The pure `CaptureSession` (core) decides per status snapshot whether to
    // grab a frame or stop; here we only turn a `Capture` into a queued frame.
    // Scope the callback so its borrow of `tx` ends before we drop `tx` (which
    // signals the worker to finish and lets us join it for the final counts).
    let watch_result = {
        let mut session = CaptureSession::new(every, wait);
        let mut on_update = |state: &ReportState| -> WatchStep {
            let st = PrinterStatus::from_state(state.get());
            match session.observe(&st) {
                CaptureAction::Capture { frame_no, layer } => {
                    let frame = out_dir.join(format!("frame_{frame_no:06}_layer_{layer:05}.{ext}"));
                    // Enqueue; the worker captures. send fails only if the worker
                    // died, which we surface via the join below.
                    let _ = tx.send((frame, layer));
                    WatchStep::Continue
                }
                CaptureAction::Continue => WatchStep::Continue,
                CaptureAction::Stop => WatchStep::Stop,
            }
        };
        client.watch(interval, &mut on_update)
    };
    // Close the channel and drain the worker (runs any queued captures), then
    // read the tallies it accumulated.
    drop(tx);
    let (captured, failures) = worker.join().unwrap_or((0, 0));

    let ended_by = match &watch_result {
        Ok(_) => "terminal",
        Err(ClientError::Timeout(_)) => "timeout",
        Err(_) => "error",
    };
    // A hard transport error (not a stall) is still a failure to report.
    if let Err(e) = watch_result
        && !matches!(e, ClientError::Timeout(_))
    {
        return Err(e.into());
    }

    eprintln!("done: {captured} frame(s) captured, {failures} failure(s) ({ended_by})");
    let suggested = ffmpeg_suggestion(out_dir, ext);
    if want_json(cli) {
        print_json(&serde_json::json!({
            "captured": captured,
            "failures": failures,
            "out_dir": out_dir.to_string_lossy(),
            "ended_by": ended_by,
            "suggested_assemble": (captured > 0).then_some(suggested.clone()),
        }));
    }
    if captured == 0 {
        eprintln!(
            "no frames captured — start this during an active print (the printer \
             must be RUNNING and advancing layers), or pass --wait to launch it \
             first and have it wait for the print to start."
        );
        return Ok(());
    }
    // Frames are written; stitching is left to the user (avoids a second
    // command-with-flags arg, and ffmpeg invocations vary). Print the suggestion.
    if !want_json(cli) {
        println!("to build a video:\n  {suggested}");
    }
    Ok(())
}

/// A suggested `ffmpeg` line to stitch the frames (glob handles the layer suffix
/// in frame names; sequential `frame_NNNNNN` keeps them ordered).
fn ffmpeg_suggestion(out_dir: &std::path::Path, ext: &str) -> String {
    let dir = out_dir.display();
    format!(
        "ffmpeg -framerate 12 -pattern_type glob -i '{dir}/frame_*.{ext}' \
         -c:v libx264 -pix_fmt yuv420p {dir}/timelapse.mp4"
    )
}

/// Substitute the capture-command tokens in one argv element. Pure so the
/// (security-relevant) substitution is unit-testable; values land in distinct
/// argv elements and are never re-parsed by a shell.
fn subst_capture_tokens(s: &str, frame: &str, layer: i64, out_dir: &str) -> String {
    s.replace("{frame}", frame)
        .replace("{layer}", &layer.to_string())
        .replace("{outdir}", out_dir)
}

/// Run one capture command (argv, no shell), substituting frame/layer/outdir.
fn run_capture_cmd(
    argv: &[String],
    frame: &std::path::Path,
    layer: i64,
    out_dir: &std::path::Path,
) -> Result<(), String> {
    let frame = frame.to_string_lossy();
    let dir = out_dir.to_string_lossy();
    let subst = |s: &str| subst_capture_tokens(s, &frame, layer, &dir);
    let prog = subst(&argv[0]);
    let args: Vec<String> = argv[1..].iter().map(|a| subst(a)).collect();
    let status = std::process::Command::new(&prog)
        .args(&args)
        .status()
        .map_err(|e| format!("spawn {prog:?}: {e}"))?;
    if status.success() {
        Ok(())
    } else {
        Err(format!("{prog:?} exited with {status}"))
    }
}

/// Resolve a connection target from the selected profile + overrides.
fn resolve_target(cli: &Cli) -> Result<ResolvedTarget, CliError> {
    let cfg = Config::load_or_default(&config_path()?)?;
    let profile = selected_profile_name(cli, &cfg)?.and_then(|n| cfg.profile(&n).cloned());
    let overrides = flag_overrides(cli).over(Overrides::from_env());
    Ok(config::resolve(profile.as_ref(), &overrides)?)
}

/// Resolve the target and build a client with the given timeout (shared setup
/// for control commands).
fn connect_client(cli: &Cli, timeout_secs: u64) -> Result<LanMqttClient, CliError> {
    Ok(LanMqttClient::new(resolve_target(cli)?).with_timeout(Duration::from_secs(timeout_secs)))
}

/// Map a control command's verification outcome to output + an exit code.
///
/// Under `--json` the outcome is emitted to stdout as a stable object for every
/// variant (so an agent gets a machine-readable verdict on writes, not just
/// reads); the exit code is unchanged. Without `--json` the verdict is the exit
/// code plus a human line (stderr).
fn report_command_outcome(cli: &Cli, outcome: CommandOutcome) -> Result<(), CliError> {
    if want_json(cli) {
        let v = match &outcome {
            CommandOutcome::Verified => serde_json::json!({ "outcome": "verified" }),
            CommandOutcome::Rejected { reason } => {
                serde_json::json!({ "outcome": "rejected", "reason": reason })
            }
            CommandOutcome::Unverified { stage } => serde_json::json!({
                "outcome": "unverified",
                "stage": match stage {
                    VerifyStage::Ack => "ack",
                    VerifyStage::Effect => "effect",
                },
            }),
        };
        print_json(&v);
    }
    match outcome {
        CommandOutcome::Verified => {
            if !want_json(cli) {
                eprintln!("verified: the printer confirmed the command took effect");
            }
            Ok(())
        }
        CommandOutcome::Rejected { reason } => Err(CliError::new(
            exit::DEVICE_REJECTED,
            format!("the printer rejected the command: {reason}"),
        )),
        CommandOutcome::Unverified {
            stage: VerifyStage::Ack,
        } => Err(CliError::new(
            exit::VERIFY_TIMEOUT,
            "command published but not acknowledged within the timeout (unverified)",
        )),
        CommandOutcome::Unverified {
            stage: VerifyStage::Effect,
        } => Err(CliError::new(
            exit::VERIFY_TIMEOUT,
            "command was acknowledged but its effect never showed in the report \
             (the printer's state didn't change — e.g. a print that won't start \
             or a light that won't switch); unverified — check `bambu status`",
        )),
    }
}

/// A print is "done" for watching once it finishes, fails, or returns to idle.
fn is_watch_terminal(state: GcodeState) -> bool {
    matches!(
        state,
        GcodeState::Finish | GcodeState::Failed | GcodeState::Idle
    )
}

/// Resolve which profile to use: explicit `--printer`, else the configured
/// default. Returns `None` when neither is set (the caller then relies on
/// flag/env overrides). A name that IS set but is not in the config is an error
/// — we never silently fall back to a different target (e.g. on a `--printer`
/// typo with `BAMBU_*` in the environment).
fn selected_profile_name(cli: &Cli, cfg: &Config) -> Result<Option<String>, CliError> {
    let name = match cli.printer.clone().or_else(|| cfg.default_printer.clone()) {
        Some(n) => n,
        None => return Ok(None),
    };
    if cfg.printers.contains_key(&name) {
        Ok(Some(name))
    } else {
        Err(CliError::from(ConfigError::UnknownProfile(name)))
    }
}

/// JSON output is the default when stdout is not a TTY, or when `--json` is set.
fn want_json(cli: &Cli) -> bool {
    // Output is human-readable by default and JSON only with an explicit
    // `--json` — no TTY auto-detection (that magic surprised users piping into
    // e.g. `watch`). Agents/scripts pass `--json`; matches `gh`'s convention.
    cli.json
}

fn flag_overrides(cli: &Cli) -> Overrides {
    Overrides {
        ip: cli.ip.clone(),
        serial: cli.serial.clone(),
        access_code: cli.access_code.clone(),
        model: cli.model.clone(),
    }
}

fn print_json<T: Serialize>(value: &T) {
    match serde_json::to_string_pretty(value) {
        Ok(s) => println!("{s}"),
        Err(e) => eprintln!("error: failed to serialize output: {e}"),
    }
}

fn print_status_human(o: &StatusOutput) {
    let s = &o.status;
    println!(
        "printer: {} ({})",
        o.printer.as_deref().unwrap_or("-"),
        o.model
    );
    println!("state:   {}", s.gcode_state.as_deref().unwrap_or("?"));
    // A device-level fault (print_error) is the most important thing to see.
    if let Some(err) = &s.error {
        println!("error:   ⚠ {} (print_error {})", err.hex, err.code);
        println!("         {}", err.lookup_url);
    }
    // Show the current activity only when it's a real special stage; the
    // no-stage markers (0 / 255) just echo idle-or-printing.
    if let (Some(stage), Some(id)) = (s.stage.as_deref(), s.stg_cur)
        && !Stage(id).is_no_stage()
    {
        println!("stage:   {stage} ({id})");
    }
    if let Some(f) = &s.filament {
        let name = f.name.as_deref().or(f.material.as_deref()).unwrap_or("?");
        let color = f
            .color
            .as_deref()
            .map(|c| format!(" #{c}"))
            .unwrap_or_default();
        println!("filament: {name} @ {}{color}", f.location);
    }
    if let (Some(n), Some(b)) = (s.nozzle_temper, s.bed_temper) {
        println!("temps:   nozzle {n:.1}°C / bed {b:.1}°C");
    }
    if let Some(tl) = s.timelapse_mode() {
        println!("timelapse: {tl}");
    }
    if let Some(lvl) = s.spd_lvl {
        let name = SpeedLevel::from_level(lvl)
            .map(|l| l.as_str())
            .unwrap_or("?");
        println!("speed:   {name} ({lvl})");
    }
    if let Some(p) = s.mc_percent {
        let layer = s.layer_num.unwrap_or(0);
        let total = s.total_layer_num.unwrap_or(0);
        let eta = match s.remaining_time_min.filter(|m| *m > 0) {
            Some(m) => format!(", ETA {}", fmt_eta(m)),
            None => String::new(),
        };
        println!("progress: {p}% (layer {layer}/{total}{eta})");
    }
}

/// Format a remaining-time estimate in minutes as `15m` or `1h35m`.
fn fmt_eta(min: i64) -> String {
    if min >= 60 {
        format!("{}h{:02}m", min / 60, min % 60)
    } else {
        format!("{min}m")
    }
}

#[cfg(test)]
mod tests {
    use super::{ams_mapping_preview, fmt_eta, subst_capture_tokens, validate_ams_map};

    #[cfg(feature = "server")]
    #[test]
    fn serve_status_url_joins_and_trims_trailing_slash() {
        use super::serve_status_url;
        assert_eq!(
            serve_status_url("http://127.0.0.1:8088"),
            "http://127.0.0.1:8088/api/status"
        );
        // a trailing slash on the base must not double up
        assert_eq!(
            serve_status_url("http://h:8088/"),
            "http://h:8088/api/status"
        );
    }

    #[test]
    fn encode_args_for_an_mjpeg_stream() {
        use super::build_ffmpeg_args;
        use std::path::Path;
        let args = build_ffmpeg_args(
            Path::new("/r/plain.mjpeg"),
            Path::new("/r/plain.mp4"),
            30,
            8,
        )
        .unwrap();
        let joined = args.join(" ");
        assert!(joined.contains("-f mpjpeg"), "{joined}");
        assert!(joined.contains("-i /r/plain.mjpeg"));
        assert!(joined.contains("framestep=8"), "speed>1 ⇒ framestep");
        assert!(joined.contains("setpts=N/30/TB"));
        assert!(joined.trim_end().ends_with("/r/plain.mp4"));
    }

    #[test]
    fn encode_args_for_an_image_sequence_dir() {
        use super::build_ffmpeg_args;
        let dir = std::env::temp_dir().join(format!("bambu-enc-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let out = dir.join("x.mp4");
        let args = build_ffmpeg_args(&dir, &out, 20, 1).unwrap();
        let joined = args.join(" ");
        assert!(joined.contains("-framerate 20"), "{joined}");
        assert!(joined.contains("-pattern_type glob"));
        assert!(joined.contains("frame_*.jpg"));
        assert!(!joined.contains("framestep"), "speed=1 ⇒ no framestep");

        // speed>1 must actually speed up: framestep AND a PTS reset (not just drop
        // frames at the original spacing).
        let fast = build_ffmpeg_args(&dir, &out, 20, 4).unwrap().join(" ");
        assert!(fast.contains("framestep=4"), "{fast}");
        assert!(
            fast.contains("setpts=N/20/TB"),
            "stepped frames must be re-timed: {fast}"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn encode_rejects_a_non_dir_non_mjpeg_input() {
        use super::build_ffmpeg_args;
        use std::path::Path;
        let e = build_ffmpeg_args(Path::new("/no/such/file.txt"), Path::new("/o.mp4"), 30, 1)
            .unwrap_err();
        assert_eq!(e.code, super::exit::VALIDATION);
    }

    #[test]
    fn default_mp4_out_swaps_the_suffix() {
        use super::default_mp4_out;
        use std::path::Path;
        assert_eq!(
            default_mp4_out(Path::new("/r/plain.mjpeg")),
            Path::new("/r/plain.mp4")
        );
        assert_eq!(
            default_mp4_out(Path::new("/r/ext-1")),
            Path::new("/r/ext-1.mp4")
        );
    }

    #[test]
    fn watch_line_formats_state_progress_and_temps() {
        use super::format_watch_line;
        use crate::core::status::PrinterStatus;
        let st = PrinterStatus::from_state(&serde_json::json!({ "print": {
            "gcode_state": "RUNNING", "mc_percent": 42, "layer_num": 10, "total_layer_num": 240,
            "nozzle_temper": 215.0, "nozzle_target_temper": 245.0,
            "bed_temper": 60.0, "bed_target_temper": 60.0,
        }}));
        let line = format_watch_line(&st);
        for needle in ["RUNNING", "42%", "layer 10/240", "N215/245", "B60/60"] {
            assert!(line.contains(needle), "{needle:?} missing from {line:?}");
        }
    }

    #[test]
    fn watch_key_rounds_temps_so_subdegree_jitter_is_one_line() {
        use super::watch_key;
        use crate::core::status::PrinterStatus;
        let noz = |n: f64| {
            PrinterStatus::from_state(&serde_json::json!({ "print": { "nozzle_temper": n } }))
        };
        // sub-degree jitter folds to the same key (no redundant line)
        assert!(watch_key(&noz(215.1)) == watch_key(&noz(215.4)));
        // a full-degree step is a new key (prints, so heating stays visible)
        assert!(watch_key(&noz(215.0)) != watch_key(&noz(216.0)));
    }

    #[test]
    fn eta_formats_minutes_and_hours() {
        assert_eq!(fmt_eta(15), "15m");
        assert_eq!(fmt_eta(59), "59m");
        assert_eq!(fmt_eta(60), "1h00m");
        assert_eq!(fmt_eta(95), "1h35m");
    }

    #[test]
    fn ams_map_range_is_always_checked() {
        // -1..=3 are fine (count unknown).
        assert!(validate_ams_map(&[0, 3, -1], None).is_ok());
        // Out of range -> error even without a filament count.
        assert!(validate_ams_map(&[0, 4], None).is_err());
        assert!(validate_ams_map(&[-2], None).is_err());
    }

    #[test]
    fn ams_map_length_must_match_filament_count_when_known() {
        // 2 filaments, 2 entries -> ok.
        assert!(validate_ams_map(&[0, 1], Some(2)).is_ok());
        // 2 entries but 3 filaments -> error.
        assert!(validate_ams_map(&[0, 1], Some(3)).is_err());
        // 1 entry, 2 filaments -> error (the classic footgun).
        assert!(validate_ams_map(&[0], Some(2)).is_err());
    }

    #[test]
    fn ams_map_warns_on_multiple_external_spools() {
        let warns = validate_ams_map(&[-1, -1], Some(2)).unwrap();
        assert!(warns.iter().any(|w| w.contains("external spool")));
        // A single -1 is fine, no warning.
        assert!(validate_ams_map(&[0, -1], Some(2)).unwrap().is_empty());
    }

    #[test]
    fn ams_preview_pairs_filaments_with_trays() {
        let colors = vec!["#F2754E".to_string(), "#0000FF".to_string()];
        let v = ams_mapping_preview(&colors, &[2, -1]);
        let arr = v.as_array().unwrap();
        assert_eq!(arr[0]["color"], "#F2754E");
        assert_eq!(arr[0]["tray"], 2);
        assert_eq!(arr[0]["source"], "AMS tray 2");
        assert_eq!(arr[1]["tray"], -1);
        assert_eq!(arr[1]["source"], "external spool");
    }

    #[test]
    fn capture_tokens_substitute_per_argv_element() {
        assert_eq!(
            subst_capture_tokens("{outdir}/f_{layer}.jpg", "/t/frame.jpg", 42, "/t"),
            "/t/f_42.jpg"
        );
        assert_eq!(
            subst_capture_tokens("{frame}", "/t/frame.jpg", 7, "/t"),
            "/t/frame.jpg"
        );
        // No tokens -> unchanged.
        assert_eq!(subst_capture_tokens("-r", "/f.jpg", 1, "/t"), "-r");
    }

    #[test]
    fn capture_tokens_do_not_interpret_shell_metacharacters() {
        // The substituted value lands verbatim in a single argv element (no
        // shell parses it), so metacharacters are inert — documents that
        // `bambu timelapse capture` runs argv directly, not via a shell.
        let layer_with_meta = subst_capture_tokens("{frame}", "/t/a b;rm -rf $HOME.jpg", 1, "/t");
        assert_eq!(layer_with_meta, "/t/a b;rm -rf $HOME.jpg");
    }
}

#[derive(Serialize)]
struct StatusOutput {
    printer: Option<String>,
    model: String,
    #[serde(flatten)]
    status: PrinterStatus,
}

/// A profile view with the access code redacted, for `config show`.
#[derive(Serialize)]
struct RedactedProfile<'a> {
    name: &'a str,
    ip: &'a str,
    serial: &'a str,
    model: &'a str,
    mode: &'a str,
    access_code: &'static str,
}

impl<'a> RedactedProfile<'a> {
    fn from(name: &'a str, p: &'a Profile) -> Self {
        Self {
            name,
            ip: &p.ip,
            serial: &p.serial,
            model: &p.model,
            mode: &p.mode,
            access_code: "<redacted>",
        }
    }
}

impl std::fmt::Display for RedactedProfile<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}: ip={} serial={} model={} mode={} access_code={}",
            self.name, self.ip, self.serial, self.model, self.mode, self.access_code
        )
    }
}